Compare commits
20 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2af8c82977 | |||
| d4286ab90a | |||
| f7c6947220 | |||
| 8fccc2a286 | |||
| 7fdaeacb5b | |||
| 9716eb797f | |||
| 91deaf094e | |||
| 3a548152a9 | |||
| a8f7cda167 | |||
| 8fe5c1041a | |||
| a24753f074 | |||
| 079ee687a8 | |||
| e08c67b88f | |||
| bb2756d0fb | |||
| c87bb43aaa | |||
| 8f58c08d0d | |||
| e6f18ba801 | |||
| 7d495aa772 | |||
| db8180aa31 | |||
| 1586451862 |
@@ -1 +1 @@
|
||||
v22.4.1
|
||||
22.12.0
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
# All-in-One Assistant for Claude Code, Codex & Gemini CLI
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://tauri.app/)
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
@@ -15,7 +15,7 @@ English | [中文](README_ZH.md) | [日本語](README_JA.md) | [Changelog](CHANG
|
||||
|
||||
## ❤️Sponsor
|
||||
|
||||

|
||||
[](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)!
|
||||
|
||||
@@ -23,19 +23,18 @@ This project is sponsored by Z.ai, supporting us with their GLM CODING PLAN.GLM
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="180"><img src="assets/partners/logos/packycode.png" alt="PackyCode" width="150"></td>
|
||||
<td width="180"><a href="https://www.packyapi.com/register?aff=cc-switch"><img src="assets/partners/logos/packycode.png" alt="PackyCode" width="150"></a></td>
|
||||
<td>Thanks to PackyCode for sponsoring this project! PackyCode is a reliable and efficient API relay service provider, offering relay services for Claude Code, Codex, Gemini, and more. PackyCode provides special discounts for our software users: register using <a href="https://www.packyapi.com/register?aff=cc-switch">this link</a> and enter the "cc-switch" promo code during recharge to get 10% off.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><img src="assets/partners/logos/sds-en.png" alt="ShanDianShuo" width="150"></td>
|
||||
<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>
|
||||
<td width="180"><a href="https://aigocode.com/invite/CC-SWITCH"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></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>
|
||||
|
||||
<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>
|
||||
<td width="180"><a href="https://www.dmxapi.cn/register?aff=bUHu"><img src="assets/partners/logos/dmx-en.jpg" alt="DMXAPI" width="150"></a></td>
|
||||
<td>Thanks to DMXAPI for sponsoring this project! DMXAPI provides global large model API services to 200+ enterprise users. One API key for all global models. Features include: instant invoicing, unlimited concurrency, starting from $0.15, 24/7 technical support. GPT/Claude/Gemini all at 32% off, domestic models 20-50% off, Claude Code exclusive models at 66% off! <a href="https://www.dmxapi.cn/register?aff=bUHu">Register here</a></td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
@@ -48,7 +47,7 @@ This project is sponsored by Z.ai, supporting us with their GLM CODING PLAN.GLM
|
||||
|
||||
## Features
|
||||
|
||||
### Current Version: v3.8.2 | [Full Changelog](CHANGELOG.md) | [Release Notes](docs/release-note-v3.8.0-en.md)
|
||||
### Current Version: v3.8.3 | [Full Changelog](CHANGELOG.md) | [Release Notes](docs/release-note-v3.8.0-en.md)
|
||||
|
||||
**v3.8.0 Major Update (2025-11-28)**
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
# Claude Code / Codex / Gemini CLI オールインワン・アシスタント
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://tauri.app/)
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
## ❤️スポンサー
|
||||
|
||||

|
||||
[](https://z.ai/subscribe?ic=8JVLJQFSKB)
|
||||
|
||||
本プロジェクトは 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% オフになります!
|
||||
|
||||
@@ -23,20 +23,18 @@
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="180"><img src="assets/partners/logos/packycode.png" alt="PackyCode" width="150"></td>
|
||||
<td width="180"><a href="https://www.packyapi.com/register?aff=cc-switch"><img src="assets/partners/logos/packycode.png" alt="PackyCode" width="150"></a></td>
|
||||
<td>PackyCode のご支援に感謝します!PackyCode は Claude Code、Codex、Gemini などのリレーサービスを提供する信頼性の高い API 中継プラットフォームです。本ソフト利用者向けに特別割引があります:<a href="https://www.packyapi.com/register?aff=cc-switch">このリンク</a>で登録し、チャージ時に「cc-switch」クーポンを入力すると 10% オフになります。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><img src="assets/partners/logos/sds-en.png" alt="ShanDianShuo" width="150"></td>
|
||||
<td>ShanDianShuo のご支援に感謝します!ShanDianShuo はローカルファーストの音声入力ツールで、ミリ秒遅延・データは端末から外に出ず・キーボード入力の 4 倍の速度・AI 自動補正・プライバシー優先で完全無料。Claude Code と組み合わせればコーディング効率が倍増します。<a href="https://www.shandianshuo.cn">Mac/Win 版を無料ダウンロード</a></td>
|
||||
<td width="180"><a href="https://aigocode.com/invite/CC-SWITCH"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
|
||||
<td>本プロジェクトは AIGoCode のスポンサー提供でお届けしています。AIGoCode は、Claude Code・Codex・最新の Gemini モデルを統合したオールインワンのAIコーディングプラットフォームで、安定性・高速性・コストパフォーマンスに優れた開発サービスを提供します。柔軟なサブスクリプションプランを備え、レスポンスも非常に高速です。さらに、CC Switch ユーザー向けの特典として、<a href="https://aigocode.com/invite/CC-SWITCH">このリンク</a>から登録すると、初回チャージ時に10%分のボーナスクレジットが付与されます!</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>
|
||||
<td width="180"><a href="https://www.dmxapi.cn/register?aff=bUHu"><img src="assets/partners/logos/dmx-en.jpg" alt="DMXAPI" width="150"></a></td>
|
||||
<td>DMXAPI のご支援に感謝します!DMXAPI は 200 社以上の企業ユーザーにグローバル大規模モデル API サービスを提供しています。1 つの API キーで全世界のモデルにアクセス可能。即時請求書発行、同時接続数無制限、最低 $0.15 から、24 時間年中無休のテクニカルサポート。GPT/Claude/Gemini が全て 32% オフ、国内モデルは 20〜50% オフ、Claude Code 専用モデルは 66% オフ実施中!<a href="https://www.dmxapi.cn/register?aff=bUHu">登録はこちら</a></td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
@@ -49,7 +47,7 @@
|
||||
|
||||
## 特長
|
||||
|
||||
### 現在のバージョン:v3.8.2 | [完全な更新履歴](CHANGELOG.md) | [リリースノート](docs/release-note-v3.8.0-en.md)
|
||||
### 現在のバージョン:v3.8.3 | [完全な更新履歴](CHANGELOG.md) | [リリースノート](docs/release-note-v3.8.0-en.md)
|
||||
|
||||
**v3.8.0 メジャーアップデート (2025-11-28)**
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
# Claude Code / Codex / Gemini CLI 全方位辅助工具
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://tauri.app/)
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
## ❤️赞助商
|
||||
|
||||

|
||||
[](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)购买可以享受九折优惠。
|
||||
|
||||
@@ -23,20 +23,20 @@
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="180"><img src="assets/partners/logos/packycode.png" alt="PackyCode" width="150"></td>
|
||||
<td width="180"><a href="https://www.packyapi.com/register?aff=cc-switch"><img src="assets/partners/logos/packycode.png" alt="PackyCode" width="150"></a></td>
|
||||
<td>感谢 PackyCode 赞助了本项目!PackyCode 是一家稳定、高效的API中转服务商,提供 Claude Code、Codex、Gemini 等多种中转服务。PackyCode 为本软件的用户提供了特别优惠,使用<a href="https://www.packyapi.com/register?aff=cc-switch">此链接</a>注册并在充值时填写"cc-switch"优惠码,可以享受9折优惠。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><img src="assets/partners/logos/sds-zh.png" alt="ShanDianShuo" width="150"></td>
|
||||
<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 width="180"><a href="https://aigocode.com/invite/CC-SWITCH"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
|
||||
<td>感谢 AIGoCode 赞助了本项目!AIGoCode 是一个集成了 Claude Code、Codex 以及 Gemini 最新模型的一站式平台,为你提供稳定、高效且高性价比的AI编程服务。本站提供灵活的订阅计划,零封号风险,国内直连,无需魔法,极速响应。AIGoCode 为 CC Switch 的用户提供了特别福利,通过<a href="https://aigocode.com/invite/CC-SWITCH">此链接</a>注册的用户首次充值可以获得额外10%奖励额度!</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.dmxapi.cn/register?aff=bUHu"><img src="assets/partners/logos/dmx-zh.jpeg" alt="DMXAPI" width="150"></a></td>
|
||||
<td>感谢 DMXAPI(大模型API)赞助了本项目! DMXAPI,一个Key用全球大模型。
|
||||
为200多家企业用户提供全球大模型API服务。· 充值即开票 ·当天开票 ·并发不限制 ·1元起充 · 7x24 在线技术辅导,GPT/Claude/Gemini全部6.8折,国内模型5~8折,Claude Code 专属模型3.4折进行中!<a href="https://www.dmxapi.cn/register?aff=bUHu">点击这里注册</a></td>
|
||||
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## 界面预览
|
||||
@@ -47,7 +47,7 @@
|
||||
|
||||
## 功能特性
|
||||
|
||||
### 当前版本:v3.8.2 | [完整更新日志](CHANGELOG.md)
|
||||
### 当前版本:v3.8.3 | [完整更新日志](CHANGELOG.md)
|
||||
|
||||
**v3.8.0 重大更新(2025-11-28)**
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 102 KiB After Width: | Height: | Size: 264 KiB |
|
Before Width: | Height: | Size: 110 KiB After Width: | Height: | Size: 299 KiB |
|
After Width: | Height: | Size: 41 KiB |
|
After Width: | Height: | Size: 22 KiB |
@@ -4,7 +4,7 @@
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "tailwind.config.js",
|
||||
"config": "tailwind.config.cjs",
|
||||
"css": "src/index.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"name": "cc-switch",
|
||||
"version": "3.9.0-2",
|
||||
"description": "All-in-One Assistant for Claude Code, Codex & Gemini CLI",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "pnpm tauri dev",
|
||||
"build": "pnpm tauri build",
|
||||
@@ -27,6 +28,7 @@
|
||||
"@types/react-dom": "^18.2.0",
|
||||
"@vitejs/plugin-react": "^4.2.0",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"code-inspector-plugin": "^1.3.3",
|
||||
"cross-fetch": "^4.1.0",
|
||||
"jsdom": "^25.0.0",
|
||||
"msw": "^2.11.6",
|
||||
@@ -34,7 +36,7 @@
|
||||
"prettier": "^3.6.2",
|
||||
"tailwindcss": "^3.4.17",
|
||||
"typescript": "^5.3.0",
|
||||
"vite": "^5.0.0",
|
||||
"vite": "^7.3.0",
|
||||
"vitest": "^2.0.5"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -85,4 +87,4 @@
|
||||
"zod": "^4.1.12"
|
||||
},
|
||||
"packageManager": "pnpm@10.10.0+sha512.d615db246fe70f25dcfea6d8d73dee782ce23e2245e3c4f6f888249fb568149318637dca73c2c5c8ef2a4ca0d5657fb9567188bfab47f566d1ee6ce987815c39"
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,36 @@
|
||||
use crate::error::AppError;
|
||||
use auto_launch::{AutoLaunch, AutoLaunchBuilder};
|
||||
|
||||
/// 获取 macOS 上的 .app bundle 路径
|
||||
/// 将 `/path/to/CC Switch.app/Contents/MacOS/CC Switch` 转换为 `/path/to/CC Switch.app`
|
||||
#[cfg(target_os = "macos")]
|
||||
fn get_macos_app_bundle_path(exe_path: &std::path::Path) -> Option<std::path::PathBuf> {
|
||||
let path_str = exe_path.to_string_lossy();
|
||||
// 查找 .app/Contents/MacOS/ 模式
|
||||
if let Some(app_pos) = path_str.find(".app/Contents/MacOS/") {
|
||||
let app_bundle_end = app_pos + 4; // ".app" 的结束位置
|
||||
Some(std::path::PathBuf::from(&path_str[..app_bundle_end]))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// 初始化 AutoLaunch 实例
|
||||
fn get_auto_launch() -> Result<AutoLaunch, AppError> {
|
||||
let app_name = "CC Switch";
|
||||
let app_path =
|
||||
let exe_path =
|
||||
std::env::current_exe().map_err(|e| AppError::Message(format!("无法获取应用路径: {e}")))?;
|
||||
|
||||
// macOS 需要使用 .app bundle 路径,否则 AppleScript login item 会打开终端
|
||||
#[cfg(target_os = "macos")]
|
||||
let app_path = get_macos_app_bundle_path(&exe_path).unwrap_or(exe_path);
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let app_path = exe_path;
|
||||
|
||||
// 使用 AutoLaunchBuilder 消除平台差异
|
||||
// Windows/Linux: new() 接受 3 参数
|
||||
// macOS: new() 接受 4 参数(含 hidden 参数)
|
||||
// Builder 模式自动处理这些差异
|
||||
// macOS: 使用 AppleScript 方式(默认),需要 .app bundle 路径
|
||||
// Windows/Linux: 使用注册表/XDG autostart
|
||||
let auto_launch = AutoLaunchBuilder::new()
|
||||
.set_app_name(app_name)
|
||||
.set_app_path(&app_path.to_string_lossy())
|
||||
@@ -47,3 +67,50 @@ pub fn is_auto_launch_enabled() -> Result<bool, AppError> {
|
||||
.is_enabled()
|
||||
.map_err(|e| AppError::Message(format!("检查开机自启状态失败: {e}")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn test_get_macos_app_bundle_path_valid() {
|
||||
let exe_path = std::path::Path::new("/Applications/CC Switch.app/Contents/MacOS/CC Switch");
|
||||
let result = get_macos_app_bundle_path(exe_path);
|
||||
assert_eq!(
|
||||
result,
|
||||
Some(std::path::PathBuf::from("/Applications/CC Switch.app"))
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn test_get_macos_app_bundle_path_with_spaces() {
|
||||
let exe_path =
|
||||
std::path::Path::new("/Users/test/My Apps/CC Switch.app/Contents/MacOS/CC Switch");
|
||||
let result = get_macos_app_bundle_path(exe_path);
|
||||
assert_eq!(
|
||||
result,
|
||||
Some(std::path::PathBuf::from(
|
||||
"/Users/test/My Apps/CC Switch.app"
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn test_get_macos_app_bundle_path_not_in_bundle() {
|
||||
let exe_path = std::path::Path::new("/usr/local/bin/cc-switch");
|
||||
let result = get_macos_app_bundle_path(exe_path);
|
||||
assert_eq!(result, None);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn test_get_macos_app_bundle_path_dev_build() {
|
||||
// 开发环境下的路径通常不在 .app bundle 内
|
||||
let exe_path = std::path::Path::new("/Users/dev/project/target/debug/cc-switch");
|
||||
let result = get_macos_app_bundle_path(exe_path);
|
||||
assert_eq!(result, None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! 故障转移队列命令
|
||||
//!
|
||||
//! 管理代理模式下的故障转移队列
|
||||
//! 管理代理模式下的故障转移队列(基于 providers 表的 in_failover_queue 字段)
|
||||
|
||||
use crate::database::FailoverQueueItem;
|
||||
use crate::provider::Provider;
|
||||
@@ -56,54 +56,47 @@ pub async fn remove_from_failover_queue(
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 重新排序故障转移队列
|
||||
/// 获取指定应用的自动故障转移开关状态(从 proxy_config 表读取)
|
||||
#[tauri::command]
|
||||
pub async fn reorder_failover_queue(
|
||||
pub async fn get_auto_failover_enabled(
|
||||
state: tauri::State<'_, AppState>,
|
||||
app_type: String,
|
||||
provider_ids: Vec<String>,
|
||||
) -> Result<(), String> {
|
||||
) -> Result<bool, String> {
|
||||
state
|
||||
.db
|
||||
.reorder_failover_queue(&app_type, &provider_ids)
|
||||
.get_proxy_config_for_app(&app_type)
|
||||
.await
|
||||
.map(|config| config.auto_failover_enabled)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 设置故障转移队列项的启用状态
|
||||
#[tauri::command]
|
||||
pub async fn set_failover_item_enabled(
|
||||
state: tauri::State<'_, AppState>,
|
||||
app_type: String,
|
||||
provider_id: String,
|
||||
enabled: bool,
|
||||
) -> Result<(), String> {
|
||||
state
|
||||
.db
|
||||
.set_failover_item_enabled(&app_type, &provider_id, enabled)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 获取自动故障转移总开关状态
|
||||
#[tauri::command]
|
||||
pub async fn get_auto_failover_enabled(state: tauri::State<'_, AppState>) -> Result<bool, String> {
|
||||
state
|
||||
.db
|
||||
.get_setting("auto_failover_enabled")
|
||||
.map(|v| v.map(|s| s == "true").unwrap_or(false)) // 默认关闭
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 设置自动故障转移总开关状态
|
||||
/// 设置指定应用的自动故障转移开关状态(写入 proxy_config 表)
|
||||
///
|
||||
/// 注意:关闭故障转移时不会清除队列,队列内容会保留供下次开启时使用
|
||||
#[tauri::command]
|
||||
pub async fn set_auto_failover_enabled(
|
||||
state: tauri::State<'_, AppState>,
|
||||
app_type: String,
|
||||
enabled: bool,
|
||||
) -> Result<(), String> {
|
||||
log::info!(
|
||||
"[Failover] Setting auto_failover_enabled: app_type='{app_type}', enabled={enabled}"
|
||||
);
|
||||
|
||||
// 读取当前配置
|
||||
let mut config = state
|
||||
.db
|
||||
.get_proxy_config_for_app(&app_type)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
// 更新 auto_failover_enabled 字段
|
||||
config.auto_failover_enabled = enabled;
|
||||
|
||||
// 写回数据库
|
||||
state
|
||||
.db
|
||||
.set_setting(
|
||||
"auto_failover_enabled",
|
||||
if enabled { "true" } else { "false" },
|
||||
)
|
||||
.update_proxy_config_for_app(config)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
@@ -4,6 +4,12 @@ use crate::init_status::InitErrorPayload;
|
||||
use tauri::AppHandle;
|
||||
use tauri_plugin_opener::OpenerExt;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::os::windows::process::CommandExt;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
const CREATE_NO_WINDOW: u32 = 0x08000000;
|
||||
|
||||
/// 打开外部链接
|
||||
#[tauri::command]
|
||||
pub async fn open_external(app: AppHandle, url: String) -> Result<bool, String> {
|
||||
@@ -142,11 +148,16 @@ fn extract_version(raw: &str) -> String {
|
||||
fn try_get_version(tool: &str) -> (Option<String>, Option<String>) {
|
||||
use std::process::Command;
|
||||
|
||||
let output = if cfg!(target_os = "windows") {
|
||||
#[cfg(target_os = "windows")]
|
||||
let output = {
|
||||
Command::new("cmd")
|
||||
.args(["/C", &format!("{tool} --version")])
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.output()
|
||||
} else {
|
||||
};
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let output = {
|
||||
Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(format!("{tool} --version"))
|
||||
@@ -239,10 +250,22 @@ fn scan_cli_version(tool: &str) -> (Option<String>, Option<String>) {
|
||||
let current_path = std::env::var("PATH").unwrap_or_default();
|
||||
let new_path = format!("{}:{}", path.display(), current_path);
|
||||
|
||||
let output = Command::new(&tool_path)
|
||||
.arg("--version")
|
||||
.env("PATH", &new_path)
|
||||
.output();
|
||||
#[cfg(target_os = "windows")]
|
||||
let output = {
|
||||
Command::new(&tool_path)
|
||||
.arg("--version")
|
||||
.env("PATH", &new_path)
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.output()
|
||||
};
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let output = {
|
||||
Command::new(&tool_path)
|
||||
.arg("--version")
|
||||
.env("PATH", &new_path)
|
||||
.output()
|
||||
};
|
||||
|
||||
if let Ok(out) = output {
|
||||
let stdout = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
|
||||
@@ -229,3 +229,97 @@ pub fn update_providers_sort_order(
|
||||
let app_type = AppType::from_str(&app).map_err(|e| e.to_string())?;
|
||||
ProviderService::update_sort_order(state.inner(), app_type, updates).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 统一供应商(Universal Provider)命令
|
||||
// ============================================================================
|
||||
|
||||
use crate::provider::UniversalProvider;
|
||||
use std::collections::HashMap;
|
||||
use tauri::{AppHandle, Emitter};
|
||||
|
||||
/// 统一供应商同步完成事件的 payload
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
pub struct UniversalProviderSyncedEvent {
|
||||
/// 操作类型: "upsert" | "delete" | "sync"
|
||||
pub action: String,
|
||||
/// 统一供应商 ID
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
/// 发送统一供应商同步事件,通知前端刷新供应商列表
|
||||
fn emit_universal_provider_synced(app: &AppHandle, action: &str, id: &str) {
|
||||
let _ = app.emit(
|
||||
"universal-provider-synced",
|
||||
UniversalProviderSyncedEvent {
|
||||
action: action.to_string(),
|
||||
id: id.to_string(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// 获取所有统一供应商
|
||||
#[tauri::command]
|
||||
pub fn get_universal_providers(
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<HashMap<String, UniversalProvider>, String> {
|
||||
ProviderService::list_universal(state.inner()).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 获取单个统一供应商
|
||||
#[tauri::command]
|
||||
pub fn get_universal_provider(
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
) -> Result<Option<UniversalProvider>, String> {
|
||||
ProviderService::get_universal(state.inner(), &id).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 添加或更新统一供应商
|
||||
#[tauri::command]
|
||||
pub fn upsert_universal_provider(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
provider: UniversalProvider,
|
||||
) -> Result<bool, String> {
|
||||
let id = provider.id.clone();
|
||||
let result =
|
||||
ProviderService::upsert_universal(state.inner(), provider).map_err(|e| e.to_string())?;
|
||||
|
||||
// 发送事件通知前端刷新
|
||||
emit_universal_provider_synced(&app, "upsert", &id);
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// 删除统一供应商
|
||||
#[tauri::command]
|
||||
pub fn delete_universal_provider(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
) -> Result<bool, String> {
|
||||
let result =
|
||||
ProviderService::delete_universal(state.inner(), &id).map_err(|e| e.to_string())?;
|
||||
|
||||
// 发送事件通知前端刷新
|
||||
emit_universal_provider_synced(&app, "delete", &id);
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// 同步统一供应商到各应用(手动触发)
|
||||
#[tauri::command]
|
||||
pub fn sync_universal_provider(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
) -> Result<bool, String> {
|
||||
let result =
|
||||
ProviderService::sync_universal_to_apps(state.inner(), &id).map_err(|e| e.to_string())?;
|
||||
|
||||
// 发送事件通知前端刷新
|
||||
emit_universal_provider_synced(&app, "sync", &id);
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
@@ -14,14 +14,6 @@ pub async fn start_proxy_server(
|
||||
state.proxy_service.start().await
|
||||
}
|
||||
|
||||
/// 启动代理服务器(带 Live 配置接管)
|
||||
#[tauri::command]
|
||||
pub async fn start_proxy_with_takeover(
|
||||
state: tauri::State<'_, AppState>,
|
||||
) -> Result<ProxyServerInfo, String> {
|
||||
state.proxy_service.start_with_takeover().await
|
||||
}
|
||||
|
||||
/// 停止代理服务器(恢复 Live 配置)
|
||||
#[tauri::command]
|
||||
pub async fn stop_proxy_with_restore(state: tauri::State<'_, AppState>) -> Result<(), String> {
|
||||
@@ -70,6 +62,63 @@ pub async fn update_proxy_config(
|
||||
state.proxy_service.update_config(&config).await
|
||||
}
|
||||
|
||||
// ==================== Global & Per-App Config ====================
|
||||
|
||||
/// 获取全局代理配置
|
||||
///
|
||||
/// 返回统一的全局配置字段(代理开关、监听地址、端口、日志开关)
|
||||
#[tauri::command]
|
||||
pub async fn get_global_proxy_config(
|
||||
state: tauri::State<'_, AppState>,
|
||||
) -> Result<GlobalProxyConfig, String> {
|
||||
let db = &state.db;
|
||||
db.get_global_proxy_config()
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 更新全局代理配置
|
||||
///
|
||||
/// 更新统一的全局配置字段,会同时更新三行(claude/codex/gemini)
|
||||
#[tauri::command]
|
||||
pub async fn update_global_proxy_config(
|
||||
state: tauri::State<'_, AppState>,
|
||||
config: GlobalProxyConfig,
|
||||
) -> Result<(), String> {
|
||||
let db = &state.db;
|
||||
db.update_global_proxy_config(config)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 获取指定应用的代理配置
|
||||
///
|
||||
/// 返回应用级配置(enabled、auto_failover、超时、熔断器等)
|
||||
#[tauri::command]
|
||||
pub async fn get_proxy_config_for_app(
|
||||
state: tauri::State<'_, AppState>,
|
||||
app_type: String,
|
||||
) -> Result<AppProxyConfig, String> {
|
||||
let db = &state.db;
|
||||
db.get_proxy_config_for_app(&app_type)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 更新指定应用的代理配置
|
||||
///
|
||||
/// 更新应用级配置(enabled、auto_failover、超时、熔断器等)
|
||||
#[tauri::command]
|
||||
pub async fn update_proxy_config_for_app(
|
||||
state: tauri::State<'_, AppState>,
|
||||
config: AppProxyConfig,
|
||||
) -> Result<(), String> {
|
||||
let db = &state.db;
|
||||
db.update_proxy_config_for_app(config)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 检查代理服务器是否正在运行
|
||||
#[tauri::command]
|
||||
pub async fn is_proxy_running(state: tauri::State<'_, AppState>) -> Result<bool, String> {
|
||||
@@ -111,8 +160,13 @@ pub async fn get_provider_health(
|
||||
}
|
||||
|
||||
/// 重置熔断器
|
||||
///
|
||||
/// 重置后会检查是否应该切回队列中优先级更高的供应商:
|
||||
/// 1. 检查自动故障转移是否开启
|
||||
/// 2. 如果恢复的供应商在队列中优先级更高(queue_order 更小),则自动切换
|
||||
#[tauri::command]
|
||||
pub async fn reset_circuit_breaker(
|
||||
app_handle: tauri::AppHandle,
|
||||
state: tauri::State<'_, AppState>,
|
||||
provider_id: String,
|
||||
app_type: String,
|
||||
@@ -129,6 +183,68 @@ pub async fn reset_circuit_breaker(
|
||||
.reset_provider_circuit_breaker(&provider_id, &app_type)
|
||||
.await?;
|
||||
|
||||
// 3. 检查是否应该切回优先级更高的供应商(从 proxy_config 表读取)
|
||||
let auto_failover_enabled = match db.get_proxy_config_for_app(&app_type).await {
|
||||
Ok(config) => config.auto_failover_enabled,
|
||||
Err(e) => {
|
||||
log::error!(
|
||||
"[{app_type}] Failed to read proxy_config for auto_failover_enabled: {e}, defaulting to disabled"
|
||||
);
|
||||
false
|
||||
}
|
||||
};
|
||||
|
||||
if auto_failover_enabled && state.proxy_service.is_running().await {
|
||||
// 获取当前供应商 ID
|
||||
let current_id = db
|
||||
.get_current_provider(&app_type)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
if let Some(current_id) = current_id {
|
||||
// 获取故障转移队列
|
||||
let queue = db
|
||||
.get_failover_queue(&app_type)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
// 找到恢复的供应商和当前供应商在队列中的位置(使用 sort_index)
|
||||
let restored_order = queue
|
||||
.iter()
|
||||
.find(|item| item.provider_id == provider_id)
|
||||
.and_then(|item| item.sort_index);
|
||||
|
||||
let current_order = queue
|
||||
.iter()
|
||||
.find(|item| item.provider_id == current_id)
|
||||
.and_then(|item| item.sort_index);
|
||||
|
||||
// 如果恢复的供应商优先级更高(sort_index 更小),则切换
|
||||
if let (Some(restored), Some(current)) = (restored_order, current_order) {
|
||||
if restored < current {
|
||||
log::info!(
|
||||
"[Recovery] 供应商 {provider_id} 已恢复且优先级更高 (P{restored} vs P{current}),自动切换"
|
||||
);
|
||||
|
||||
// 获取供应商名称用于日志和事件
|
||||
let provider_name = db
|
||||
.get_all_providers(&app_type)
|
||||
.ok()
|
||||
.and_then(|providers| providers.get(&provider_id).map(|p| p.name.clone()))
|
||||
.unwrap_or_else(|| provider_id.clone());
|
||||
|
||||
// 创建故障转移切换管理器并执行切换
|
||||
let switch_manager =
|
||||
crate::proxy::failover_switch::FailoverSwitchManager::new(db.clone());
|
||||
if let Err(e) = switch_manager
|
||||
.try_switch(Some(&app_handle), &app_type, &provider_id, &provider_name)
|
||||
.await
|
||||
{
|
||||
log::error!("[Recovery] 自动切换失败: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -52,9 +52,7 @@ pub async fn stream_check_all_providers(
|
||||
}
|
||||
if let Ok(queue) = state.db.get_failover_queue(app_type.as_str()) {
|
||||
for item in queue {
|
||||
if item.enabled {
|
||||
ids.insert(item.provider_id);
|
||||
}
|
||||
ids.insert(item.provider_id);
|
||||
}
|
||||
}
|
||||
Some(ids)
|
||||
|
||||
@@ -1,36 +1,32 @@
|
||||
//! 故障转移队列 DAO
|
||||
//!
|
||||
//! 管理代理模式下的故障转移队列
|
||||
//! 管理代理模式下的故障转移队列(基于 providers 表的 in_failover_queue 字段)
|
||||
|
||||
use crate::database::{lock_conn, Database};
|
||||
use crate::error::AppError;
|
||||
use crate::provider::Provider;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// 故障转移队列条目
|
||||
/// 故障转移队列条目(简化版,用于前端展示)
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FailoverQueueItem {
|
||||
pub provider_id: String,
|
||||
pub provider_name: String,
|
||||
pub queue_order: i32,
|
||||
pub enabled: bool,
|
||||
pub created_at: i64,
|
||||
pub sort_index: Option<usize>,
|
||||
}
|
||||
|
||||
impl Database {
|
||||
/// 获取故障转移队列(按 queue_order 排序)
|
||||
/// 获取故障转移队列(按 sort_index 排序)
|
||||
pub fn get_failover_queue(&self, app_type: &str) -> Result<Vec<FailoverQueueItem>, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT fq.provider_id, p.name, fq.queue_order, fq.enabled, fq.created_at
|
||||
FROM failover_queue fq
|
||||
JOIN providers p ON fq.provider_id = p.id AND fq.app_type = p.app_type
|
||||
WHERE fq.app_type = ?1
|
||||
ORDER BY fq.queue_order ASC",
|
||||
"SELECT id, name, sort_index
|
||||
FROM providers
|
||||
WHERE app_type = ?1 AND in_failover_queue = 1
|
||||
ORDER BY COALESCE(sort_index, 999999), id ASC",
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
@@ -39,9 +35,7 @@ impl Database {
|
||||
Ok(FailoverQueueItem {
|
||||
provider_id: row.get(0)?,
|
||||
provider_name: row.get(1)?,
|
||||
queue_order: row.get(2)?,
|
||||
enabled: row.get(3)?,
|
||||
created_at: row.get(4)?,
|
||||
sort_index: row.get(2)?,
|
||||
})
|
||||
})
|
||||
.map_err(|e| AppError::Database(e.to_string()))?
|
||||
@@ -53,43 +47,23 @@ impl Database {
|
||||
|
||||
/// 获取故障转移队列中的供应商(完整 Provider 信息,按顺序)
|
||||
pub fn get_failover_providers(&self, app_type: &str) -> Result<Vec<Provider>, AppError> {
|
||||
let queue = self.get_failover_queue(app_type)?;
|
||||
let all_providers = self.get_all_providers(app_type)?;
|
||||
|
||||
let mut result = Vec::new();
|
||||
for item in queue {
|
||||
if item.enabled {
|
||||
if let Some(provider) = all_providers.get(&item.provider_id) {
|
||||
result.push(provider.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let result: Vec<Provider> = all_providers
|
||||
.into_values()
|
||||
.filter(|p| p.in_failover_queue)
|
||||
.collect();
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// 添加供应商到故障转移队列末尾
|
||||
/// 添加供应商到故障转移队列
|
||||
pub fn add_to_failover_queue(&self, app_type: &str, provider_id: &str) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
// 获取当前最大 queue_order
|
||||
let max_order: i32 = conn
|
||||
.query_row(
|
||||
"SELECT COALESCE(MAX(queue_order), 0) FROM failover_queue WHERE app_type = ?1",
|
||||
[app_type],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs() as i64;
|
||||
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO failover_queue (app_type, provider_id, queue_order, enabled, created_at)
|
||||
VALUES (?1, ?2, ?3, 1, ?4)",
|
||||
rusqlite::params![app_type, provider_id, max_order + 1, now],
|
||||
"UPDATE providers SET in_failover_queue = 1 WHERE id = ?1 AND app_type = ?2",
|
||||
rusqlite::params![provider_id, app_type],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
@@ -104,103 +78,21 @@ impl Database {
|
||||
) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
// 获取被删除项的 queue_order
|
||||
let removed_order: Option<i32> = conn
|
||||
.query_row(
|
||||
"SELECT queue_order FROM failover_queue WHERE app_type = ?1 AND provider_id = ?2",
|
||||
[app_type, provider_id],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.ok();
|
||||
|
||||
// 删除该项
|
||||
// 1. 从队列中移除
|
||||
conn.execute(
|
||||
"DELETE FROM failover_queue WHERE app_type = ?1 AND provider_id = ?2",
|
||||
[app_type, provider_id],
|
||||
"UPDATE providers SET in_failover_queue = 0 WHERE id = ?1 AND app_type = ?2",
|
||||
rusqlite::params![provider_id, app_type],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 重新排序后面的项(填补空隙)
|
||||
if let Some(order) = removed_order {
|
||||
conn.execute(
|
||||
"UPDATE failover_queue
|
||||
SET queue_order = queue_order - 1
|
||||
WHERE app_type = ?1 AND queue_order > ?2",
|
||||
rusqlite::params![app_type, order],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
}
|
||||
// 2. 清除该供应商的健康状态(退出队列后不再需要健康监控)
|
||||
conn.execute(
|
||||
"DELETE FROM provider_health WHERE provider_id = ?1 AND app_type = ?2",
|
||||
rusqlite::params![provider_id, app_type],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 重新排序故障转移队列
|
||||
/// provider_ids: 按新顺序排列的 provider_id 列表
|
||||
pub fn reorder_failover_queue(
|
||||
&self,
|
||||
app_type: &str,
|
||||
provider_ids: &[String],
|
||||
) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
// 使用事务确保原子性
|
||||
conn.execute("BEGIN TRANSACTION", [])
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
let result = (|| {
|
||||
for (index, provider_id) in provider_ids.iter().enumerate() {
|
||||
conn.execute(
|
||||
"UPDATE failover_queue
|
||||
SET queue_order = ?3
|
||||
WHERE app_type = ?1 AND provider_id = ?2",
|
||||
rusqlite::params![app_type, provider_id, (index + 1) as i32],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
|
||||
match result {
|
||||
Ok(_) => {
|
||||
conn.execute("COMMIT", [])
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
conn.execute("ROLLBACK", []).ok();
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 设置故障转移队列中供应商的启用状态
|
||||
pub fn set_failover_item_enabled(
|
||||
&self,
|
||||
app_type: &str,
|
||||
provider_id: &str,
|
||||
enabled: bool,
|
||||
) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
let rows_affected = conn
|
||||
.execute(
|
||||
"UPDATE failover_queue SET enabled = ?3 WHERE app_type = ?1 AND provider_id = ?2",
|
||||
rusqlite::params![app_type, provider_id, enabled],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
if rows_affected == 0 {
|
||||
log::warn!(
|
||||
"set_failover_item_enabled: 未找到匹配记录 app_type={app_type}, provider_id={provider_id}"
|
||||
);
|
||||
return Err(AppError::Database(format!(
|
||||
"未找到故障转移队列项: app_type={app_type}, provider_id={provider_id}"
|
||||
)));
|
||||
}
|
||||
|
||||
log::info!(
|
||||
"set_failover_item_enabled: 已更新 app_type={app_type}, provider_id={provider_id}, enabled={enabled}"
|
||||
);
|
||||
log::info!("已从故障转移队列移除供应商 {provider_id} ({app_type}), 并清除其健康状态");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -209,8 +101,11 @@ impl Database {
|
||||
pub fn clear_failover_queue(&self, app_type: &str) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
conn.execute("DELETE FROM failover_queue WHERE app_type = ?1", [app_type])
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
conn.execute(
|
||||
"UPDATE providers SET in_failover_queue = 0 WHERE app_type = ?1",
|
||||
[app_type],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -223,15 +118,15 @@ impl Database {
|
||||
) -> Result<bool, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
let count: i32 = conn
|
||||
let in_queue: bool = conn
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM failover_queue WHERE app_type = ?1 AND provider_id = ?2",
|
||||
[app_type, provider_id],
|
||||
"SELECT in_failover_queue FROM providers WHERE id = ?1 AND app_type = ?2",
|
||||
rusqlite::params![provider_id, app_type],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
.unwrap_or(false);
|
||||
|
||||
Ok(count > 0)
|
||||
Ok(in_queue)
|
||||
}
|
||||
|
||||
/// 获取可添加到故障转移队列的供应商(不在队列中的)
|
||||
@@ -240,14 +135,10 @@ impl Database {
|
||||
app_type: &str,
|
||||
) -> Result<Vec<Provider>, AppError> {
|
||||
let all_providers = self.get_all_providers(app_type)?;
|
||||
let queue = self.get_failover_queue(app_type)?;
|
||||
|
||||
let queue_ids: std::collections::HashSet<_> =
|
||||
queue.iter().map(|item| &item.provider_id).collect();
|
||||
|
||||
let available: Vec<Provider> = all_providers
|
||||
.into_values()
|
||||
.filter(|p| !queue_ids.contains(&p.id))
|
||||
.filter(|p| !p.in_failover_queue)
|
||||
.collect();
|
||||
|
||||
Ok(available)
|
||||
|
||||
@@ -10,6 +10,7 @@ pub mod proxy;
|
||||
pub mod settings;
|
||||
pub mod skills;
|
||||
pub mod stream_check;
|
||||
pub mod universal_providers;
|
||||
|
||||
// 所有 DAO 方法都通过 Database impl 提供,无需单独导出
|
||||
// 导出 FailoverQueueItem 供外部使用
|
||||
|
||||
@@ -17,7 +17,7 @@ impl Database {
|
||||
) -> Result<IndexMap<String, Provider>, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id, name, settings_config, website_url, category, created_at, sort_index, notes, icon, icon_color, meta
|
||||
"SELECT id, name, settings_config, website_url, category, created_at, sort_index, notes, icon, icon_color, meta, in_failover_queue
|
||||
FROM providers WHERE app_type = ?1
|
||||
ORDER BY COALESCE(sort_index, 999999), created_at ASC, id ASC"
|
||||
).map_err(|e| AppError::Database(e.to_string()))?;
|
||||
@@ -35,6 +35,7 @@ impl Database {
|
||||
let icon: Option<String> = row.get(8)?;
|
||||
let icon_color: Option<String> = row.get(9)?;
|
||||
let meta_str: String = row.get(10)?;
|
||||
let in_failover_queue: bool = row.get(11)?;
|
||||
|
||||
let settings_config =
|
||||
serde_json::from_str(&settings_config_str).unwrap_or(serde_json::Value::Null);
|
||||
@@ -54,6 +55,7 @@ impl Database {
|
||||
meta: Some(meta),
|
||||
icon,
|
||||
icon_color,
|
||||
in_failover_queue,
|
||||
},
|
||||
))
|
||||
})
|
||||
@@ -129,7 +131,7 @@ impl Database {
|
||||
) -> Result<Option<Provider>, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
let result = conn.query_row(
|
||||
"SELECT name, settings_config, website_url, category, created_at, sort_index, notes, icon, icon_color, meta
|
||||
"SELECT name, settings_config, website_url, category, created_at, sort_index, notes, icon, icon_color, meta, in_failover_queue
|
||||
FROM providers WHERE id = ?1 AND app_type = ?2",
|
||||
params![id, app_type],
|
||||
|row| {
|
||||
@@ -143,6 +145,7 @@ impl Database {
|
||||
let icon: Option<String> = row.get(7)?;
|
||||
let icon_color: Option<String> = row.get(8)?;
|
||||
let meta_str: String = row.get(9)?;
|
||||
let in_failover_queue: bool = row.get(10)?;
|
||||
|
||||
let settings_config = serde_json::from_str(&settings_config_str).unwrap_or(serde_json::Value::Null);
|
||||
let meta: ProviderMeta = serde_json::from_str(&meta_str).unwrap_or_default();
|
||||
@@ -159,6 +162,7 @@ impl Database {
|
||||
meta: Some(meta),
|
||||
icon,
|
||||
icon_color,
|
||||
in_failover_queue,
|
||||
})
|
||||
},
|
||||
);
|
||||
@@ -184,17 +188,18 @@ impl Database {
|
||||
let mut meta_clone = provider.meta.clone().unwrap_or_default();
|
||||
let endpoints = std::mem::take(&mut meta_clone.custom_endpoints);
|
||||
|
||||
// 检查是否存在(用于判断新增/更新,以及保留 is_current)
|
||||
let existing: Option<bool> = tx
|
||||
// 检查是否存在(用于判断新增/更新,以及保留 is_current 和 in_failover_queue)
|
||||
let existing: Option<(bool, bool)> = tx
|
||||
.query_row(
|
||||
"SELECT is_current FROM providers WHERE id = ?1 AND app_type = ?2",
|
||||
"SELECT is_current, in_failover_queue FROM providers WHERE id = ?1 AND app_type = ?2",
|
||||
params![provider.id, app_type],
|
||||
|row| row.get(0),
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)
|
||||
.ok();
|
||||
|
||||
let is_update = existing.is_some();
|
||||
let is_current = existing.unwrap_or(false);
|
||||
let (is_current, in_failover_queue) =
|
||||
existing.unwrap_or((false, provider.in_failover_queue));
|
||||
|
||||
if is_update {
|
||||
// 更新模式:使用 UPDATE 避免触发 ON DELETE CASCADE
|
||||
@@ -210,8 +215,9 @@ impl Database {
|
||||
icon = ?8,
|
||||
icon_color = ?9,
|
||||
meta = ?10,
|
||||
is_current = ?11
|
||||
WHERE id = ?12 AND app_type = ?13",
|
||||
is_current = ?11,
|
||||
in_failover_queue = ?12
|
||||
WHERE id = ?13 AND app_type = ?14",
|
||||
params![
|
||||
provider.name,
|
||||
serde_json::to_string(&provider.settings_config).unwrap(),
|
||||
@@ -224,6 +230,7 @@ impl Database {
|
||||
provider.icon_color,
|
||||
serde_json::to_string(&meta_clone).unwrap(),
|
||||
is_current,
|
||||
in_failover_queue,
|
||||
provider.id,
|
||||
app_type,
|
||||
],
|
||||
@@ -234,8 +241,8 @@ impl Database {
|
||||
tx.execute(
|
||||
"INSERT INTO providers (
|
||||
id, app_type, name, settings_config, website_url, category,
|
||||
created_at, sort_index, notes, icon, icon_color, meta, is_current
|
||||
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)",
|
||||
created_at, sort_index, notes, icon, icon_color, meta, is_current, in_failover_queue
|
||||
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)",
|
||||
params![
|
||||
provider.id,
|
||||
app_type,
|
||||
@@ -250,6 +257,7 @@ impl Database {
|
||||
provider.icon_color,
|
||||
serde_json::to_string(&meta_clone).unwrap(),
|
||||
is_current,
|
||||
in_failover_queue,
|
||||
],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
@@ -8,62 +8,66 @@ use crate::proxy::types::*;
|
||||
use super::super::{lock_conn, Database};
|
||||
|
||||
impl Database {
|
||||
// ==================== Proxy Config ====================
|
||||
// ==================== Global Proxy Config ====================
|
||||
|
||||
/// 获取代理配置
|
||||
pub async fn get_proxy_config(&self) -> Result<ProxyConfig, AppError> {
|
||||
// 在一个作用域内获取锁并查询,确保锁在await之前释放
|
||||
/// 获取全局代理配置(统一字段)
|
||||
///
|
||||
/// 从 claude 行读取(三行镜像一致)
|
||||
pub async fn get_global_proxy_config(&self) -> Result<GlobalProxyConfig, AppError> {
|
||||
// 使用 block 限制 conn 的作用域,避免跨 await 持有锁
|
||||
let result = {
|
||||
let conn = lock_conn!(self.conn);
|
||||
conn.query_row(
|
||||
"SELECT listen_address, listen_port, max_retries,
|
||||
request_timeout, enable_logging, live_takeover_active
|
||||
FROM proxy_config WHERE id = 1",
|
||||
"SELECT proxy_enabled, listen_address, listen_port, enable_logging
|
||||
FROM proxy_config WHERE app_type = 'claude'",
|
||||
[],
|
||||
|row| {
|
||||
Ok(ProxyConfig {
|
||||
listen_address: row.get(0)?,
|
||||
listen_port: row.get::<_, i32>(1)? as u16,
|
||||
max_retries: row.get::<_, i32>(2)? as u8,
|
||||
request_timeout: row.get::<_, i32>(3)? as u64,
|
||||
enable_logging: row.get::<_, i32>(4)? != 0,
|
||||
live_takeover_active: row.get::<_, i32>(5).unwrap_or(0) != 0,
|
||||
Ok(GlobalProxyConfig {
|
||||
proxy_enabled: row.get::<_, i32>(0)? != 0,
|
||||
listen_address: row.get(1)?,
|
||||
listen_port: row.get::<_, i32>(2)? as u16,
|
||||
enable_logging: row.get::<_, i32>(3)? != 0,
|
||||
})
|
||||
},
|
||||
)
|
||||
}; // conn锁在这里释放
|
||||
};
|
||||
// conn 已在 block 结束时释放
|
||||
|
||||
match result {
|
||||
Ok(config) => Ok(config),
|
||||
Err(rusqlite::Error::QueryReturnedNoRows) => {
|
||||
// 如果不存在,插入默认配置
|
||||
let default_config = ProxyConfig::default();
|
||||
self.update_proxy_config(default_config.clone()).await?;
|
||||
Ok(default_config)
|
||||
// 如果不存在,创建默认配置
|
||||
self.init_proxy_config_rows().await?;
|
||||
Ok(GlobalProxyConfig {
|
||||
proxy_enabled: false,
|
||||
listen_address: "127.0.0.1".to_string(),
|
||||
listen_port: 5000,
|
||||
enable_logging: true,
|
||||
})
|
||||
}
|
||||
Err(e) => Err(AppError::Database(e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// 更新代理配置
|
||||
pub async fn update_proxy_config(&self, config: ProxyConfig) -> Result<(), AppError> {
|
||||
/// 更新全局代理配置(镜像写三行)
|
||||
pub async fn update_global_proxy_config(
|
||||
&self,
|
||||
config: GlobalProxyConfig,
|
||||
) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO proxy_config
|
||||
(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'))",
|
||||
"UPDATE proxy_config SET
|
||||
proxy_enabled = ?1,
|
||||
listen_address = ?2,
|
||||
listen_port = ?3,
|
||||
enable_logging = ?4,
|
||||
updated_at = datetime('now')",
|
||||
rusqlite::params![
|
||||
0, // 已移除自动启用逻辑,保留列但固定为 0
|
||||
if config.proxy_enabled { 1 } else { 0 },
|
||||
config.listen_address,
|
||||
config.listen_port as i32,
|
||||
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", // 兼容旧字段,写入默认值
|
||||
],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
@@ -71,27 +75,214 @@ impl Database {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 设置 Live 接管状态(仅更新 proxy_config 表,兼容旧逻辑)
|
||||
///
|
||||
/// 注意:此方法不会清除 settings 表中的 proxy_takeover_* 状态。
|
||||
/// settings 表的状态由 set_proxy_takeover_enabled 单独管理,用于跨重启保持状态。
|
||||
pub async fn set_live_takeover_active(&self, active: bool) -> Result<(), AppError> {
|
||||
// 仅更新 proxy_config 表(兼容旧版本)
|
||||
/// 获取应用级代理配置
|
||||
pub async fn get_proxy_config_for_app(
|
||||
&self,
|
||||
app_type: &str,
|
||||
) -> Result<AppProxyConfig, AppError> {
|
||||
// 使用 block 限制 conn 的作用域,避免跨 await 持有锁
|
||||
let app_type_owned = app_type.to_string();
|
||||
let result = {
|
||||
let conn = lock_conn!(self.conn);
|
||||
conn.query_row(
|
||||
"SELECT app_type, enabled, auto_failover_enabled,
|
||||
max_retries, streaming_first_byte_timeout, streaming_idle_timeout, non_streaming_timeout,
|
||||
circuit_failure_threshold, circuit_success_threshold, circuit_timeout_seconds,
|
||||
circuit_error_rate_threshold, circuit_min_requests
|
||||
FROM proxy_config WHERE app_type = ?1",
|
||||
[app_type],
|
||||
|row| {
|
||||
Ok(AppProxyConfig {
|
||||
app_type: row.get(0)?,
|
||||
enabled: row.get::<_, i32>(1)? != 0,
|
||||
auto_failover_enabled: row.get::<_, i32>(2)? != 0,
|
||||
max_retries: row.get::<_, i32>(3)? as u32,
|
||||
streaming_first_byte_timeout: row.get::<_, i32>(4)? as u32,
|
||||
streaming_idle_timeout: row.get::<_, i32>(5)? as u32,
|
||||
non_streaming_timeout: row.get::<_, i32>(6)? as u32,
|
||||
circuit_failure_threshold: row.get::<_, i32>(7)? as u32,
|
||||
circuit_success_threshold: row.get::<_, i32>(8)? as u32,
|
||||
circuit_timeout_seconds: row.get::<_, i32>(9)? as u32,
|
||||
circuit_error_rate_threshold: row.get(10)?,
|
||||
circuit_min_requests: row.get::<_, i32>(11)? as u32,
|
||||
})
|
||||
},
|
||||
)
|
||||
};
|
||||
// conn 已在 block 结束时释放
|
||||
|
||||
match result {
|
||||
Ok(config) => Ok(config),
|
||||
Err(rusqlite::Error::QueryReturnedNoRows) => {
|
||||
// 如果不存在,创建默认配置
|
||||
self.init_proxy_config_rows().await?;
|
||||
Ok(AppProxyConfig {
|
||||
app_type: app_type_owned,
|
||||
enabled: false,
|
||||
auto_failover_enabled: false,
|
||||
max_retries: 3,
|
||||
streaming_first_byte_timeout: 30,
|
||||
streaming_idle_timeout: 60,
|
||||
non_streaming_timeout: 300,
|
||||
circuit_failure_threshold: 5,
|
||||
circuit_success_threshold: 2,
|
||||
circuit_timeout_seconds: 60,
|
||||
circuit_error_rate_threshold: 0.5,
|
||||
circuit_min_requests: 10,
|
||||
})
|
||||
}
|
||||
Err(e) => Err(AppError::Database(e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// 更新应用级代理配置
|
||||
pub async fn update_proxy_config_for_app(
|
||||
&self,
|
||||
config: AppProxyConfig,
|
||||
) -> 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 }],
|
||||
"UPDATE proxy_config SET
|
||||
enabled = ?2,
|
||||
auto_failover_enabled = ?3,
|
||||
max_retries = ?4,
|
||||
streaming_first_byte_timeout = ?5,
|
||||
streaming_idle_timeout = ?6,
|
||||
non_streaming_timeout = ?7,
|
||||
circuit_failure_threshold = ?8,
|
||||
circuit_success_threshold = ?9,
|
||||
circuit_timeout_seconds = ?10,
|
||||
circuit_error_rate_threshold = ?11,
|
||||
circuit_min_requests = ?12,
|
||||
updated_at = datetime('now')
|
||||
WHERE app_type = ?1",
|
||||
rusqlite::params![
|
||||
config.app_type,
|
||||
if config.enabled { 1 } else { 0 },
|
||||
if config.auto_failover_enabled { 1 } else { 0 },
|
||||
config.max_retries as i32,
|
||||
config.streaming_first_byte_timeout as i32,
|
||||
config.streaming_idle_timeout as i32,
|
||||
config.non_streaming_timeout as i32,
|
||||
config.circuit_failure_threshold as i32,
|
||||
config.circuit_success_threshold as i32,
|
||||
config.circuit_timeout_seconds as i32,
|
||||
config.circuit_error_rate_threshold,
|
||||
config.circuit_min_requests as i32,
|
||||
],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 初始化 proxy_config 表的三行数据
|
||||
async fn init_proxy_config_rows(&self) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
for app_type in &["claude", "codex", "gemini"] {
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO proxy_config (app_type) VALUES (?1)",
|
||||
[app_type],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ==================== Legacy Proxy Config (兼容旧代码) ====================
|
||||
|
||||
/// 获取代理配置(兼容旧接口,返回 claude 行的配置)
|
||||
pub async fn get_proxy_config(&self) -> Result<ProxyConfig, AppError> {
|
||||
// 使用 block 限制 conn 的作用域,避免跨 await 持有锁
|
||||
let result = {
|
||||
let conn = lock_conn!(self.conn);
|
||||
conn.query_row(
|
||||
"SELECT listen_address, listen_port, max_retries,
|
||||
enable_logging,
|
||||
streaming_first_byte_timeout, streaming_idle_timeout, non_streaming_timeout
|
||||
FROM proxy_config WHERE app_type = 'claude'",
|
||||
[],
|
||||
|row| {
|
||||
Ok(ProxyConfig {
|
||||
listen_address: row.get(0)?,
|
||||
listen_port: row.get::<_, i32>(1)? as u16,
|
||||
max_retries: row.get::<_, i32>(2)? as u8,
|
||||
request_timeout: 300, // 废弃字段,返回默认值
|
||||
enable_logging: row.get::<_, i32>(3)? != 0,
|
||||
live_takeover_active: false, // 废弃字段
|
||||
streaming_first_byte_timeout: row.get::<_, i32>(4).unwrap_or(30) as u64,
|
||||
streaming_idle_timeout: row.get::<_, i32>(5).unwrap_or(60) as u64,
|
||||
non_streaming_timeout: row.get::<_, i32>(6).unwrap_or(300) as u64,
|
||||
})
|
||||
},
|
||||
)
|
||||
};
|
||||
// conn 已在 block 结束时释放
|
||||
|
||||
match result {
|
||||
Ok(config) => Ok(config),
|
||||
Err(rusqlite::Error::QueryReturnedNoRows) => {
|
||||
// 如果不存在,初始化默认配置
|
||||
self.init_proxy_config_rows().await?;
|
||||
Ok(ProxyConfig::default())
|
||||
}
|
||||
Err(e) => Err(AppError::Database(e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// 更新代理配置(兼容旧接口,更新所有三行的公共字段)
|
||||
pub async fn update_proxy_config(&self, config: ProxyConfig) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
// 更新所有三行的公共字段
|
||||
conn.execute(
|
||||
"UPDATE proxy_config SET
|
||||
listen_address = ?1,
|
||||
listen_port = ?2,
|
||||
max_retries = ?3,
|
||||
enable_logging = ?4,
|
||||
streaming_first_byte_timeout = ?5,
|
||||
streaming_idle_timeout = ?6,
|
||||
non_streaming_timeout = ?7,
|
||||
updated_at = datetime('now')",
|
||||
rusqlite::params![
|
||||
config.listen_address,
|
||||
config.listen_port as i32,
|
||||
config.max_retries as i32,
|
||||
if config.enable_logging { 1 } else { 0 },
|
||||
config.streaming_first_byte_timeout as i32,
|
||||
config.streaming_idle_timeout as i32,
|
||||
config.non_streaming_timeout as i32,
|
||||
],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 设置 Live 接管状态(兼容旧版本,更新 enabled 字段)
|
||||
pub async fn set_live_takeover_active(&self, _active: bool) -> Result<(), AppError> {
|
||||
// 不再使用此字段,由 enabled 字段替代
|
||||
// 保留空实现以兼容旧代码
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 检查是否处于 Live 接管模式
|
||||
///
|
||||
/// v3.8.0+:以 settings 表中的 `proxy_takeover_{app_type}` 为真实来源
|
||||
/// 检查是否有任一 app 的 enabled = true
|
||||
pub async fn is_live_takeover_active(&self) -> Result<bool, AppError> {
|
||||
self.has_any_proxy_takeover()
|
||||
let conn = lock_conn!(self.conn);
|
||||
let count: i64 = conn
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM proxy_config WHERE enabled = 1",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
Ok(count > 0)
|
||||
}
|
||||
|
||||
// ==================== Provider Health ====================
|
||||
@@ -102,28 +293,45 @@ impl Database {
|
||||
provider_id: &str,
|
||||
app_type: &str,
|
||||
) -> Result<ProviderHealth, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
let result = {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
conn.query_row(
|
||||
"SELECT provider_id, app_type, is_healthy, consecutive_failures,
|
||||
last_success_at, last_failure_at, last_error, updated_at
|
||||
FROM provider_health
|
||||
WHERE provider_id = ?1 AND app_type = ?2",
|
||||
rusqlite::params![provider_id, app_type],
|
||||
|row| {
|
||||
Ok(ProviderHealth {
|
||||
provider_id: row.get(0)?,
|
||||
app_type: row.get(1)?,
|
||||
is_healthy: row.get::<_, i64>(2)? != 0,
|
||||
consecutive_failures: row.get::<_, i64>(3)? as u32,
|
||||
last_success_at: row.get(4)?,
|
||||
last_failure_at: row.get(5)?,
|
||||
last_error: row.get(6)?,
|
||||
updated_at: row.get(7)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))
|
||||
conn.query_row(
|
||||
"SELECT provider_id, app_type, is_healthy, consecutive_failures,
|
||||
last_success_at, last_failure_at, last_error, updated_at
|
||||
FROM provider_health
|
||||
WHERE provider_id = ?1 AND app_type = ?2",
|
||||
rusqlite::params![provider_id, app_type],
|
||||
|row| {
|
||||
Ok(ProviderHealth {
|
||||
provider_id: row.get(0)?,
|
||||
app_type: row.get(1)?,
|
||||
is_healthy: row.get::<_, i64>(2)? != 0,
|
||||
consecutive_failures: row.get::<_, i64>(3)? as u32,
|
||||
last_success_at: row.get(4)?,
|
||||
last_failure_at: row.get(5)?,
|
||||
last_error: row.get(6)?,
|
||||
updated_at: row.get(7)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
match result {
|
||||
Ok(health) => Ok(health),
|
||||
// 缺少记录时视为健康(关闭后清空状态,再次打开时默认正常)
|
||||
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(ProviderHealth {
|
||||
provider_id: provider_id.to_string(),
|
||||
app_type: app_type.to_string(),
|
||||
is_healthy: true,
|
||||
consecutive_failures: 0,
|
||||
last_success_at: None,
|
||||
last_failure_at: None,
|
||||
last_error: None,
|
||||
updated_at: chrono::Utc::now().to_rfc3339(),
|
||||
}),
|
||||
Err(e) => Err(AppError::Database(e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// 更新Provider健康状态
|
||||
@@ -228,6 +436,20 @@ impl Database {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 清空指定应用的健康状态(关闭单个代理时使用)
|
||||
pub async fn clear_provider_health_for_app(&self, app_type: &str) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
conn.execute(
|
||||
"DELETE FROM provider_health WHERE app_type = ?1",
|
||||
[app_type],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
log::debug!("Cleared provider health records for app {app_type}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 清空所有Provider健康状态(代理停止时调用)
|
||||
pub async fn clear_all_provider_health(&self) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
@@ -239,19 +461,22 @@ impl Database {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ==================== Circuit Breaker Config ====================
|
||||
// ==================== Circuit Breaker Config (Legacy Compatibility) ====================
|
||||
|
||||
/// 获取熔断器配置
|
||||
/// 获取熔断器配置(兼容旧接口,从 claude 行读取)
|
||||
///
|
||||
/// 熔断器配置已合并到 proxy_config 表,每 app 独立
|
||||
/// 此方法保留用于兼容旧代码,建议使用 get_proxy_config_for_app
|
||||
pub async fn get_circuit_breaker_config(
|
||||
&self,
|
||||
) -> Result<crate::proxy::circuit_breaker::CircuitBreakerConfig, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
let config = conn
|
||||
.query_row(
|
||||
"SELECT failure_threshold, success_threshold, timeout_seconds,
|
||||
error_rate_threshold, min_requests
|
||||
FROM circuit_breaker_config WHERE id = 1",
|
||||
// 使用 block 限制 conn 的作用域,避免跨 await 持有锁
|
||||
let result = {
|
||||
let conn = lock_conn!(self.conn);
|
||||
conn.query_row(
|
||||
"SELECT circuit_failure_threshold, circuit_success_threshold, circuit_timeout_seconds,
|
||||
circuit_error_rate_threshold, circuit_min_requests
|
||||
FROM proxy_config WHERE app_type = 'claude'",
|
||||
[],
|
||||
|row| {
|
||||
Ok(crate::proxy::circuit_breaker::CircuitBreakerConfig {
|
||||
@@ -263,27 +488,39 @@ impl Database {
|
||||
})
|
||||
},
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
};
|
||||
// conn 已在 block 结束时释放
|
||||
|
||||
Ok(config)
|
||||
match result {
|
||||
Ok(config) => Ok(config),
|
||||
Err(rusqlite::Error::QueryReturnedNoRows) => {
|
||||
// 如果不存在,初始化默认配置
|
||||
self.init_proxy_config_rows().await?;
|
||||
Ok(crate::proxy::circuit_breaker::CircuitBreakerConfig::default())
|
||||
}
|
||||
Err(e) => Err(AppError::Database(e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// 更新熔断器配置
|
||||
/// 更新熔断器配置(兼容旧接口,更新所有三行)
|
||||
///
|
||||
/// 熔断器配置已合并到 proxy_config 表
|
||||
/// 此方法保留用于兼容旧代码,建议使用 update_proxy_config_for_app
|
||||
pub async fn update_circuit_breaker_config(
|
||||
&self,
|
||||
config: &crate::proxy::circuit_breaker::CircuitBreakerConfig,
|
||||
) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
// 更新所有三行的熔断器配置
|
||||
conn.execute(
|
||||
"UPDATE circuit_breaker_config
|
||||
SET failure_threshold = ?1,
|
||||
success_threshold = ?2,
|
||||
timeout_seconds = ?3,
|
||||
error_rate_threshold = ?4,
|
||||
min_requests = ?5,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = 1",
|
||||
"UPDATE proxy_config SET
|
||||
circuit_failure_threshold = ?1,
|
||||
circuit_success_threshold = ?2,
|
||||
circuit_timeout_seconds = ?3,
|
||||
circuit_error_rate_threshold = ?4,
|
||||
circuit_min_requests = ?5,
|
||||
updated_at = datetime('now')",
|
||||
rusqlite::params![
|
||||
config.failure_threshold as i32,
|
||||
config.success_threshold as i32,
|
||||
|
||||
@@ -63,11 +63,13 @@ impl Database {
|
||||
}
|
||||
}
|
||||
|
||||
// --- 代理接管状态管理 ---
|
||||
// --- 代理接管状态管理(已废弃,使用 proxy_config.enabled 替代)---
|
||||
|
||||
/// 获取指定应用的代理接管状态
|
||||
///
|
||||
/// 使用 settings 表存储各应用的接管状态,key 格式: `proxy_takeover_{app_type}`
|
||||
/// **已废弃**: 请使用 `proxy_config.enabled` 字段替代
|
||||
/// 此方法仅用于数据库迁移时读取旧数据
|
||||
#[deprecated(since = "3.9.0", note = "使用 get_proxy_config_for_app().enabled 替代")]
|
||||
pub fn get_proxy_takeover_enabled(&self, app_type: &str) -> Result<bool, AppError> {
|
||||
let key = format!("proxy_takeover_{app_type}");
|
||||
match self.get_setting(&key)? {
|
||||
@@ -78,8 +80,11 @@ impl Database {
|
||||
|
||||
/// 设置指定应用的代理接管状态
|
||||
///
|
||||
/// - `true` = 开启代理接管
|
||||
/// - `false` = 关闭代理接管
|
||||
/// **已废弃**: 请使用 `proxy_config.enabled` 字段替代
|
||||
#[deprecated(
|
||||
since = "3.9.0",
|
||||
note = "使用 update_proxy_config_for_app() 修改 enabled 字段"
|
||||
)]
|
||||
pub fn set_proxy_takeover_enabled(
|
||||
&self,
|
||||
app_type: &str,
|
||||
@@ -91,6 +96,9 @@ impl Database {
|
||||
}
|
||||
|
||||
/// 检查是否有任一应用开启了代理接管
|
||||
///
|
||||
/// **已废弃**: 请使用 `is_live_takeover_active()` 替代
|
||||
#[deprecated(since = "3.9.0", note = "使用 is_live_takeover_active() 替代")]
|
||||
pub fn has_any_proxy_takeover(&self) -> Result<bool, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
let count: i64 = conn
|
||||
@@ -104,6 +112,12 @@ impl Database {
|
||||
}
|
||||
|
||||
/// 清除所有代理接管状态(将所有 proxy_takeover_* 设置为 false)
|
||||
///
|
||||
/// **已废弃**: settings 表不再用于存储代理状态
|
||||
#[deprecated(
|
||||
since = "3.9.0",
|
||||
note = "使用 update_proxy_config_for_app() 清除各应用的 enabled 字段"
|
||||
)]
|
||||
pub fn clear_all_proxy_takeover(&self) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
conn.execute(
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
//! 统一供应商 (Universal Provider) DAO
|
||||
//!
|
||||
//! 提供统一供应商的 CRUD 操作。
|
||||
|
||||
use crate::database::{lock_conn, to_json_string, Database};
|
||||
use crate::error::AppError;
|
||||
use crate::provider::UniversalProvider;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// 统一供应商的 Settings Key
|
||||
const UNIVERSAL_PROVIDERS_KEY: &str = "universal_providers";
|
||||
|
||||
impl Database {
|
||||
/// 获取所有统一供应商
|
||||
pub fn get_all_universal_providers(
|
||||
&self,
|
||||
) -> Result<HashMap<String, UniversalProvider>, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT value FROM settings WHERE key = ?")
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
let result: Option<String> = stmt
|
||||
.query_row([UNIVERSAL_PROVIDERS_KEY], |row| row.get(0))
|
||||
.ok();
|
||||
|
||||
match result {
|
||||
Some(json) => serde_json::from_str(&json)
|
||||
.map_err(|e| AppError::Database(format!("解析统一供应商数据失败: {e}"))),
|
||||
None => Ok(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取单个统一供应商
|
||||
pub fn get_universal_provider(&self, id: &str) -> Result<Option<UniversalProvider>, AppError> {
|
||||
let providers = self.get_all_universal_providers()?;
|
||||
Ok(providers.get(id).cloned())
|
||||
}
|
||||
|
||||
/// 保存统一供应商(添加或更新)
|
||||
pub fn save_universal_provider(&self, provider: &UniversalProvider) -> Result<(), AppError> {
|
||||
let mut providers = self.get_all_universal_providers()?;
|
||||
providers.insert(provider.id.clone(), provider.clone());
|
||||
self.save_all_universal_providers(&providers)
|
||||
}
|
||||
|
||||
/// 删除统一供应商
|
||||
pub fn delete_universal_provider(&self, id: &str) -> Result<bool, AppError> {
|
||||
let mut providers = self.get_all_universal_providers()?;
|
||||
let existed = providers.remove(id).is_some();
|
||||
if existed {
|
||||
self.save_all_universal_providers(&providers)?;
|
||||
}
|
||||
Ok(existed)
|
||||
}
|
||||
|
||||
/// 保存所有统一供应商(内部方法)
|
||||
fn save_all_universal_providers(
|
||||
&self,
|
||||
providers: &HashMap<String, UniversalProvider>,
|
||||
) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
let json = to_json_string(providers)?;
|
||||
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)",
|
||||
[UNIVERSAL_PROVIDERS_KEY, &json],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,7 @@ impl Database {
|
||||
icon_color TEXT,
|
||||
meta TEXT NOT NULL DEFAULT '{}',
|
||||
is_current BOOLEAN NOT NULL DEFAULT 0,
|
||||
in_failover_queue BOOLEAN NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (id, app_type)
|
||||
)",
|
||||
[],
|
||||
@@ -54,47 +55,28 @@ impl Database {
|
||||
// 3. MCP Servers 表
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS mcp_servers (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
server_config TEXT NOT NULL,
|
||||
description TEXT,
|
||||
homepage TEXT,
|
||||
docs TEXT,
|
||||
tags TEXT NOT NULL DEFAULT '[]',
|
||||
enabled_claude BOOLEAN NOT NULL DEFAULT 0,
|
||||
enabled_codex BOOLEAN NOT NULL DEFAULT 0,
|
||||
enabled_gemini BOOLEAN NOT NULL DEFAULT 0
|
||||
)",
|
||||
id TEXT PRIMARY KEY, name TEXT NOT NULL, server_config TEXT NOT NULL,
|
||||
description TEXT, homepage TEXT, docs TEXT, tags TEXT NOT NULL DEFAULT '[]',
|
||||
enabled_claude BOOLEAN NOT NULL DEFAULT 0, enabled_codex BOOLEAN NOT NULL DEFAULT 0,
|
||||
enabled_gemini BOOLEAN NOT NULL DEFAULT 0
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 4. Prompts 表
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS prompts (
|
||||
id TEXT NOT NULL,
|
||||
app_type TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
description TEXT,
|
||||
enabled BOOLEAN NOT NULL DEFAULT 1,
|
||||
created_at INTEGER,
|
||||
updated_at INTEGER,
|
||||
PRIMARY KEY (id, app_type)
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS prompts (
|
||||
id TEXT NOT NULL, app_type TEXT NOT NULL, name TEXT NOT NULL, content TEXT NOT NULL,
|
||||
description TEXT, enabled BOOLEAN NOT NULL DEFAULT 1, created_at INTEGER, updated_at INTEGER,
|
||||
PRIMARY KEY (id, app_type)
|
||||
)", []).map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 5. Skills 表
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS skills (
|
||||
directory TEXT NOT NULL,
|
||||
app_type TEXT NOT NULL,
|
||||
installed BOOLEAN NOT NULL DEFAULT 0,
|
||||
installed_at INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (directory, app_type)
|
||||
)",
|
||||
directory TEXT NOT NULL, app_type TEXT NOT NULL, installed BOOLEAN NOT NULL DEFAULT 0,
|
||||
installed_at INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (directory, app_type)
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
@@ -102,169 +84,130 @@ impl Database {
|
||||
// 6. Skill Repos 表
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS skill_repos (
|
||||
owner TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
branch TEXT NOT NULL DEFAULT 'main',
|
||||
enabled BOOLEAN NOT NULL DEFAULT 1,
|
||||
PRIMARY KEY (owner, name)
|
||||
)",
|
||||
owner TEXT NOT NULL, name TEXT NOT NULL, branch TEXT NOT NULL DEFAULT 'main',
|
||||
enabled BOOLEAN NOT NULL DEFAULT 1, PRIMARY KEY (owner, name)
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 7. Settings 表 (通用配置)
|
||||
// 7. Settings 表
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT
|
||||
)",
|
||||
"CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 8. Proxy Config 表 (代理服务器配置)
|
||||
// 代理配置表(单例)
|
||||
// 8. Proxy Config 表(三行结构,app_type 主键)
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS proxy_config (
|
||||
app_type TEXT PRIMARY KEY CHECK (app_type IN ('claude','codex','gemini')),
|
||||
proxy_enabled INTEGER NOT NULL DEFAULT 0, listen_address TEXT NOT NULL DEFAULT '127.0.0.1',
|
||||
listen_port INTEGER NOT NULL DEFAULT 5000, enable_logging INTEGER NOT NULL DEFAULT 1,
|
||||
enabled INTEGER NOT NULL DEFAULT 0, auto_failover_enabled INTEGER NOT NULL DEFAULT 0,
|
||||
max_retries INTEGER NOT NULL DEFAULT 3, streaming_first_byte_timeout INTEGER NOT NULL DEFAULT 30,
|
||||
streaming_idle_timeout INTEGER NOT NULL DEFAULT 60, non_streaming_timeout INTEGER NOT NULL DEFAULT 300,
|
||||
circuit_failure_threshold INTEGER NOT NULL DEFAULT 5, circuit_success_threshold INTEGER NOT NULL DEFAULT 2,
|
||||
circuit_timeout_seconds INTEGER NOT NULL DEFAULT 60, circuit_error_rate_threshold REAL NOT NULL DEFAULT 0.5,
|
||||
circuit_min_requests INTEGER NOT NULL DEFAULT 10,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')), updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
)", []).map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 初始化三行数据(每应用不同默认值)
|
||||
//
|
||||
// 兼容旧数据库:
|
||||
// - 老版本 proxy_config 是单例表(没有 app_type 列),此时不能执行三行 seed insert;
|
||||
// - 旧表会在 apply_schema_migrations() 中迁移为三行结构后再插入。
|
||||
if Self::has_column(conn, "proxy_config", "app_type")? {
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO proxy_config (app_type, max_retries,
|
||||
streaming_first_byte_timeout, streaming_idle_timeout, non_streaming_timeout,
|
||||
circuit_failure_threshold, circuit_success_threshold, circuit_timeout_seconds,
|
||||
circuit_error_rate_threshold, circuit_min_requests)
|
||||
VALUES ('claude', 6, 45, 90, 300, 8, 3, 90, 0.6, 15)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO proxy_config (app_type, max_retries,
|
||||
streaming_first_byte_timeout, streaming_idle_timeout, non_streaming_timeout,
|
||||
circuit_failure_threshold, circuit_success_threshold, circuit_timeout_seconds,
|
||||
circuit_error_rate_threshold, circuit_min_requests)
|
||||
VALUES ('codex', 3, 30, 60, 300, 5, 2, 60, 0.5, 10)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO proxy_config (app_type, max_retries,
|
||||
streaming_first_byte_timeout, streaming_idle_timeout, non_streaming_timeout,
|
||||
circuit_failure_threshold, circuit_success_threshold, circuit_timeout_seconds,
|
||||
circuit_error_rate_threshold, circuit_min_requests)
|
||||
VALUES ('gemini', 5, 30, 60, 300, 5, 2, 60, 0.5, 10)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
}
|
||||
|
||||
// 9. Provider Health 表
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS provider_health (
|
||||
provider_id TEXT NOT NULL, app_type TEXT NOT NULL, is_healthy INTEGER NOT NULL DEFAULT 1,
|
||||
consecutive_failures INTEGER NOT NULL DEFAULT 0, last_success_at TEXT, last_failure_at TEXT,
|
||||
last_error TEXT, updated_at TEXT NOT NULL,
|
||||
PRIMARY KEY (provider_id, app_type),
|
||||
FOREIGN KEY (provider_id, app_type) REFERENCES providers(id, app_type) ON DELETE CASCADE
|
||||
)", []).map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 10. Proxy Request Logs 表
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS proxy_request_logs (
|
||||
request_id TEXT PRIMARY KEY, provider_id TEXT NOT NULL, app_type TEXT NOT NULL, model TEXT NOT NULL,
|
||||
input_tokens INTEGER NOT NULL DEFAULT 0, output_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
cache_read_tokens INTEGER NOT NULL DEFAULT 0, cache_creation_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
input_cost_usd TEXT NOT NULL DEFAULT '0', output_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
cache_read_cost_usd TEXT NOT NULL DEFAULT '0', cache_creation_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
total_cost_usd TEXT NOT NULL DEFAULT '0', latency_ms INTEGER NOT NULL, first_token_ms INTEGER,
|
||||
duration_ms INTEGER, status_code INTEGER NOT NULL, error_message TEXT, session_id TEXT,
|
||||
provider_type TEXT, is_streaming INTEGER NOT NULL DEFAULT 0,
|
||||
cost_multiplier TEXT NOT NULL DEFAULT '1.0', created_at INTEGER NOT NULL
|
||||
)", []).map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_request_logs_provider ON proxy_request_logs(provider_id, app_type)", [])
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_request_logs_created_at ON proxy_request_logs(created_at)", [])
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS proxy_config (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
enabled INTEGER NOT NULL DEFAULT 0,
|
||||
listen_address TEXT NOT NULL DEFAULT '127.0.0.1',
|
||||
listen_port INTEGER NOT NULL DEFAULT 5000,
|
||||
max_retries INTEGER NOT NULL DEFAULT 3,
|
||||
request_timeout INTEGER NOT NULL DEFAULT 300,
|
||||
enable_logging INTEGER NOT NULL DEFAULT 1,
|
||||
target_app TEXT NOT NULL DEFAULT 'claude',
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_request_logs_model ON proxy_request_logs(model)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 尝试添加 target_app 列(如果表已存在但缺少该列)
|
||||
// 忽略 "duplicate column name" 错误
|
||||
let _ = conn.execute(
|
||||
"ALTER TABLE proxy_config ADD COLUMN target_app TEXT NOT NULL DEFAULT 'claude'",
|
||||
[],
|
||||
);
|
||||
|
||||
// 9. Provider Health 表 (Provider健康状态)
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS provider_health (
|
||||
provider_id TEXT NOT NULL,
|
||||
app_type TEXT NOT NULL,
|
||||
is_healthy INTEGER NOT NULL DEFAULT 1,
|
||||
consecutive_failures INTEGER NOT NULL DEFAULT 0,
|
||||
last_success_at TEXT,
|
||||
last_failure_at TEXT,
|
||||
last_error TEXT,
|
||||
updated_at TEXT NOT NULL,
|
||||
PRIMARY KEY (provider_id, app_type),
|
||||
FOREIGN KEY (provider_id, app_type) REFERENCES providers(id, app_type) ON DELETE CASCADE
|
||||
)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_request_logs_session ON proxy_request_logs(session_id)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 10. Proxy Request Logs 表 (详细请求日志)
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS proxy_request_logs (
|
||||
request_id TEXT PRIMARY KEY,
|
||||
provider_id TEXT NOT NULL,
|
||||
app_type TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
input_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
output_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
cache_read_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
cache_creation_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
input_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
output_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
cache_read_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
cache_creation_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
total_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
latency_ms INTEGER NOT NULL,
|
||||
first_token_ms INTEGER,
|
||||
duration_ms INTEGER,
|
||||
status_code INTEGER NOT NULL,
|
||||
error_message TEXT,
|
||||
session_id TEXT,
|
||||
provider_type TEXT,
|
||||
is_streaming INTEGER NOT NULL DEFAULT 0,
|
||||
cost_multiplier TEXT NOT NULL DEFAULT '1.0',
|
||||
created_at INTEGER NOT NULL
|
||||
)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_request_logs_status ON proxy_request_logs(status_code)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_request_logs_provider
|
||||
ON proxy_request_logs(provider_id, app_type)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_request_logs_created_at
|
||||
ON proxy_request_logs(created_at)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_request_logs_model
|
||||
ON proxy_request_logs(model)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_request_logs_session
|
||||
ON proxy_request_logs(session_id)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_request_logs_status
|
||||
ON proxy_request_logs(status_code)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 11. Model Pricing 表 (模型定价)
|
||||
// 11. Model Pricing 表
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS model_pricing (
|
||||
model_id TEXT PRIMARY KEY,
|
||||
display_name TEXT NOT NULL,
|
||||
input_cost_per_million TEXT NOT NULL,
|
||||
output_cost_per_million TEXT NOT NULL,
|
||||
cache_read_cost_per_million TEXT NOT NULL DEFAULT '0',
|
||||
cache_creation_cost_per_million TEXT NOT NULL DEFAULT '0'
|
||||
)",
|
||||
model_id TEXT PRIMARY KEY, display_name TEXT NOT NULL,
|
||||
input_cost_per_million TEXT NOT NULL, output_cost_per_million TEXT NOT NULL,
|
||||
cache_read_cost_per_million TEXT NOT NULL DEFAULT '0',
|
||||
cache_creation_cost_per_million TEXT NOT NULL DEFAULT '0'
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 12. Stream Check Logs 表 (流式健康检查日志)
|
||||
conn.execute(
|
||||
"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,
|
||||
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
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
// 12. Stream Check Logs 表
|
||||
conn.execute("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, 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
|
||||
)", []).map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_stream_check_logs_provider
|
||||
@@ -273,35 +216,13 @@ impl Database {
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 13. Circuit Breaker Config 表 (熔断器配置)
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS circuit_breaker_config (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
failure_threshold INTEGER NOT NULL DEFAULT 5,
|
||||
success_threshold INTEGER NOT NULL DEFAULT 2,
|
||||
timeout_seconds INTEGER NOT NULL DEFAULT 60,
|
||||
error_rate_threshold REAL NOT NULL DEFAULT 0.5,
|
||||
min_requests INTEGER NOT NULL DEFAULT 10,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 插入默认熔断器配置
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO circuit_breaker_config (id) VALUES (1)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
// 注意:circuit_breaker_config 已合并到 proxy_config 表中
|
||||
|
||||
// 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
|
||||
)",
|
||||
app_type TEXT PRIMARY KEY, original_config TEXT NOT NULL, backed_up_at TEXT NOT NULL
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
@@ -312,29 +233,64 @@ impl Database {
|
||||
[],
|
||||
);
|
||||
|
||||
// 14. Failover Queue 表 (故障转移队列)
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS failover_queue (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
app_type TEXT NOT NULL,
|
||||
provider_id TEXT NOT NULL,
|
||||
queue_order INTEGER NOT NULL,
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
created_at INTEGER NOT NULL,
|
||||
UNIQUE (app_type, provider_id),
|
||||
FOREIGN KEY (provider_id, app_type) REFERENCES providers(id, app_type) ON DELETE CASCADE
|
||||
)",
|
||||
// 尝试添加基础配置列到 proxy_config 表(兼容 v3.9.0-2 升级)
|
||||
let _ = conn.execute(
|
||||
"ALTER TABLE proxy_config ADD COLUMN proxy_enabled INTEGER NOT NULL DEFAULT 0",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
);
|
||||
let _ = conn.execute(
|
||||
"ALTER TABLE proxy_config ADD COLUMN listen_address TEXT NOT NULL DEFAULT '127.0.0.1'",
|
||||
[],
|
||||
);
|
||||
let _ = conn.execute(
|
||||
"ALTER TABLE proxy_config ADD COLUMN listen_port INTEGER NOT NULL DEFAULT 5000",
|
||||
[],
|
||||
);
|
||||
let _ = conn.execute(
|
||||
"ALTER TABLE proxy_config ADD COLUMN enable_logging INTEGER NOT NULL DEFAULT 1",
|
||||
[],
|
||||
);
|
||||
|
||||
// 为故障转移队列创建索引
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_failover_queue_order
|
||||
ON failover_queue(app_type, queue_order)",
|
||||
// 尝试添加超时配置列到 proxy_config 表
|
||||
let _ = conn.execute(
|
||||
"ALTER TABLE proxy_config ADD COLUMN streaming_first_byte_timeout INTEGER NOT NULL DEFAULT 30",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
);
|
||||
let _ = conn.execute(
|
||||
"ALTER TABLE proxy_config ADD COLUMN streaming_idle_timeout INTEGER NOT NULL DEFAULT 60",
|
||||
[],
|
||||
);
|
||||
let _ = conn.execute(
|
||||
"ALTER TABLE proxy_config ADD COLUMN non_streaming_timeout INTEGER NOT NULL DEFAULT 300",
|
||||
[],
|
||||
);
|
||||
|
||||
// 兼容:若旧版 proxy_config 仍为单例结构(无 app_type),则在启动时直接转换为三行结构
|
||||
// 说明:user_version=2 时不会再触发 v1->v2 迁移,但新代码查询依赖 app_type 列。
|
||||
if Self::table_exists(conn, "proxy_config")?
|
||||
&& !Self::has_column(conn, "proxy_config", "app_type")?
|
||||
{
|
||||
Self::migrate_proxy_config_to_per_app(conn)?;
|
||||
}
|
||||
|
||||
// 确保 in_failover_queue 列存在(对于已存在的 v2 数据库)
|
||||
Self::add_column_if_missing(
|
||||
conn,
|
||||
"providers",
|
||||
"in_failover_queue",
|
||||
"BOOLEAN NOT NULL DEFAULT 0",
|
||||
)?;
|
||||
|
||||
// 删除旧的 failover_queue 表(如果存在)
|
||||
let _ = conn.execute("DROP INDEX IF EXISTS idx_failover_queue_order", []);
|
||||
let _ = conn.execute("DROP TABLE IF EXISTS failover_queue", []);
|
||||
|
||||
// 为故障转移队列创建索引(基于 providers 表)
|
||||
let _ = conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_providers_failover
|
||||
ON providers(app_type, in_failover_queue, sort_index)",
|
||||
[],
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -472,37 +428,88 @@ impl Database {
|
||||
Self::add_column_if_missing(conn, "providers", "limit_daily_usd", "TEXT")?;
|
||||
Self::add_column_if_missing(conn, "providers", "limit_monthly_usd", "TEXT")?;
|
||||
Self::add_column_if_missing(conn, "providers", "provider_type", "TEXT")?;
|
||||
|
||||
// proxy_request_logs 表(包含所有字段)
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS proxy_request_logs (
|
||||
request_id TEXT PRIMARY KEY,
|
||||
provider_id TEXT NOT NULL,
|
||||
app_type TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
input_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
output_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
cache_read_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
cache_creation_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
input_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
output_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
cache_read_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
cache_creation_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
total_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
latency_ms INTEGER NOT NULL,
|
||||
first_token_ms INTEGER,
|
||||
duration_ms INTEGER,
|
||||
status_code INTEGER NOT NULL,
|
||||
error_message TEXT,
|
||||
session_id TEXT,
|
||||
provider_type TEXT,
|
||||
is_streaming INTEGER NOT NULL DEFAULT 0,
|
||||
cost_multiplier TEXT NOT NULL DEFAULT '1.0',
|
||||
created_at INTEGER NOT NULL
|
||||
)",
|
||||
[],
|
||||
Self::add_column_if_missing(
|
||||
conn,
|
||||
"providers",
|
||||
"in_failover_queue",
|
||||
"BOOLEAN NOT NULL DEFAULT 0",
|
||||
)?;
|
||||
|
||||
// 添加代理超时配置字段
|
||||
if Self::table_exists(conn, "proxy_config")? {
|
||||
// 兼容旧版本缺失的基础字段
|
||||
Self::add_column_if_missing(
|
||||
conn,
|
||||
"proxy_config",
|
||||
"proxy_enabled",
|
||||
"INTEGER NOT NULL DEFAULT 0",
|
||||
)?;
|
||||
Self::add_column_if_missing(
|
||||
conn,
|
||||
"proxy_config",
|
||||
"listen_address",
|
||||
"TEXT NOT NULL DEFAULT '127.0.0.1'",
|
||||
)?;
|
||||
Self::add_column_if_missing(
|
||||
conn,
|
||||
"proxy_config",
|
||||
"listen_port",
|
||||
"INTEGER NOT NULL DEFAULT 5000",
|
||||
)?;
|
||||
Self::add_column_if_missing(
|
||||
conn,
|
||||
"proxy_config",
|
||||
"enable_logging",
|
||||
"INTEGER NOT NULL DEFAULT 1",
|
||||
)?;
|
||||
|
||||
Self::add_column_if_missing(
|
||||
conn,
|
||||
"proxy_config",
|
||||
"streaming_first_byte_timeout",
|
||||
"INTEGER NOT NULL DEFAULT 30",
|
||||
)?;
|
||||
Self::add_column_if_missing(
|
||||
conn,
|
||||
"proxy_config",
|
||||
"streaming_idle_timeout",
|
||||
"INTEGER NOT NULL DEFAULT 60",
|
||||
)?;
|
||||
Self::add_column_if_missing(
|
||||
conn,
|
||||
"proxy_config",
|
||||
"non_streaming_timeout",
|
||||
"INTEGER NOT NULL DEFAULT 300",
|
||||
)?;
|
||||
}
|
||||
|
||||
// 删除旧的 failover_queue 表(如果存在)
|
||||
conn.execute("DROP INDEX IF EXISTS idx_failover_queue_order", [])
|
||||
.map_err(|e| AppError::Database(format!("删除 failover_queue 索引失败: {e}")))?;
|
||||
conn.execute("DROP TABLE IF EXISTS failover_queue", [])
|
||||
.map_err(|e| AppError::Database(format!("删除 failover_queue 表失败: {e}")))?;
|
||||
|
||||
// 创建 failover 索引
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_providers_failover
|
||||
ON providers(app_type, in_failover_queue, sort_index)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(format!("创建 failover 索引失败: {e}")))?;
|
||||
|
||||
// proxy_request_logs 表
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS proxy_request_logs (
|
||||
request_id TEXT PRIMARY KEY, provider_id TEXT NOT NULL, app_type TEXT NOT NULL, model TEXT NOT NULL,
|
||||
input_tokens INTEGER NOT NULL DEFAULT 0, output_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
cache_read_tokens INTEGER NOT NULL DEFAULT 0, cache_creation_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
input_cost_usd TEXT NOT NULL DEFAULT '0', output_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
cache_read_cost_usd TEXT NOT NULL DEFAULT '0', cache_creation_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
total_cost_usd TEXT NOT NULL DEFAULT '0', latency_ms INTEGER NOT NULL, first_token_ms INTEGER,
|
||||
duration_ms INTEGER, status_code INTEGER NOT NULL, error_message TEXT, session_id TEXT,
|
||||
provider_type TEXT, is_streaming INTEGER NOT NULL DEFAULT 0,
|
||||
cost_multiplier TEXT NOT NULL DEFAULT '1.0', created_at INTEGER NOT NULL
|
||||
)", [])?;
|
||||
|
||||
// 为已存在的表添加新字段
|
||||
Self::add_column_if_missing(conn, "proxy_request_logs", "provider_type", "TEXT")?;
|
||||
Self::add_column_if_missing(
|
||||
@@ -523,13 +530,11 @@ impl Database {
|
||||
// model_pricing 表
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS model_pricing (
|
||||
model_id TEXT PRIMARY KEY,
|
||||
display_name TEXT NOT NULL,
|
||||
input_cost_per_million TEXT NOT NULL,
|
||||
output_cost_per_million TEXT NOT NULL,
|
||||
cache_read_cost_per_million TEXT NOT NULL DEFAULT '0',
|
||||
cache_creation_cost_per_million TEXT NOT NULL DEFAULT '0'
|
||||
)",
|
||||
model_id TEXT PRIMARY KEY, display_name TEXT NOT NULL,
|
||||
input_cost_per_million TEXT NOT NULL, output_cost_per_million TEXT NOT NULL,
|
||||
cache_read_cost_per_million TEXT NOT NULL DEFAULT '0',
|
||||
cache_creation_cost_per_million TEXT NOT NULL DEFAULT '0'
|
||||
)",
|
||||
[],
|
||||
)?;
|
||||
|
||||
@@ -541,6 +546,144 @@ impl Database {
|
||||
// 重构 skills 表(添加 app_type 字段)
|
||||
Self::migrate_skills_table(conn)?;
|
||||
|
||||
// 重构 proxy_config 为三行结构(每应用独立配置)
|
||||
Self::migrate_proxy_config_to_per_app(conn)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 将 proxy_config 迁移为三行结构(每应用独立配置)
|
||||
fn migrate_proxy_config_to_per_app(conn: &Connection) -> Result<(), AppError> {
|
||||
// 检查是否已经是新表结构(幂等性)
|
||||
if !Self::table_exists(conn, "proxy_config")? {
|
||||
// 表不存在,跳过迁移(新安装)
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if Self::has_column(conn, "proxy_config", "app_type")? {
|
||||
// 已经是三行结构,跳过迁移
|
||||
log::info!("proxy_config 已经是三行结构,跳过迁移");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// 读取旧配置
|
||||
let old_config = conn
|
||||
.query_row(
|
||||
"SELECT listen_address, listen_port, max_retries, enable_logging,
|
||||
streaming_first_byte_timeout, streaming_idle_timeout, non_streaming_timeout
|
||||
FROM proxy_config WHERE id = 1",
|
||||
[],
|
||||
|row| {
|
||||
Ok((
|
||||
row.get::<_, String>(0)?,
|
||||
row.get::<_, i32>(1)?,
|
||||
row.get::<_, i32>(2)?,
|
||||
row.get::<_, i32>(3)?,
|
||||
row.get::<_, i32>(4).unwrap_or(30),
|
||||
row.get::<_, i32>(5).unwrap_or(60),
|
||||
row.get::<_, i32>(6).unwrap_or(300),
|
||||
))
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|_| ("127.0.0.1".to_string(), 5000, 3, 1, 30, 60, 300));
|
||||
|
||||
let old_cb = conn.query_row(
|
||||
"SELECT failure_threshold, success_threshold, timeout_seconds, error_rate_threshold, min_requests
|
||||
FROM circuit_breaker_config WHERE id = 1", [],
|
||||
|row| Ok((row.get::<_, i32>(0)?, row.get::<_, i32>(1)?, row.get::<_, i64>(2)?,
|
||||
row.get::<_, f64>(3)?, row.get::<_, i32>(4)?))
|
||||
).unwrap_or((5, 2, 60, 0.5, 10));
|
||||
|
||||
let get_bool = |key: &str| -> bool {
|
||||
conn.query_row("SELECT value FROM settings WHERE key = ?", [key], |r| {
|
||||
r.get::<_, String>(0)
|
||||
})
|
||||
.map(|v| v == "true" || v == "1")
|
||||
.unwrap_or(false)
|
||||
};
|
||||
|
||||
let apps = [
|
||||
(
|
||||
"claude",
|
||||
get_bool("proxy_takeover_claude"),
|
||||
get_bool("auto_failover_enabled_claude"),
|
||||
6,
|
||||
45,
|
||||
90,
|
||||
8,
|
||||
3,
|
||||
90,
|
||||
0.6,
|
||||
15,
|
||||
),
|
||||
(
|
||||
"codex",
|
||||
get_bool("proxy_takeover_codex"),
|
||||
get_bool("auto_failover_enabled_codex"),
|
||||
3,
|
||||
old_config.4,
|
||||
old_config.5,
|
||||
old_cb.0,
|
||||
old_cb.1,
|
||||
old_cb.2,
|
||||
old_cb.3,
|
||||
old_cb.4,
|
||||
),
|
||||
(
|
||||
"gemini",
|
||||
get_bool("proxy_takeover_gemini"),
|
||||
get_bool("auto_failover_enabled_gemini"),
|
||||
5,
|
||||
old_config.4,
|
||||
old_config.5,
|
||||
old_cb.0,
|
||||
old_cb.1,
|
||||
old_cb.2,
|
||||
old_cb.3,
|
||||
old_cb.4,
|
||||
),
|
||||
];
|
||||
|
||||
// 创建新表
|
||||
conn.execute("DROP TABLE IF EXISTS proxy_config_new", [])?;
|
||||
conn.execute("CREATE TABLE proxy_config_new (
|
||||
app_type TEXT PRIMARY KEY CHECK (app_type IN ('claude','codex','gemini')),
|
||||
proxy_enabled INTEGER NOT NULL DEFAULT 0, listen_address TEXT NOT NULL DEFAULT '127.0.0.1',
|
||||
listen_port INTEGER NOT NULL DEFAULT 5000, enable_logging INTEGER NOT NULL DEFAULT 1,
|
||||
enabled INTEGER NOT NULL DEFAULT 0, auto_failover_enabled INTEGER NOT NULL DEFAULT 0,
|
||||
max_retries INTEGER NOT NULL DEFAULT 3, streaming_first_byte_timeout INTEGER NOT NULL DEFAULT 30,
|
||||
streaming_idle_timeout INTEGER NOT NULL DEFAULT 60, non_streaming_timeout INTEGER NOT NULL DEFAULT 300,
|
||||
circuit_failure_threshold INTEGER NOT NULL DEFAULT 5, circuit_success_threshold INTEGER NOT NULL DEFAULT 2,
|
||||
circuit_timeout_seconds INTEGER NOT NULL DEFAULT 60, circuit_error_rate_threshold REAL NOT NULL DEFAULT 0.5,
|
||||
circuit_min_requests INTEGER NOT NULL DEFAULT 10,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')), updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
)", [])?;
|
||||
|
||||
// 插入三行配置
|
||||
for (app, takeover, failover, retries, fb, idle, cb_f, cb_s, cb_t, cb_r, cb_m) in apps {
|
||||
conn.execute(
|
||||
"INSERT INTO proxy_config_new (app_type, proxy_enabled, listen_address, listen_port, enable_logging,
|
||||
enabled, auto_failover_enabled, max_retries, streaming_first_byte_timeout, streaming_idle_timeout,
|
||||
non_streaming_timeout, circuit_failure_threshold, circuit_success_threshold, circuit_timeout_seconds,
|
||||
circuit_error_rate_threshold, circuit_min_requests)
|
||||
VALUES (?1, 0, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)",
|
||||
rusqlite::params![app, old_config.0, old_config.1, old_config.3,
|
||||
if takeover { 1 } else { 0 }, if failover { 1 } else { 0 },
|
||||
retries, fb, idle, old_config.6, cb_f, cb_s, cb_t, cb_r, cb_m]
|
||||
).map_err(|e| AppError::Database(format!("插入 {app} 配置失败: {e}")))?;
|
||||
}
|
||||
|
||||
// 替换表并清理
|
||||
conn.execute("DROP TABLE IF EXISTS proxy_config", [])?;
|
||||
conn.execute("ALTER TABLE proxy_config_new RENAME TO proxy_config", [])?;
|
||||
conn.execute("DROP TABLE IF EXISTS circuit_breaker_config", [])?;
|
||||
conn.execute("DELETE FROM settings WHERE key LIKE 'proxy_takeover_%'", [])?;
|
||||
conn.execute(
|
||||
"DELETE FROM settings WHERE key LIKE 'auto_failover_enabled_%'",
|
||||
[],
|
||||
)?;
|
||||
|
||||
log::info!("proxy_config 已迁移为三行结构");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -201,6 +201,53 @@ fn migration_aligns_column_defaults_and_types() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_tables_repairs_legacy_proxy_config_singleton_to_per_app() {
|
||||
let conn = Connection::open_in_memory().expect("open memory db");
|
||||
|
||||
// 模拟测试版 v2:user_version=2,但 proxy_config 仍是单例结构(无 app_type)
|
||||
Database::set_user_version(&conn, 2).expect("set user_version");
|
||||
conn.execute_batch(
|
||||
r#"
|
||||
CREATE TABLE proxy_config (
|
||||
id INTEGER PRIMARY KEY,
|
||||
enabled INTEGER NOT NULL DEFAULT 0,
|
||||
listen_address TEXT NOT NULL DEFAULT '127.0.0.1',
|
||||
listen_port INTEGER NOT NULL DEFAULT 5000,
|
||||
max_retries INTEGER NOT NULL DEFAULT 3,
|
||||
request_timeout INTEGER NOT NULL DEFAULT 300,
|
||||
enable_logging INTEGER NOT NULL DEFAULT 1,
|
||||
target_app TEXT NOT NULL DEFAULT 'claude',
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
INSERT INTO proxy_config (id, enabled) VALUES (1, 1);
|
||||
"#,
|
||||
)
|
||||
.expect("seed legacy proxy_config");
|
||||
|
||||
Database::create_tables_on_conn(&conn).expect("create tables should repair proxy_config");
|
||||
|
||||
assert!(
|
||||
Database::has_column(&conn, "proxy_config", "app_type").expect("check app_type"),
|
||||
"proxy_config should be migrated to per-app structure"
|
||||
);
|
||||
|
||||
let count: i32 = conn
|
||||
.query_row("SELECT COUNT(*) FROM proxy_config", [], |r| r.get(0))
|
||||
.expect("count rows");
|
||||
assert_eq!(count, 3, "per-app proxy_config should have 3 rows");
|
||||
|
||||
// 新结构下应能按 app_type 查询
|
||||
let _: i32 = conn
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM proxy_config WHERE app_type = 'claude'",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.expect("query by app_type");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dry_run_does_not_write_to_disk() {
|
||||
// Create minimal valid config for migration
|
||||
@@ -245,6 +292,7 @@ fn dry_run_validates_schema_compatibility() {
|
||||
meta: None,
|
||||
icon: None,
|
||||
icon_color: None,
|
||||
in_failover_queue: false,
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -132,6 +132,7 @@ pub(crate) fn build_provider_from_request(
|
||||
meta,
|
||||
icon: request.icon.clone(),
|
||||
icon_color: None,
|
||||
in_failover_queue: false,
|
||||
};
|
||||
|
||||
Ok(provider)
|
||||
|
||||
@@ -596,7 +596,7 @@ pub fn run() {
|
||||
commands::upsert_mcp_server_in_config,
|
||||
commands::delete_mcp_server_in_config,
|
||||
commands::set_mcp_enabled,
|
||||
// v3.7.0: Unified MCP management
|
||||
// Unified MCP management
|
||||
commands::get_mcp_servers,
|
||||
commands::upsert_mcp_server,
|
||||
commands::delete_mcp_server,
|
||||
@@ -650,13 +650,17 @@ pub fn run() {
|
||||
commands::get_auto_launch_status,
|
||||
// Proxy server management
|
||||
commands::start_proxy_server,
|
||||
commands::start_proxy_with_takeover,
|
||||
commands::stop_proxy_with_restore,
|
||||
commands::get_proxy_takeover_status,
|
||||
commands::set_proxy_takeover_for_app,
|
||||
commands::get_proxy_status,
|
||||
commands::get_proxy_config,
|
||||
commands::update_proxy_config,
|
||||
// Global & Per-App Config
|
||||
commands::get_global_proxy_config,
|
||||
commands::update_global_proxy_config,
|
||||
commands::get_proxy_config_for_app,
|
||||
commands::update_proxy_config_for_app,
|
||||
commands::is_proxy_running,
|
||||
commands::is_live_takeover_active,
|
||||
commands::switch_proxy_provider,
|
||||
@@ -671,8 +675,6 @@ pub fn run() {
|
||||
commands::get_available_providers_for_failover,
|
||||
commands::add_to_failover_queue,
|
||||
commands::remove_from_failover_queue,
|
||||
commands::reorder_failover_queue,
|
||||
commands::set_failover_item_enabled,
|
||||
commands::get_auto_failover_enabled,
|
||||
commands::set_auto_failover_enabled,
|
||||
// Usage statistics
|
||||
@@ -692,6 +694,12 @@ pub fn run() {
|
||||
commands::get_stream_check_config,
|
||||
commands::save_stream_check_config,
|
||||
commands::get_tool_versions,
|
||||
// Universal Provider management
|
||||
commands::get_universal_providers,
|
||||
commands::get_universal_provider,
|
||||
commands::upsert_universal_provider,
|
||||
commands::delete_universal_provider,
|
||||
commands::sync_universal_provider,
|
||||
]);
|
||||
|
||||
let app = builder
|
||||
@@ -848,22 +856,20 @@ pub async fn cleanup_before_exit(app_handle: &tauri::AppHandle) {
|
||||
// 启动时恢复代理状态
|
||||
// ============================================================
|
||||
|
||||
/// 启动时根据 settings 表中的代理状态自动恢复代理服务
|
||||
/// 启动时根据 proxy_config 表中的代理状态自动恢复代理服务
|
||||
///
|
||||
/// 检查 `proxy_takeover_claude`、`proxy_takeover_codex`、`proxy_takeover_gemini` 的值,
|
||||
/// 如果有任一应用的状态为 `true`,则自动启动代理服务并接管对应应用的 Live 配置。
|
||||
/// 检查 `proxy_config.enabled` 字段,如果有任一应用的状态为 `true`,
|
||||
/// 则自动启动代理服务并接管对应应用的 Live 配置。
|
||||
async fn restore_proxy_state_on_startup(state: &store::AppState) {
|
||||
// 收集需要恢复接管的应用列表
|
||||
let apps_to_restore: Vec<&str> = ["claude", "codex", "gemini"]
|
||||
.iter()
|
||||
.filter(|app_type| {
|
||||
state
|
||||
.db
|
||||
.get_proxy_takeover_enabled(app_type)
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.copied()
|
||||
.collect();
|
||||
// 收集需要恢复接管的应用列表(从 proxy_config.enabled 读取)
|
||||
let mut apps_to_restore = Vec::new();
|
||||
for app_type in ["claude", "codex", "gemini"] {
|
||||
if let Ok(config) = state.db.get_proxy_config_for_app(app_type).await {
|
||||
if config.enabled {
|
||||
apps_to_restore.push(app_type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if apps_to_restore.is_empty() {
|
||||
log::debug!("启动时无需恢复代理状态");
|
||||
@@ -885,7 +891,11 @@ async fn restore_proxy_state_on_startup(state: &store::AppState) {
|
||||
Err(e) => {
|
||||
log::error!("✗ 恢复 {app_type} 的代理接管状态失败: {e}");
|
||||
// 失败时清除该应用的状态,避免下次启动再次尝试
|
||||
if let Err(clear_err) = state.db.set_proxy_takeover_enabled(app_type, false) {
|
||||
if let Err(clear_err) = state
|
||||
.proxy_service
|
||||
.set_takeover_for_app(app_type, false)
|
||||
.await
|
||||
{
|
||||
log::error!("清除 {app_type} 代理状态失败: {clear_err}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -359,9 +359,14 @@ pub fn sync_single_server_to_codex(
|
||||
let mut doc = if config_path.exists() {
|
||||
let content =
|
||||
std::fs::read_to_string(&config_path).map_err(|e| AppError::io(&config_path, e))?;
|
||||
content
|
||||
.parse::<toml_edit::DocumentMut>()
|
||||
.map_err(|e| AppError::McpValidation(format!("解析 Codex config.toml 失败: {e}")))?
|
||||
// 尝试解析现有配置,如果失败则创建新文档(容错处理)
|
||||
match content.parse::<toml_edit::DocumentMut>() {
|
||||
Ok(doc) => doc,
|
||||
Err(e) => {
|
||||
log::warn!("解析 Codex config.toml 失败: {e},将创建新配置");
|
||||
toml_edit::DocumentMut::new()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
toml_edit::DocumentMut::new()
|
||||
};
|
||||
@@ -409,9 +414,14 @@ pub fn remove_server_from_codex(id: &str) -> Result<(), AppError> {
|
||||
let content =
|
||||
std::fs::read_to_string(&config_path).map_err(|e| AppError::io(&config_path, e))?;
|
||||
|
||||
let mut doc = content
|
||||
.parse::<toml_edit::DocumentMut>()
|
||||
.map_err(|e| AppError::McpValidation(format!("解析 Codex config.toml 失败: {e}")))?;
|
||||
// 尝试解析现有配置,如果失败则直接返回(无法删除不存在的内容)
|
||||
let mut doc = match content.parse::<toml_edit::DocumentMut>() {
|
||||
Ok(doc) => doc,
|
||||
Err(e) => {
|
||||
log::warn!("解析 Codex config.toml 失败: {e},跳过删除操作");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
// 从正确的位置删除:[mcp_servers]
|
||||
if let Some(mcp_servers) = doc.get_mut("mcp_servers").and_then(|s| s.as_table_mut()) {
|
||||
|
||||
@@ -36,6 +36,10 @@ pub struct Provider {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(rename = "iconColor")]
|
||||
pub icon_color: Option<String>,
|
||||
/// 是否加入故障转移队列
|
||||
#[serde(default)]
|
||||
#[serde(rename = "inFailoverQueue")]
|
||||
pub in_failover_queue: bool,
|
||||
}
|
||||
|
||||
impl Provider {
|
||||
@@ -58,6 +62,7 @@ impl Provider {
|
||||
meta: None,
|
||||
icon: None,
|
||||
icon_color: None,
|
||||
in_failover_queue: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -168,3 +173,286 @@ impl ProviderManager {
|
||||
&self.providers
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 统一供应商(Universal Provider)- 跨应用共享配置
|
||||
// ============================================================================
|
||||
|
||||
/// 统一供应商的应用启用状态
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct UniversalProviderApps {
|
||||
#[serde(default)]
|
||||
pub claude: bool,
|
||||
#[serde(default)]
|
||||
pub codex: bool,
|
||||
#[serde(default)]
|
||||
pub gemini: bool,
|
||||
}
|
||||
|
||||
/// Claude 模型配置
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct ClaudeModelConfig {
|
||||
/// 主模型
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub model: Option<String>,
|
||||
/// Haiku 默认模型
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(rename = "haikuModel")]
|
||||
pub haiku_model: Option<String>,
|
||||
/// Sonnet 默认模型
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(rename = "sonnetModel")]
|
||||
pub sonnet_model: Option<String>,
|
||||
/// Opus 默认模型
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(rename = "opusModel")]
|
||||
pub opus_model: Option<String>,
|
||||
}
|
||||
|
||||
/// Codex 模型配置
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct CodexModelConfig {
|
||||
/// 模型名称
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub model: Option<String>,
|
||||
/// 推理强度
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(rename = "reasoningEffort")]
|
||||
pub reasoning_effort: Option<String>,
|
||||
}
|
||||
|
||||
/// Gemini 模型配置
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct GeminiModelConfig {
|
||||
/// 模型名称
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub model: Option<String>,
|
||||
}
|
||||
|
||||
/// 各应用的模型配置
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct UniversalProviderModels {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub claude: Option<ClaudeModelConfig>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub codex: Option<CodexModelConfig>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub gemini: Option<GeminiModelConfig>,
|
||||
}
|
||||
|
||||
/// 统一供应商(跨应用共享配置)
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct UniversalProvider {
|
||||
/// 唯一标识
|
||||
pub id: String,
|
||||
/// 供应商名称
|
||||
pub name: String,
|
||||
/// 供应商类型(如 "newapi", "custom")
|
||||
#[serde(rename = "providerType")]
|
||||
pub provider_type: String,
|
||||
/// 应用启用状态
|
||||
pub apps: UniversalProviderApps,
|
||||
/// API 基础地址
|
||||
#[serde(rename = "baseUrl")]
|
||||
pub base_url: String,
|
||||
/// API 密钥
|
||||
#[serde(rename = "apiKey")]
|
||||
pub api_key: String,
|
||||
/// 各应用的模型配置
|
||||
#[serde(default)]
|
||||
pub models: UniversalProviderModels,
|
||||
/// 网站链接
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(rename = "websiteUrl")]
|
||||
pub website_url: Option<String>,
|
||||
/// 备注信息
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub notes: Option<String>,
|
||||
/// 图标名称
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub icon: Option<String>,
|
||||
/// 图标颜色
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(rename = "iconColor")]
|
||||
pub icon_color: Option<String>,
|
||||
/// 元数据
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub meta: Option<ProviderMeta>,
|
||||
/// 创建时间戳
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(rename = "createdAt")]
|
||||
pub created_at: Option<i64>,
|
||||
/// 排序索引
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(rename = "sortIndex")]
|
||||
pub sort_index: Option<usize>,
|
||||
}
|
||||
|
||||
impl UniversalProvider {
|
||||
/// 创建新的统一供应商
|
||||
pub fn new(
|
||||
id: String,
|
||||
name: String,
|
||||
provider_type: String,
|
||||
base_url: String,
|
||||
api_key: String,
|
||||
) -> Self {
|
||||
Self {
|
||||
id,
|
||||
name,
|
||||
provider_type,
|
||||
apps: UniversalProviderApps::default(),
|
||||
base_url,
|
||||
api_key,
|
||||
models: UniversalProviderModels::default(),
|
||||
website_url: None,
|
||||
notes: None,
|
||||
icon: None,
|
||||
icon_color: None,
|
||||
meta: None,
|
||||
created_at: Some(chrono::Utc::now().timestamp_millis()),
|
||||
sort_index: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 生成 Claude 供应商配置
|
||||
pub fn to_claude_provider(&self) -> Option<Provider> {
|
||||
if !self.apps.claude {
|
||||
return None;
|
||||
}
|
||||
|
||||
let models = self.models.claude.as_ref();
|
||||
let model = models
|
||||
.and_then(|m| m.model.clone())
|
||||
.unwrap_or_else(|| "claude-sonnet-4-20250514".to_string());
|
||||
let haiku = models
|
||||
.and_then(|m| m.haiku_model.clone())
|
||||
.unwrap_or_else(|| model.clone());
|
||||
let sonnet = models
|
||||
.and_then(|m| m.sonnet_model.clone())
|
||||
.unwrap_or_else(|| model.clone());
|
||||
let opus = models
|
||||
.and_then(|m| m.opus_model.clone())
|
||||
.unwrap_or_else(|| model.clone());
|
||||
|
||||
let settings_config = serde_json::json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": self.base_url,
|
||||
"ANTHROPIC_AUTH_TOKEN": self.api_key,
|
||||
"ANTHROPIC_MODEL": model,
|
||||
"ANTHROPIC_DEFAULT_HAIKU_MODEL": haiku,
|
||||
"ANTHROPIC_DEFAULT_SONNET_MODEL": sonnet,
|
||||
"ANTHROPIC_DEFAULT_OPUS_MODEL": opus,
|
||||
}
|
||||
});
|
||||
|
||||
Some(Provider {
|
||||
id: format!("universal-claude-{}", self.id),
|
||||
name: self.name.clone(),
|
||||
settings_config,
|
||||
website_url: self.website_url.clone(),
|
||||
category: Some("aggregator".to_string()),
|
||||
created_at: self.created_at,
|
||||
sort_index: self.sort_index,
|
||||
notes: self.notes.clone(),
|
||||
meta: self.meta.clone(),
|
||||
icon: self.icon.clone(),
|
||||
icon_color: self.icon_color.clone(),
|
||||
in_failover_queue: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// 生成 Codex 供应商配置
|
||||
pub fn to_codex_provider(&self) -> Option<Provider> {
|
||||
if !self.apps.codex {
|
||||
return None;
|
||||
}
|
||||
|
||||
let models = self.models.codex.as_ref();
|
||||
let model = models
|
||||
.and_then(|m| m.model.clone())
|
||||
.unwrap_or_else(|| "gpt-4o".to_string());
|
||||
let reasoning_effort = models
|
||||
.and_then(|m| m.reasoning_effort.clone())
|
||||
.unwrap_or_else(|| "high".to_string());
|
||||
|
||||
// 确保 base_url 以 /v1 结尾(Codex 使用 OpenAI 兼容 API)
|
||||
let codex_base_url = if self.base_url.ends_with("/v1") {
|
||||
self.base_url.clone()
|
||||
} else {
|
||||
format!("{}/v1", self.base_url.trim_end_matches('/'))
|
||||
};
|
||||
|
||||
// 生成 Codex 的 config.toml 内容
|
||||
let config_toml = format!(
|
||||
r#"model_provider = "newapi"
|
||||
model = "{}"
|
||||
model_reasoning_effort = "{}"
|
||||
disable_response_storage = true
|
||||
|
||||
[model_providers.newapi]
|
||||
name = "NewAPI"
|
||||
base_url = "{}"
|
||||
wire_api = "responses"
|
||||
requires_openai_auth = true"#,
|
||||
model, reasoning_effort, codex_base_url
|
||||
);
|
||||
|
||||
let settings_config = serde_json::json!({
|
||||
"auth": {
|
||||
"OPENAI_API_KEY": self.api_key
|
||||
},
|
||||
"config": config_toml
|
||||
});
|
||||
|
||||
Some(Provider {
|
||||
id: format!("universal-codex-{}", self.id),
|
||||
name: self.name.clone(),
|
||||
settings_config,
|
||||
website_url: self.website_url.clone(),
|
||||
category: Some("aggregator".to_string()),
|
||||
created_at: self.created_at,
|
||||
sort_index: self.sort_index,
|
||||
notes: self.notes.clone(),
|
||||
meta: self.meta.clone(),
|
||||
icon: self.icon.clone(),
|
||||
icon_color: self.icon_color.clone(),
|
||||
in_failover_queue: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// 生成 Gemini 供应商配置
|
||||
pub fn to_gemini_provider(&self) -> Option<Provider> {
|
||||
if !self.apps.gemini {
|
||||
return None;
|
||||
}
|
||||
|
||||
let models = self.models.gemini.as_ref();
|
||||
let model = models
|
||||
.and_then(|m| m.model.clone())
|
||||
.unwrap_or_else(|| "gemini-2.5-pro".to_string());
|
||||
|
||||
let settings_config = serde_json::json!({
|
||||
"env": {
|
||||
"GOOGLE_GEMINI_BASE_URL": self.base_url,
|
||||
"GEMINI_API_KEY": self.api_key,
|
||||
"GEMINI_MODEL": model,
|
||||
}
|
||||
});
|
||||
|
||||
Some(Provider {
|
||||
id: format!("universal-gemini-{}", self.id),
|
||||
name: self.name.clone(),
|
||||
settings_config,
|
||||
website_url: self.website_url.clone(),
|
||||
category: Some("aggregator".to_string()),
|
||||
created_at: self.created_at,
|
||||
sort_index: self.sort_index,
|
||||
notes: self.notes.clone(),
|
||||
meta: self.meta.clone(),
|
||||
icon: self.icon.clone(),
|
||||
icon_color: self.icon_color.clone(),
|
||||
in_failover_queue: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,16 @@ use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
pub struct ForwardResult {
|
||||
pub response: Response,
|
||||
pub provider: Provider,
|
||||
}
|
||||
|
||||
pub struct ForwardError {
|
||||
pub error: ProxyError,
|
||||
pub provider: Option<Provider>,
|
||||
}
|
||||
|
||||
pub struct RequestForwarder {
|
||||
client: Client,
|
||||
/// 共享的 ProviderRouter(持有熔断器状态)
|
||||
@@ -29,7 +39,7 @@ pub struct RequestForwarder {
|
||||
failover_manager: Arc<FailoverSwitchManager>,
|
||||
/// AppHandle,用于发射事件和更新托盘
|
||||
app_handle: Option<tauri::AppHandle>,
|
||||
/// 请求开始时的“当前供应商 ID”(用于判断是否需要同步 UI/托盘)
|
||||
/// 请求开始时的"当前供应商 ID"(用于判断是否需要同步 UI/托盘)
|
||||
current_provider_id_at_start: String,
|
||||
}
|
||||
|
||||
@@ -37,17 +47,27 @@ impl RequestForwarder {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
router: Arc<ProviderRouter>,
|
||||
timeout_secs: u64,
|
||||
non_streaming_timeout: u64,
|
||||
max_retries: u8,
|
||||
status: Arc<RwLock<ProxyStatus>>,
|
||||
current_providers: Arc<RwLock<std::collections::HashMap<String, (String, String)>>>,
|
||||
failover_manager: Arc<FailoverSwitchManager>,
|
||||
app_handle: Option<tauri::AppHandle>,
|
||||
current_provider_id_at_start: String,
|
||||
_streaming_first_byte_timeout: u64,
|
||||
_streaming_idle_timeout: u64,
|
||||
) -> Self {
|
||||
// 全局超时设置为 1800 秒(30 分钟),确保业务层超时配置能正常工作
|
||||
// 参考 Claude Code Hub 的 undici 全局超时设计
|
||||
const GLOBAL_TIMEOUT_SECS: u64 = 1800;
|
||||
|
||||
let mut client_builder = Client::builder();
|
||||
if timeout_secs > 0 {
|
||||
client_builder = client_builder.timeout(Duration::from_secs(timeout_secs));
|
||||
if non_streaming_timeout > 0 {
|
||||
// 使用配置的非流式超时
|
||||
client_builder = client_builder.timeout(Duration::from_secs(non_streaming_timeout));
|
||||
} else {
|
||||
// 禁用超时时使用全局超时作为保底
|
||||
client_builder = client_builder.timeout(Duration::from_secs(GLOBAL_TIMEOUT_SECS));
|
||||
}
|
||||
|
||||
let client = client_builder
|
||||
@@ -134,13 +154,16 @@ impl RequestForwarder {
|
||||
body: Value,
|
||||
headers: axum::http::HeaderMap,
|
||||
providers: Vec<Provider>,
|
||||
) -> Result<Response, ProxyError> {
|
||||
) -> Result<ForwardResult, ForwardError> {
|
||||
// 获取适配器
|
||||
let adapter = get_adapter(app_type);
|
||||
let app_type_str = app_type.as_str();
|
||||
|
||||
if providers.is_empty() {
|
||||
return Err(ProxyError::NoAvailableProvider);
|
||||
return Err(ForwardError {
|
||||
error: ProxyError::NoAvailableProvider,
|
||||
provider: None,
|
||||
});
|
||||
}
|
||||
|
||||
log::info!(
|
||||
@@ -150,16 +173,27 @@ impl RequestForwarder {
|
||||
);
|
||||
|
||||
let mut last_error = None;
|
||||
let mut last_provider = None;
|
||||
let mut attempted_providers = 0usize;
|
||||
|
||||
// 单 Provider 场景下跳过熔断器检查(故障转移关闭时)
|
||||
let bypass_circuit_breaker = providers.len() == 1;
|
||||
|
||||
// 依次尝试每个供应商
|
||||
for provider in providers.iter() {
|
||||
// 发起请求前先获取熔断器放行许可(HalfOpen 会占用探测名额)
|
||||
let permit = self
|
||||
.router
|
||||
.allow_provider_request(&provider.id, app_type_str)
|
||||
.await;
|
||||
if !permit.allowed {
|
||||
// 单 Provider 场景下跳过此检查,避免熔断器阻塞所有请求
|
||||
let (allowed, used_half_open_permit) = if bypass_circuit_breaker {
|
||||
(true, false)
|
||||
} else {
|
||||
let permit = self
|
||||
.router
|
||||
.allow_provider_request(&provider.id, app_type_str)
|
||||
.await;
|
||||
(permit.allowed, permit.used_half_open_permit)
|
||||
};
|
||||
|
||||
if !allowed {
|
||||
log::debug!(
|
||||
"[{}] Provider {} 熔断器拒绝本次请求,跳过",
|
||||
app_type_str,
|
||||
@@ -168,8 +202,6 @@ impl RequestForwarder {
|
||||
continue;
|
||||
}
|
||||
|
||||
let used_half_open_permit = permit.used_half_open_permit;
|
||||
|
||||
attempted_providers += 1;
|
||||
|
||||
log::info!(
|
||||
@@ -269,7 +301,10 @@ impl RequestForwarder {
|
||||
latency
|
||||
);
|
||||
|
||||
return Ok(response);
|
||||
return Ok(ForwardResult {
|
||||
response,
|
||||
provider: provider.clone(),
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
let latency = start.elapsed().as_millis() as u64;
|
||||
@@ -310,6 +345,7 @@ impl RequestForwarder {
|
||||
);
|
||||
|
||||
last_error = Some(e);
|
||||
last_provider = Some(provider.clone());
|
||||
// 继续尝试下一个供应商
|
||||
continue;
|
||||
}
|
||||
@@ -331,7 +367,10 @@ impl RequestForwarder {
|
||||
provider.name,
|
||||
e
|
||||
);
|
||||
return Err(e);
|
||||
return Err(ForwardError {
|
||||
error: e,
|
||||
provider: Some(provider.clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -349,7 +388,10 @@ impl RequestForwarder {
|
||||
(status.success_requests as f32 / status.total_requests as f32) * 100.0;
|
||||
}
|
||||
}
|
||||
return Err(ProxyError::NoAvailableProvider);
|
||||
return Err(ForwardError {
|
||||
error: ProxyError::NoAvailableProvider,
|
||||
provider: None,
|
||||
});
|
||||
}
|
||||
|
||||
// 所有供应商都失败了
|
||||
@@ -369,7 +411,10 @@ impl RequestForwarder {
|
||||
providers.len()
|
||||
);
|
||||
|
||||
Err(last_error.unwrap_or(ProxyError::MaxRetriesExceeded))
|
||||
Err(ForwardError {
|
||||
error: last_error.unwrap_or(ProxyError::MaxRetriesExceeded),
|
||||
provider: last_provider,
|
||||
})
|
||||
}
|
||||
|
||||
/// 转发单个请求(使用适配器)
|
||||
@@ -385,12 +430,19 @@ impl RequestForwarder {
|
||||
let base_url = adapter.extract_base_url(provider)?;
|
||||
log::info!("[{}] base_url: {}", adapter.name(), base_url);
|
||||
|
||||
// 使用适配器构建 URL
|
||||
let url = adapter.build_url(&base_url, endpoint);
|
||||
|
||||
// 检查是否需要格式转换
|
||||
let needs_transform = adapter.needs_transform(provider);
|
||||
|
||||
let effective_endpoint =
|
||||
if needs_transform && adapter.name() == "Claude" && endpoint == "/v1/messages" {
|
||||
"/v1/chat/completions"
|
||||
} else {
|
||||
endpoint
|
||||
};
|
||||
|
||||
// 使用适配器构建 URL
|
||||
let url = adapter.build_url(&base_url, effective_endpoint);
|
||||
|
||||
// 记录原始请求 JSON
|
||||
log::info!(
|
||||
"[{}] ====== 请求开始 ======\n>>> 原始请求 JSON:\n{}",
|
||||
@@ -398,10 +450,23 @@ impl RequestForwarder {
|
||||
serde_json::to_string_pretty(body).unwrap_or_else(|_| body.to_string())
|
||||
);
|
||||
|
||||
// 应用模型映射(独立于格式转换)
|
||||
let (mapped_body, _original_model, mapped_model) =
|
||||
super::model_mapper::apply_model_mapping(body.clone(), provider);
|
||||
|
||||
if let Some(ref mapped) = mapped_model {
|
||||
log::info!(
|
||||
"[{}] >>> 模型映射后的请求 JSON:\n{}",
|
||||
adapter.name(),
|
||||
serde_json::to_string_pretty(&mapped_body).unwrap_or_default()
|
||||
);
|
||||
log::info!("[{}] 模型已映射到: {}", adapter.name(), mapped);
|
||||
}
|
||||
|
||||
// 转换请求体(如果需要)
|
||||
let request_body = if needs_transform {
|
||||
log::info!("[{}] 转换请求格式 (Anthropic → OpenAI)", adapter.name());
|
||||
let transformed = adapter.transform_request(body.clone(), provider)?;
|
||||
let transformed = adapter.transform_request(mapped_body, provider)?;
|
||||
log::info!(
|
||||
"[{}] >>> 转换后的请求 JSON:\n{}",
|
||||
adapter.name(),
|
||||
@@ -409,7 +474,7 @@ impl RequestForwarder {
|
||||
);
|
||||
transformed
|
||||
} else {
|
||||
body.clone()
|
||||
mapped_body
|
||||
};
|
||||
|
||||
log::info!(
|
||||
|
||||
@@ -31,13 +31,26 @@ pub struct UsageParserConfig {
|
||||
// 模型提取器实现
|
||||
// ============================================================================
|
||||
|
||||
/// Claude 流式响应模型提取(直接使用请求模型)
|
||||
fn claude_model_extractor(_events: &[Value], request_model: &str) -> String {
|
||||
/// Claude 流式响应模型提取(优先使用 usage.model)
|
||||
fn claude_model_extractor(events: &[Value], request_model: &str) -> String {
|
||||
// 首先尝试从解析的 usage 中获取模型
|
||||
if let Some(usage) = TokenUsage::from_claude_stream_events(events) {
|
||||
if let Some(model) = usage.model {
|
||||
return model;
|
||||
}
|
||||
}
|
||||
request_model.to_string()
|
||||
}
|
||||
|
||||
/// OpenAI Chat Completions 流式响应模型提取
|
||||
/// OpenAI Chat Completions 流式响应模型提取(优先使用 usage.model)
|
||||
fn openai_model_extractor(events: &[Value], request_model: &str) -> String {
|
||||
// 首先尝试从解析的 usage 中获取模型
|
||||
if let Some(usage) = TokenUsage::from_openai_stream_events(events) {
|
||||
if let Some(model) = usage.model {
|
||||
return model;
|
||||
}
|
||||
}
|
||||
// 回退:从事件中直接提取
|
||||
events
|
||||
.iter()
|
||||
.find_map(|e| e.get("model")?.as_str())
|
||||
@@ -45,8 +58,15 @@ fn openai_model_extractor(events: &[Value], request_model: &str) -> String {
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// Codex Responses API 流式响应模型提取
|
||||
/// Codex Responses API 流式响应模型提取(优先使用 usage.model)
|
||||
fn codex_model_extractor(events: &[Value], request_model: &str) -> String {
|
||||
// 首先尝试从解析的 usage 中获取模型
|
||||
if let Some(usage) = TokenUsage::from_codex_stream_events(events) {
|
||||
if let Some(model) = usage.model {
|
||||
return model;
|
||||
}
|
||||
}
|
||||
// 回退:从 response.completed 事件中提取
|
||||
events
|
||||
.iter()
|
||||
.find_map(|e| {
|
||||
|
||||
@@ -5,23 +5,32 @@
|
||||
use crate::app_config::AppType;
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::{
|
||||
forwarder::RequestForwarder, server::ProxyState, types::ProxyConfig, ProxyError,
|
||||
forwarder::RequestForwarder, server::ProxyState, types::AppProxyConfig, ProxyError,
|
||||
};
|
||||
use std::time::Instant;
|
||||
|
||||
/// 流式超时配置
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct StreamingTimeoutConfig {
|
||||
/// 首字节超时(秒),0 表示禁用
|
||||
pub first_byte_timeout: u64,
|
||||
/// 静默期超时(秒),0 表示禁用
|
||||
pub idle_timeout: u64,
|
||||
}
|
||||
|
||||
/// 请求上下文
|
||||
///
|
||||
/// 贯穿整个请求生命周期,包含:
|
||||
/// - 计时信息
|
||||
/// - 代理配置
|
||||
/// - 应用级代理配置(per-app)
|
||||
/// - 选中的 Provider 列表(用于故障转移)
|
||||
/// - 请求模型名称
|
||||
/// - 日志标签
|
||||
pub struct RequestContext {
|
||||
/// 请求开始时间
|
||||
pub start_time: Instant,
|
||||
/// 代理配置快照
|
||||
pub config: ProxyConfig,
|
||||
/// 应用级代理配置(per-app,包含重试次数和超时配置)
|
||||
pub app_config: AppProxyConfig,
|
||||
/// 选中的 Provider(故障转移链的第一个)
|
||||
pub provider: Provider,
|
||||
/// 完整的 Provider 列表(用于故障转移)
|
||||
@@ -62,7 +71,14 @@ impl RequestContext {
|
||||
app_type_str: &'static str,
|
||||
) -> Result<Self, ProxyError> {
|
||||
let start_time = Instant::now();
|
||||
let config = state.config.read().await.clone();
|
||||
|
||||
// 从数据库读取应用级代理配置(per-app)
|
||||
let app_config = state
|
||||
.db
|
||||
.get_proxy_config_for_app(app_type_str)
|
||||
.await
|
||||
.map_err(|e| ProxyError::DatabaseError(e.to_string()))?;
|
||||
|
||||
let current_provider_id =
|
||||
crate::settings::get_current_provider(&app_type).unwrap_or_default();
|
||||
|
||||
@@ -96,7 +112,7 @@ impl RequestContext {
|
||||
|
||||
Ok(Self {
|
||||
start_time,
|
||||
config,
|
||||
app_config,
|
||||
provider,
|
||||
providers,
|
||||
current_provider_id,
|
||||
@@ -135,13 +151,15 @@ impl RequestContext {
|
||||
pub fn create_forwarder(&self, state: &ProxyState) -> RequestForwarder {
|
||||
RequestForwarder::new(
|
||||
state.provider_router.clone(),
|
||||
self.config.request_timeout,
|
||||
self.config.max_retries,
|
||||
self.app_config.non_streaming_timeout as u64,
|
||||
self.app_config.max_retries as u8,
|
||||
state.status.clone(),
|
||||
state.current_providers.clone(),
|
||||
state.failover_manager.clone(),
|
||||
state.app_handle.clone(),
|
||||
self.current_provider_id.clone(),
|
||||
self.app_config.streaming_first_byte_timeout as u64,
|
||||
self.app_config.streaming_idle_timeout as u64,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -157,4 +175,13 @@ impl RequestContext {
|
||||
pub fn latency_ms(&self) -> u64 {
|
||||
self.start_time.elapsed().as_millis() as u64
|
||||
}
|
||||
|
||||
/// 获取流式超时配置
|
||||
#[inline]
|
||||
pub fn streaming_timeout_config(&self) -> StreamingTimeoutConfig {
|
||||
StreamingTimeoutConfig {
|
||||
first_byte_timeout: self.app_config.streaming_first_byte_timeout as u64,
|
||||
idle_timeout: self.app_config.streaming_idle_timeout as u64,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,27 +61,16 @@ pub async fn handle_messages(
|
||||
headers: axum::http::HeaderMap,
|
||||
Json(body): Json<Value>,
|
||||
) -> Result<axum::response::Response, ProxyError> {
|
||||
let ctx = RequestContext::new(&state, &body, AppType::Claude, "Claude", "claude").await?;
|
||||
|
||||
// 检查是否需要格式转换(OpenRouter 等中转服务)
|
||||
let adapter = get_adapter(&AppType::Claude);
|
||||
let needs_transform = adapter.needs_transform(&ctx.provider);
|
||||
let mut ctx = RequestContext::new(&state, &body, AppType::Claude, "Claude", "claude").await?;
|
||||
|
||||
let is_stream = body
|
||||
.get("stream")
|
||||
.and_then(|s| s.as_bool())
|
||||
.unwrap_or(false);
|
||||
|
||||
log::info!(
|
||||
"[Claude] Provider: {}, needs_transform: {}, is_stream: {}",
|
||||
ctx.provider.name,
|
||||
needs_transform,
|
||||
is_stream
|
||||
);
|
||||
|
||||
// 转发请求
|
||||
let forwarder = ctx.create_forwarder(&state);
|
||||
let response = match forwarder
|
||||
let result = match forwarder
|
||||
.forward_with_retry(
|
||||
&AppType::Claude,
|
||||
"/v1/messages",
|
||||
@@ -91,13 +80,30 @@ pub async fn handle_messages(
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(resp) => resp,
|
||||
Err(e) => {
|
||||
log_forward_error(&state, &ctx, is_stream, &e);
|
||||
return Err(e);
|
||||
Ok(result) => result,
|
||||
Err(mut err) => {
|
||||
if let Some(provider) = err.provider.take() {
|
||||
ctx.provider = provider;
|
||||
}
|
||||
log_forward_error(&state, &ctx, is_stream, &err.error);
|
||||
return Err(err.error);
|
||||
}
|
||||
};
|
||||
|
||||
ctx.provider = result.provider;
|
||||
let response = result.response;
|
||||
|
||||
// 检查是否需要格式转换(OpenRouter 等中转服务)
|
||||
let adapter = get_adapter(&AppType::Claude);
|
||||
let needs_transform = adapter.needs_transform(&ctx.provider);
|
||||
|
||||
log::info!(
|
||||
"[Claude] Provider: {}, needs_transform: {}, is_stream: {}",
|
||||
ctx.provider.name,
|
||||
needs_transform,
|
||||
is_stream
|
||||
);
|
||||
|
||||
let status = response.status();
|
||||
log::info!("[Claude] 上游响应状态: {status}");
|
||||
|
||||
@@ -164,10 +170,14 @@ async fn handle_claude_transform(
|
||||
})
|
||||
};
|
||||
|
||||
// 获取流式超时配置
|
||||
let timeout_config = ctx.streaming_timeout_config();
|
||||
|
||||
let logged_stream = create_logged_passthrough_stream(
|
||||
sse_stream,
|
||||
"Claude/OpenRouter",
|
||||
Some(usage_collector),
|
||||
timeout_config,
|
||||
);
|
||||
|
||||
let mut headers = axum::http::HeaderMap::new();
|
||||
@@ -295,7 +305,7 @@ pub async fn handle_chat_completions(
|
||||
) -> Result<axum::response::Response, ProxyError> {
|
||||
log::info!("[Codex] ====== /v1/chat/completions 请求开始 ======");
|
||||
|
||||
let ctx = RequestContext::new(&state, &body, AppType::Codex, "Codex", "codex").await?;
|
||||
let mut ctx = RequestContext::new(&state, &body, AppType::Codex, "Codex", "codex").await?;
|
||||
|
||||
let is_stream = body
|
||||
.get("stream")
|
||||
@@ -309,7 +319,7 @@ pub async fn handle_chat_completions(
|
||||
);
|
||||
|
||||
let forwarder = ctx.create_forwarder(&state);
|
||||
let response = match forwarder
|
||||
let result = match forwarder
|
||||
.forward_with_retry(
|
||||
&AppType::Codex,
|
||||
"/v1/chat/completions",
|
||||
@@ -319,13 +329,19 @@ pub async fn handle_chat_completions(
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(resp) => resp,
|
||||
Err(e) => {
|
||||
log_forward_error(&state, &ctx, is_stream, &e);
|
||||
return Err(e);
|
||||
Ok(result) => result,
|
||||
Err(mut err) => {
|
||||
if let Some(provider) = err.provider.take() {
|
||||
ctx.provider = provider;
|
||||
}
|
||||
log_forward_error(&state, &ctx, is_stream, &err.error);
|
||||
return Err(err.error);
|
||||
}
|
||||
};
|
||||
|
||||
ctx.provider = result.provider;
|
||||
let response = result.response;
|
||||
|
||||
log::info!("[Codex] 上游响应状态: {}", response.status());
|
||||
|
||||
process_response(response, &ctx, &state, &OPENAI_PARSER_CONFIG).await
|
||||
@@ -337,7 +353,7 @@ pub async fn handle_responses(
|
||||
headers: axum::http::HeaderMap,
|
||||
Json(body): Json<Value>,
|
||||
) -> Result<axum::response::Response, ProxyError> {
|
||||
let ctx = RequestContext::new(&state, &body, AppType::Codex, "Codex", "codex").await?;
|
||||
let mut ctx = RequestContext::new(&state, &body, AppType::Codex, "Codex", "codex").await?;
|
||||
|
||||
let is_stream = body
|
||||
.get("stream")
|
||||
@@ -345,7 +361,7 @@ pub async fn handle_responses(
|
||||
.unwrap_or(false);
|
||||
|
||||
let forwarder = ctx.create_forwarder(&state);
|
||||
let response = match forwarder
|
||||
let result = match forwarder
|
||||
.forward_with_retry(
|
||||
&AppType::Codex,
|
||||
"/v1/responses",
|
||||
@@ -355,13 +371,19 @@ pub async fn handle_responses(
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(resp) => resp,
|
||||
Err(e) => {
|
||||
log_forward_error(&state, &ctx, is_stream, &e);
|
||||
return Err(e);
|
||||
Ok(result) => result,
|
||||
Err(mut err) => {
|
||||
if let Some(provider) = err.provider.take() {
|
||||
ctx.provider = provider;
|
||||
}
|
||||
log_forward_error(&state, &ctx, is_stream, &err.error);
|
||||
return Err(err.error);
|
||||
}
|
||||
};
|
||||
|
||||
ctx.provider = result.provider;
|
||||
let response = result.response;
|
||||
|
||||
log::info!("[Codex] 上游响应状态: {}", response.status());
|
||||
|
||||
process_response(response, &ctx, &state, &CODEX_PARSER_CONFIG).await
|
||||
@@ -379,7 +401,7 @@ pub async fn handle_gemini(
|
||||
Json(body): Json<Value>,
|
||||
) -> Result<axum::response::Response, ProxyError> {
|
||||
// Gemini 的模型名称在 URI 中
|
||||
let ctx = RequestContext::new(&state, &body, AppType::Gemini, "Gemini", "gemini")
|
||||
let mut ctx = RequestContext::new(&state, &body, AppType::Gemini, "Gemini", "gemini")
|
||||
.await?
|
||||
.with_model_from_uri(&uri);
|
||||
|
||||
@@ -397,7 +419,7 @@ pub async fn handle_gemini(
|
||||
.unwrap_or(false);
|
||||
|
||||
let forwarder = ctx.create_forwarder(&state);
|
||||
let response = match forwarder
|
||||
let result = match forwarder
|
||||
.forward_with_retry(
|
||||
&AppType::Gemini,
|
||||
endpoint,
|
||||
@@ -407,13 +429,19 @@ pub async fn handle_gemini(
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(resp) => resp,
|
||||
Err(e) => {
|
||||
log_forward_error(&state, &ctx, is_stream, &e);
|
||||
return Err(e);
|
||||
Ok(result) => result,
|
||||
Err(mut err) => {
|
||||
if let Some(provider) = err.provider.take() {
|
||||
ctx.provider = provider;
|
||||
}
|
||||
log_forward_error(&state, &ctx, is_stream, &err.error);
|
||||
return Err(err.error);
|
||||
}
|
||||
};
|
||||
|
||||
ctx.provider = result.provider;
|
||||
let response = result.response;
|
||||
|
||||
log::info!("[Gemini] 上游响应状态: {}", response.status());
|
||||
|
||||
process_response(response, &ctx, &state, &GEMINI_PARSER_CONFIG).await
|
||||
|
||||
@@ -11,6 +11,7 @@ pub mod handler_config;
|
||||
pub mod handler_context;
|
||||
mod handlers;
|
||||
mod health;
|
||||
pub mod model_mapper;
|
||||
pub mod provider_router;
|
||||
pub mod providers;
|
||||
pub mod response_handler;
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
//! 模型映射模块
|
||||
//!
|
||||
//! 在请求转发前,根据 Provider 配置替换请求中的模型名称
|
||||
|
||||
use crate::provider::Provider;
|
||||
use serde_json::Value;
|
||||
|
||||
/// 模型映射配置
|
||||
pub struct ModelMapping {
|
||||
pub haiku_model: Option<String>,
|
||||
pub sonnet_model: Option<String>,
|
||||
pub opus_model: Option<String>,
|
||||
pub default_model: Option<String>,
|
||||
pub reasoning_model: Option<String>,
|
||||
}
|
||||
|
||||
impl ModelMapping {
|
||||
/// 从 Provider 配置中提取模型映射
|
||||
pub fn from_provider(provider: &Provider) -> Self {
|
||||
let env = provider.settings_config.get("env");
|
||||
|
||||
Self {
|
||||
haiku_model: env
|
||||
.and_then(|e| e.get("ANTHROPIC_DEFAULT_HAIKU_MODEL"))
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(String::from),
|
||||
sonnet_model: env
|
||||
.and_then(|e| e.get("ANTHROPIC_DEFAULT_SONNET_MODEL"))
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(String::from),
|
||||
opus_model: env
|
||||
.and_then(|e| e.get("ANTHROPIC_DEFAULT_OPUS_MODEL"))
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(String::from),
|
||||
default_model: env
|
||||
.and_then(|e| e.get("ANTHROPIC_MODEL"))
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(String::from),
|
||||
reasoning_model: env
|
||||
.and_then(|e| e.get("ANTHROPIC_REASONING_MODEL"))
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(String::from),
|
||||
}
|
||||
}
|
||||
|
||||
/// 检查是否配置了任何模型映射
|
||||
pub fn has_mapping(&self) -> bool {
|
||||
self.haiku_model.is_some()
|
||||
|| self.sonnet_model.is_some()
|
||||
|| self.opus_model.is_some()
|
||||
|| self.default_model.is_some()
|
||||
}
|
||||
|
||||
/// 根据原始模型名称获取映射后的模型
|
||||
pub fn map_model(&self, original_model: &str, has_thinking: bool) -> String {
|
||||
let model_lower = original_model.to_lowercase();
|
||||
|
||||
// 1. thinking 模式优先使用推理模型
|
||||
if has_thinking {
|
||||
if let Some(ref m) = self.reasoning_model {
|
||||
return m.clone();
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 按模型类型匹配
|
||||
if model_lower.contains("haiku") {
|
||||
if let Some(ref m) = self.haiku_model {
|
||||
return m.clone();
|
||||
}
|
||||
}
|
||||
if model_lower.contains("opus") {
|
||||
if let Some(ref m) = self.opus_model {
|
||||
return m.clone();
|
||||
}
|
||||
}
|
||||
if model_lower.contains("sonnet") {
|
||||
if let Some(ref m) = self.sonnet_model {
|
||||
return m.clone();
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 默认模型
|
||||
if let Some(ref m) = self.default_model {
|
||||
return m.clone();
|
||||
}
|
||||
|
||||
// 4. 无映射,保持原样
|
||||
original_model.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// 检测请求是否启用了 thinking 模式
|
||||
pub fn has_thinking_enabled(body: &Value) -> bool {
|
||||
body.get("thinking")
|
||||
.and_then(|v| v.as_object())
|
||||
.and_then(|o| o.get("type"))
|
||||
.and_then(|t| t.as_str())
|
||||
== Some("enabled")
|
||||
}
|
||||
|
||||
/// 对请求体应用模型映射
|
||||
///
|
||||
/// 返回 (映射后的请求体, 原始模型名, 映射后模型名)
|
||||
pub fn apply_model_mapping(
|
||||
mut body: Value,
|
||||
provider: &Provider,
|
||||
) -> (Value, Option<String>, Option<String>) {
|
||||
let mapping = ModelMapping::from_provider(provider);
|
||||
|
||||
// 如果没有配置映射,直接返回
|
||||
if !mapping.has_mapping() {
|
||||
let original = body.get("model").and_then(|m| m.as_str()).map(String::from);
|
||||
return (body, original, None);
|
||||
}
|
||||
|
||||
// 提取原始模型名
|
||||
let original_model = body.get("model").and_then(|m| m.as_str()).map(String::from);
|
||||
|
||||
if let Some(ref original) = original_model {
|
||||
let has_thinking = has_thinking_enabled(&body);
|
||||
let mapped = mapping.map_model(original, has_thinking);
|
||||
|
||||
if mapped != *original {
|
||||
log::info!("[ModelMapper] 模型映射: {original} → {mapped}");
|
||||
body["model"] = serde_json::json!(mapped);
|
||||
return (body, Some(original.clone()), Some(mapped));
|
||||
}
|
||||
}
|
||||
|
||||
(body, original_model, None)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn create_provider_with_mapping() -> Provider {
|
||||
Provider {
|
||||
id: "test".to_string(),
|
||||
name: "Test".to_string(),
|
||||
settings_config: json!({
|
||||
"env": {
|
||||
"ANTHROPIC_MODEL": "default-model",
|
||||
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "haiku-mapped",
|
||||
"ANTHROPIC_DEFAULT_SONNET_MODEL": "sonnet-mapped",
|
||||
"ANTHROPIC_DEFAULT_OPUS_MODEL": "opus-mapped",
|
||||
"ANTHROPIC_REASONING_MODEL": "reasoning-model"
|
||||
}
|
||||
}),
|
||||
website_url: None,
|
||||
category: None,
|
||||
created_at: None,
|
||||
sort_index: None,
|
||||
notes: None,
|
||||
meta: None,
|
||||
icon: None,
|
||||
icon_color: None,
|
||||
in_failover_queue: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn create_provider_without_mapping() -> Provider {
|
||||
Provider {
|
||||
id: "test".to_string(),
|
||||
name: "Test".to_string(),
|
||||
settings_config: json!({}),
|
||||
website_url: None,
|
||||
category: None,
|
||||
created_at: None,
|
||||
sort_index: None,
|
||||
notes: None,
|
||||
meta: None,
|
||||
icon: None,
|
||||
icon_color: None,
|
||||
in_failover_queue: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sonnet_mapping() {
|
||||
let provider = create_provider_with_mapping();
|
||||
let body = json!({"model": "claude-sonnet-4-5-20250929"});
|
||||
let (result, original, mapped) = apply_model_mapping(body, &provider);
|
||||
assert_eq!(result["model"], "sonnet-mapped");
|
||||
assert_eq!(original, Some("claude-sonnet-4-5-20250929".to_string()));
|
||||
assert_eq!(mapped, Some("sonnet-mapped".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_haiku_mapping() {
|
||||
let provider = create_provider_with_mapping();
|
||||
let body = json!({"model": "claude-haiku-4-5"});
|
||||
let (result, _, mapped) = apply_model_mapping(body, &provider);
|
||||
assert_eq!(result["model"], "haiku-mapped");
|
||||
assert_eq!(mapped, Some("haiku-mapped".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_opus_mapping() {
|
||||
let provider = create_provider_with_mapping();
|
||||
let body = json!({"model": "claude-opus-4-5"});
|
||||
let (result, _, mapped) = apply_model_mapping(body, &provider);
|
||||
assert_eq!(result["model"], "opus-mapped");
|
||||
assert_eq!(mapped, Some("opus-mapped".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_thinking_mode() {
|
||||
let provider = create_provider_with_mapping();
|
||||
let body = json!({
|
||||
"model": "claude-sonnet-4-5",
|
||||
"thinking": {"type": "enabled"}
|
||||
});
|
||||
let (result, _, mapped) = apply_model_mapping(body, &provider);
|
||||
assert_eq!(result["model"], "reasoning-model");
|
||||
assert_eq!(mapped, Some("reasoning-model".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_thinking_disabled() {
|
||||
let provider = create_provider_with_mapping();
|
||||
let body = json!({
|
||||
"model": "claude-sonnet-4-5",
|
||||
"thinking": {"type": "disabled"}
|
||||
});
|
||||
let (result, _, mapped) = apply_model_mapping(body, &provider);
|
||||
assert_eq!(result["model"], "sonnet-mapped");
|
||||
assert_eq!(mapped, Some("sonnet-mapped".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_unknown_model_uses_default() {
|
||||
let provider = create_provider_with_mapping();
|
||||
let body = json!({"model": "some-unknown-model"});
|
||||
let (result, _, mapped) = apply_model_mapping(body, &provider);
|
||||
assert_eq!(result["model"], "default-model");
|
||||
assert_eq!(mapped, Some("default-model".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_mapping_configured() {
|
||||
let provider = create_provider_without_mapping();
|
||||
let body = json!({"model": "claude-sonnet-4-5"});
|
||||
let (result, original, mapped) = apply_model_mapping(body, &provider);
|
||||
assert_eq!(result["model"], "claude-sonnet-4-5");
|
||||
assert_eq!(original, Some("claude-sonnet-4-5".to_string()));
|
||||
assert!(mapped.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_case_insensitive() {
|
||||
let provider = create_provider_with_mapping();
|
||||
let body = json!({"model": "Claude-SONNET-4-5"});
|
||||
let (result, _, mapped) = apply_model_mapping(body, &provider);
|
||||
assert_eq!(result["model"], "sonnet-mapped");
|
||||
assert_eq!(mapped, Some("sonnet-mapped".to_string()));
|
||||
}
|
||||
}
|
||||
@@ -30,87 +30,75 @@ impl ProviderRouter {
|
||||
/// 选择可用的供应商(支持故障转移)
|
||||
///
|
||||
/// 返回按优先级排序的可用供应商列表:
|
||||
/// 1. 当前供应商(is_current=true)始终第一位
|
||||
/// 2. 故障转移队列中的其他供应商(按 queue_order 排序)- 仅当自动故障转移开关开启时
|
||||
/// 3. 只返回熔断器未打开的供应商
|
||||
/// - 故障转移关闭时:仅返回当前供应商
|
||||
/// - 故障转移开启时:完全按照故障转移队列顺序返回,忽略当前供应商设置
|
||||
pub async fn select_providers(&self, app_type: &str) -> Result<Vec<Provider>, AppError> {
|
||||
let mut result = Vec::new();
|
||||
let all_providers = self.db.get_all_providers(app_type)?;
|
||||
|
||||
// 检查自动故障转移总开关是否开启
|
||||
let auto_failover_enabled = self
|
||||
.db
|
||||
.get_setting("auto_failover_enabled")
|
||||
.map(|v| v.map(|s| s == "true").unwrap_or(false)) // 默认关闭
|
||||
.unwrap_or(false);
|
||||
// 检查该应用的自动故障转移开关是否开启(从 proxy_config 表读取)
|
||||
let auto_failover_enabled = match self.db.get_proxy_config_for_app(app_type).await {
|
||||
Ok(config) => {
|
||||
let enabled = config.auto_failover_enabled;
|
||||
log::info!("[{app_type}] Failover enabled from proxy_config: {enabled}");
|
||||
enabled
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!(
|
||||
"[{app_type}] Failed to read proxy_config for auto_failover_enabled: {e}, defaulting to disabled"
|
||||
);
|
||||
false
|
||||
}
|
||||
};
|
||||
|
||||
// 1. 当前供应商始终第一位
|
||||
if let Some(current_id) = self.db.get_current_provider(app_type)? {
|
||||
if let Some(current) = all_providers.get(¤t_id) {
|
||||
let circuit_key = format!("{}:{}", app_type, current.id);
|
||||
if auto_failover_enabled {
|
||||
// 故障转移开启:使用 in_failover_queue 标记的供应商,按 sort_index 排序
|
||||
let failover_providers = self.db.get_failover_providers(app_type)?;
|
||||
log::info!(
|
||||
"[{}] Failover enabled, using queue order ({} items)",
|
||||
app_type,
|
||||
failover_providers.len()
|
||||
);
|
||||
|
||||
for provider in failover_providers {
|
||||
// 检查熔断器状态
|
||||
let circuit_key = format!("{}:{}", app_type, provider.id);
|
||||
let breaker = self.get_or_create_circuit_breaker(&circuit_key).await;
|
||||
|
||||
if breaker.is_available().await {
|
||||
log::info!(
|
||||
"[{}] Current provider available: {} ({})",
|
||||
"[{}] Queue provider available: {} ({}) at sort_index {:?}",
|
||||
app_type,
|
||||
provider.name,
|
||||
provider.id,
|
||||
provider.sort_index
|
||||
);
|
||||
result.push(provider);
|
||||
} else {
|
||||
log::debug!(
|
||||
"[{}] Queue provider {} circuit breaker open, skipping",
|
||||
app_type,
|
||||
provider.name
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 故障转移关闭:仅使用当前供应商,跳过熔断器检查
|
||||
// 原因:单 Provider 场景下,熔断器打开会导致所有请求失败,用户体验差
|
||||
log::info!("[{app_type}] Failover disabled, using current provider only (circuit breaker bypassed)");
|
||||
|
||||
if let Some(current_id) = self.db.get_current_provider(app_type)? {
|
||||
if let Some(current) = self.db.get_provider_by_id(¤t_id, app_type)? {
|
||||
log::info!(
|
||||
"[{}] Current provider: {} ({})",
|
||||
app_type,
|
||||
current.name,
|
||||
current.id
|
||||
);
|
||||
result.push(current.clone());
|
||||
} else {
|
||||
log::warn!(
|
||||
"[{}] Current provider {} circuit breaker open, checking failover queue",
|
||||
app_type,
|
||||
current.name
|
||||
);
|
||||
result.push(current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 获取故障转移队列中的供应商(仅当自动故障转移开关开启时)
|
||||
if auto_failover_enabled {
|
||||
let queue = self.db.get_failover_queue(app_type)?;
|
||||
|
||||
for item in queue {
|
||||
// 跳过已添加的当前供应商
|
||||
if result.iter().any(|p| p.id == item.provider_id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 跳过禁用的队列项
|
||||
if !item.enabled {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 获取供应商信息
|
||||
if let Some(provider) = all_providers.get(&item.provider_id) {
|
||||
// 检查熔断器状态
|
||||
let circuit_key = format!("{}:{}", app_type, provider.id);
|
||||
let breaker = self.get_or_create_circuit_breaker(&circuit_key).await;
|
||||
|
||||
if breaker.is_available().await {
|
||||
log::info!(
|
||||
"[{}] Failover provider available: {} ({}) at queue position {}",
|
||||
app_type,
|
||||
provider.name,
|
||||
provider.id,
|
||||
item.queue_order
|
||||
);
|
||||
result.push(provider.clone());
|
||||
} else {
|
||||
log::debug!(
|
||||
"[{}] Failover provider {} circuit breaker open, skipping",
|
||||
app_type,
|
||||
provider.name
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log::info!("[{app_type}] Auto-failover disabled, using only current provider");
|
||||
}
|
||||
|
||||
if result.is_empty() {
|
||||
return Err(AppError::Config(format!(
|
||||
"No available provider for {app_type} (all circuit breakers open or no providers configured)"
|
||||
@@ -118,7 +106,7 @@ impl ProviderRouter {
|
||||
}
|
||||
|
||||
log::info!(
|
||||
"[{}] Failover chain: {} provider(s) available",
|
||||
"[{}] Provider chain: {} provider(s) available",
|
||||
app_type,
|
||||
result.len()
|
||||
);
|
||||
@@ -149,9 +137,16 @@ impl ProviderRouter {
|
||||
success: bool,
|
||||
error_msg: Option<String>,
|
||||
) -> Result<(), AppError> {
|
||||
// 1. 获取熔断器配置(用于更新健康状态和判断是否禁用)
|
||||
let config = self.db.get_circuit_breaker_config().await.ok();
|
||||
let failure_threshold = config.map(|c| c.failure_threshold).unwrap_or(5);
|
||||
// 1. 按应用独立获取熔断器配置(用于更新健康状态和判断是否禁用)
|
||||
let failure_threshold = match self.db.get_proxy_config_for_app(app_type).await {
|
||||
Ok(app_config) => app_config.circuit_failure_threshold,
|
||||
Err(e) => {
|
||||
log::warn!(
|
||||
"Failed to load circuit config for {app_type}, using default threshold: {e}"
|
||||
);
|
||||
5 // 默认值
|
||||
}
|
||||
};
|
||||
|
||||
// 2. 更新熔断器状态
|
||||
let circuit_key = format!("{app_type}:{provider_id}");
|
||||
@@ -248,12 +243,34 @@ impl ProviderRouter {
|
||||
return breaker.clone();
|
||||
}
|
||||
|
||||
// 从数据库加载配置
|
||||
let config = self
|
||||
.db
|
||||
.get_circuit_breaker_config()
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
// 从 key 中提取 app_type (格式: "app_type:provider_id")
|
||||
let app_type = key.split(':').next().unwrap_or("claude");
|
||||
|
||||
// 按应用独立读取熔断器配置
|
||||
let config = match self.db.get_proxy_config_for_app(app_type).await {
|
||||
Ok(app_config) => {
|
||||
log::debug!(
|
||||
"Loading circuit breaker config for {key} (app={app_type}): \
|
||||
failure_threshold={}, success_threshold={}, timeout={}s",
|
||||
app_config.circuit_failure_threshold,
|
||||
app_config.circuit_success_threshold,
|
||||
app_config.circuit_timeout_seconds
|
||||
);
|
||||
crate::proxy::circuit_breaker::CircuitBreakerConfig {
|
||||
failure_threshold: app_config.circuit_failure_threshold,
|
||||
success_threshold: app_config.circuit_success_threshold,
|
||||
timeout_seconds: app_config.circuit_timeout_seconds as u64,
|
||||
error_rate_threshold: app_config.circuit_error_rate_threshold,
|
||||
min_requests: app_config.circuit_min_requests,
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!(
|
||||
"Failed to load circuit breaker config for {key} (app={app_type}): {e}, using default"
|
||||
);
|
||||
crate::proxy::circuit_breaker::CircuitBreakerConfig::default()
|
||||
}
|
||||
};
|
||||
|
||||
log::debug!("Creating new circuit breaker for {key} with config: {config:?}");
|
||||
|
||||
@@ -275,25 +292,14 @@ mod tests {
|
||||
let db = Arc::new(Database::memory().unwrap());
|
||||
let router = ProviderRouter::new(db);
|
||||
|
||||
// 测试创建熔断器
|
||||
let breaker = router.get_or_create_circuit_breaker("claude:test").await;
|
||||
assert!(breaker.allow_request().await.allowed);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn select_providers_does_not_consume_half_open_permit() {
|
||||
async fn test_failover_disabled_uses_current_provider() {
|
||||
let db = Arc::new(Database::memory().unwrap());
|
||||
|
||||
// 配置:让熔断器 Open 后立刻进入 HalfOpen(timeout_seconds=0),并用 1 次失败就打开熔断器
|
||||
db.update_circuit_breaker_config(&CircuitBreakerConfig {
|
||||
failure_threshold: 1,
|
||||
timeout_seconds: 0,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// 准备 2 个 Provider:A(当前)+ B(队列)
|
||||
let provider_a =
|
||||
Provider::with_id("a".to_string(), "Provider A".to_string(), json!({}), None);
|
||||
let provider_b =
|
||||
@@ -304,19 +310,84 @@ mod tests {
|
||||
db.set_current_provider("claude", "a").unwrap();
|
||||
db.add_to_failover_queue("claude", "b").unwrap();
|
||||
|
||||
let router = ProviderRouter::new(db.clone());
|
||||
let providers = router.select_providers("claude").await.unwrap();
|
||||
|
||||
assert_eq!(providers.len(), 1);
|
||||
assert_eq!(providers[0].id, "a");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_failover_enabled_uses_queue_order() {
|
||||
let db = Arc::new(Database::memory().unwrap());
|
||||
|
||||
// 设置 sort_index 来控制顺序:b=1, a=2
|
||||
let mut provider_a =
|
||||
Provider::with_id("a".to_string(), "Provider A".to_string(), json!({}), None);
|
||||
provider_a.sort_index = Some(2);
|
||||
let mut provider_b =
|
||||
Provider::with_id("b".to_string(), "Provider B".to_string(), json!({}), None);
|
||||
provider_b.sort_index = Some(1);
|
||||
|
||||
db.save_provider("claude", &provider_a).unwrap();
|
||||
db.save_provider("claude", &provider_b).unwrap();
|
||||
db.set_current_provider("claude", "a").unwrap();
|
||||
|
||||
db.add_to_failover_queue("claude", "b").unwrap();
|
||||
db.add_to_failover_queue("claude", "a").unwrap();
|
||||
|
||||
// 启用自动故障转移(使用新的 proxy_config API)
|
||||
let mut config = db.get_proxy_config_for_app("claude").await.unwrap();
|
||||
config.auto_failover_enabled = true;
|
||||
db.update_proxy_config_for_app(config).await.unwrap();
|
||||
|
||||
let router = ProviderRouter::new(db.clone());
|
||||
let providers = router.select_providers("claude").await.unwrap();
|
||||
|
||||
assert_eq!(providers.len(), 2);
|
||||
// 按 sort_index 排序:b(1) 在前,a(2) 在后
|
||||
assert_eq!(providers[0].id, "b");
|
||||
assert_eq!(providers[1].id, "a");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_select_providers_does_not_consume_half_open_permit() {
|
||||
let db = Arc::new(Database::memory().unwrap());
|
||||
|
||||
db.update_circuit_breaker_config(&CircuitBreakerConfig {
|
||||
failure_threshold: 1,
|
||||
timeout_seconds: 0,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let provider_a =
|
||||
Provider::with_id("a".to_string(), "Provider A".to_string(), json!({}), None);
|
||||
let provider_b =
|
||||
Provider::with_id("b".to_string(), "Provider B".to_string(), json!({}), None);
|
||||
|
||||
db.save_provider("claude", &provider_a).unwrap();
|
||||
db.save_provider("claude", &provider_b).unwrap();
|
||||
|
||||
db.add_to_failover_queue("claude", "a").unwrap();
|
||||
db.add_to_failover_queue("claude", "b").unwrap();
|
||||
|
||||
// 启用自动故障转移(使用新的 proxy_config API)
|
||||
let mut config = db.get_proxy_config_for_app("claude").await.unwrap();
|
||||
config.auto_failover_enabled = true;
|
||||
db.update_proxy_config_for_app(config).await.unwrap();
|
||||
|
||||
let router = ProviderRouter::new(db.clone());
|
||||
|
||||
// 让 B 进入 Open 状态(failure_threshold=1)
|
||||
router
|
||||
.record_result("b", "claude", false, false, Some("fail".to_string()))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// select_providers 只做“可用性判断”,不应占用 HalfOpen 探测名额
|
||||
let providers = router.select_providers("claude").await.unwrap();
|
||||
assert_eq!(providers.len(), 2);
|
||||
|
||||
// 如果 select_providers 错误地消耗了 HalfOpen 名额,这里会返回 false(被限流拒绝)
|
||||
assert!(router.allow_provider_request("b", "claude").await.allowed);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +48,24 @@ impl ClaudeAdapter {
|
||||
false
|
||||
}
|
||||
|
||||
/// 检测 OpenRouter 是否启用兼容模式
|
||||
fn is_openrouter_compat_enabled(&self, provider: &Provider) -> bool {
|
||||
if !self.is_openrouter(provider) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let raw = provider.settings_config.get("openrouter_compat_mode");
|
||||
match raw {
|
||||
Some(serde_json::Value::Bool(enabled)) => *enabled,
|
||||
Some(serde_json::Value::Number(num)) => num.as_i64().unwrap_or(0) != 0,
|
||||
Some(serde_json::Value::String(value)) => {
|
||||
let normalized = value.trim().to_lowercase();
|
||||
normalized == "true" || normalized == "1"
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// 检测是否为仅 Bearer 认证模式
|
||||
fn is_bearer_only_mode(&self, provider: &Provider) -> bool {
|
||||
// 检查 settings_config 中的 auth_mode
|
||||
@@ -197,11 +215,7 @@ impl ProviderAdapter for ClaudeAdapter {
|
||||
// 映射到 `/v1/chat/completions`,并做 Anthropic ↔ OpenAI 的格式转换。
|
||||
//
|
||||
// 现在 OpenRouter 已推出 Claude Code 兼容接口,因此默认直接透传 endpoint。
|
||||
// 如需回退旧逻辑,可恢复下面这段分支:
|
||||
//
|
||||
// if base_url.contains("openrouter.ai") {
|
||||
// return format!("{}/v1/chat/completions", base_url.trim_end_matches('/'));
|
||||
// }
|
||||
// 如需回退旧逻辑,可在 forwarder 中根据 needs_transform 改写 endpoint。
|
||||
|
||||
format!(
|
||||
"{}/{}",
|
||||
@@ -235,8 +249,7 @@ impl ProviderAdapter for ClaudeAdapter {
|
||||
// Anthropic ↔ OpenAI 的格式转换。
|
||||
//
|
||||
// 如果未来需要回退到旧的 OpenAI Chat Completions 方案,可恢复下面这行:
|
||||
// self.is_openrouter(_provider)
|
||||
false
|
||||
self.is_openrouter_compat_enabled(_provider)
|
||||
}
|
||||
|
||||
fn transform_request(
|
||||
@@ -270,6 +283,7 @@ mod tests {
|
||||
meta: None,
|
||||
icon: None,
|
||||
icon_color: None,
|
||||
in_failover_queue: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -429,6 +443,14 @@ mod tests {
|
||||
"ANTHROPIC_BASE_URL": "https://openrouter.ai/api"
|
||||
}
|
||||
}));
|
||||
assert!(!adapter.needs_transform(&openrouter_provider));
|
||||
assert!(adapter.needs_transform(&openrouter_provider));
|
||||
|
||||
let openrouter_disabled = create_provider(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://openrouter.ai/api"
|
||||
},
|
||||
"openrouter_compat_mode": false
|
||||
}));
|
||||
assert!(!adapter.needs_transform(&openrouter_disabled));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,6 +174,7 @@ mod tests {
|
||||
meta: None,
|
||||
icon: None,
|
||||
icon_color: None,
|
||||
in_failover_queue: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -250,6 +250,7 @@ mod tests {
|
||||
meta: None,
|
||||
icon: None,
|
||||
icon_color: None,
|
||||
in_failover_queue: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -209,6 +209,7 @@ mod tests {
|
||||
meta: None,
|
||||
icon: None,
|
||||
icon_color: None,
|
||||
in_failover_queue: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -394,6 +394,7 @@ mod tests {
|
||||
meta: None,
|
||||
icon: None,
|
||||
icon_color: None,
|
||||
in_failover_queue: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,11 @@
|
||||
//! 统一处理流式和非流式 API 响应
|
||||
|
||||
use super::{
|
||||
handler_config::UsageParserConfig, handler_context::RequestContext, server::ProxyState,
|
||||
usage::parser::TokenUsage, ProxyError,
|
||||
handler_config::UsageParserConfig,
|
||||
handler_context::{RequestContext, StreamingTimeoutConfig},
|
||||
server::ProxyState,
|
||||
usage::parser::TokenUsage,
|
||||
ProxyError,
|
||||
};
|
||||
use axum::response::Response;
|
||||
use bytes::Bytes;
|
||||
@@ -17,6 +20,7 @@ use std::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
@@ -60,8 +64,12 @@ pub async fn handle_streaming(
|
||||
// 创建使用量收集器
|
||||
let usage_collector = create_usage_collector(ctx, state, status.as_u16(), parser_config);
|
||||
|
||||
// 创建带日志的透传流
|
||||
let logged_stream = create_logged_passthrough_stream(stream, ctx.tag, Some(usage_collector));
|
||||
// 获取流式超时配置
|
||||
let timeout_config = ctx.streaming_timeout_config();
|
||||
|
||||
// 创建带日志和超时的透传流
|
||||
let logged_stream =
|
||||
create_logged_passthrough_stream(stream, ctx.tag, Some(usage_collector), timeout_config);
|
||||
|
||||
let body = axum::body::Body::from_stream(logged_stream);
|
||||
builder.body(body).unwrap()
|
||||
@@ -93,12 +101,16 @@ pub async fn handle_non_streaming(
|
||||
|
||||
// 解析使用量
|
||||
if let Some(usage) = (parser_config.response_parser)(&json_value) {
|
||||
let model = json_value
|
||||
.get("model")
|
||||
.and_then(|m| m.as_str())
|
||||
.unwrap_or(&ctx.request_model);
|
||||
// 优先使用 usage 中解析出的模型名称,其次使用响应中的 model 字段,最后回退到请求模型
|
||||
let model = if let Some(ref m) = usage.model {
|
||||
m.clone()
|
||||
} else if let Some(m) = json_value.get("model").and_then(|m| m.as_str()) {
|
||||
m.to_string()
|
||||
} else {
|
||||
ctx.request_model.clone()
|
||||
};
|
||||
|
||||
spawn_log_usage(state, ctx, usage, model, status.as_u16(), false);
|
||||
spawn_log_usage(state, ctx, usage, &model, status.as_u16(), false);
|
||||
} else {
|
||||
log::debug!(
|
||||
"[{}] 未能解析 usage 信息,跳过记录",
|
||||
@@ -344,21 +356,60 @@ async fn log_usage_internal(
|
||||
}
|
||||
}
|
||||
|
||||
/// 创建带日志记录的透传流
|
||||
/// 创建带日志记录和超时控制的透传流
|
||||
pub fn create_logged_passthrough_stream(
|
||||
stream: impl Stream<Item = Result<Bytes, std::io::Error>> + Send + 'static,
|
||||
tag: &'static str,
|
||||
usage_collector: Option<SseUsageCollector>,
|
||||
timeout_config: StreamingTimeoutConfig,
|
||||
) -> impl Stream<Item = Result<Bytes, std::io::Error>> + Send {
|
||||
async_stream::stream! {
|
||||
let mut buffer = String::new();
|
||||
let mut collector = usage_collector;
|
||||
let mut is_first_chunk = true;
|
||||
|
||||
// 超时配置
|
||||
let first_byte_timeout = if timeout_config.first_byte_timeout > 0 {
|
||||
Some(Duration::from_secs(timeout_config.first_byte_timeout))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let idle_timeout = if timeout_config.idle_timeout > 0 {
|
||||
Some(Duration::from_secs(timeout_config.idle_timeout))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
tokio::pin!(stream);
|
||||
|
||||
while let Some(chunk) = stream.next().await {
|
||||
match chunk {
|
||||
Ok(bytes) => {
|
||||
loop {
|
||||
// 选择超时时间:首字节超时或静默期超时
|
||||
let timeout_duration = if is_first_chunk {
|
||||
first_byte_timeout
|
||||
} else {
|
||||
idle_timeout
|
||||
};
|
||||
|
||||
let chunk_result = match timeout_duration {
|
||||
Some(duration) => {
|
||||
match tokio::time::timeout(duration, stream.next()).await {
|
||||
Ok(Some(chunk)) => Some(chunk),
|
||||
Ok(None) => None, // 流结束
|
||||
Err(_) => {
|
||||
// 超时
|
||||
let timeout_type = if is_first_chunk { "首字节" } else { "静默期" };
|
||||
log::error!("[{tag}] 流式响应{}超时 ({}秒)", timeout_type, duration.as_secs());
|
||||
yield Err(std::io::Error::other(format!("流式响应{timeout_type}超时")));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
None => stream.next().await, // 无超时限制
|
||||
};
|
||||
|
||||
match chunk_result {
|
||||
Some(Ok(bytes)) => {
|
||||
is_first_chunk = false;
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
buffer.push_str(&text);
|
||||
|
||||
@@ -394,11 +445,15 @@ pub fn create_logged_passthrough_stream(
|
||||
|
||||
yield Ok(bytes);
|
||||
}
|
||||
Err(e) => {
|
||||
Some(Err(e)) => {
|
||||
log::error!("[{tag}] 流错误: {e}");
|
||||
yield Err(std::io::Error::other(e.to_string()));
|
||||
break;
|
||||
}
|
||||
None => {
|
||||
// 流正常结束
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,13 +9,34 @@ pub struct ProxyConfig {
|
||||
pub listen_port: u16,
|
||||
/// 最大重试次数
|
||||
pub max_retries: u8,
|
||||
/// 请求超时时间(秒)
|
||||
/// 请求超时时间(秒)- 已废弃,保留兼容
|
||||
pub request_timeout: u64,
|
||||
/// 是否启用日志
|
||||
pub enable_logging: bool,
|
||||
/// 是否正在接管 Live 配置
|
||||
#[serde(default)]
|
||||
pub live_takeover_active: bool,
|
||||
/// 流式首字超时(秒)- 等待首个数据块的最大时间
|
||||
#[serde(default = "default_streaming_first_byte_timeout")]
|
||||
pub streaming_first_byte_timeout: u64,
|
||||
/// 流式静默超时(秒)- 两个数据块之间的最大间隔
|
||||
#[serde(default = "default_streaming_idle_timeout")]
|
||||
pub streaming_idle_timeout: u64,
|
||||
/// 非流式总超时(秒)- 非流式请求的总超时时间
|
||||
#[serde(default = "default_non_streaming_timeout")]
|
||||
pub non_streaming_timeout: u64,
|
||||
}
|
||||
|
||||
fn default_streaming_first_byte_timeout() -> u64 {
|
||||
30
|
||||
}
|
||||
|
||||
fn default_streaming_idle_timeout() -> u64 {
|
||||
60
|
||||
}
|
||||
|
||||
fn default_non_streaming_timeout() -> u64 {
|
||||
600
|
||||
}
|
||||
|
||||
impl Default for ProxyConfig {
|
||||
@@ -27,6 +48,9 @@ impl Default for ProxyConfig {
|
||||
request_timeout: 300,
|
||||
enable_logging: true,
|
||||
live_takeover_active: false,
|
||||
streaming_first_byte_timeout: 30,
|
||||
streaming_idle_timeout: 60,
|
||||
non_streaming_timeout: 600,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -123,3 +147,47 @@ pub struct LiveBackup {
|
||||
/// 备份时间
|
||||
pub backed_up_at: String,
|
||||
}
|
||||
|
||||
/// 全局代理配置(统一字段,三行镜像)
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GlobalProxyConfig {
|
||||
/// 代理总开关
|
||||
pub proxy_enabled: bool,
|
||||
/// 监听地址
|
||||
pub listen_address: String,
|
||||
/// 监听端口
|
||||
pub listen_port: u16,
|
||||
/// 是否启用日志
|
||||
pub enable_logging: bool,
|
||||
}
|
||||
|
||||
/// 应用级代理配置(每个 app 独立)
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AppProxyConfig {
|
||||
/// 应用类型 (claude/codex/gemini)
|
||||
pub app_type: String,
|
||||
/// 该 app 代理启用开关
|
||||
pub enabled: bool,
|
||||
/// 该 app 自动故障转移开关
|
||||
pub auto_failover_enabled: bool,
|
||||
/// 最大重试次数
|
||||
pub max_retries: u32,
|
||||
/// 流式首字超时(秒)
|
||||
pub streaming_first_byte_timeout: u32,
|
||||
/// 流式静默超时(秒)
|
||||
pub streaming_idle_timeout: u32,
|
||||
/// 非流式总超时(秒)
|
||||
pub non_streaming_timeout: u32,
|
||||
/// 熔断失败阈值
|
||||
pub circuit_failure_threshold: u32,
|
||||
/// 熔断恢复阈值
|
||||
pub circuit_success_threshold: u32,
|
||||
/// 熔断恢复等待时间(秒)
|
||||
pub circuit_timeout_seconds: u32,
|
||||
/// 错误率阈值
|
||||
pub circuit_error_rate_threshold: f64,
|
||||
/// 计算错误率的最小请求数
|
||||
pub circuit_min_requests: u32,
|
||||
}
|
||||
|
||||
@@ -34,6 +34,12 @@ impl TokenUsage {
|
||||
/// 从 Claude API 非流式响应解析
|
||||
pub fn from_claude_response(body: &Value) -> Option<Self> {
|
||||
let usage = body.get("usage")?;
|
||||
// 提取响应中的模型名称
|
||||
let model = body
|
||||
.get("model")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
|
||||
Some(Self {
|
||||
input_tokens: usage.get("input_tokens")?.as_u64()? as u32,
|
||||
output_tokens: usage.get("output_tokens")?.as_u64()? as u32,
|
||||
@@ -45,7 +51,7 @@ impl TokenUsage {
|
||||
.get("cache_creation_input_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(0) as u32,
|
||||
model: None,
|
||||
model,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -53,11 +59,20 @@ impl TokenUsage {
|
||||
#[allow(dead_code)]
|
||||
pub fn from_claude_stream_events(events: &[Value]) -> Option<Self> {
|
||||
let mut usage = Self::default();
|
||||
let mut model: Option<String> = None;
|
||||
|
||||
for event in events {
|
||||
if let Some(event_type) = event.get("type").and_then(|v| v.as_str()) {
|
||||
match event_type {
|
||||
"message_start" => {
|
||||
// 从 message_start 提取模型名称
|
||||
if model.is_none() {
|
||||
if let Some(message) = event.get("message") {
|
||||
if let Some(m) = message.get("model").and_then(|v| v.as_str()) {
|
||||
model = Some(m.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(msg_usage) = event.get("message").and_then(|m| m.get("usage")) {
|
||||
// 从 message_start 获取 input_tokens(原生 Claude API)
|
||||
if let Some(input) =
|
||||
@@ -102,6 +117,7 @@ impl TokenUsage {
|
||||
}
|
||||
|
||||
if usage.input_tokens > 0 || usage.output_tokens > 0 {
|
||||
usage.model = model;
|
||||
Some(usage)
|
||||
} else {
|
||||
None
|
||||
@@ -141,6 +157,12 @@ impl TokenUsage {
|
||||
return None;
|
||||
}
|
||||
|
||||
// 提取响应中的模型名称
|
||||
let model = body
|
||||
.get("model")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
|
||||
Some(Self {
|
||||
input_tokens: input_tokens? as u32,
|
||||
output_tokens: output_tokens? as u32,
|
||||
@@ -152,7 +174,7 @@ impl TokenUsage {
|
||||
.get("cache_creation_input_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(0) as u32,
|
||||
model: None,
|
||||
model,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -222,12 +244,18 @@ impl TokenUsage {
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(0) as u32;
|
||||
|
||||
// 提取响应中的模型名称
|
||||
let model = body
|
||||
.get("model")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
|
||||
Some(Self {
|
||||
input_tokens: prompt_tokens as u32,
|
||||
output_tokens: completion_tokens as u32,
|
||||
cache_read_tokens: cached_tokens,
|
||||
cache_creation_tokens: 0,
|
||||
model: None,
|
||||
model,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -322,6 +350,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_claude_response_parsing() {
|
||||
let response = json!({
|
||||
"model": "claude-sonnet-4-20250514",
|
||||
"usage": {
|
||||
"input_tokens": 100,
|
||||
"output_tokens": 50,
|
||||
@@ -335,10 +364,60 @@ mod tests {
|
||||
assert_eq!(usage.output_tokens, 50);
|
||||
assert_eq!(usage.cache_read_tokens, 20);
|
||||
assert_eq!(usage.cache_creation_tokens, 10);
|
||||
assert_eq!(usage.model, Some("claude-sonnet-4-20250514".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_claude_response_parsing_no_model() {
|
||||
let response = json!({
|
||||
"usage": {
|
||||
"input_tokens": 100,
|
||||
"output_tokens": 50,
|
||||
"cache_read_input_tokens": 20,
|
||||
"cache_creation_input_tokens": 10
|
||||
}
|
||||
});
|
||||
|
||||
let usage = TokenUsage::from_claude_response(&response).unwrap();
|
||||
assert_eq!(usage.input_tokens, 100);
|
||||
assert_eq!(usage.output_tokens, 50);
|
||||
assert_eq!(usage.cache_read_tokens, 20);
|
||||
assert_eq!(usage.cache_creation_tokens, 10);
|
||||
assert_eq!(usage.model, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_claude_stream_parsing() {
|
||||
let events = vec![
|
||||
json!({
|
||||
"type": "message_start",
|
||||
"message": {
|
||||
"model": "claude-sonnet-4-20250514",
|
||||
"usage": {
|
||||
"input_tokens": 100,
|
||||
"cache_read_input_tokens": 20,
|
||||
"cache_creation_input_tokens": 10
|
||||
}
|
||||
}
|
||||
}),
|
||||
json!({
|
||||
"type": "message_delta",
|
||||
"usage": {
|
||||
"output_tokens": 50
|
||||
}
|
||||
}),
|
||||
];
|
||||
|
||||
let usage = TokenUsage::from_claude_stream_events(&events).unwrap();
|
||||
assert_eq!(usage.input_tokens, 100);
|
||||
assert_eq!(usage.output_tokens, 50);
|
||||
assert_eq!(usage.cache_read_tokens, 20);
|
||||
assert_eq!(usage.cache_creation_tokens, 10);
|
||||
assert_eq!(usage.model, Some("claude-sonnet-4-20250514".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_claude_stream_parsing_no_model() {
|
||||
let events = vec![
|
||||
json!({
|
||||
"type": "message_start",
|
||||
@@ -363,6 +442,7 @@ mod tests {
|
||||
assert_eq!(usage.output_tokens, 50);
|
||||
assert_eq!(usage.cache_read_tokens, 20);
|
||||
assert_eq!(usage.cache_creation_tokens, 10);
|
||||
assert_eq!(usage.model, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -481,6 +561,7 @@ mod tests {
|
||||
json!({
|
||||
"type": "message_start",
|
||||
"message": {
|
||||
"model": "claude-sonnet-4-20250514",
|
||||
"usage": {
|
||||
"input_tokens": 0,
|
||||
"output_tokens": 0
|
||||
@@ -502,6 +583,7 @@ mod tests {
|
||||
let usage = TokenUsage::from_claude_stream_events(&events).unwrap();
|
||||
assert_eq!(usage.input_tokens, 150);
|
||||
assert_eq!(usage.output_tokens, 75);
|
||||
assert_eq!(usage.model, Some("claude-sonnet-4-20250514".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -512,6 +594,7 @@ mod tests {
|
||||
json!({
|
||||
"type": "message_start",
|
||||
"message": {
|
||||
"model": "claude-sonnet-4-20250514",
|
||||
"usage": {
|
||||
"input_tokens": 200,
|
||||
"cache_read_input_tokens": 50
|
||||
@@ -530,5 +613,6 @@ mod tests {
|
||||
assert_eq!(usage.input_tokens, 200);
|
||||
assert_eq!(usage.output_tokens, 100);
|
||||
assert_eq!(usage.cache_read_tokens, 50);
|
||||
assert_eq!(usage.model, Some("claude-sonnet-4-20250514".to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,7 +146,9 @@ impl ConfigService {
|
||||
let cfg_text = settings.get("config").and_then(Value::as_str);
|
||||
|
||||
crate::codex_config::write_codex_live_atomic(auth, cfg_text)?;
|
||||
crate::mcp::sync_enabled_to_codex(config)?;
|
||||
// 注意:MCP 同步在 v3.7.0 中已通过 McpService 进行,不再在此调用
|
||||
// sync_enabled_to_codex 使用旧的 config.mcp.codex 结构,在新架构中为空
|
||||
// MCP 的启用/禁用应通过 McpService::toggle_app 进行
|
||||
|
||||
let cfg_text_after = crate::codex_config::read_and_validate_codex_config_text()?;
|
||||
if let Some(manager) = config.get_manager_mut(&AppType::Codex) {
|
||||
|
||||
@@ -690,3 +690,140 @@ pub struct ProviderSortUpdate {
|
||||
#[serde(rename = "sortIndex")]
|
||||
pub sort_index: usize,
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 统一供应商(Universal Provider)服务方法
|
||||
// ============================================================================
|
||||
|
||||
use crate::provider::UniversalProvider;
|
||||
use std::collections::HashMap;
|
||||
|
||||
impl ProviderService {
|
||||
/// 获取所有统一供应商
|
||||
pub fn list_universal(
|
||||
state: &AppState,
|
||||
) -> Result<HashMap<String, UniversalProvider>, AppError> {
|
||||
state.db.get_all_universal_providers()
|
||||
}
|
||||
|
||||
/// 获取单个统一供应商
|
||||
pub fn get_universal(
|
||||
state: &AppState,
|
||||
id: &str,
|
||||
) -> Result<Option<UniversalProvider>, AppError> {
|
||||
state.db.get_universal_provider(id)
|
||||
}
|
||||
|
||||
/// 添加或更新统一供应商(不自动同步,需手动调用 sync_universal_to_apps)
|
||||
pub fn upsert_universal(
|
||||
state: &AppState,
|
||||
provider: UniversalProvider,
|
||||
) -> Result<bool, AppError> {
|
||||
// 保存统一供应商
|
||||
state.db.save_universal_provider(&provider)?;
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// 删除统一供应商
|
||||
pub fn delete_universal(state: &AppState, id: &str) -> Result<bool, AppError> {
|
||||
// 获取统一供应商(用于删除生成的子供应商)
|
||||
let provider = state.db.get_universal_provider(id)?;
|
||||
|
||||
// 删除统一供应商
|
||||
state.db.delete_universal_provider(id)?;
|
||||
|
||||
// 删除生成的子供应商
|
||||
if let Some(p) = provider {
|
||||
if p.apps.claude {
|
||||
let claude_id = format!("universal-claude-{}", id);
|
||||
let _ = state.db.delete_provider("claude", &claude_id);
|
||||
}
|
||||
if p.apps.codex {
|
||||
let codex_id = format!("universal-codex-{}", id);
|
||||
let _ = state.db.delete_provider("codex", &codex_id);
|
||||
}
|
||||
if p.apps.gemini {
|
||||
let gemini_id = format!("universal-gemini-{}", id);
|
||||
let _ = state.db.delete_provider("gemini", &gemini_id);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// 同步统一供应商到各应用
|
||||
pub fn sync_universal_to_apps(state: &AppState, id: &str) -> Result<bool, AppError> {
|
||||
let provider = state
|
||||
.db
|
||||
.get_universal_provider(id)?
|
||||
.ok_or_else(|| AppError::Message(format!("统一供应商 {} 不存在", id)))?;
|
||||
|
||||
// 同步到 Claude
|
||||
if let Some(mut claude_provider) = provider.to_claude_provider() {
|
||||
// 合并已有配置
|
||||
if let Some(existing) = state.db.get_provider_by_id(&claude_provider.id, "claude")? {
|
||||
let mut merged = existing.settings_config.clone();
|
||||
Self::merge_json(&mut merged, &claude_provider.settings_config);
|
||||
claude_provider.settings_config = merged;
|
||||
}
|
||||
state.db.save_provider("claude", &claude_provider)?;
|
||||
} else {
|
||||
// 如果禁用了 Claude,删除对应的子供应商
|
||||
let claude_id = format!("universal-claude-{}", id);
|
||||
let _ = state.db.delete_provider("claude", &claude_id);
|
||||
}
|
||||
|
||||
// 同步到 Codex
|
||||
if let Some(mut codex_provider) = provider.to_codex_provider() {
|
||||
// 合并已有配置
|
||||
if let Some(existing) = state.db.get_provider_by_id(&codex_provider.id, "codex")? {
|
||||
let mut merged = existing.settings_config.clone();
|
||||
Self::merge_json(&mut merged, &codex_provider.settings_config);
|
||||
codex_provider.settings_config = merged;
|
||||
}
|
||||
state.db.save_provider("codex", &codex_provider)?;
|
||||
} else {
|
||||
let codex_id = format!("universal-codex-{}", id);
|
||||
let _ = state.db.delete_provider("codex", &codex_id);
|
||||
}
|
||||
|
||||
// 同步到 Gemini
|
||||
if let Some(mut gemini_provider) = provider.to_gemini_provider() {
|
||||
// 合并已有配置
|
||||
if let Some(existing) = state.db.get_provider_by_id(&gemini_provider.id, "gemini")? {
|
||||
let mut merged = existing.settings_config.clone();
|
||||
Self::merge_json(&mut merged, &gemini_provider.settings_config);
|
||||
gemini_provider.settings_config = merged;
|
||||
}
|
||||
state.db.save_provider("gemini", &gemini_provider)?;
|
||||
} else {
|
||||
let gemini_id = format!("universal-gemini-{}", id);
|
||||
let _ = state.db.delete_provider("gemini", &gemini_id);
|
||||
}
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// 递归合并 JSON:base 为底,patch 覆盖同名字段
|
||||
fn merge_json(base: &mut serde_json::Value, patch: &serde_json::Value) {
|
||||
use serde_json::Value;
|
||||
|
||||
match (base, patch) {
|
||||
(Value::Object(base_map), Value::Object(patch_map)) => {
|
||||
for (k, v_patch) in patch_map {
|
||||
match base_map.get_mut(k) {
|
||||
Some(v_base) => Self::merge_json(v_base, v_patch),
|
||||
None => {
|
||||
base_map.insert(k.clone(), v_patch.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 其它类型:直接覆盖
|
||||
(base_val, patch_val) => {
|
||||
*base_val = patch_val.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,7 +43,22 @@ impl ProxyService {
|
||||
|
||||
/// 启动代理服务器
|
||||
pub async fn start(&self) -> Result<ProxyServerInfo, String> {
|
||||
// 1. 获取配置
|
||||
// 1. 启动时自动设置 proxy_enabled = true
|
||||
let mut global_config = self
|
||||
.db
|
||||
.get_global_proxy_config()
|
||||
.await
|
||||
.map_err(|e| format!("获取全局代理配置失败: {e}"))?;
|
||||
|
||||
if !global_config.proxy_enabled {
|
||||
global_config.proxy_enabled = true;
|
||||
self.db
|
||||
.update_global_proxy_config(global_config.clone())
|
||||
.await
|
||||
.map_err(|e| format!("更新代理总开关失败: {e}"))?;
|
||||
}
|
||||
|
||||
// 2. 获取配置
|
||||
let config = self
|
||||
.db
|
||||
.get_proxy_config()
|
||||
@@ -115,14 +130,7 @@ impl ProxyService {
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
// 5. 设置 settings 表中所有应用的接管状态(用于重启后自动恢复)
|
||||
for app in ["claude", "codex", "gemini"] {
|
||||
if let Err(e) = self.db.set_proxy_takeover_enabled(app, true) {
|
||||
log::warn!("设置 {app} 接管状态失败: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
// 6. 启动代理服务器
|
||||
// 5. 启动代理服务器
|
||||
match self.start().await {
|
||||
Ok(info) => Ok(info),
|
||||
Err(e) => {
|
||||
@@ -132,8 +140,6 @@ impl ProxyService {
|
||||
Ok(()) => {
|
||||
let _ = self.db.set_live_takeover_active(false).await;
|
||||
let _ = self.db.delete_all_live_backups().await;
|
||||
// 清除 settings 状态
|
||||
let _ = self.db.clear_all_proxy_takeover();
|
||||
}
|
||||
Err(restore_err) => {
|
||||
log::error!("恢复原始配置失败,将保留备份以便下次启动恢复: {restore_err}");
|
||||
@@ -146,29 +152,30 @@ impl ProxyService {
|
||||
|
||||
/// 获取各应用的接管状态(是否改写该应用的 Live 配置指向本地代理)
|
||||
pub async fn get_takeover_status(&self) -> Result<ProxyTakeoverStatus, String> {
|
||||
let claude = self
|
||||
// 从 proxy_config.enabled 读取(优先),兼容旧的 live_backup 备份检测
|
||||
let claude_enabled = self
|
||||
.db
|
||||
.get_live_backup("claude")
|
||||
.get_proxy_config_for_app("claude")
|
||||
.await
|
||||
.map_err(|e| format!("获取 Claude 接管状态失败: {e}"))?
|
||||
.is_some();
|
||||
let codex = self
|
||||
.map(|c| c.enabled)
|
||||
.unwrap_or(false);
|
||||
let codex_enabled = self
|
||||
.db
|
||||
.get_live_backup("codex")
|
||||
.get_proxy_config_for_app("codex")
|
||||
.await
|
||||
.map_err(|e| format!("获取 Codex 接管状态失败: {e}"))?
|
||||
.is_some();
|
||||
let gemini = self
|
||||
.map(|c| c.enabled)
|
||||
.unwrap_or(false);
|
||||
let gemini_enabled = self
|
||||
.db
|
||||
.get_live_backup("gemini")
|
||||
.get_proxy_config_for_app("gemini")
|
||||
.await
|
||||
.map_err(|e| format!("获取 Gemini 接管状态失败: {e}"))?
|
||||
.is_some();
|
||||
.map(|c| c.enabled)
|
||||
.unwrap_or(false);
|
||||
|
||||
Ok(ProxyTakeoverStatus {
|
||||
claude,
|
||||
codex,
|
||||
gemini,
|
||||
claude: claude_enabled,
|
||||
codex: codex_enabled,
|
||||
gemini: gemini_enabled,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -187,13 +194,13 @@ impl ProxyService {
|
||||
}
|
||||
|
||||
// 2) 已接管则直接返回(幂等)
|
||||
if self
|
||||
let current_config = self
|
||||
.db
|
||||
.get_live_backup(app_type_str)
|
||||
.get_proxy_config_for_app(app_type_str)
|
||||
.await
|
||||
.map_err(|e| format!("检查 {app_type_str} Live 备份失败: {e}"))?
|
||||
.is_some()
|
||||
{
|
||||
.map_err(|e| format!("获取 {app_type_str} 配置失败: {e}"))?;
|
||||
|
||||
if current_config.enabled {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -223,25 +230,32 @@ impl ProxyService {
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
// 6) 设置 settings 表中的接管状态
|
||||
// 6) 设置 proxy_config.enabled = true
|
||||
let mut updated_config = self
|
||||
.db
|
||||
.get_proxy_config_for_app(app_type_str)
|
||||
.await
|
||||
.map_err(|e| format!("获取 {app_type_str} 配置失败: {e}"))?;
|
||||
updated_config.enabled = true;
|
||||
self.db
|
||||
.set_proxy_takeover_enabled(app_type_str, true)
|
||||
.map_err(|e| format!("设置 {app_type_str} 接管状态失败: {e}"))?;
|
||||
.update_proxy_config_for_app(updated_config)
|
||||
.await
|
||||
.map_err(|e| format!("设置 {app_type_str} enabled 状态失败: {e}"))?;
|
||||
|
||||
// 7) 兼容旧逻辑:写入 any-of 标志(失败不影响功能)
|
||||
let _ = self.db.set_live_takeover_active(true).await;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// 关闭接管:无备份则视为未接管(幂等)
|
||||
let has_backup = self
|
||||
// 关闭接管:检查 enabled 状态
|
||||
let current_config = self
|
||||
.db
|
||||
.get_live_backup(app_type_str)
|
||||
.get_proxy_config_for_app(app_type_str)
|
||||
.await
|
||||
.map_err(|e| format!("检查 {app_type_str} Live 备份失败: {e}"))?
|
||||
.is_some();
|
||||
if !has_backup {
|
||||
return Ok(());
|
||||
.map_err(|e| format!("获取 {app_type_str} 配置失败: {e}"))?;
|
||||
|
||||
if !current_config.enabled {
|
||||
return Ok(()); // 未接管,幂等返回
|
||||
}
|
||||
|
||||
// 1) 恢复 Live 配置
|
||||
@@ -253,18 +267,33 @@ impl ProxyService {
|
||||
.await
|
||||
.map_err(|e| format!("删除 {app_type_str} Live 备份失败: {e}"))?;
|
||||
|
||||
// 3) 清除 settings 表中该应用的接管状态
|
||||
self.db
|
||||
.set_proxy_takeover_enabled(app_type_str, false)
|
||||
.map_err(|e| format!("清除 {app_type_str} 接管状态失败: {e}"))?;
|
||||
|
||||
// 4) 若无其它接管,更新旧标志,并停止代理服务
|
||||
let has_any_backup = self
|
||||
// 3) 设置 proxy_config.enabled = false
|
||||
let mut updated_config = self
|
||||
.db
|
||||
.has_any_live_backup()
|
||||
.get_proxy_config_for_app(app_type_str)
|
||||
.await
|
||||
.map_err(|e| format!("检查 Live 备份失败: {e}"))?;
|
||||
if !has_any_backup {
|
||||
.map_err(|e| format!("获取 {app_type_str} 配置失败: {e}"))?;
|
||||
updated_config.enabled = false;
|
||||
self.db
|
||||
.update_proxy_config_for_app(updated_config)
|
||||
.await
|
||||
.map_err(|e| format!("清除 {app_type_str} enabled 状态失败: {e}"))?;
|
||||
|
||||
// 4) 清除该应用的健康状态(关闭代理时重置队列状态)
|
||||
self.db
|
||||
.clear_provider_health_for_app(app_type_str)
|
||||
.await
|
||||
.map_err(|e| format!("清除 {app_type_str} 健康状态失败: {e}"))?;
|
||||
|
||||
// 5) 若无其它接管,更新旧标志,并停止代理服务
|
||||
// 检查是否还有其它 app 的 enabled = true
|
||||
let any_enabled = self
|
||||
.db
|
||||
.is_live_takeover_active()
|
||||
.await
|
||||
.map_err(|e| format!("检查接管状态失败: {e}"))?;
|
||||
|
||||
if !any_enabled {
|
||||
let _ = self.db.set_live_takeover_active(false).await;
|
||||
|
||||
if self.is_running().await {
|
||||
@@ -496,6 +525,20 @@ impl ProxyService {
|
||||
.await
|
||||
.map_err(|e| format!("停止代理服务器失败: {e}"))?;
|
||||
|
||||
// 停止时设置 proxy_enabled = false
|
||||
let mut global_config = self
|
||||
.db
|
||||
.get_global_proxy_config()
|
||||
.await
|
||||
.map_err(|e| format!("获取全局代理配置失败: {e}"))?;
|
||||
|
||||
if global_config.proxy_enabled {
|
||||
global_config.proxy_enabled = false;
|
||||
if let Err(e) = self.db.update_global_proxy_config(global_config).await {
|
||||
log::warn!("更新代理总开关失败: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
log::info!("代理服务器已停止");
|
||||
Ok(())
|
||||
} else {
|
||||
@@ -521,10 +564,17 @@ impl ProxyService {
|
||||
.await
|
||||
.map_err(|e| format!("清除接管状态失败: {e}"))?;
|
||||
|
||||
// 4. 清除 settings 表中的代理状态(用户手动关闭,不需要下次自动恢复)
|
||||
self.db
|
||||
.clear_all_proxy_takeover()
|
||||
.map_err(|e| format!("清除代理状态失败: {e}"))?;
|
||||
// 4. 清除所有应用的 enabled 状态(用户手动关闭,不需要下次自动恢复)
|
||||
for app_type in ["claude", "codex", "gemini"] {
|
||||
if let Ok(mut config) = self.db.get_proxy_config_for_app(app_type).await {
|
||||
if config.enabled {
|
||||
config.enabled = false;
|
||||
if let Err(e) = self.db.update_proxy_config_for_app(config).await {
|
||||
log::warn!("清除 {app_type} enabled 状态失败: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. 删除备份
|
||||
self.db
|
||||
@@ -538,6 +588,7 @@ impl ProxyService {
|
||||
.await
|
||||
.map_err(|e| format!("重置健康状态失败: {e}"))?;
|
||||
|
||||
// 注意:不清除故障转移队列和开关状态,保留供下次开启代理时使用
|
||||
log::info!("代理已停止,Live 配置已恢复");
|
||||
Ok(())
|
||||
}
|
||||
@@ -555,7 +606,7 @@ impl ProxyService {
|
||||
self.restore_live_configs().await?;
|
||||
|
||||
// 3. 更新 proxy_config 表中的 live_takeover_active 标志(兼容旧版)
|
||||
// 注意:仅更新 proxy_config 表,不清除 settings 表中的 proxy_takeover_* 状态
|
||||
// 注意:保留 proxy_config.enabled 状态,下次启动时自动恢复
|
||||
if let Ok(mut config) = self.db.get_proxy_config().await {
|
||||
config.live_takeover_active = false;
|
||||
let _ = self.db.update_proxy_config(config).await;
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! 使用流式 API 进行快速健康检查,只需接收首个 chunk 即判定成功。
|
||||
|
||||
use futures::StreamExt;
|
||||
use regex::Regex;
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
@@ -141,15 +142,17 @@ impl StreamCheckService {
|
||||
.build()
|
||||
.map_err(|e| AppError::Message(format!("创建客户端失败: {e}")))?;
|
||||
|
||||
let model_to_test = Self::resolve_test_model(app_type, provider, config);
|
||||
|
||||
let result = match app_type {
|
||||
AppType::Claude => {
|
||||
Self::check_claude_stream(&client, &base_url, &auth, &config.claude_model).await
|
||||
Self::check_claude_stream(&client, &base_url, &auth, &model_to_test).await
|
||||
}
|
||||
AppType::Codex => {
|
||||
Self::check_codex_stream(&client, &base_url, &auth, &config.codex_model).await
|
||||
Self::check_codex_stream(&client, &base_url, &auth, &model_to_test).await
|
||||
}
|
||||
AppType::Gemini => {
|
||||
Self::check_gemini_stream(&client, &base_url, &auth, &config.gemini_model).await
|
||||
Self::check_gemini_stream(&client, &base_url, &auth, &model_to_test).await
|
||||
}
|
||||
};
|
||||
|
||||
@@ -379,6 +382,48 @@ impl StreamCheckService {
|
||||
AppError::Message(e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_test_model(
|
||||
app_type: &AppType,
|
||||
provider: &Provider,
|
||||
config: &StreamCheckConfig,
|
||||
) -> String {
|
||||
match app_type {
|
||||
AppType::Claude => Self::extract_env_model(provider, "ANTHROPIC_MODEL")
|
||||
.unwrap_or_else(|| config.claude_model.clone()),
|
||||
AppType::Codex => {
|
||||
Self::extract_codex_model(provider).unwrap_or_else(|| config.codex_model.clone())
|
||||
}
|
||||
AppType::Gemini => Self::extract_env_model(provider, "GEMINI_MODEL")
|
||||
.unwrap_or_else(|| config.gemini_model.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_env_model(provider: &Provider, key: &str) -> Option<String> {
|
||||
provider
|
||||
.settings_config
|
||||
.get("env")
|
||||
.and_then(|env| env.get(key))
|
||||
.and_then(|value| value.as_str())
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
fn extract_codex_model(provider: &Provider) -> Option<String> {
|
||||
let config_text = provider
|
||||
.settings_config
|
||||
.get("config")
|
||||
.and_then(|value| value.as_str())?;
|
||||
if config_text.trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let re = Regex::new(r#"^model\s*=\s*["']([^"']+)["']"#).ok()?;
|
||||
re.captures(config_text)
|
||||
.and_then(|caps| caps.get(1))
|
||||
.map(|m| m.as_str().trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -76,19 +76,8 @@ fn sync_codex_provider_writes_auth_and_config() {
|
||||
|
||||
let mut config = MultiAppConfig::default();
|
||||
|
||||
// 添加入测 MCP 启用项,确保 sync_enabled_to_codex 会写入 TOML
|
||||
config.mcp.codex.servers.insert(
|
||||
"echo-server".into(),
|
||||
json!({
|
||||
"id": "echo-server",
|
||||
"enabled": true,
|
||||
"server": {
|
||||
"type": "stdio",
|
||||
"command": "echo",
|
||||
"args": ["hello"]
|
||||
}
|
||||
}),
|
||||
);
|
||||
// 注意:v3.7.0 后 MCP 同步由 McpService 独立处理,不再通过 provider 切换触发
|
||||
// 此测试仅验证 auth.json 和 config.toml 基础配置的写入
|
||||
|
||||
let provider_config = json!({
|
||||
"auth": {
|
||||
@@ -133,9 +122,10 @@ fn sync_codex_provider_writes_auth_and_config() {
|
||||
);
|
||||
|
||||
let toml_text = fs::read_to_string(&config_path).expect("read config.toml");
|
||||
// 验证基础配置正确写入
|
||||
assert!(
|
||||
toml_text.contains("command = \"echo\""),
|
||||
"config.toml should contain serialized enabled MCP server"
|
||||
toml_text.contains("base_url"),
|
||||
"config.toml should contain base_url from provider config"
|
||||
);
|
||||
|
||||
// 当前供应商应同步最新 config 文本
|
||||
|
||||
@@ -43,9 +43,17 @@ import PromptPanel from "@/components/prompts/PromptPanel";
|
||||
import { SkillsPage } from "@/components/skills/SkillsPage";
|
||||
import { DeepLinkImportDialog } from "@/components/DeepLinkImportDialog";
|
||||
import { AgentsPanel } from "@/components/agents/AgentsPanel";
|
||||
import { UniversalProviderPanel } from "@/components/universal";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
type View = "providers" | "settings" | "prompts" | "skills" | "mcp" | "agents";
|
||||
type View =
|
||||
| "providers"
|
||||
| "settings"
|
||||
| "prompts"
|
||||
| "skills"
|
||||
| "mcp"
|
||||
| "agents"
|
||||
| "universal";
|
||||
|
||||
const DRAG_BAR_HEIGHT = 28; // px
|
||||
const HEADER_HEIGHT = 64; // px
|
||||
@@ -65,6 +73,22 @@ function App() {
|
||||
const [envConflicts, setEnvConflicts] = useState<EnvConflict[]>([]);
|
||||
const [showEnvBanner, setShowEnvBanner] = useState(false);
|
||||
|
||||
// 保存最后一个有效的 provider,用于动画退出期间显示内容
|
||||
const lastUsageProviderRef = useRef<Provider | null>(null);
|
||||
const lastEditingProviderRef = useRef<Provider | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (usageProvider) {
|
||||
lastUsageProviderRef.current = usageProvider;
|
||||
}
|
||||
}, [usageProvider]);
|
||||
|
||||
useEffect(() => {
|
||||
if (editingProvider) {
|
||||
lastEditingProviderRef.current = editingProvider;
|
||||
}
|
||||
}, [editingProvider]);
|
||||
|
||||
const promptPanelRef = useRef<any>(null);
|
||||
const mcpPanelRef = useRef<any>(null);
|
||||
const skillsPageRef = useRef<any>(null);
|
||||
@@ -72,9 +96,20 @@ 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, takeoverStatus } = useProxyStatus();
|
||||
const {
|
||||
isRunning: isProxyRunning,
|
||||
takeoverStatus,
|
||||
status: proxyStatus,
|
||||
} = useProxyStatus();
|
||||
// 当前应用的代理是否开启
|
||||
const isCurrentAppTakeoverActive = takeoverStatus?.[activeApp] || false;
|
||||
// 当前应用代理实际使用的供应商 ID(从 active_targets 中获取)
|
||||
const activeProviderId = useMemo(() => {
|
||||
const target = proxyStatus?.active_targets?.find(
|
||||
(t) => t.app_type === activeApp,
|
||||
);
|
||||
return target?.provider_id;
|
||||
}, [proxyStatus?.active_targets, activeApp]);
|
||||
|
||||
// 获取供应商列表,当代理服务运行时自动刷新
|
||||
const { data, isLoading, refetch } = useProvidersQuery(activeApp, {
|
||||
@@ -105,7 +140,7 @@ function App() {
|
||||
if (event.appType === activeApp) {
|
||||
await refetch();
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("[App] Failed to subscribe provider switch event", error);
|
||||
@@ -118,6 +153,38 @@ function App() {
|
||||
};
|
||||
}, [activeApp, refetch]);
|
||||
|
||||
// 监听统一供应商同步事件,刷新所有应用的供应商列表
|
||||
useEffect(() => {
|
||||
let unsubscribe: (() => void) | undefined;
|
||||
|
||||
const setupListener = async () => {
|
||||
try {
|
||||
const { listen } = await import("@tauri-apps/api/event");
|
||||
unsubscribe = await listen("universal-provider-synced", async () => {
|
||||
// 统一供应商同步后刷新所有应用的供应商列表
|
||||
// 使用 invalidateQueries 使所有 providers 查询失效
|
||||
await queryClient.invalidateQueries({ queryKey: ["providers"] });
|
||||
// 同时更新托盘菜单
|
||||
try {
|
||||
await providersApi.updateTrayMenu();
|
||||
} catch (error) {
|
||||
console.error("[App] Failed to update tray menu", error);
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"[App] Failed to subscribe universal-provider-synced event",
|
||||
error,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
setupListener();
|
||||
return () => {
|
||||
unsubscribe?.();
|
||||
};
|
||||
}, [queryClient]);
|
||||
|
||||
// 应用启动时检测所有应用的环境变量冲突
|
||||
useEffect(() => {
|
||||
const checkEnvOnStartup = async () => {
|
||||
@@ -135,7 +202,7 @@ function App() {
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"[App] Failed to check environment conflicts on startup:",
|
||||
error
|
||||
error,
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -151,7 +218,7 @@ function App() {
|
||||
if (migrated) {
|
||||
toast.success(
|
||||
t("migration.success", { defaultValue: "配置迁移成功" }),
|
||||
{ closeButton: true }
|
||||
{ closeButton: true },
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -172,10 +239,10 @@ function App() {
|
||||
// 合并新检测到的冲突
|
||||
setEnvConflicts((prev) => {
|
||||
const existingKeys = new Set(
|
||||
prev.map((c) => `${c.varName}:${c.sourcePath}`)
|
||||
prev.map((c) => `${c.varName}:${c.sourcePath}`),
|
||||
);
|
||||
const newConflicts = conflicts.filter(
|
||||
(c) => !existingKeys.has(`${c.varName}:${c.sourcePath}`)
|
||||
(c) => !existingKeys.has(`${c.varName}:${c.sourcePath}`),
|
||||
);
|
||||
return [...prev, ...newConflicts];
|
||||
});
|
||||
@@ -187,7 +254,7 @@ function App() {
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"[App] Failed to check environment conflicts on app switch:",
|
||||
error
|
||||
error,
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -195,6 +262,21 @@ function App() {
|
||||
checkEnvOnSwitch();
|
||||
}, [activeApp]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleGlobalShortcut = (event: KeyboardEvent) => {
|
||||
if (event.key !== "," || !(event.metaKey || event.ctrlKey)) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
setCurrentView("settings");
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", handleGlobalShortcut);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", handleGlobalShortcut);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 打开网站链接
|
||||
const handleOpenWebsite = async (url: string) => {
|
||||
try {
|
||||
@@ -248,7 +330,7 @@ function App() {
|
||||
(p) =>
|
||||
p.sortIndex !== undefined &&
|
||||
p.sortIndex >= newSortIndex! &&
|
||||
p.id !== provider.id
|
||||
p.id !== provider.id,
|
||||
)
|
||||
.map((p) => ({
|
||||
id: p.id,
|
||||
@@ -264,7 +346,7 @@ function App() {
|
||||
toast.error(
|
||||
t("provider.sortUpdateFailed", {
|
||||
defaultValue: "排序更新失败",
|
||||
})
|
||||
}),
|
||||
);
|
||||
return; // 如果排序更新失败,不继续添加
|
||||
}
|
||||
@@ -334,7 +416,15 @@ function App() {
|
||||
/>
|
||||
);
|
||||
case "agents":
|
||||
return <AgentsPanel onOpenChange={() => setCurrentView("providers")} />;
|
||||
return (
|
||||
<AgentsPanel onOpenChange={() => setCurrentView("providers")} />
|
||||
);
|
||||
case "universal":
|
||||
return (
|
||||
<div className="mx-auto max-w-[56rem] px-5 pt-4">
|
||||
<UniversalProviderPanel />
|
||||
</div>
|
||||
);
|
||||
default:
|
||||
return (
|
||||
<div className="mx-auto max-w-[56rem] px-5 flex flex-col h-[calc(100vh-8rem)] overflow-hidden">
|
||||
@@ -355,7 +445,10 @@ function App() {
|
||||
appId={activeApp}
|
||||
isLoading={isLoading}
|
||||
isProxyRunning={isProxyRunning}
|
||||
isProxyTakeover={isProxyRunning && isCurrentAppTakeoverActive}
|
||||
isProxyTakeover={
|
||||
isProxyRunning && isCurrentAppTakeoverActive
|
||||
}
|
||||
activeProviderId={activeProviderId}
|
||||
onSwitch={switchProvider}
|
||||
onEdit={setEditingProvider}
|
||||
onDelete={setConfirmDelete}
|
||||
@@ -418,7 +511,7 @@ function App() {
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"[App] Failed to re-check conflicts after deletion:",
|
||||
error
|
||||
error,
|
||||
);
|
||||
}
|
||||
}}
|
||||
@@ -462,6 +555,10 @@ function App() {
|
||||
{currentView === "skills" && t("skills.title")}
|
||||
{currentView === "mcp" && t("mcp.unifiedPanel.title")}
|
||||
{currentView === "agents" && t("agents.title")}
|
||||
{currentView === "universal" &&
|
||||
t("universalProvider.title", {
|
||||
defaultValue: "统一供应商",
|
||||
})}
|
||||
</h1>
|
||||
</div>
|
||||
) : (
|
||||
@@ -475,7 +572,7 @@ function App() {
|
||||
"text-xl font-semibold transition-colors",
|
||||
isProxyRunning && isCurrentAppTakeoverActive
|
||||
? "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"
|
||||
: "text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300",
|
||||
)}
|
||||
>
|
||||
CC Switch
|
||||
@@ -496,7 +593,7 @@ function App() {
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="flex items-center gap-2 min-h-[40px]"
|
||||
className="flex items-center gap-2 h-[32px]"
|
||||
style={{ WebkitAppRegion: "no-drag" } as any}
|
||||
>
|
||||
{currentView === "prompts" && (
|
||||
@@ -557,7 +654,7 @@ function App() {
|
||||
"transition-all duration-200 ease-in-out overflow-hidden",
|
||||
hasSkillsSupport
|
||||
? "opacity-100 w-8 scale-100 px-2"
|
||||
: "opacity-0 w-0 scale-75 pointer-events-none px-0 -ml-1"
|
||||
: "opacity-0 w-0 scale-75 pointer-events-none px-0 -ml-1",
|
||||
)}
|
||||
title={t("skills.manage")}
|
||||
>
|
||||
@@ -609,11 +706,7 @@ function App() {
|
||||
</header>
|
||||
|
||||
<main className="flex-1 pb-12 animate-fade-in ">
|
||||
<div
|
||||
className={cn("pb-12", currentView === "providers" ? "pt-6" : "pt-4")}
|
||||
>
|
||||
{renderContent()}
|
||||
</div>
|
||||
<div className="pb-12">{renderContent()}</div>
|
||||
</main>
|
||||
|
||||
<AddProviderDialog
|
||||
@@ -625,7 +718,7 @@ function App() {
|
||||
|
||||
<EditProviderDialog
|
||||
open={Boolean(editingProvider)}
|
||||
provider={editingProvider}
|
||||
provider={lastEditingProviderRef.current}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setEditingProvider(null);
|
||||
@@ -636,14 +729,16 @@ function App() {
|
||||
isProxyTakeover={isProxyRunning && isCurrentAppTakeoverActive}
|
||||
/>
|
||||
|
||||
{usageProvider && (
|
||||
{lastUsageProviderRef.current && (
|
||||
<UsageScriptModal
|
||||
provider={usageProvider}
|
||||
provider={lastUsageProviderRef.current}
|
||||
appId={activeApp}
|
||||
isOpen={Boolean(usageProvider)}
|
||||
onClose={() => setUsageProvider(null)}
|
||||
onSave={(script) => {
|
||||
void saveUsageScript(usageProvider, script);
|
||||
if (usageProvider) {
|
||||
void saveUsageScript(usageProvider, script);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { motion } from "framer-motion";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import { ArrowLeft } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
@@ -33,49 +33,57 @@ export const FullScreenPanel: React.FC<FullScreenPanelProps> = ({
|
||||
};
|
||||
}, [isOpen]);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return createPortal(
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className="fixed inset-0 z-[60] flex flex-col"
|
||||
style={{ backgroundColor: "hsl(var(--background))" }}
|
||||
>
|
||||
{/* Header */}
|
||||
<div
|
||||
className="flex-shrink-0 py-3 border-b border-border-default"
|
||||
style={{ backgroundColor: "hsl(var(--background))" }}
|
||||
>
|
||||
<div className="h-4 w-full" data-tauri-drag-region />
|
||||
<div className="mx-auto max-w-[56rem] px-6 flex items-center gap-4">
|
||||
<Button type="button" variant="outline" size="icon" onClick={onClose}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<h2 className="text-lg font-semibold text-foreground">{title}</h2>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 overflow-y-auto scroll-overlay">
|
||||
<div className="mx-auto max-w-[56rem] px-6 py-6 space-y-6 w-full">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
{footer && (
|
||||
<div
|
||||
className="flex-shrink-0 py-4 border-t border-border-default"
|
||||
<AnimatePresence>
|
||||
{isOpen && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className="fixed inset-0 z-[60] flex flex-col"
|
||||
style={{ backgroundColor: "hsl(var(--background))" }}
|
||||
>
|
||||
<div className="mx-auto max-w-[56rem] px-6 flex items-center justify-end gap-3">
|
||||
{footer}
|
||||
{/* Header */}
|
||||
<div
|
||||
className="flex-shrink-0 py-3 border-b border-border-default"
|
||||
style={{ backgroundColor: "hsl(var(--background))" }}
|
||||
>
|
||||
<div className="h-4 w-full" data-tauri-drag-region />
|
||||
<div className="mx-auto max-w-[56rem] px-6 flex items-center gap-4">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={onClose}
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<h2 className="text-lg font-semibold text-foreground">{title}</h2>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 overflow-y-auto scroll-overlay">
|
||||
<div className="mx-auto max-w-[56rem] px-6 py-6 space-y-6 w-full">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
{footer && (
|
||||
<div
|
||||
className="flex-shrink-0 py-4 border-t border-border-default"
|
||||
style={{ backgroundColor: "hsl(var(--background))" }}
|
||||
>
|
||||
<div className="mx-auto max-w-[56rem] px-6 flex items-center justify-end gap-3">
|
||||
{footer}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
)}
|
||||
</motion.div>,
|
||||
</AnimatePresence>,
|
||||
document.body,
|
||||
);
|
||||
};
|
||||
|
||||
@@ -191,11 +191,11 @@ export function EnvWarningBanner({
|
||||
<div className="flex-1 min-w-0">
|
||||
<label
|
||||
htmlFor={key}
|
||||
className="block text-sm font-medium text-gray-900 dark:text-gray-100 cursor-pointer"
|
||||
className="block text-sm font-medium text-foreground cursor-pointer"
|
||||
>
|
||||
{conflict.varName}
|
||||
</label>
|
||||
<p className="text-xs text-gray-600 dark:text-gray-400 mt-1 break-all">
|
||||
<p className="text-xs text-muted-foreground mt-1 break-all">
|
||||
{t("env.field.value")}: {conflict.varValue}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
|
||||
@@ -239,7 +239,7 @@ const McpWizardModal: React.FC<McpWizardModalProps> = ({
|
||||
<div className="flex-1 overflow-y-auto px-6 py-4 space-y-4">
|
||||
{/* Hint */}
|
||||
<div className="rounded-lg border border-border-default bg-gray-100/50 dark:bg-gray-800/50 p-3">
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("mcp.wizard.hint")}
|
||||
</p>
|
||||
</div>
|
||||
@@ -248,7 +248,7 @@ const McpWizardModal: React.FC<McpWizardModalProps> = ({
|
||||
<div className="space-y-4 min-h-[400px]">
|
||||
{/* Type */}
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
<label className="mb-2 block text-sm font-medium text-foreground">
|
||||
{t("mcp.wizard.type")} <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<div className="flex gap-4">
|
||||
@@ -262,7 +262,7 @@ const McpWizardModal: React.FC<McpWizardModalProps> = ({
|
||||
}
|
||||
className="w-4 h-4 accent-blue-500"
|
||||
/>
|
||||
<span className="text-sm text-gray-900 dark:text-gray-100">
|
||||
<span className="text-sm text-foreground">
|
||||
{t("mcp.wizard.typeStdio")}
|
||||
</span>
|
||||
</label>
|
||||
@@ -276,7 +276,7 @@ const McpWizardModal: React.FC<McpWizardModalProps> = ({
|
||||
}
|
||||
className="w-4 h-4 accent-blue-500"
|
||||
/>
|
||||
<span className="text-sm text-gray-900 dark:text-gray-100">
|
||||
<span className="text-sm text-foreground">
|
||||
{t("mcp.wizard.typeHttp")}
|
||||
</span>
|
||||
</label>
|
||||
@@ -290,7 +290,7 @@ const McpWizardModal: React.FC<McpWizardModalProps> = ({
|
||||
}
|
||||
className="w-4 h-4 accent-blue-500"
|
||||
/>
|
||||
<span className="text-sm text-gray-900 dark:text-gray-100">
|
||||
<span className="text-sm text-foreground">
|
||||
{t("mcp.wizard.typeSse")}
|
||||
</span>
|
||||
</label>
|
||||
@@ -299,7 +299,7 @@ const McpWizardModal: React.FC<McpWizardModalProps> = ({
|
||||
|
||||
{/* Title */}
|
||||
<div>
|
||||
<label className="mb-1 block text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
<label className="mb-1 block text-sm font-medium text-foreground">
|
||||
{t("mcp.form.title")} <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<Input
|
||||
@@ -317,7 +317,7 @@ const McpWizardModal: React.FC<McpWizardModalProps> = ({
|
||||
<>
|
||||
{/* Command */}
|
||||
<div>
|
||||
<label className="mb-1 block text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
<label className="mb-1 block text-sm font-medium text-foreground">
|
||||
{t("mcp.wizard.command")}{" "}
|
||||
<span className="text-red-500">*</span>
|
||||
</label>
|
||||
@@ -333,7 +333,7 @@ const McpWizardModal: React.FC<McpWizardModalProps> = ({
|
||||
|
||||
{/* Args */}
|
||||
<div>
|
||||
<label className="mb-1 block text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
<label className="mb-1 block text-sm font-medium text-foreground">
|
||||
{t("mcp.wizard.args")}
|
||||
</label>
|
||||
<textarea
|
||||
@@ -341,13 +341,13 @@ const McpWizardModal: React.FC<McpWizardModalProps> = ({
|
||||
onChange={(e) => setWizardArgs(e.target.value)}
|
||||
placeholder={t("mcp.wizard.argsPlaceholder")}
|
||||
rows={3}
|
||||
className="w-full rounded-md border border-border-default bg-white dark:bg-gray-800 px-3 py-2 text-sm font-mono text-gray-900 dark:text-gray-100 placeholder:text-gray-400 dark:placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20 resize-y"
|
||||
className="w-full rounded-md border border-border-default bg-background px-3 py-2 text-sm font-mono text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-blue-500/20 resize-y"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Env */}
|
||||
<div>
|
||||
<label className="mb-1 block text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
<label className="mb-1 block text-sm font-medium text-foreground">
|
||||
{t("mcp.wizard.env")}
|
||||
</label>
|
||||
<textarea
|
||||
@@ -355,7 +355,7 @@ const McpWizardModal: React.FC<McpWizardModalProps> = ({
|
||||
onChange={(e) => setWizardEnv(e.target.value)}
|
||||
placeholder={t("mcp.wizard.envPlaceholder")}
|
||||
rows={3}
|
||||
className="w-full rounded-md border border-border-default bg-white dark:bg-gray-800 px-3 py-2 text-sm font-mono text-gray-900 dark:text-gray-100 placeholder:text-gray-400 dark:placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20 resize-y"
|
||||
className="w-full rounded-md border border-border-default bg-background px-3 py-2 text-sm font-mono text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-blue-500/20 resize-y"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
@@ -366,7 +366,7 @@ const McpWizardModal: React.FC<McpWizardModalProps> = ({
|
||||
<>
|
||||
{/* URL */}
|
||||
<div>
|
||||
<label className="mb-1 block text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
<label className="mb-1 block text-sm font-medium text-foreground">
|
||||
{t("mcp.wizard.url")}{" "}
|
||||
<span className="text-red-500">*</span>
|
||||
</label>
|
||||
@@ -382,7 +382,7 @@ const McpWizardModal: React.FC<McpWizardModalProps> = ({
|
||||
|
||||
{/* Headers */}
|
||||
<div>
|
||||
<label className="mb-1 block text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
<label className="mb-1 block text-sm font-medium text-foreground">
|
||||
{t("mcp.wizard.headers")}
|
||||
</label>
|
||||
<textarea
|
||||
@@ -390,7 +390,7 @@ const McpWizardModal: React.FC<McpWizardModalProps> = ({
|
||||
onChange={(e) => setWizardHeaders(e.target.value)}
|
||||
placeholder={t("mcp.wizard.headersPlaceholder")}
|
||||
rows={3}
|
||||
className="w-full rounded-md border border-border-default bg-white dark:bg-gray-800 px-3 py-2 text-sm font-mono text-gray-900 dark:text-gray-100 placeholder:text-gray-400 dark:placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20 resize-y"
|
||||
className="w-full rounded-md border border-border-default bg-background px-3 py-2 text-sm font-mono text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-blue-500/20 resize-y"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
@@ -404,7 +404,7 @@ const McpWizardModal: React.FC<McpWizardModalProps> = ({
|
||||
wizardUrl ||
|
||||
wizardHeaders) && (
|
||||
<div className="space-y-2 border-t border-border-default pt-4">
|
||||
<h3 className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
<h3 className="text-sm font-medium text-foreground">
|
||||
{t("mcp.wizard.preview")}
|
||||
</h3>
|
||||
<pre className="overflow-x-auto rounded-lg bg-gray-100 dark:bg-gray-800 p-3 text-xs font-mono text-gray-700 dark:text-gray-300">
|
||||
|
||||
@@ -1,17 +1,23 @@
|
||||
import { useCallback } from "react";
|
||||
import { useCallback, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Plus } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { FullScreenPanel } from "@/components/common/FullScreenPanel";
|
||||
import type { Provider, CustomEndpoint } from "@/types";
|
||||
import type { Provider, CustomEndpoint, UniversalProvider } from "@/types";
|
||||
import type { AppId } from "@/lib/api";
|
||||
import { universalProvidersApi } from "@/lib/api";
|
||||
import {
|
||||
ProviderForm,
|
||||
type ProviderFormValues,
|
||||
} from "@/components/providers/forms/ProviderForm";
|
||||
import { UniversalProviderFormModal } from "@/components/universal/UniversalProviderFormModal";
|
||||
import { UniversalProviderPanel } from "@/components/universal";
|
||||
import { providerPresets } from "@/config/claudeProviderPresets";
|
||||
import { codexProviderPresets } from "@/config/codexProviderPresets";
|
||||
import { geminiProviderPresets } from "@/config/geminiProviderPresets";
|
||||
import type { UniversalProviderPreset } from "@/config/universalProviderPresets";
|
||||
|
||||
interface AddProviderDialogProps {
|
||||
open: boolean;
|
||||
@@ -27,6 +33,46 @@ export function AddProviderDialog({
|
||||
onSubmit,
|
||||
}: AddProviderDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [activeTab, setActiveTab] = useState<"app-specific" | "universal">(
|
||||
"app-specific",
|
||||
);
|
||||
const [universalFormOpen, setUniversalFormOpen] = useState(false);
|
||||
const [selectedUniversalPreset, setSelectedUniversalPreset] =
|
||||
useState<UniversalProviderPreset | null>(null);
|
||||
|
||||
// Handle universal provider save
|
||||
const handleUniversalProviderSave = useCallback(
|
||||
async (provider: UniversalProvider) => {
|
||||
try {
|
||||
await universalProvidersApi.upsert(provider);
|
||||
toast.success(
|
||||
t("universalProvider.addSuccess", {
|
||||
defaultValue: "统一供应商添加成功",
|
||||
}),
|
||||
);
|
||||
setUniversalFormOpen(false);
|
||||
setSelectedUniversalPreset(null);
|
||||
onOpenChange(false);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"[AddProviderDialog] Failed to save universal provider",
|
||||
error,
|
||||
);
|
||||
toast.error(
|
||||
t("universalProvider.addFailed", {
|
||||
defaultValue: "统一供应商添加失败",
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
[t, onOpenChange],
|
||||
);
|
||||
|
||||
// Close universal form and return to main dialog
|
||||
const handleUniversalFormClose = useCallback(() => {
|
||||
setUniversalFormOpen(false);
|
||||
setSelectedUniversalPreset(null);
|
||||
}, []);
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
async (values: ProviderFormValues) => {
|
||||
@@ -156,46 +202,86 @@ export function AddProviderDialog({
|
||||
[appId, onSubmit, onOpenChange],
|
||||
);
|
||||
|
||||
const submitLabel =
|
||||
appId === "claude"
|
||||
? t("provider.addClaudeProvider")
|
||||
: appId === "codex"
|
||||
? t("provider.addCodexProvider")
|
||||
: t("provider.addGeminiProvider");
|
||||
|
||||
const footer = (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
className="border-border/20 hover:bg-accent hover:text-accent-foreground"
|
||||
>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
form="provider-form"
|
||||
className="bg-primary text-primary-foreground hover:bg-primary/90"
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
{t("common.add")}
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
// 动态 footer:根据当前 Tab 显示不同按钮
|
||||
const footer =
|
||||
activeTab === "app-specific" ? (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
className="border-border/20 hover:bg-accent hover:text-accent-foreground"
|
||||
>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
form="provider-form"
|
||||
className="bg-primary text-primary-foreground hover:bg-primary/90"
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
{t("common.add")}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
className="border-border/20 hover:bg-accent hover:text-accent-foreground"
|
||||
>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => setUniversalFormOpen(true)}
|
||||
className="bg-primary text-primary-foreground hover:bg-primary/90"
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
{t("universalProvider.add")}
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<FullScreenPanel
|
||||
isOpen={open}
|
||||
title={submitLabel}
|
||||
title={t("provider.addNewProvider")}
|
||||
onClose={() => onOpenChange(false)}
|
||||
footer={footer}
|
||||
>
|
||||
<ProviderForm
|
||||
appId={appId}
|
||||
submitLabel={t("common.add")}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => onOpenChange(false)}
|
||||
showButtons={false}
|
||||
<Tabs
|
||||
value={activeTab}
|
||||
onValueChange={(v) => setActiveTab(v as "app-specific" | "universal")}
|
||||
>
|
||||
<TabsList className="grid w-full grid-cols-2 mb-6">
|
||||
<TabsTrigger value="app-specific">
|
||||
{t(`apps.${appId}`)} {t("provider.tabProvider")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="universal">
|
||||
{t("provider.tabUniversal")}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="app-specific" className="mt-0">
|
||||
<ProviderForm
|
||||
appId={appId}
|
||||
submitLabel={t("common.add")}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => onOpenChange(false)}
|
||||
showButtons={false}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="universal" className="mt-0">
|
||||
<UniversalProviderPanel />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
{/* Universal Provider Form Modal */}
|
||||
<UniversalProviderFormModal
|
||||
isOpen={universalFormOpen}
|
||||
onClose={handleUniversalFormClose}
|
||||
onSave={handleUniversalProviderSave}
|
||||
initialPreset={selectedUniversalPreset}
|
||||
/>
|
||||
</FullScreenPanel>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
interface FailoverPriorityBadgeProps {
|
||||
priority: number; // 1, 2, 3, ...
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 故障转移优先级徽章
|
||||
* 显示供应商在故障转移队列中的优先级顺序
|
||||
*/
|
||||
export function FailoverPriorityBadge({
|
||||
priority,
|
||||
className,
|
||||
}: FailoverPriorityBadgeProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-semibold",
|
||||
"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",
|
||||
className,
|
||||
)}
|
||||
title={t("failover.priority.tooltip", {
|
||||
priority,
|
||||
defaultValue: `故障转移优先级 ${priority}`,
|
||||
})}
|
||||
>
|
||||
P{priority}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
Edit,
|
||||
Loader2,
|
||||
Play,
|
||||
Plus,
|
||||
TestTube2,
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
@@ -22,6 +23,10 @@ interface ProviderActionsProps {
|
||||
onTest?: () => void;
|
||||
onConfigureUsage: () => void;
|
||||
onDelete: () => void;
|
||||
// 故障转移相关
|
||||
isAutoFailoverEnabled?: boolean;
|
||||
isInFailoverQueue?: boolean;
|
||||
onToggleFailover?: (enabled: boolean) => void;
|
||||
}
|
||||
|
||||
export function ProviderActions({
|
||||
@@ -34,38 +39,88 @@ export function ProviderActions({
|
||||
onTest,
|
||||
onConfigureUsage,
|
||||
onDelete,
|
||||
// 故障转移相关
|
||||
isAutoFailoverEnabled = false,
|
||||
isInFailoverQueue = false,
|
||||
onToggleFailover,
|
||||
}: ProviderActionsProps) {
|
||||
const { t } = useTranslation();
|
||||
const iconButtonClass = "h-8 w-8 p-1";
|
||||
|
||||
// 故障转移模式下的按钮逻辑
|
||||
const isFailoverMode = isAutoFailoverEnabled && onToggleFailover;
|
||||
|
||||
// 处理主按钮点击
|
||||
const handleMainButtonClick = () => {
|
||||
if (isFailoverMode) {
|
||||
// 故障转移模式:切换队列状态
|
||||
onToggleFailover(!isInFailoverQueue);
|
||||
} else {
|
||||
// 普通模式:切换供应商
|
||||
onSwitch();
|
||||
}
|
||||
};
|
||||
|
||||
// 主按钮的状态和样式
|
||||
const getMainButtonState = () => {
|
||||
if (isFailoverMode) {
|
||||
// 故障转移模式
|
||||
if (isInFailoverQueue) {
|
||||
return {
|
||||
disabled: false,
|
||||
variant: "secondary" as const,
|
||||
className:
|
||||
"bg-blue-100 text-blue-600 hover:bg-blue-200 dark:bg-blue-900/50 dark:text-blue-400 dark:hover:bg-blue-900/70",
|
||||
icon: <Check className="h-4 w-4" />,
|
||||
text: t("failover.inQueue", { defaultValue: "已加入" }),
|
||||
};
|
||||
}
|
||||
return {
|
||||
disabled: false,
|
||||
variant: "default" as const,
|
||||
className:
|
||||
"bg-blue-500 hover:bg-blue-600 dark:bg-blue-600 dark:hover:bg-blue-700",
|
||||
icon: <Plus className="h-4 w-4" />,
|
||||
text: t("failover.addQueue", { defaultValue: "加入" }),
|
||||
};
|
||||
}
|
||||
|
||||
// 普通模式
|
||||
if (isCurrent) {
|
||||
return {
|
||||
disabled: true,
|
||||
variant: "secondary" as const,
|
||||
className:
|
||||
"bg-gray-200 text-muted-foreground hover:bg-gray-200 hover:text-muted-foreground dark:bg-gray-700 dark:hover:bg-gray-700",
|
||||
icon: <Check className="h-4 w-4" />,
|
||||
text: t("provider.inUse"),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
disabled: false,
|
||||
variant: "default" as const,
|
||||
className: isProxyTakeover
|
||||
? "bg-emerald-500 hover:bg-emerald-600 dark:bg-emerald-600 dark:hover:bg-emerald-700"
|
||||
: "",
|
||||
icon: <Play className="h-4 w-4" />,
|
||||
text: t("provider.enable"),
|
||||
};
|
||||
};
|
||||
|
||||
const buttonState = getMainButtonState();
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
size="sm"
|
||||
variant={isCurrent ? "secondary" : "default"}
|
||||
onClick={onSwitch}
|
||||
disabled={isCurrent}
|
||||
className={cn(
|
||||
"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",
|
||||
)}
|
||||
variant={buttonState.variant}
|
||||
onClick={handleMainButtonClick}
|
||||
disabled={buttonState.disabled}
|
||||
className={cn("w-[4.5rem] px-2.5", buttonState.className)}
|
||||
>
|
||||
{isCurrent ? (
|
||||
<>
|
||||
<Check className="h-4 w-4" />
|
||||
{t("provider.inUse")}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Play className="h-4 w-4" />
|
||||
{t("provider.enable")}
|
||||
</>
|
||||
)}
|
||||
{buttonState.icon}
|
||||
{buttonState.text}
|
||||
</Button>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
|
||||
@@ -12,6 +12,7 @@ import { ProviderActions } from "@/components/providers/ProviderActions";
|
||||
import { ProviderIcon } from "@/components/ProviderIcon";
|
||||
import UsageFooter from "@/components/UsageFooter";
|
||||
import { ProviderHealthBadge } from "@/components/providers/ProviderHealthBadge";
|
||||
import { FailoverPriorityBadge } from "@/components/providers/FailoverPriorityBadge";
|
||||
import { useProviderHealth } from "@/lib/query/failover";
|
||||
import { useUsageQuery } from "@/lib/query/queries";
|
||||
|
||||
@@ -36,6 +37,12 @@ interface ProviderCardProps {
|
||||
isProxyRunning: boolean;
|
||||
isProxyTakeover?: boolean; // 代理接管模式(Live配置已被接管,切换为热切换)
|
||||
dragHandleProps?: DragHandleProps;
|
||||
// 故障转移相关
|
||||
isAutoFailoverEnabled?: boolean; // 是否开启自动故障转移
|
||||
failoverPriority?: number; // 故障转移优先级(1 = P1, 2 = P2, ...)
|
||||
isInFailoverQueue?: boolean; // 是否在故障转移队列中
|
||||
onToggleFailover?: (enabled: boolean) => void; // 切换故障转移队列
|
||||
activeProviderId?: string; // 代理当前实际使用的供应商 ID(用于故障转移模式下标注绿色边框)
|
||||
}
|
||||
|
||||
const extractApiUrl = (provider: Provider, fallbackText: string) => {
|
||||
@@ -88,6 +95,12 @@ export function ProviderCard({
|
||||
isProxyRunning,
|
||||
isProxyTakeover = false,
|
||||
dragHandleProps,
|
||||
// 故障转移相关
|
||||
isAutoFailoverEnabled = false,
|
||||
failoverPriority,
|
||||
isInFailoverQueue = false,
|
||||
onToggleFailover,
|
||||
activeProviderId,
|
||||
}: ProviderCardProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -148,21 +161,32 @@ export function ProviderCard({
|
||||
onOpenWebsite(displayUrl);
|
||||
};
|
||||
|
||||
// 判断是否是"当前使用中"的供应商
|
||||
// - 故障转移模式:代理实际使用的供应商(activeProviderId)
|
||||
// - 代理接管模式(非故障转移):isCurrent
|
||||
// - 普通模式:isCurrent
|
||||
const isActiveProvider = isAutoFailoverEnabled
|
||||
? activeProviderId === provider.id
|
||||
: isCurrent;
|
||||
|
||||
// 判断是否使用绿色(代理接管模式)还是蓝色(普通模式)
|
||||
const shouldUseGreen = isProxyTakeover && isActiveProvider;
|
||||
const shouldUseBlue = !isProxyTakeover && isActiveProvider;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"relative overflow-hidden rounded-xl border border-border p-4 transition-all duration-300",
|
||||
"bg-card text-card-foreground group",
|
||||
// 代理接管模式下 hover 使用绿色边框,否则使用蓝色
|
||||
isProxyTakeover
|
||||
// hover 时的边框效果
|
||||
isAutoFailoverEnabled || 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",
|
||||
// 当前激活的供应商边框样式
|
||||
shouldUseGreen &&
|
||||
"border-emerald-500/60 shadow-sm shadow-emerald-500/10",
|
||||
shouldUseBlue && "border-blue-500/60 shadow-sm shadow-blue-500/10",
|
||||
!isActiveProvider && "hover:shadow-sm",
|
||||
dragHandleProps?.isDragging &&
|
||||
"cursor-grabbing border-primary shadow-lg scale-105 z-10",
|
||||
)}
|
||||
@@ -170,11 +194,11 @@ export function ProviderCard({
|
||||
<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",
|
||||
// 代理接管模式使用绿色渐变,普通模式使用蓝色渐变
|
||||
shouldUseGreen && "from-emerald-500/10",
|
||||
shouldUseBlue && "from-blue-500/10",
|
||||
!isActiveProvider && "from-primary/10",
|
||||
isActiveProvider ? "opacity-100" : "opacity-0",
|
||||
)}
|
||||
/>
|
||||
<div className="relative flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
@@ -209,13 +233,20 @@ export function ProviderCard({
|
||||
{provider.name}
|
||||
</h3>
|
||||
|
||||
{/* 健康状态徽章和优先级 */}
|
||||
{isProxyRunning && health && (
|
||||
{/* 健康状态徽章 */}
|
||||
{isProxyRunning && isInFailoverQueue && health && (
|
||||
<ProviderHealthBadge
|
||||
consecutiveFailures={health.consecutive_failures}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 故障转移优先级徽章 */}
|
||||
{isAutoFailoverEnabled &&
|
||||
isInFailoverQueue &&
|
||||
failoverPriority && (
|
||||
<FailoverPriorityBadge priority={failoverPriority} />
|
||||
)}
|
||||
|
||||
{provider.category === "third_party" &&
|
||||
provider.meta?.isPartner && (
|
||||
<span
|
||||
@@ -308,6 +339,10 @@ export function ProviderCard({
|
||||
onTest={onTest ? () => onTest(provider) : undefined}
|
||||
onConfigureUsage={() => onConfigureUsage(provider)}
|
||||
onDelete={() => onDelete(provider)}
|
||||
// 故障转移相关
|
||||
isAutoFailoverEnabled={isAutoFailoverEnabled}
|
||||
isInFailoverQueue={isInFailoverQueue}
|
||||
onToggleFailover={onToggleFailover}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -21,6 +21,13 @@ import { useDragSort } from "@/hooks/useDragSort";
|
||||
import { useStreamCheck } from "@/hooks/useStreamCheck";
|
||||
import { ProviderCard } from "@/components/providers/ProviderCard";
|
||||
import { ProviderEmptyState } from "@/components/providers/ProviderEmptyState";
|
||||
import {
|
||||
useAutoFailoverEnabled,
|
||||
useFailoverQueue,
|
||||
useAddToFailoverQueue,
|
||||
useRemoveFromFailoverQueue,
|
||||
} from "@/lib/query/failover";
|
||||
import { useCallback } from "react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
@@ -38,6 +45,7 @@ interface ProviderListProps {
|
||||
isLoading?: boolean;
|
||||
isProxyRunning?: boolean; // 代理服务运行状态
|
||||
isProxyTakeover?: boolean; // 代理接管模式(Live配置已被接管)
|
||||
activeProviderId?: string; // 代理当前实际使用的供应商 ID(用于故障转移模式下标注绿色边框)
|
||||
}
|
||||
|
||||
export function ProviderList({
|
||||
@@ -52,18 +60,62 @@ export function ProviderList({
|
||||
onOpenWebsite,
|
||||
onCreate,
|
||||
isLoading = false,
|
||||
isProxyRunning = false, // 默认值为 false
|
||||
isProxyTakeover = false, // 默认值为 false
|
||||
isProxyRunning = false,
|
||||
isProxyTakeover = false,
|
||||
activeProviderId,
|
||||
}: ProviderListProps) {
|
||||
const { t } = useTranslation();
|
||||
const { sortedProviders, sensors, handleDragEnd } = useDragSort(
|
||||
providers,
|
||||
appId
|
||||
appId,
|
||||
);
|
||||
|
||||
// 流式健康检查
|
||||
const { checkProvider, isChecking } = useStreamCheck(appId);
|
||||
|
||||
// 故障转移相关
|
||||
const { data: isAutoFailoverEnabled } = useAutoFailoverEnabled(appId);
|
||||
const { data: failoverQueue } = useFailoverQueue(appId);
|
||||
const addToQueue = useAddToFailoverQueue();
|
||||
const removeFromQueue = useRemoveFromFailoverQueue();
|
||||
|
||||
// 联动状态:只有当前应用开启代理接管且故障转移开启时才启用故障转移模式
|
||||
const isFailoverModeActive =
|
||||
isProxyTakeover === true && isAutoFailoverEnabled === true;
|
||||
|
||||
// 计算供应商在故障转移队列中的优先级(基于 sortIndex 排序)
|
||||
const getFailoverPriority = useCallback(
|
||||
(providerId: string): number | undefined => {
|
||||
if (!isFailoverModeActive || !failoverQueue) return undefined;
|
||||
const index = failoverQueue.findIndex(
|
||||
(item) => item.providerId === providerId,
|
||||
);
|
||||
return index >= 0 ? index + 1 : undefined;
|
||||
},
|
||||
[isFailoverModeActive, failoverQueue],
|
||||
);
|
||||
|
||||
// 判断供应商是否在故障转移队列中
|
||||
const isInFailoverQueue = useCallback(
|
||||
(providerId: string): boolean => {
|
||||
if (!isFailoverModeActive || !failoverQueue) return false;
|
||||
return failoverQueue.some((item) => item.providerId === providerId);
|
||||
},
|
||||
[isFailoverModeActive, failoverQueue],
|
||||
);
|
||||
|
||||
// 切换供应商的故障转移队列状态
|
||||
const handleToggleFailover = useCallback(
|
||||
(providerId: string, enabled: boolean) => {
|
||||
if (enabled) {
|
||||
addToQueue.mutate({ appType: appId, providerId });
|
||||
} else {
|
||||
removeFromQueue.mutate({ appType: appId, providerId });
|
||||
}
|
||||
},
|
||||
[appId, addToQueue, removeFromQueue],
|
||||
);
|
||||
|
||||
const handleTest = (provider: Provider) => {
|
||||
checkProvider(provider.id, provider.name);
|
||||
};
|
||||
@@ -106,7 +158,7 @@ export function ProviderList({
|
||||
return sortedProviders.filter((provider) => {
|
||||
const fields = [provider.name, provider.notes, provider.websiteUrl];
|
||||
return fields.some((field) =>
|
||||
field?.toString().toLowerCase().includes(keyword)
|
||||
field?.toString().toLowerCase().includes(keyword),
|
||||
);
|
||||
});
|
||||
}, [searchTerm, sortedProviders]);
|
||||
@@ -155,6 +207,14 @@ export function ProviderList({
|
||||
isTesting={isChecking(provider.id)}
|
||||
isProxyRunning={isProxyRunning}
|
||||
isProxyTakeover={isProxyTakeover}
|
||||
// 故障转移相关:联动状态
|
||||
isAutoFailoverEnabled={isFailoverModeActive}
|
||||
failoverPriority={getFailoverPriority(provider.id)}
|
||||
isInFailoverQueue={isInFailoverQueue(provider.id)}
|
||||
onToggleFailover={(enabled) =>
|
||||
handleToggleFailover(provider.id, enabled)
|
||||
}
|
||||
activeProviderId={activeProviderId}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -255,6 +315,12 @@ interface SortableProviderCardProps {
|
||||
isTesting: boolean;
|
||||
isProxyRunning: boolean;
|
||||
isProxyTakeover: boolean;
|
||||
// 故障转移相关
|
||||
isAutoFailoverEnabled: boolean;
|
||||
failoverPriority?: number;
|
||||
isInFailoverQueue: boolean;
|
||||
onToggleFailover: (enabled: boolean) => void;
|
||||
activeProviderId?: string;
|
||||
}
|
||||
|
||||
function SortableProviderCard({
|
||||
@@ -271,6 +337,11 @@ function SortableProviderCard({
|
||||
isTesting,
|
||||
isProxyRunning,
|
||||
isProxyTakeover,
|
||||
isAutoFailoverEnabled,
|
||||
failoverPriority,
|
||||
isInFailoverQueue,
|
||||
onToggleFailover,
|
||||
activeProviderId,
|
||||
}: SortableProviderCardProps) {
|
||||
const {
|
||||
setNodeRef,
|
||||
@@ -309,6 +380,12 @@ function SortableProviderCard({
|
||||
listeners,
|
||||
isDragging,
|
||||
}}
|
||||
// 故障转移相关
|
||||
isAutoFailoverEnabled={isAutoFailoverEnabled}
|
||||
failoverPriority={failoverPriority}
|
||||
isInFailoverQueue={isInFailoverQueue}
|
||||
onToggleFailover={onToggleFailover}
|
||||
activeProviderId={activeProviderId}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -31,15 +31,12 @@ const ApiKeyInput: React.FC<ApiKeyInputProps> = ({
|
||||
const inputClass = `w-full px-3 py-2 pr-10 border rounded-lg text-sm transition-colors ${
|
||||
disabled
|
||||
? "bg-muted border-border-default text-muted-foreground cursor-not-allowed"
|
||||
: "border-border-default dark:bg-gray-800 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500/20 dark:focus:ring-blue-400/20"
|
||||
: "border-border-default bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-blue-500/20 dark:focus:ring-blue-400/20"
|
||||
}`;
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor={id}
|
||||
className="block text-sm font-medium text-gray-900 dark:text-gray-100"
|
||||
>
|
||||
<label htmlFor={id} className="block text-sm font-medium text-foreground">
|
||||
{label} {required && "*"}
|
||||
</label>
|
||||
<div className="relative">
|
||||
@@ -58,7 +55,7 @@ const ApiKeyInput: React.FC<ApiKeyInputProps> = ({
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleShowKey}
|
||||
className="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
|
||||
className="absolute inset-y-0 right-0 flex items-center pr-3 text-muted-foreground hover:text-foreground transition-colors"
|
||||
aria-label={showKey ? t("apiKeyInput.hide") : t("apiKeyInput.show")}
|
||||
>
|
||||
{showKey ? <EyeOff size={16} /> : <Eye size={16} />}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FormLabel } from "@/components/ui/form";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import EndpointSpeedTest from "./EndpointSpeedTest";
|
||||
import { ApiKeySection, EndpointField } from "./shared";
|
||||
@@ -39,12 +40,14 @@ interface ClaudeFormFieldsProps {
|
||||
// Model Selector
|
||||
shouldShowModelSelector: boolean;
|
||||
claudeModel: string;
|
||||
reasoningModel: string;
|
||||
defaultHaikuModel: string;
|
||||
defaultSonnetModel: string;
|
||||
defaultOpusModel: string;
|
||||
onModelChange: (
|
||||
field:
|
||||
| "ANTHROPIC_MODEL"
|
||||
| "ANTHROPIC_REASONING_MODEL"
|
||||
| "ANTHROPIC_DEFAULT_HAIKU_MODEL"
|
||||
| "ANTHROPIC_DEFAULT_SONNET_MODEL"
|
||||
| "ANTHROPIC_DEFAULT_OPUS_MODEL",
|
||||
@@ -53,6 +56,11 @@ interface ClaudeFormFieldsProps {
|
||||
|
||||
// Speed Test Endpoints
|
||||
speedTestEndpoints: EndpointCandidate[];
|
||||
|
||||
// OpenRouter Compat
|
||||
showOpenRouterCompatToggle: boolean;
|
||||
openRouterCompatEnabled: boolean;
|
||||
onOpenRouterCompatChange: (enabled: boolean) => void;
|
||||
}
|
||||
|
||||
export function ClaudeFormFields({
|
||||
@@ -77,11 +85,15 @@ export function ClaudeFormFields({
|
||||
onCustomEndpointsChange,
|
||||
shouldShowModelSelector,
|
||||
claudeModel,
|
||||
reasoningModel,
|
||||
defaultHaikuModel,
|
||||
defaultSonnetModel,
|
||||
defaultOpusModel,
|
||||
onModelChange,
|
||||
speedTestEndpoints,
|
||||
showOpenRouterCompatToggle,
|
||||
openRouterCompatEnabled,
|
||||
onOpenRouterCompatChange,
|
||||
}: ClaudeFormFieldsProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -162,6 +174,28 @@ export function ClaudeFormFields({
|
||||
/>
|
||||
)}
|
||||
|
||||
{showOpenRouterCompatToggle && (
|
||||
<div className="flex items-center justify-between rounded-lg border border-white/10 bg-background/60 p-4">
|
||||
<div className="space-y-1">
|
||||
<FormLabel>
|
||||
{t("providerForm.openrouterCompatMode", {
|
||||
defaultValue: "OpenRouter 兼容模式",
|
||||
})}
|
||||
</FormLabel>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("providerForm.openrouterCompatModeHint", {
|
||||
defaultValue:
|
||||
"使用 OpenAI Chat Completions 接口并转换为 Anthropic SSE。",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={openRouterCompatEnabled}
|
||||
onCheckedChange={onOpenRouterCompatChange}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 模型选择器 */}
|
||||
{shouldShowModelSelector && (
|
||||
<div className="space-y-3">
|
||||
@@ -185,6 +219,27 @@ export function ClaudeFormFields({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 推理模型 */}
|
||||
<div className="space-y-2">
|
||||
<FormLabel htmlFor="reasoningModel">
|
||||
{t("providerForm.anthropicReasoningModel", {
|
||||
defaultValue: "推理模型 (Thinking)",
|
||||
})}
|
||||
</FormLabel>
|
||||
<Input
|
||||
id="reasoningModel"
|
||||
type="text"
|
||||
value={reasoningModel}
|
||||
onChange={(e) =>
|
||||
onModelChange("ANTHROPIC_REASONING_MODEL", e.target.value)
|
||||
}
|
||||
placeholder={t("providerForm.reasoningModelPlaceholder", {
|
||||
defaultValue: "",
|
||||
})}
|
||||
autoComplete="off"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 默认 Haiku */}
|
||||
<div className="space-y-2">
|
||||
<FormLabel htmlFor="claudeDefaultHaikuModel">
|
||||
|
||||
@@ -47,7 +47,7 @@ export const CodexAuthSection: React.FC<CodexAuthSectionProps> = ({
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="codexAuth"
|
||||
className="block text-sm font-medium text-gray-900 dark:text-gray-100"
|
||||
className="block text-sm font-medium text-foreground"
|
||||
>
|
||||
{t("codexConfig.authJson")}
|
||||
</label>
|
||||
@@ -67,7 +67,7 @@ export const CodexAuthSection: React.FC<CodexAuthSectionProps> = ({
|
||||
)}
|
||||
|
||||
{!error && (
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("codexConfig.authJsonHint")}
|
||||
</p>
|
||||
)}
|
||||
@@ -120,12 +120,12 @@ export const CodexConfigSection: React.FC<CodexConfigSectionProps> = ({
|
||||
<div className="flex items-center justify-between">
|
||||
<label
|
||||
htmlFor="codexConfig"
|
||||
className="block text-sm font-medium text-gray-900 dark:text-gray-100"
|
||||
className="block text-sm font-medium text-foreground"
|
||||
>
|
||||
{t("codexConfig.configToml")}
|
||||
</label>
|
||||
|
||||
<label className="inline-flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400 cursor-pointer">
|
||||
<label className="inline-flex items-center gap-2 text-sm text-muted-foreground cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={useCommonConfig}
|
||||
@@ -167,7 +167,7 @@ export const CodexConfigSection: React.FC<CodexConfigSectionProps> = ({
|
||||
)}
|
||||
|
||||
{!configError && (
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("codexConfig.configTomlHint")}
|
||||
</p>
|
||||
)}
|
||||
|
||||
@@ -98,7 +98,7 @@ export function CodexFormFields({
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="codexModelName"
|
||||
className="block text-sm font-medium text-gray-900 dark:text-gray-100"
|
||||
className="block text-sm font-medium text-foreground"
|
||||
>
|
||||
{t("codexConfig.modelName", { defaultValue: "模型名称" })}
|
||||
</label>
|
||||
@@ -110,9 +110,9 @@ export function CodexFormFields({
|
||||
placeholder={t("codexConfig.modelNamePlaceholder", {
|
||||
defaultValue: "例如: gpt-5-codex",
|
||||
})}
|
||||
className="w-full px-3 py-2 border border-border-default dark:bg-gray-800 dark:text-gray-100 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 dark:focus:ring-blue-400/20 transition-colors"
|
||||
className="w-full px-3 py-2 border border-border-default bg-background text-foreground rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 dark:focus:ring-blue-400/20 transition-colors"
|
||||
/>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("codexConfig.modelNameHint", {
|
||||
defaultValue: "指定使用的模型,将自动更新到 config.toml 中",
|
||||
})}
|
||||
|
||||
@@ -47,7 +47,7 @@ export const GeminiEnvSection: React.FC<GeminiEnvSectionProps> = ({
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="geminiEnv"
|
||||
className="block text-sm font-medium text-gray-900 dark:text-gray-100"
|
||||
className="block text-sm font-medium text-foreground"
|
||||
>
|
||||
{t("geminiConfig.envFile", { defaultValue: "环境变量 (.env)" })}
|
||||
</label>
|
||||
@@ -69,7 +69,7 @@ GEMINI_MODEL=gemini-3-pro-preview`}
|
||||
)}
|
||||
|
||||
{!error && (
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("geminiConfig.envFileHint", {
|
||||
defaultValue: "使用 .env 格式配置 Gemini 环境变量",
|
||||
})}
|
||||
@@ -124,14 +124,14 @@ export const GeminiConfigSection: React.FC<GeminiConfigSectionProps> = ({
|
||||
<div className="flex items-center justify-between">
|
||||
<label
|
||||
htmlFor="geminiConfig"
|
||||
className="block text-sm font-medium text-gray-900 dark:text-gray-100"
|
||||
className="block text-sm font-medium text-foreground"
|
||||
>
|
||||
{t("geminiConfig.configJson", {
|
||||
defaultValue: "配置文件 (config.json)",
|
||||
})}
|
||||
</label>
|
||||
|
||||
<label className="inline-flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400 cursor-pointer">
|
||||
<label className="inline-flex items-center gap-2 text-sm text-muted-foreground cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={useCommonConfig}
|
||||
@@ -180,7 +180,7 @@ export const GeminiConfigSection: React.FC<GeminiConfigSectionProps> = ({
|
||||
)}
|
||||
|
||||
{!configError && (
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("geminiConfig.configJsonHint", {
|
||||
defaultValue: "使用 JSON 格式配置 Gemini 扩展参数(可选)",
|
||||
})}
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
geminiProviderPresets,
|
||||
type GeminiProviderPreset,
|
||||
} from "@/config/geminiProviderPresets";
|
||||
import type { UniversalProviderPreset } from "@/config/universalProviderPresets";
|
||||
import { applyTemplateValues } from "@/utils/providerConfigUtils";
|
||||
import { mergeProviderMeta } from "@/utils/providerMetaUtils";
|
||||
import { getCodexCustomTemplate } from "@/config/codexTemplates";
|
||||
@@ -72,6 +73,8 @@ interface ProviderFormProps {
|
||||
submitLabel: string;
|
||||
onSubmit: (values: ProviderFormValues) => void;
|
||||
onCancel: () => void;
|
||||
onUniversalPresetSelect?: (preset: UniversalProviderPreset) => void;
|
||||
onManageUniversalProviders?: () => void;
|
||||
initialData?: {
|
||||
name?: string;
|
||||
websiteUrl?: string;
|
||||
@@ -91,6 +94,8 @@ export function ProviderForm({
|
||||
submitLabel,
|
||||
onSubmit,
|
||||
onCancel,
|
||||
onUniversalPresetSelect,
|
||||
onManageUniversalProviders,
|
||||
initialData,
|
||||
showButtons = true,
|
||||
}: ProviderFormProps) {
|
||||
@@ -162,6 +167,8 @@ export function ProviderForm({
|
||||
mode: "onSubmit",
|
||||
});
|
||||
|
||||
const settingsConfigValue = form.watch("settingsConfig");
|
||||
|
||||
// 使用 API Key hook
|
||||
const {
|
||||
apiKey,
|
||||
@@ -187,9 +194,10 @@ export function ProviderForm({
|
||||
},
|
||||
});
|
||||
|
||||
// 使用 Model hook(新:主模型 + Haiku/Sonnet/Opus 默认模型)
|
||||
// 使用 Model hook(新:主模型 + 推理模型 + Haiku/Sonnet/Opus 默认模型)
|
||||
const {
|
||||
claudeModel,
|
||||
reasoningModel,
|
||||
defaultHaikuModel,
|
||||
defaultSonnetModel,
|
||||
defaultOpusModel,
|
||||
@@ -199,6 +207,53 @@ export function ProviderForm({
|
||||
onConfigChange: (config) => form.setValue("settingsConfig", config),
|
||||
});
|
||||
|
||||
const isOpenRouterProvider = useMemo(() => {
|
||||
if (appId !== "claude") return false;
|
||||
const normalized = baseUrl.trim().toLowerCase();
|
||||
if (normalized.includes("openrouter.ai")) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
const config = JSON.parse(settingsConfigValue || "{}");
|
||||
const envUrl = config?.env?.ANTHROPIC_BASE_URL;
|
||||
return typeof envUrl === "string" && envUrl.includes("openrouter.ai");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}, [appId, baseUrl, settingsConfigValue]);
|
||||
|
||||
const openRouterCompatEnabled = useMemo(() => {
|
||||
if (!isOpenRouterProvider) return false;
|
||||
try {
|
||||
const config = JSON.parse(settingsConfigValue || "{}");
|
||||
const raw = config?.openrouter_compat_mode;
|
||||
if (typeof raw === "boolean") return raw;
|
||||
if (typeof raw === "number") return raw !== 0;
|
||||
if (typeof raw === "string") {
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
return normalized === "true" || normalized === "1";
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
return true;
|
||||
}, [isOpenRouterProvider, settingsConfigValue]);
|
||||
|
||||
const handleOpenRouterCompatChange = useCallback(
|
||||
(enabled: boolean) => {
|
||||
try {
|
||||
const currentConfig = JSON.parse(
|
||||
form.getValues("settingsConfig") || "{}",
|
||||
);
|
||||
currentConfig.openrouter_compat_mode = enabled;
|
||||
form.setValue("settingsConfig", JSON.stringify(currentConfig, null, 2));
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
},
|
||||
[form],
|
||||
);
|
||||
|
||||
// 使用 Codex 配置 hook (仅 Codex 模式)
|
||||
const {
|
||||
codexAuth,
|
||||
@@ -753,6 +808,8 @@ export function ProviderForm({
|
||||
categoryKeys={categoryKeys}
|
||||
presetCategoryLabels={presetCategoryLabels}
|
||||
onPresetChange={handlePresetChange}
|
||||
onUniversalPresetSelect={onUniversalPresetSelect}
|
||||
onManageUniversalProviders={onManageUniversalProviders}
|
||||
category={category}
|
||||
/>
|
||||
)}
|
||||
@@ -789,11 +846,15 @@ export function ProviderForm({
|
||||
}
|
||||
shouldShowModelSelector={category !== "official"}
|
||||
claudeModel={claudeModel}
|
||||
reasoningModel={reasoningModel}
|
||||
defaultHaikuModel={defaultHaikuModel}
|
||||
defaultSonnetModel={defaultSonnetModel}
|
||||
defaultOpusModel={defaultOpusModel}
|
||||
onModelChange={handleModelChange}
|
||||
speedTestEndpoints={speedTestEndpoints}
|
||||
showOpenRouterCompatToggle={isOpenRouterProvider}
|
||||
openRouterCompatEnabled={openRouterCompatEnabled}
|
||||
onOpenRouterCompatChange={handleOpenRouterCompatChange}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FormLabel } from "@/components/ui/form";
|
||||
import { ClaudeIcon, CodexIcon, GeminiIcon } from "@/components/BrandIcons";
|
||||
import { Zap, Star } from "lucide-react";
|
||||
import { Zap, Star, Layers, Settings2 } from "lucide-react";
|
||||
import type { ProviderPreset } from "@/config/claudeProviderPresets";
|
||||
import type { CodexProviderPreset } from "@/config/codexProviderPresets";
|
||||
import type { GeminiProviderPreset } from "@/config/geminiProviderPresets";
|
||||
import type { ProviderCategory } from "@/types";
|
||||
import {
|
||||
universalProviderPresets,
|
||||
type UniversalProviderPreset,
|
||||
} from "@/config/universalProviderPresets";
|
||||
import { ProviderIcon } from "@/components/ProviderIcon";
|
||||
|
||||
type PresetEntry = {
|
||||
id: string;
|
||||
@@ -18,6 +23,8 @@ interface ProviderPresetSelectorProps {
|
||||
categoryKeys: string[];
|
||||
presetCategoryLabels: Record<string, string>;
|
||||
onPresetChange: (value: string) => void;
|
||||
onUniversalPresetSelect?: (preset: UniversalProviderPreset) => void;
|
||||
onManageUniversalProviders?: () => void;
|
||||
category?: ProviderCategory; // 当前选中的分类
|
||||
}
|
||||
|
||||
@@ -27,6 +34,8 @@ export function ProviderPresetSelector({
|
||||
categoryKeys,
|
||||
presetCategoryLabels,
|
||||
onPresetChange,
|
||||
onUniversalPresetSelect,
|
||||
onManageUniversalProviders,
|
||||
category,
|
||||
}: ProviderPresetSelectorProps) {
|
||||
const { t } = useTranslation();
|
||||
@@ -164,6 +173,49 @@ export function ProviderPresetSelector({
|
||||
});
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* 统一供应商预设(新的一行) */}
|
||||
{onUniversalPresetSelect && universalProviderPresets.length > 0 && (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{universalProviderPresets.map((preset) => (
|
||||
<button
|
||||
key={`universal-${preset.providerType}`}
|
||||
type="button"
|
||||
onClick={() => onUniversalPresetSelect(preset)}
|
||||
className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors bg-accent text-muted-foreground hover:bg-accent/80 relative"
|
||||
title={t("universalProvider.hint", {
|
||||
defaultValue:
|
||||
"跨应用统一配置,自动同步到 Claude/Codex/Gemini",
|
||||
})}
|
||||
>
|
||||
<ProviderIcon icon={preset.icon} name={preset.name} size={14} />
|
||||
{preset.name}
|
||||
<span className="absolute -top-1 -right-1 flex items-center gap-0.5 rounded-full bg-gradient-to-r from-indigo-500 to-purple-500 px-1.5 py-0.5 text-[10px] font-bold text-white shadow-md">
|
||||
<Layers className="h-2.5 w-2.5" />
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
{/* 管理统一供应商按钮 */}
|
||||
{onManageUniversalProviders && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onManageUniversalProviders}
|
||||
className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors bg-accent text-muted-foreground hover:bg-accent/80"
|
||||
title={t("universalProvider.manage", {
|
||||
defaultValue: "管理统一供应商",
|
||||
})}
|
||||
>
|
||||
<Settings2 className="h-4 w-4" />
|
||||
{t("universalProvider.manage", {
|
||||
defaultValue: "管理",
|
||||
})}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-muted-foreground">{getCategoryHint()}</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -7,13 +7,14 @@ interface UseModelStateProps {
|
||||
|
||||
/**
|
||||
* 管理模型选择状态
|
||||
* 支持 ANTHROPIC_MODEL 和 ANTHROPIC_SMALL_FAST_MODEL
|
||||
* 支持 ANTHROPIC_MODEL, ANTHROPIC_REASONING_MODEL 和各类型默认模型
|
||||
*/
|
||||
export function useModelState({
|
||||
settingsConfig,
|
||||
onConfigChange,
|
||||
}: UseModelStateProps) {
|
||||
const [claudeModel, setClaudeModel] = useState("");
|
||||
const [reasoningModel, setReasoningModel] = useState("");
|
||||
const [defaultHaikuModel, setDefaultHaikuModel] = useState("");
|
||||
const [defaultSonnetModel, setDefaultSonnetModel] = useState("");
|
||||
const [defaultOpusModel, setDefaultOpusModel] = useState("");
|
||||
@@ -29,6 +30,10 @@ export function useModelState({
|
||||
const env = cfg?.env || {};
|
||||
const model =
|
||||
typeof env.ANTHROPIC_MODEL === "string" ? env.ANTHROPIC_MODEL : "";
|
||||
const reasoning =
|
||||
typeof env.ANTHROPIC_REASONING_MODEL === "string"
|
||||
? env.ANTHROPIC_REASONING_MODEL
|
||||
: "";
|
||||
const small =
|
||||
typeof env.ANTHROPIC_SMALL_FAST_MODEL === "string"
|
||||
? env.ANTHROPIC_SMALL_FAST_MODEL
|
||||
@@ -47,6 +52,7 @@ export function useModelState({
|
||||
: model || small;
|
||||
|
||||
setClaudeModel(model || "");
|
||||
setReasoningModel(reasoning || "");
|
||||
setDefaultHaikuModel(haiku || "");
|
||||
setDefaultSonnetModel(sonnet || "");
|
||||
setDefaultOpusModel(opus || "");
|
||||
@@ -59,12 +65,14 @@ export function useModelState({
|
||||
(
|
||||
field:
|
||||
| "ANTHROPIC_MODEL"
|
||||
| "ANTHROPIC_REASONING_MODEL"
|
||||
| "ANTHROPIC_DEFAULT_HAIKU_MODEL"
|
||||
| "ANTHROPIC_DEFAULT_SONNET_MODEL"
|
||||
| "ANTHROPIC_DEFAULT_OPUS_MODEL",
|
||||
value: string,
|
||||
) => {
|
||||
if (field === "ANTHROPIC_MODEL") setClaudeModel(value);
|
||||
if (field === "ANTHROPIC_REASONING_MODEL") setReasoningModel(value);
|
||||
if (field === "ANTHROPIC_DEFAULT_HAIKU_MODEL")
|
||||
setDefaultHaikuModel(value);
|
||||
if (field === "ANTHROPIC_DEFAULT_SONNET_MODEL")
|
||||
@@ -98,6 +106,8 @@ export function useModelState({
|
||||
return {
|
||||
claudeModel,
|
||||
setClaudeModel,
|
||||
reasoningModel,
|
||||
setReasoningModel,
|
||||
defaultHaikuModel,
|
||||
setDefaultHaikuModel,
|
||||
defaultSonnetModel,
|
||||
|
||||
@@ -40,7 +40,7 @@ export function EndpointField({
|
||||
<button
|
||||
type="button"
|
||||
onClick={onManageClick}
|
||||
className="flex items-center gap-1 text-xs text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
|
||||
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<Zap className="h-3.5 w-3.5" />
|
||||
{manageButtonLabel || defaultManageLabel}
|
||||
|
||||
@@ -6,51 +6,67 @@ import { Label } from "@/components/ui/label";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Save, Loader2, Info } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
useCircuitBreakerConfig,
|
||||
useUpdateCircuitBreakerConfig,
|
||||
} from "@/lib/query/failover";
|
||||
import { useAppProxyConfig, useUpdateAppProxyConfig } from "@/lib/query/proxy";
|
||||
|
||||
export interface AutoFailoverConfigPanelProps {
|
||||
enabled: boolean;
|
||||
onEnabledChange: (enabled: boolean) => void;
|
||||
appType: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function AutoFailoverConfigPanel({
|
||||
enabled,
|
||||
onEnabledChange: _onEnabledChange,
|
||||
appType,
|
||||
disabled = false,
|
||||
}: 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();
|
||||
const { data: config, isLoading, error } = useAppProxyConfig(appType);
|
||||
const updateConfig = useUpdateAppProxyConfig();
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
failureThreshold: 5,
|
||||
successThreshold: 2,
|
||||
timeoutSeconds: 60,
|
||||
errorRateThreshold: 0.5,
|
||||
minRequests: 10,
|
||||
autoFailoverEnabled: false,
|
||||
maxRetries: 3,
|
||||
streamingFirstByteTimeout: 30,
|
||||
streamingIdleTimeout: 60,
|
||||
nonStreamingTimeout: 300,
|
||||
circuitFailureThreshold: 5,
|
||||
circuitSuccessThreshold: 2,
|
||||
circuitTimeoutSeconds: 60,
|
||||
circuitErrorRateThreshold: 0.5,
|
||||
circuitMinRequests: 10,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (config) {
|
||||
setFormData({
|
||||
...config,
|
||||
autoFailoverEnabled: config.autoFailoverEnabled,
|
||||
maxRetries: config.maxRetries,
|
||||
streamingFirstByteTimeout: config.streamingFirstByteTimeout,
|
||||
streamingIdleTimeout: config.streamingIdleTimeout,
|
||||
nonStreamingTimeout: config.nonStreamingTimeout,
|
||||
circuitFailureThreshold: config.circuitFailureThreshold,
|
||||
circuitSuccessThreshold: config.circuitSuccessThreshold,
|
||||
circuitTimeoutSeconds: config.circuitTimeoutSeconds,
|
||||
circuitErrorRateThreshold: config.circuitErrorRateThreshold,
|
||||
circuitMinRequests: config.circuitMinRequests,
|
||||
});
|
||||
}
|
||||
}, [config]);
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!config) return;
|
||||
try {
|
||||
await updateConfig.mutateAsync({
|
||||
failureThreshold: formData.failureThreshold,
|
||||
successThreshold: formData.successThreshold,
|
||||
timeoutSeconds: formData.timeoutSeconds,
|
||||
errorRateThreshold: formData.errorRateThreshold,
|
||||
minRequests: formData.minRequests,
|
||||
appType,
|
||||
enabled: config.enabled,
|
||||
autoFailoverEnabled: formData.autoFailoverEnabled,
|
||||
maxRetries: formData.maxRetries,
|
||||
streamingFirstByteTimeout: formData.streamingFirstByteTimeout,
|
||||
streamingIdleTimeout: formData.streamingIdleTimeout,
|
||||
nonStreamingTimeout: formData.nonStreamingTimeout,
|
||||
circuitFailureThreshold: formData.circuitFailureThreshold,
|
||||
circuitSuccessThreshold: formData.circuitSuccessThreshold,
|
||||
circuitTimeoutSeconds: formData.circuitTimeoutSeconds,
|
||||
circuitErrorRateThreshold: formData.circuitErrorRateThreshold,
|
||||
circuitMinRequests: formData.circuitMinRequests,
|
||||
});
|
||||
toast.success(
|
||||
t("proxy.autoFailover.configSaved", "自动故障转移配置已保存"),
|
||||
@@ -66,7 +82,16 @@ export function AutoFailoverConfigPanel({
|
||||
const handleReset = () => {
|
||||
if (config) {
|
||||
setFormData({
|
||||
...config,
|
||||
autoFailoverEnabled: config.autoFailoverEnabled,
|
||||
maxRetries: config.maxRetries,
|
||||
streamingFirstByteTimeout: config.streamingFirstByteTimeout,
|
||||
streamingIdleTimeout: config.streamingIdleTimeout,
|
||||
nonStreamingTimeout: config.nonStreamingTimeout,
|
||||
circuitFailureThreshold: config.circuitFailureThreshold,
|
||||
circuitSuccessThreshold: config.circuitSuccessThreshold,
|
||||
circuitTimeoutSeconds: config.circuitTimeoutSeconds,
|
||||
circuitErrorRateThreshold: config.circuitErrorRateThreshold,
|
||||
circuitMinRequests: config.circuitMinRequests,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -79,16 +104,10 @@ export function AutoFailoverConfigPanel({
|
||||
);
|
||||
}
|
||||
|
||||
const isDisabled = disabled || updateConfig.isPending;
|
||||
|
||||
return (
|
||||
<div className="border-0 rounded-none shadow-none bg-transparent">
|
||||
{/* Header Switch moved to parent accordion logic or kept here absolutely positioned if styling permits.
|
||||
Since we need it in the accordion header, and this component is inside the content, we can use a portal or
|
||||
absolute positioning trick similar to ProxyPanel, OR cleaner, just duplicate the switch logic in SettingsPage
|
||||
and pass it down. But for now, let's use the absolute positioning trick to "lift" it visually.
|
||||
Better yet, let's just render the content directly without the wrapping Card header/collapse logic
|
||||
since the user requested "click to expand is detailed info, no need to fold again" (implying the accordion handles folding).
|
||||
*/}
|
||||
|
||||
<div className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
@@ -114,22 +133,48 @@ export function AutoFailoverConfigPanel({
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="failureThreshold">
|
||||
{t("proxy.autoFailover.failureThreshold", "失败阈值")}
|
||||
<Label htmlFor={`maxRetries-${appType}`}>
|
||||
{t("proxy.autoFailover.maxRetries", "最大重试次数")}
|
||||
</Label>
|
||||
<Input
|
||||
id="failureThreshold"
|
||||
id={`maxRetries-${appType}`}
|
||||
type="number"
|
||||
min="1"
|
||||
max="20"
|
||||
value={formData.failureThreshold}
|
||||
min="0"
|
||||
max="10"
|
||||
value={formData.maxRetries}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
failureThreshold: parseInt(e.target.value) || 5,
|
||||
maxRetries: parseInt(e.target.value) || 3,
|
||||
})
|
||||
}
|
||||
disabled={!enabled}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
"proxy.autoFailover.maxRetriesHint",
|
||||
"请求失败时的重试次数(0-10)",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={`failureThreshold-${appType}`}>
|
||||
{t("proxy.autoFailover.failureThreshold", "失败阈值")}
|
||||
</Label>
|
||||
<Input
|
||||
id={`failureThreshold-${appType}`}
|
||||
type="number"
|
||||
min="1"
|
||||
max="20"
|
||||
value={formData.circuitFailureThreshold}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
circuitFailureThreshold: parseInt(e.target.value) || 5,
|
||||
})
|
||||
}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
@@ -138,59 +183,123 @@ export function AutoFailoverConfigPanel({
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 超时配置 */}
|
||||
<div className="space-y-4 rounded-lg border border-white/10 bg-muted/30 p-4">
|
||||
<h4 className="text-sm font-semibold">
|
||||
{t("proxy.autoFailover.timeoutSettings", "超时配置")}
|
||||
</h4>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="timeoutSeconds">
|
||||
{t("proxy.autoFailover.timeout", "恢复等待时间(秒)")}
|
||||
<Label htmlFor={`streamingFirstByte-${appType}`}>
|
||||
{t(
|
||||
"proxy.autoFailover.streamingFirstByte",
|
||||
"流式首字节超时(秒)",
|
||||
)}
|
||||
</Label>
|
||||
<Input
|
||||
id="timeoutSeconds"
|
||||
id={`streamingFirstByte-${appType}`}
|
||||
type="number"
|
||||
min="10"
|
||||
max="300"
|
||||
value={formData.timeoutSeconds}
|
||||
min="0"
|
||||
max="180"
|
||||
value={formData.streamingFirstByteTimeout}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
timeoutSeconds: parseInt(e.target.value) || 60,
|
||||
streamingFirstByteTimeout: parseInt(e.target.value) || 30,
|
||||
})
|
||||
}
|
||||
disabled={!enabled}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
"proxy.autoFailover.timeoutHint",
|
||||
"熔断器打开后,等待多久后尝试恢复(建议: 30-120)",
|
||||
"proxy.autoFailover.streamingFirstByteHint",
|
||||
"等待首个数据块的最大时间",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={`streamingIdle-${appType}`}>
|
||||
{t("proxy.autoFailover.streamingIdle", "流式静默超时(秒)")}
|
||||
</Label>
|
||||
<Input
|
||||
id={`streamingIdle-${appType}`}
|
||||
type="number"
|
||||
min="0"
|
||||
max="600"
|
||||
value={formData.streamingIdleTimeout}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
streamingIdleTimeout: parseInt(e.target.value) || 60,
|
||||
})
|
||||
}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
"proxy.autoFailover.streamingIdleHint",
|
||||
"数据块之间的最大间隔",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={`nonStreaming-${appType}`}>
|
||||
{t("proxy.autoFailover.nonStreaming", "非流式超时(秒)")}
|
||||
</Label>
|
||||
<Input
|
||||
id={`nonStreaming-${appType}`}
|
||||
type="number"
|
||||
min="0"
|
||||
max="1800"
|
||||
value={formData.nonStreamingTimeout}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
nonStreamingTimeout: parseInt(e.target.value) || 300,
|
||||
})
|
||||
}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
"proxy.autoFailover.nonStreamingHint",
|
||||
"非流式请求的总超时时间",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 熔断器高级配置 */}
|
||||
{/* 熔断器配置 */}
|
||||
<div className="space-y-4 rounded-lg border border-white/10 bg-muted/30 p-4">
|
||||
<h4 className="text-sm font-semibold">
|
||||
{t("proxy.autoFailover.circuitBreakerSettings", "熔断器高级设置")}
|
||||
{t("proxy.autoFailover.circuitBreakerSettings", "熔断器配置")}
|
||||
</h4>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="successThreshold">
|
||||
<Label htmlFor={`successThreshold-${appType}`}>
|
||||
{t("proxy.autoFailover.successThreshold", "恢复成功阈值")}
|
||||
</Label>
|
||||
<Input
|
||||
id="successThreshold"
|
||||
id={`successThreshold-${appType}`}
|
||||
type="number"
|
||||
min="1"
|
||||
max="10"
|
||||
value={formData.successThreshold}
|
||||
value={formData.circuitSuccessThreshold}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
successThreshold: parseInt(e.target.value) || 2,
|
||||
circuitSuccessThreshold: parseInt(e.target.value) || 2,
|
||||
})
|
||||
}
|
||||
disabled={!enabled}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
@@ -201,23 +310,50 @@ export function AutoFailoverConfigPanel({
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="errorRateThreshold">
|
||||
<Label htmlFor={`timeoutSeconds-${appType}`}>
|
||||
{t("proxy.autoFailover.timeout", "恢复等待时间(秒)")}
|
||||
</Label>
|
||||
<Input
|
||||
id={`timeoutSeconds-${appType}`}
|
||||
type="number"
|
||||
min="10"
|
||||
max="300"
|
||||
value={formData.circuitTimeoutSeconds}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
circuitTimeoutSeconds: parseInt(e.target.value) || 60,
|
||||
})
|
||||
}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
"proxy.autoFailover.timeoutHint",
|
||||
"熔断器打开后,等待多久后尝试恢复(建议: 30-120)",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={`errorRateThreshold-${appType}`}>
|
||||
{t("proxy.autoFailover.errorRate", "错误率阈值 (%)")}
|
||||
</Label>
|
||||
<Input
|
||||
id="errorRateThreshold"
|
||||
id={`errorRateThreshold-${appType}`}
|
||||
type="number"
|
||||
min="0"
|
||||
max="100"
|
||||
step="5"
|
||||
value={Math.round(formData.errorRateThreshold * 100)}
|
||||
value={Math.round(formData.circuitErrorRateThreshold * 100)}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
errorRateThreshold: (parseInt(e.target.value) || 50) / 100,
|
||||
circuitErrorRateThreshold:
|
||||
(parseInt(e.target.value) || 50) / 100,
|
||||
})
|
||||
}
|
||||
disabled={!enabled}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
@@ -228,22 +364,22 @@ export function AutoFailoverConfigPanel({
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="minRequests">
|
||||
<Label htmlFor={`minRequests-${appType}`}>
|
||||
{t("proxy.autoFailover.minRequests", "最小请求数")}
|
||||
</Label>
|
||||
<Input
|
||||
id="minRequests"
|
||||
id={`minRequests-${appType}`}
|
||||
type="number"
|
||||
min="5"
|
||||
max="100"
|
||||
value={formData.minRequests}
|
||||
value={formData.circuitMinRequests}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
minRequests: parseInt(e.target.value) || 10,
|
||||
circuitMinRequests: parseInt(e.target.value) || 10,
|
||||
})
|
||||
}
|
||||
disabled={!enabled}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
@@ -257,17 +393,10 @@ export function AutoFailoverConfigPanel({
|
||||
|
||||
{/* 操作按钮 */}
|
||||
<div className="flex justify-end gap-3 pt-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleReset}
|
||||
disabled={updateConfig.isPending || !enabled}
|
||||
>
|
||||
<Button variant="outline" onClick={handleReset} disabled={isDisabled}>
|
||||
{t("common.reset", "重置")}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
disabled={updateConfig.isPending || !enabled}
|
||||
>
|
||||
<Button onClick={handleSave} disabled={isDisabled}>
|
||||
{updateConfig.isPending ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
@@ -281,59 +410,6 @@ export function AutoFailoverConfigPanel({
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 说明信息 */}
|
||||
<div className="p-4 bg-muted/50 rounded-lg space-y-2 text-sm">
|
||||
<h4 className="font-medium">
|
||||
{t("proxy.autoFailover.explanationTitle", "工作原理")}
|
||||
</h4>
|
||||
<ul className="space-y-1 text-muted-foreground">
|
||||
<li>
|
||||
•{" "}
|
||||
<strong>
|
||||
{t("proxy.autoFailover.failureThresholdLabel", "失败阈值")}
|
||||
</strong>
|
||||
:
|
||||
{t(
|
||||
"proxy.autoFailover.failureThresholdExplain",
|
||||
"连续失败达到此次数时,熔断器打开,该供应商暂时不可用",
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
•{" "}
|
||||
<strong>
|
||||
{t("proxy.autoFailover.timeoutLabel", "恢复等待时间")}
|
||||
</strong>
|
||||
:
|
||||
{t(
|
||||
"proxy.autoFailover.timeoutExplain",
|
||||
"熔断器打开后,等待此时间后尝试半开状态",
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
•{" "}
|
||||
<strong>
|
||||
{t("proxy.autoFailover.successThresholdLabel", "恢复成功阈值")}
|
||||
</strong>
|
||||
:
|
||||
{t(
|
||||
"proxy.autoFailover.successThresholdExplain",
|
||||
"半开状态下,成功达到此次数时关闭熔断器,供应商恢复可用",
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
•{" "}
|
||||
<strong>
|
||||
{t("proxy.autoFailover.errorRateLabel", "错误率阈值")}
|
||||
</strong>
|
||||
:
|
||||
{t(
|
||||
"proxy.autoFailover.errorRateExplain",
|
||||
"错误率超过此值时,即使未达到失败阈值也会打开熔断器",
|
||||
)}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -2,37 +2,14 @@
|
||||
* 故障转移队列管理组件
|
||||
*
|
||||
* 允许用户管理代理模式下的故障转移队列,支持:
|
||||
* - 拖拽排序
|
||||
* - 添加/移除供应商
|
||||
* - 启用/禁用队列项
|
||||
* - 队列顺序基于首页供应商列表的 sort_index
|
||||
*/
|
||||
|
||||
import { useState, useCallback, useMemo } from "react";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { CSS } from "@dnd-kit/utilities";
|
||||
import { DndContext, closestCenter } from "@dnd-kit/core";
|
||||
import {
|
||||
SortableContext,
|
||||
useSortable,
|
||||
verticalListSortingStrategy,
|
||||
} from "@dnd-kit/sortable";
|
||||
import {
|
||||
KeyboardSensor,
|
||||
PointerSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type DragEndEvent,
|
||||
} from "@dnd-kit/core";
|
||||
import { arrayMove, sortableKeyboardCoordinates } from "@dnd-kit/sortable";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
GripVertical,
|
||||
Plus,
|
||||
Trash2,
|
||||
Loader2,
|
||||
Info,
|
||||
AlertTriangle,
|
||||
} from "lucide-react";
|
||||
import { Plus, Trash2, Loader2, Info, AlertTriangle } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
@@ -51,8 +28,8 @@ import {
|
||||
useAvailableProvidersForFailover,
|
||||
useAddToFailoverQueue,
|
||||
useRemoveFromFailoverQueue,
|
||||
useReorderFailoverQueue,
|
||||
useSetFailoverItemEnabled,
|
||||
useAutoFailoverEnabled,
|
||||
useSetAutoFailoverEnabled,
|
||||
} from "@/lib/query/failover";
|
||||
|
||||
interface FailoverQueueManagerProps {
|
||||
@@ -67,6 +44,10 @@ export function FailoverQueueManager({
|
||||
const { t } = useTranslation();
|
||||
const [selectedProviderId, setSelectedProviderId] = useState<string>("");
|
||||
|
||||
// 故障转移开关状态(每个应用独立)
|
||||
const { data: isFailoverEnabled = false } = useAutoFailoverEnabled(appType);
|
||||
const setFailoverEnabled = useSetAutoFailoverEnabled();
|
||||
|
||||
// 查询数据
|
||||
const {
|
||||
data: queue,
|
||||
@@ -79,59 +60,11 @@ export function FailoverQueueManager({
|
||||
// Mutations
|
||||
const addToQueue = useAddToFailoverQueue();
|
||||
const removeFromQueue = useRemoveFromFailoverQueue();
|
||||
const reorderQueue = useReorderFailoverQueue();
|
||||
const setItemEnabled = useSetFailoverItemEnabled();
|
||||
|
||||
// 拖拽配置
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, {
|
||||
activationConstraint: { distance: 8 },
|
||||
}),
|
||||
useSensor(KeyboardSensor, {
|
||||
coordinateGetter: sortableKeyboardCoordinates,
|
||||
}),
|
||||
);
|
||||
|
||||
// 排序后的队列
|
||||
const sortedQueue = useMemo(() => {
|
||||
if (!queue) return [];
|
||||
return [...queue].sort((a, b) => a.queueOrder - b.queueOrder);
|
||||
}, [queue]);
|
||||
|
||||
// 处理拖拽结束
|
||||
const handleDragEnd = useCallback(
|
||||
async (event: DragEndEvent) => {
|
||||
const { active, over } = event;
|
||||
if (!over || active.id === over.id || !sortedQueue) return;
|
||||
|
||||
const oldIndex = sortedQueue.findIndex(
|
||||
(item) => item.providerId === active.id,
|
||||
);
|
||||
const newIndex = sortedQueue.findIndex(
|
||||
(item) => item.providerId === over.id,
|
||||
);
|
||||
|
||||
if (oldIndex === -1 || newIndex === -1) return;
|
||||
|
||||
const reordered = arrayMove(sortedQueue, oldIndex, newIndex);
|
||||
const providerIds = reordered.map((item) => item.providerId);
|
||||
|
||||
try {
|
||||
await reorderQueue.mutateAsync({ appType, providerIds });
|
||||
toast.success(
|
||||
t("proxy.failoverQueue.reorderSuccess", "队列顺序已更新"),
|
||||
{ closeButton: true },
|
||||
);
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
t("proxy.failoverQueue.reorderFailed", "更新顺序失败") +
|
||||
": " +
|
||||
String(error),
|
||||
);
|
||||
}
|
||||
},
|
||||
[sortedQueue, appType, reorderQueue, t],
|
||||
);
|
||||
// 切换故障转移开关
|
||||
const handleToggleFailover = (enabled: boolean) => {
|
||||
setFailoverEnabled.mutate({ appType, enabled });
|
||||
};
|
||||
|
||||
// 添加供应商到队列
|
||||
const handleAddProvider = async () => {
|
||||
@@ -171,19 +104,6 @@ export function FailoverQueueManager({
|
||||
}
|
||||
};
|
||||
|
||||
// 切换启用状态
|
||||
const handleToggleEnabled = async (providerId: string, enabled: boolean) => {
|
||||
try {
|
||||
await setItemEnabled.mutateAsync({ appType, providerId, enabled });
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
t("proxy.failoverQueue.toggleFailed", "状态更新失败") +
|
||||
": " +
|
||||
String(error),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
if (isQueueLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-8">
|
||||
@@ -203,13 +123,41 @@ export function FailoverQueueManager({
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* 自动故障转移开关 */}
|
||||
<div className="flex items-center justify-between p-4 rounded-lg bg-muted/50 border border-border/50">
|
||||
<div className="space-y-0.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium">
|
||||
{t("proxy.failover.autoSwitch", {
|
||||
defaultValue: "自动故障转移",
|
||||
})}
|
||||
</span>
|
||||
{isFailoverEnabled && (
|
||||
<span className="px-2 py-0.5 text-xs rounded-full bg-emerald-500/20 text-emerald-600 dark:text-emerald-400">
|
||||
{t("common.enabled", { defaultValue: "已开启" })}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("proxy.failover.autoSwitchDescription", {
|
||||
defaultValue: "开启后,请求失败时自动切换到队列中的下一个供应商",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={isFailoverEnabled}
|
||||
onCheckedChange={handleToggleFailover}
|
||||
disabled={disabled || setFailoverEnabled.isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 说明信息 */}
|
||||
<Alert className="border-blue-500/40 bg-blue-500/10">
|
||||
<Info className="h-4 w-4" />
|
||||
<AlertDescription className="text-sm">
|
||||
{t(
|
||||
"proxy.failoverQueue.info",
|
||||
"当前激活的供应商始终优先。当请求失败时,系统会按队列顺序依次尝试其他供应商。",
|
||||
"队列顺序与首页供应商列表顺序一致。当请求失败时,系统会按顺序依次尝试队列中的供应商。",
|
||||
)}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
@@ -260,7 +208,7 @@ export function FailoverQueueManager({
|
||||
</div>
|
||||
|
||||
{/* 队列列表 */}
|
||||
{sortedQueue.length === 0 ? (
|
||||
{!queue || queue.length === 0 ? (
|
||||
<div className="rounded-lg border border-dashed border-muted-foreground/40 p-8 text-center">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t(
|
||||
@@ -270,39 +218,26 @@ export function FailoverQueueManager({
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
<SortableContext
|
||||
items={sortedQueue.map((item) => item.providerId)}
|
||||
strategy={verticalListSortingStrategy}
|
||||
>
|
||||
<div className="space-y-2">
|
||||
{sortedQueue.map((item, index) => (
|
||||
<SortableQueueItem
|
||||
key={item.providerId}
|
||||
item={item}
|
||||
index={index}
|
||||
disabled={disabled}
|
||||
onToggleEnabled={handleToggleEnabled}
|
||||
onRemove={handleRemoveProvider}
|
||||
isRemoving={removeFromQueue.isPending}
|
||||
isToggling={setItemEnabled.isPending}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
<div className="space-y-2">
|
||||
{queue.map((item, index) => (
|
||||
<QueueItem
|
||||
key={item.providerId}
|
||||
item={item}
|
||||
index={index}
|
||||
disabled={disabled}
|
||||
onRemove={handleRemoveProvider}
|
||||
isRemoving={removeFromQueue.isPending}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 队列说明 */}
|
||||
{sortedQueue.length > 0 && (
|
||||
{queue && queue.length > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
"proxy.failoverQueue.dragHint",
|
||||
"拖拽供应商可调整故障转移顺序,序号越小优先级越高。",
|
||||
"proxy.failoverQueue.orderHint",
|
||||
"队列顺序与首页供应商列表顺序一致,可在首页拖拽调整顺序。",
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
@@ -310,65 +245,29 @@ export function FailoverQueueManager({
|
||||
);
|
||||
}
|
||||
|
||||
interface SortableQueueItemProps {
|
||||
interface QueueItemProps {
|
||||
item: FailoverQueueItem;
|
||||
index: number;
|
||||
disabled: boolean;
|
||||
onToggleEnabled: (providerId: string, enabled: boolean) => void;
|
||||
onRemove: (providerId: string) => void;
|
||||
isRemoving: boolean;
|
||||
isToggling: boolean;
|
||||
}
|
||||
|
||||
function SortableQueueItem({
|
||||
function QueueItem({
|
||||
item,
|
||||
index,
|
||||
disabled,
|
||||
onToggleEnabled,
|
||||
onRemove,
|
||||
isRemoving,
|
||||
isToggling,
|
||||
}: SortableQueueItemProps) {
|
||||
}: QueueItemProps) {
|
||||
const { t } = useTranslation();
|
||||
const {
|
||||
setNodeRef,
|
||||
attributes,
|
||||
listeners,
|
||||
transform,
|
||||
transition,
|
||||
isDragging,
|
||||
} = useSortable({ id: item.providerId, disabled });
|
||||
|
||||
const style = {
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
style={style}
|
||||
className={cn(
|
||||
"flex items-center gap-3 rounded-lg border bg-card p-3 transition-colors",
|
||||
isDragging && "opacity-50 shadow-lg",
|
||||
!item.enabled && "opacity-60",
|
||||
)}
|
||||
>
|
||||
{/* 拖拽手柄 */}
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"cursor-grab touch-none text-muted-foreground hover:text-foreground",
|
||||
disabled && "cursor-not-allowed opacity-50",
|
||||
)}
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
disabled={disabled}
|
||||
aria-label={t("provider.dragHandle", "拖拽排序")}
|
||||
>
|
||||
<GripVertical className="h-5 w-5" />
|
||||
</button>
|
||||
|
||||
{/* 序号 */}
|
||||
<div className="flex h-6 w-6 items-center justify-center rounded-full bg-muted text-xs font-medium">
|
||||
{index + 1}
|
||||
@@ -376,24 +275,11 @@ function SortableQueueItem({
|
||||
|
||||
{/* 供应商名称 */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<span
|
||||
className={cn(
|
||||
"text-sm font-medium truncate block",
|
||||
!item.enabled && "text-muted-foreground line-through",
|
||||
)}
|
||||
>
|
||||
<span className="text-sm font-medium truncate block">
|
||||
{item.providerName}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* 启用开关 */}
|
||||
<Switch
|
||||
checked={item.enabled}
|
||||
onCheckedChange={(checked) => onToggleEnabled(item.providerId, checked)}
|
||||
disabled={disabled || isToggling}
|
||||
aria-label={t("proxy.failoverQueue.toggleEnabled", "启用/禁用")}
|
||||
/>
|
||||
|
||||
{/* 删除按钮 */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
|
||||
@@ -1,26 +1,54 @@
|
||||
import { useState } from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import {
|
||||
Activity,
|
||||
Clock,
|
||||
TrendingUp,
|
||||
Server,
|
||||
ListOrdered,
|
||||
Settings,
|
||||
Save,
|
||||
Loader2,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { useProxyStatus } from "@/hooks/useProxyStatus";
|
||||
import { ProxySettingsDialog } from "./ProxySettingsDialog";
|
||||
import { toast } from "sonner";
|
||||
import { useFailoverQueue } from "@/lib/query/failover";
|
||||
import { ProviderHealthBadge } from "@/components/providers/ProviderHealthBadge";
|
||||
import { useProviderHealth } from "@/lib/query/failover";
|
||||
import {
|
||||
useProxyTakeoverStatus,
|
||||
useSetProxyTakeoverForApp,
|
||||
useGlobalProxyConfig,
|
||||
useUpdateGlobalProxyConfig,
|
||||
} from "@/lib/query/proxy";
|
||||
import type { ProxyStatus } from "@/types/proxy";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export function ProxyPanel() {
|
||||
const { t } = useTranslation();
|
||||
const { status, isRunning } = useProxyStatus();
|
||||
const [showSettings, setShowSettings] = useState(false);
|
||||
|
||||
// 获取应用接管状态
|
||||
const { data: takeoverStatus } = useProxyTakeoverStatus();
|
||||
const setTakeoverForApp = useSetProxyTakeoverForApp();
|
||||
|
||||
// 获取全局代理配置
|
||||
const { data: globalConfig } = useGlobalProxyConfig();
|
||||
const updateGlobalConfig = useUpdateGlobalProxyConfig();
|
||||
|
||||
// 监听地址/端口的本地状态
|
||||
const [listenAddress, setListenAddress] = useState("127.0.0.1");
|
||||
const [listenPort, setListenPort] = useState(5000);
|
||||
|
||||
// 同步全局配置到本地状态
|
||||
useEffect(() => {
|
||||
if (globalConfig) {
|
||||
setListenAddress(globalConfig.listenAddress);
|
||||
setListenPort(globalConfig.listenPort);
|
||||
}
|
||||
}, [globalConfig]);
|
||||
|
||||
// 获取所有三个应用类型的故障转移队列(不包含当前供应商)
|
||||
// 当前供应商始终优先,队列仅用于失败后的备用顺序
|
||||
@@ -28,6 +56,69 @@ export function ProxyPanel() {
|
||||
const { data: codexQueue = [] } = useFailoverQueue("codex");
|
||||
const { data: geminiQueue = [] } = useFailoverQueue("gemini");
|
||||
|
||||
const handleTakeoverChange = async (appType: string, enabled: boolean) => {
|
||||
try {
|
||||
await setTakeoverForApp.mutateAsync({ appType, enabled });
|
||||
toast.success(
|
||||
enabled
|
||||
? t("proxy.takeover.enabled", {
|
||||
app: appType,
|
||||
defaultValue: `${appType} 接管已启用`,
|
||||
})
|
||||
: t("proxy.takeover.disabled", {
|
||||
app: appType,
|
||||
defaultValue: `${appType} 接管已关闭`,
|
||||
}),
|
||||
{ closeButton: true },
|
||||
);
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
t("proxy.takeover.failed", {
|
||||
defaultValue: "切换接管状态失败",
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleLoggingChange = async (enabled: boolean) => {
|
||||
if (!globalConfig) return;
|
||||
try {
|
||||
await updateGlobalConfig.mutateAsync({
|
||||
...globalConfig,
|
||||
enableLogging: enabled,
|
||||
});
|
||||
toast.success(
|
||||
enabled
|
||||
? t("proxy.logging.enabled", { defaultValue: "日志记录已启用" })
|
||||
: t("proxy.logging.disabled", { defaultValue: "日志记录已关闭" }),
|
||||
{ closeButton: true },
|
||||
);
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
t("proxy.logging.failed", { defaultValue: "切换日志状态失败" }),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveBasicConfig = async () => {
|
||||
if (!globalConfig) return;
|
||||
try {
|
||||
await updateGlobalConfig.mutateAsync({
|
||||
...globalConfig,
|
||||
listenAddress,
|
||||
listenPort,
|
||||
});
|
||||
toast.success(
|
||||
t("proxy.settings.configSaved", { defaultValue: "代理配置已保存" }),
|
||||
{ closeButton: true },
|
||||
);
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
t("proxy.settings.configSaveFailed", { defaultValue: "保存配置失败" }),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const formatUptime = (seconds: number): string => {
|
||||
const hours = Math.floor(seconds / 3600);
|
||||
const minutes = Math.floor((seconds % 3600) / 60);
|
||||
@@ -49,22 +140,11 @@ export function ProxyPanel() {
|
||||
<div className="space-y-6">
|
||||
<div className="rounded-lg border border-border bg-muted/40 p-4 space-y-4">
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("proxy.panel.serviceAddress", {
|
||||
defaultValue: "服务地址",
|
||||
})}
|
||||
</p>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => setShowSettings(true)}
|
||||
className="h-7 gap-1.5 text-xs"
|
||||
>
|
||||
<Settings className="h-3.5 w-3.5" />
|
||||
{t("common.settings")}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mb-2">
|
||||
{t("proxy.panel.serviceAddress", {
|
||||
defaultValue: "服务地址",
|
||||
})}
|
||||
</p>
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<code className="flex-1 text-sm bg-background px-3 py-2 rounded border border-border/60">
|
||||
http://{status.address}:{status.port}
|
||||
@@ -87,6 +167,11 @@ export function ProxyPanel() {
|
||||
{t("common.copy")}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-2">
|
||||
{t("proxy.settings.restartRequired", {
|
||||
defaultValue: "修改监听地址/端口需要先停止代理服务",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="pt-3 border-t border-border space-y-2">
|
||||
@@ -130,6 +215,63 @@ export function ProxyPanel() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 应用接管开关 */}
|
||||
<div className="pt-3 border-t border-border space-y-3">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("proxyConfig.appTakeover", {
|
||||
defaultValue: "应用接管",
|
||||
})}
|
||||
</p>
|
||||
<div className="grid gap-2 sm:grid-cols-3">
|
||||
{(["claude", "codex", "gemini"] as const).map((appType) => {
|
||||
const isEnabled =
|
||||
takeoverStatus?.[
|
||||
appType as keyof typeof takeoverStatus
|
||||
] ?? false;
|
||||
return (
|
||||
<div
|
||||
key={appType}
|
||||
className="flex items-center justify-between rounded-md border border-border bg-background/60 px-3 py-2"
|
||||
>
|
||||
<span className="text-sm font-medium capitalize">
|
||||
{appType}
|
||||
</span>
|
||||
<Switch
|
||||
checked={isEnabled}
|
||||
onCheckedChange={(checked) =>
|
||||
handleTakeoverChange(appType, checked)
|
||||
}
|
||||
disabled={setTakeoverForApp.isPending}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 日志记录开关 */}
|
||||
<div className="pt-3 border-t border-border">
|
||||
<div className="flex items-center justify-between rounded-md border border-border bg-background/60 px-3 py-2">
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-sm font-medium">
|
||||
{t("proxy.settings.fields.enableLogging.label", {
|
||||
defaultValue: "启用日志记录",
|
||||
})}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("proxy.settings.fields.enableLogging.description", {
|
||||
defaultValue: "记录所有代理请求,便于排查问题",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={globalConfig?.enableLogging ?? true}
|
||||
onCheckedChange={handleLoggingChange}
|
||||
disabled={updateGlobalConfig.isPending}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 供应商队列 - 按应用类型分组展示 */}
|
||||
{(claudeQueue.length > 0 ||
|
||||
codexQueue.length > 0 ||
|
||||
@@ -147,13 +289,10 @@ export function ProxyPanel() {
|
||||
<ProviderQueueGroup
|
||||
appType="claude"
|
||||
appLabel="Claude"
|
||||
targets={claudeQueue
|
||||
.filter((item) => item.enabled)
|
||||
.sort((a, b) => a.queueOrder - b.queueOrder)
|
||||
.map((item) => ({
|
||||
id: item.providerId,
|
||||
name: item.providerName,
|
||||
}))}
|
||||
targets={claudeQueue.map((item) => ({
|
||||
id: item.providerId,
|
||||
name: item.providerName,
|
||||
}))}
|
||||
status={status}
|
||||
/>
|
||||
)}
|
||||
@@ -163,13 +302,10 @@ export function ProxyPanel() {
|
||||
<ProviderQueueGroup
|
||||
appType="codex"
|
||||
appLabel="Codex"
|
||||
targets={codexQueue
|
||||
.filter((item) => item.enabled)
|
||||
.sort((a, b) => a.queueOrder - b.queueOrder)
|
||||
.map((item) => ({
|
||||
id: item.providerId,
|
||||
name: item.providerName,
|
||||
}))}
|
||||
targets={codexQueue.map((item) => ({
|
||||
id: item.providerId,
|
||||
name: item.providerName,
|
||||
}))}
|
||||
status={status}
|
||||
/>
|
||||
)}
|
||||
@@ -179,13 +315,10 @@ export function ProxyPanel() {
|
||||
<ProviderQueueGroup
|
||||
appType="gemini"
|
||||
appLabel="Gemini"
|
||||
targets={geminiQueue
|
||||
.filter((item) => item.enabled)
|
||||
.sort((a, b) => a.queueOrder - b.queueOrder)
|
||||
.map((item) => ({
|
||||
id: item.providerId,
|
||||
name: item.providerName,
|
||||
}))}
|
||||
targets={geminiQueue.map((item) => ({
|
||||
id: item.providerId,
|
||||
name: item.providerName,
|
||||
}))}
|
||||
status={status}
|
||||
/>
|
||||
)}
|
||||
@@ -226,36 +359,109 @@ export function ProxyPanel() {
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center py-10 text-muted-foreground">
|
||||
<div className="mx-auto w-16 h-16 rounded-full bg-muted flex items-center justify-center mb-4">
|
||||
<Server className="h-8 w-8" />
|
||||
<div className="space-y-6">
|
||||
{/* 空白区域避免冲突 */}
|
||||
<div className="h-4"></div>
|
||||
|
||||
{/* 基础设置 - 监听地址/端口 */}
|
||||
<div className="rounded-lg border border-border bg-muted/40 p-4 space-y-4">
|
||||
<div>
|
||||
<h4 className="text-sm font-semibold">
|
||||
{t("proxy.settings.basic.title", {
|
||||
defaultValue: "基础设置",
|
||||
})}
|
||||
</h4>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("proxy.settings.basic.description", {
|
||||
defaultValue: "配置代理服务监听的地址与端口。",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="listen-address">
|
||||
{t("proxy.settings.fields.listenAddress.label", {
|
||||
defaultValue: "监听地址",
|
||||
})}
|
||||
</Label>
|
||||
<Input
|
||||
id="listen-address"
|
||||
value={listenAddress}
|
||||
onChange={(e) => setListenAddress(e.target.value)}
|
||||
placeholder="127.0.0.1"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("proxy.settings.fields.listenAddress.description", {
|
||||
defaultValue:
|
||||
"代理服务器监听的 IP 地址(推荐 127.0.0.1)",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="listen-port">
|
||||
{t("proxy.settings.fields.listenPort.label", {
|
||||
defaultValue: "监听端口",
|
||||
})}
|
||||
</Label>
|
||||
<Input
|
||||
id="listen-port"
|
||||
type="number"
|
||||
value={listenPort}
|
||||
onChange={(e) =>
|
||||
setListenPort(parseInt(e.target.value) || 5000)
|
||||
}
|
||||
placeholder="5000"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("proxy.settings.fields.listenPort.description", {
|
||||
defaultValue: "代理服务器监听的端口号(1024 ~ 65535)",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleSaveBasicConfig}
|
||||
disabled={updateGlobalConfig.isPending}
|
||||
>
|
||||
{updateGlobalConfig.isPending ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t("common.saving", { defaultValue: "保存中..." })}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
{t("common.save", { defaultValue: "保存" })}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 代理服务已停止提示 */}
|
||||
<div className="text-center py-6 text-muted-foreground">
|
||||
<div className="mx-auto w-16 h-16 rounded-full bg-muted flex items-center justify-center mb-4">
|
||||
<Server className="h-8 w-8" />
|
||||
</div>
|
||||
<p className="text-base font-medium text-foreground mb-1">
|
||||
{t("proxy.panel.stoppedTitle", {
|
||||
defaultValue: "代理服务已停止",
|
||||
})}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("proxy.panel.stoppedDescription", {
|
||||
defaultValue: "使用右上角开关即可启动服务",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-base font-medium text-foreground mb-1">
|
||||
{t("proxy.panel.stoppedTitle", {
|
||||
defaultValue: "代理服务已停止",
|
||||
})}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
{t("proxy.panel.stoppedDescription", {
|
||||
defaultValue: "使用右上角开关即可启动服务",
|
||||
})}
|
||||
</p>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setShowSettings(true)}
|
||||
className="gap-1.5"
|
||||
>
|
||||
<Settings className="h-4 w-4" />
|
||||
{t("proxy.panel.openSettings", {
|
||||
defaultValue: "配置代理服务",
|
||||
})}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<ProxySettingsDialog open={showSettings} onOpenChange={setShowSettings} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,403 +0,0 @@
|
||||
/**
|
||||
* 代理服务设置对话框
|
||||
*/
|
||||
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormDescription,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
import { useProxyConfig } from "@/hooks/useProxyConfig";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { AlertCircle } from "lucide-react";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { FullScreenPanel } from "@/components/common/FullScreenPanel";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
import type { ProxyConfig } from "@/types/proxy";
|
||||
|
||||
// 表单数据类型(仅包含可编辑字段)
|
||||
type ProxyConfigForm = Pick<
|
||||
ProxyConfig,
|
||||
| "listen_address"
|
||||
| "listen_port"
|
||||
| "max_retries"
|
||||
| "request_timeout"
|
||||
| "enable_logging"
|
||||
>;
|
||||
|
||||
const createProxyConfigSchema = (t: TFunction) => {
|
||||
const requestTimeoutSchema = z
|
||||
.number()
|
||||
.min(
|
||||
0,
|
||||
t("proxy.settings.validation.timeoutNonNegative", {
|
||||
defaultValue: "超时时间不能为负数",
|
||||
}),
|
||||
)
|
||||
.max(
|
||||
600,
|
||||
t("proxy.settings.validation.timeoutMax", {
|
||||
defaultValue: "超时时间最多600秒",
|
||||
}),
|
||||
)
|
||||
.refine((value) => value === 0 || value >= 10, {
|
||||
message: t("proxy.settings.validation.timeoutRange", {
|
||||
defaultValue: "请输入 0 或 10-600 之间的数值",
|
||||
}),
|
||||
});
|
||||
|
||||
return z.object({
|
||||
listen_address: z.string().regex(
|
||||
/^(\d{1,3}\.){3}\d{1,3}$/,
|
||||
t("proxy.settings.validation.addressInvalid", {
|
||||
defaultValue: "请输入有效的IP地址",
|
||||
}),
|
||||
),
|
||||
listen_port: z
|
||||
.number()
|
||||
.min(
|
||||
1024,
|
||||
t("proxy.settings.validation.portMin", {
|
||||
defaultValue: "端口必须大于1024",
|
||||
}),
|
||||
)
|
||||
.max(
|
||||
65535,
|
||||
t("proxy.settings.validation.portMax", {
|
||||
defaultValue: "端口必须小于65535",
|
||||
}),
|
||||
),
|
||||
max_retries: z
|
||||
.number()
|
||||
.min(
|
||||
0,
|
||||
t("proxy.settings.validation.retryMin", {
|
||||
defaultValue: "重试次数不能为负",
|
||||
}),
|
||||
)
|
||||
.max(
|
||||
10,
|
||||
t("proxy.settings.validation.retryMax", {
|
||||
defaultValue: "重试次数不能超过10",
|
||||
}),
|
||||
),
|
||||
request_timeout: requestTimeoutSchema,
|
||||
enable_logging: z.boolean(),
|
||||
});
|
||||
};
|
||||
|
||||
interface ProxySettingsDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function ProxySettingsDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
}: ProxySettingsDialogProps) {
|
||||
const { config, isLoading, updateConfig, isUpdating } = useProxyConfig();
|
||||
const { t } = useTranslation();
|
||||
const schema = useMemo(() => createProxyConfigSchema(t), [t]);
|
||||
|
||||
const closePanel = () => onOpenChange(false);
|
||||
|
||||
const form = useForm<ProxyConfigForm>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
listen_address: "127.0.0.1",
|
||||
listen_port: 5000,
|
||||
max_retries: 3,
|
||||
request_timeout: 300,
|
||||
enable_logging: true,
|
||||
},
|
||||
});
|
||||
|
||||
// 当配置加载完成后更新表单
|
||||
useEffect(() => {
|
||||
if (config) {
|
||||
form.reset({
|
||||
listen_address: config.listen_address,
|
||||
listen_port: config.listen_port,
|
||||
max_retries: config.max_retries,
|
||||
request_timeout: config.request_timeout,
|
||||
enable_logging: config.enable_logging,
|
||||
});
|
||||
}
|
||||
}, [config, form]);
|
||||
|
||||
const onSubmit = async (data: ProxyConfigForm) => {
|
||||
try {
|
||||
await updateConfig(data);
|
||||
closePanel();
|
||||
} catch (error) {
|
||||
console.error("Save config failed:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const formId = "proxy-settings-form";
|
||||
|
||||
return (
|
||||
<FullScreenPanel
|
||||
isOpen={open}
|
||||
title={t("proxy.settings.title", { defaultValue: "代理服务设置" })}
|
||||
onClose={closePanel}
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={closePanel}
|
||||
disabled={isUpdating}
|
||||
>
|
||||
{t("common.cancel", { defaultValue: "取消" })}
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
form={formId}
|
||||
disabled={isUpdating || isLoading}
|
||||
>
|
||||
{isUpdating
|
||||
? t("common.saving", { defaultValue: "保存中..." })
|
||||
: t("proxy.settings.actions.save", { defaultValue: "保存配置" })}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-6">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("proxy.settings.description", {
|
||||
defaultValue:
|
||||
"配置本地代理服务器的监听地址、端口和运行参数,保存后立即生效。",
|
||||
})}
|
||||
</p>
|
||||
<Alert className="border-emerald-500/40 bg-emerald-500/10">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription className="text-sm">
|
||||
{t("proxy.settings.alert.autoApply", {
|
||||
defaultValue:
|
||||
"保存后将自动同步到正在运行的代理服务,无需手动重启。",
|
||||
})}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<Form {...form}>
|
||||
<form
|
||||
id={formId}
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className="space-y-6"
|
||||
>
|
||||
<section className="space-y-4 rounded-xl border border-white/10 glass-card p-6">
|
||||
<div>
|
||||
<h3 className="text-base font-semibold text-foreground">
|
||||
{t("proxy.settings.basic.title", {
|
||||
defaultValue: "基础设置",
|
||||
})}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("proxy.settings.basic.description", {
|
||||
defaultValue: "配置代理服务监听的地址与端口。",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="listen_address"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t("proxy.settings.fields.listenAddress.label", {
|
||||
defaultValue: "监听地址",
|
||||
})}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
placeholder={t(
|
||||
"proxy.settings.fields.listenAddress.placeholder",
|
||||
{ defaultValue: "127.0.0.1" },
|
||||
)}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t("proxy.settings.fields.listenAddress.description", {
|
||||
defaultValue:
|
||||
"代理服务器监听的 IP 地址(推荐 127.0.0.1)",
|
||||
})}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="listen_port"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t("proxy.settings.fields.listenPort.label", {
|
||||
defaultValue: "监听端口",
|
||||
})}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
{...field}
|
||||
onChange={(e) =>
|
||||
field.onChange(parseInt(e.target.value, 10) || 0)
|
||||
}
|
||||
placeholder={t(
|
||||
"proxy.settings.fields.listenPort.placeholder",
|
||||
{ defaultValue: "5000" },
|
||||
)}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t("proxy.settings.fields.listenPort.description", {
|
||||
defaultValue:
|
||||
"代理服务器监听的端口号(1024 ~ 65535)",
|
||||
})}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="space-y-4 rounded-xl border border-white/10 glass-card p-6">
|
||||
<div>
|
||||
<h3 className="text-base font-semibold text-foreground">
|
||||
{t("proxy.settings.advanced.title", {
|
||||
defaultValue: "高级参数",
|
||||
})}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("proxy.settings.advanced.description", {
|
||||
defaultValue: "控制请求的稳定性和日志记录。",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="max_retries"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t("proxy.settings.fields.maxRetries.label", {
|
||||
defaultValue: "最大重试次数",
|
||||
})}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
{...field}
|
||||
onChange={(e) =>
|
||||
field.onChange(parseInt(e.target.value, 10) || 0)
|
||||
}
|
||||
placeholder={t(
|
||||
"proxy.settings.fields.maxRetries.placeholder",
|
||||
{ defaultValue: "3" },
|
||||
)}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t("proxy.settings.fields.maxRetries.description", {
|
||||
defaultValue: "请求失败时的重试次数(0 ~ 10)",
|
||||
})}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="request_timeout"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t("proxy.settings.fields.requestTimeout.label", {
|
||||
defaultValue: "请求超时(秒)",
|
||||
})}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
{...field}
|
||||
onChange={(e) =>
|
||||
field.onChange(parseInt(e.target.value, 10) || 0)
|
||||
}
|
||||
placeholder={t(
|
||||
"proxy.settings.fields.requestTimeout.placeholder",
|
||||
{ defaultValue: "0(不限)或 300" },
|
||||
)}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t("proxy.settings.fields.requestTimeout.description", {
|
||||
defaultValue:
|
||||
"单个请求的最大等待时间(0 表示不限制,或设置 10 ~ 600 秒)",
|
||||
})}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="enable_logging"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex items-center justify-between rounded-lg border border-white/10 bg-background/60 p-4">
|
||||
<div className="space-y-1">
|
||||
<FormLabel>
|
||||
{t("proxy.settings.fields.enableLogging.label", {
|
||||
defaultValue: "启用日志记录",
|
||||
})}
|
||||
</FormLabel>
|
||||
<FormDescription>
|
||||
{t("proxy.settings.fields.enableLogging.description", {
|
||||
defaultValue: "记录所有代理请求,便于排查问题",
|
||||
})}
|
||||
</FormDescription>
|
||||
</div>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</section>
|
||||
</form>
|
||||
</Form>
|
||||
</div>
|
||||
</FullScreenPanel>
|
||||
);
|
||||
}
|
||||
@@ -3,4 +3,3 @@
|
||||
*/
|
||||
|
||||
export { ProxyPanel } from "./ProxyPanel";
|
||||
export { ProxySettingsDialog } from "./ProxySettingsDialog";
|
||||
|
||||
@@ -47,10 +47,6 @@ import type { SettingsFormState } from "@/hooks/useSettings";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { useProxyStatus } from "@/hooks/useProxyStatus";
|
||||
import {
|
||||
useAutoFailoverEnabled,
|
||||
useSetAutoFailoverEnabled,
|
||||
} from "@/lib/query/failover";
|
||||
|
||||
interface SettingsDialogProps {
|
||||
open: boolean;
|
||||
@@ -187,17 +183,9 @@ export function SettingsPage({
|
||||
isPending: isProxyPending,
|
||||
} = useProxyStatus();
|
||||
|
||||
// 使用持久化的自动故障转移开关状态
|
||||
const { data: failoverEnabled = false } = useAutoFailoverEnabled();
|
||||
const setAutoFailoverEnabled = useSetAutoFailoverEnabled();
|
||||
|
||||
const handleToggleProxy = async (checked: boolean) => {
|
||||
try {
|
||||
if (!checked) {
|
||||
// 关闭代理时,同时关闭故障转移
|
||||
if (failoverEnabled) {
|
||||
setAutoFailoverEnabled.mutate(false);
|
||||
}
|
||||
await stopWithRestore();
|
||||
} else {
|
||||
await startProxyServer();
|
||||
@@ -207,19 +195,6 @@ export function SettingsPage({
|
||||
}
|
||||
};
|
||||
|
||||
// 处理故障转移开关:开启时自动启动代理
|
||||
const handleToggleFailover = async (checked: boolean) => {
|
||||
try {
|
||||
if (checked && !isRunning) {
|
||||
// 开启故障转移时,先启动代理
|
||||
await startProxyServer();
|
||||
}
|
||||
setAutoFailoverEnabled.mutate(checked);
|
||||
} catch (error) {
|
||||
console.error("Toggle failover failed:", error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-[56rem] flex flex-col h-[calc(100vh-8rem)] overflow-hidden px-6">
|
||||
{isBusy ? (
|
||||
@@ -380,80 +355,118 @@ export function SettingsPage({
|
||||
|
||||
<AccordionItem
|
||||
value="failover"
|
||||
className="rounded-xl glass-card overflow-hidden [&[data-state=open]>.accordion-header]:bg-muted/50"
|
||||
className="rounded-xl glass-card overflow-hidden"
|
||||
>
|
||||
<AccordionPrimitive.Header className="accordion-header flex items-center justify-between px-6 py-4 hover:bg-muted/50">
|
||||
<AccordionPrimitive.Trigger className="flex flex-1 items-center justify-between hover:no-underline [&[data-state=open]>svg]:rotate-180">
|
||||
<div className="flex items-center gap-3">
|
||||
<Activity className="h-5 w-5 text-orange-500" />
|
||||
<div className="text-left">
|
||||
<h3 className="text-base font-semibold">
|
||||
{t("settings.advanced.failover.title")}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground font-normal">
|
||||
{t("settings.advanced.failover.description")}
|
||||
</p>
|
||||
</div>
|
||||
<AccordionTrigger className="px-6 py-4 hover:no-underline hover:bg-muted/50 data-[state=open]:bg-muted/50">
|
||||
<div className="flex items-center gap-3">
|
||||
<Activity className="h-5 w-5 text-orange-500" />
|
||||
<div className="text-left">
|
||||
<h3 className="text-base font-semibold">
|
||||
{t("settings.advanced.failover.title")}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground font-normal">
|
||||
{t("settings.advanced.failover.description")}
|
||||
</p>
|
||||
</div>
|
||||
<ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-200" />
|
||||
</AccordionPrimitive.Trigger>
|
||||
|
||||
<div className="flex items-center gap-2 pl-4">
|
||||
<Switch
|
||||
checked={failoverEnabled && isRunning}
|
||||
onCheckedChange={handleToggleFailover}
|
||||
disabled={
|
||||
setAutoFailoverEnabled.isPending || isProxyPending
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</AccordionPrimitive.Header>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-6 pb-6 pt-4 border-t border-border/50">
|
||||
<div className="space-y-6">
|
||||
{/* 故障转移队列管理 */}
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h4 className="text-sm font-semibold">
|
||||
{t("proxy.failoverQueue.title")}
|
||||
</h4>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("proxy.failoverQueue.description")}
|
||||
{/* 代理未运行时的提示 */}
|
||||
{!isRunning && (
|
||||
<div className="p-4 rounded-lg bg-yellow-500/10 border border-yellow-500/20">
|
||||
<p className="text-sm text-yellow-600 dark:text-yellow-400">
|
||||
{t("proxy.failover.proxyRequired", {
|
||||
defaultValue:
|
||||
"需要先启动代理服务才能配置故障转移",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
<Tabs defaultValue="claude" className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-3">
|
||||
<TabsTrigger value="claude">Claude</TabsTrigger>
|
||||
<TabsTrigger value="codex">Codex</TabsTrigger>
|
||||
<TabsTrigger value="gemini">Gemini</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="claude" className="mt-4">
|
||||
)}
|
||||
|
||||
{/* 故障转移设置 - 按应用分组 */}
|
||||
<Tabs defaultValue="claude" className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-3">
|
||||
<TabsTrigger value="claude">Claude</TabsTrigger>
|
||||
<TabsTrigger value="codex">Codex</TabsTrigger>
|
||||
<TabsTrigger value="gemini">Gemini</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent
|
||||
value="claude"
|
||||
className="mt-4 space-y-6"
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h4 className="text-sm font-semibold">
|
||||
{t("proxy.failoverQueue.title")}
|
||||
</h4>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("proxy.failoverQueue.description")}
|
||||
</p>
|
||||
</div>
|
||||
<FailoverQueueManager
|
||||
appType="claude"
|
||||
disabled={!failoverEnabled || !isRunning}
|
||||
disabled={!isRunning}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="codex" className="mt-4">
|
||||
</div>
|
||||
<div className="border-t border-border/50 pt-6">
|
||||
<AutoFailoverConfigPanel
|
||||
appType="claude"
|
||||
disabled={!isRunning}
|
||||
/>
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent
|
||||
value="codex"
|
||||
className="mt-4 space-y-6"
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h4 className="text-sm font-semibold">
|
||||
{t("proxy.failoverQueue.title")}
|
||||
</h4>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("proxy.failoverQueue.description")}
|
||||
</p>
|
||||
</div>
|
||||
<FailoverQueueManager
|
||||
appType="codex"
|
||||
disabled={!failoverEnabled || !isRunning}
|
||||
disabled={!isRunning}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="gemini" className="mt-4">
|
||||
</div>
|
||||
<div className="border-t border-border/50 pt-6">
|
||||
<AutoFailoverConfigPanel
|
||||
appType="codex"
|
||||
disabled={!isRunning}
|
||||
/>
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent
|
||||
value="gemini"
|
||||
className="mt-4 space-y-6"
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h4 className="text-sm font-semibold">
|
||||
{t("proxy.failoverQueue.title")}
|
||||
</h4>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("proxy.failoverQueue.description")}
|
||||
</p>
|
||||
</div>
|
||||
<FailoverQueueManager
|
||||
appType="gemini"
|
||||
disabled={!failoverEnabled || !isRunning}
|
||||
disabled={!isRunning}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
{/* 熔断器配置 */}
|
||||
<div className="border-t border-border/50 pt-6">
|
||||
<AutoFailoverConfigPanel
|
||||
enabled={failoverEnabled && isRunning}
|
||||
onEnabledChange={handleToggleFailover}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-t border-border/50 pt-6">
|
||||
<AutoFailoverConfigPanel
|
||||
appType="gemini"
|
||||
disabled={!isRunning}
|
||||
/>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
|
||||
@@ -231,10 +231,10 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
</div>
|
||||
) : skills.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center h-64 text-center">
|
||||
<p className="text-lg font-medium text-gray-900 dark:text-gray-100">
|
||||
<p className="text-lg font-medium text-foreground">
|
||||
{t("skills.empty")}
|
||||
</p>
|
||||
<p className="mt-2 text-sm text-gray-500 dark:text-gray-400">
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
{t("skills.emptyDescription")}
|
||||
</p>
|
||||
<Button
|
||||
@@ -306,10 +306,10 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
{/* 技能列表或无结果提示 */}
|
||||
{filteredSkills.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center h-48 text-center">
|
||||
<p className="text-lg font-medium text-gray-900 dark:text-gray-100">
|
||||
<p className="text-lg font-medium text-foreground">
|
||||
{t("skills.noResults")}
|
||||
</p>
|
||||
<p className="mt-2 text-sm text-gray-500 dark:text-gray-400">
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
{t("skills.emptyDescription")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Edit2, Trash2, RefreshCw, Globe } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ProviderIcon } from "@/components/ProviderIcon";
|
||||
import type { UniversalProvider } from "@/types";
|
||||
|
||||
interface UniversalProviderCardProps {
|
||||
provider: UniversalProvider;
|
||||
onEdit: (provider: UniversalProvider) => void;
|
||||
onDelete: (id: string) => void;
|
||||
onSync: (id: string) => void;
|
||||
}
|
||||
|
||||
export function UniversalProviderCard({
|
||||
provider,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onSync,
|
||||
}: UniversalProviderCardProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// 获取启用的应用列表
|
||||
const enabledApps: string[] = [
|
||||
provider.apps.claude ? "Claude" : null,
|
||||
provider.apps.codex ? "Codex" : null,
|
||||
provider.apps.gemini ? "Gemini" : null,
|
||||
].filter((app): app is string => app !== null);
|
||||
|
||||
return (
|
||||
<div className="group relative rounded-xl border border-border/50 bg-card p-4 transition-all hover:border-border hover:shadow-md">
|
||||
{/* 头部:图标和名称 */}
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-accent">
|
||||
<ProviderIcon icon={provider.icon} name={provider.name} size={24} />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-foreground">{provider.name}</h3>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{provider.providerType}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 操作按钮 */}
|
||||
<div className="flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => onSync(provider.id)}
|
||||
title={t("universalProvider.sync", { defaultValue: "同步到应用" })}
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => onEdit(provider)}
|
||||
title={t("common.edit", { defaultValue: "编辑" })}
|
||||
>
|
||||
<Edit2 className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-destructive hover:text-destructive"
|
||||
onClick={() => onDelete(provider.id)}
|
||||
title={t("common.delete", { defaultValue: "删除" })}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 配置信息 */}
|
||||
<div className="mt-4 space-y-2">
|
||||
{/* Base URL */}
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<Globe className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<span className="truncate text-muted-foreground">
|
||||
{provider.baseUrl || "-"}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* 启用的应用 */}
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{enabledApps.map((app) => (
|
||||
<span
|
||||
key={app}
|
||||
className="inline-flex items-center rounded-full bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary"
|
||||
>
|
||||
{app}
|
||||
</span>
|
||||
))}
|
||||
{enabledApps.length === 0 && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t("universalProvider.noAppsEnabled", {
|
||||
defaultValue: "未启用任何应用",
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 备注 */}
|
||||
{provider.notes && (
|
||||
<p className="mt-3 text-xs text-muted-foreground line-clamp-2">
|
||||
{provider.notes}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,718 @@
|
||||
import { useState, useEffect, useCallback, useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Eye, EyeOff, RefreshCw } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { FullScreenPanel } from "@/components/common/FullScreenPanel";
|
||||
import { ConfirmDialog } from "@/components/ConfirmDialog";
|
||||
import { ProviderIcon } from "@/components/ProviderIcon";
|
||||
import JsonEditor from "@/components/JsonEditor";
|
||||
import type { UniversalProvider, UniversalProviderModels } from "@/types";
|
||||
import {
|
||||
universalProviderPresets,
|
||||
createUniversalProviderFromPreset,
|
||||
type UniversalProviderPreset,
|
||||
} from "@/config/universalProviderPresets";
|
||||
|
||||
interface UniversalProviderFormModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSave: (provider: UniversalProvider) => void;
|
||||
onSaveAndSync?: (provider: UniversalProvider) => void;
|
||||
editingProvider?: UniversalProvider | null;
|
||||
initialPreset?: UniversalProviderPreset | null;
|
||||
}
|
||||
|
||||
export function UniversalProviderFormModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSave,
|
||||
onSaveAndSync,
|
||||
editingProvider,
|
||||
initialPreset,
|
||||
}: UniversalProviderFormModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const isEditMode = !!editingProvider;
|
||||
|
||||
// 表单状态
|
||||
const [selectedPreset, setSelectedPreset] =
|
||||
useState<UniversalProviderPreset | null>(null);
|
||||
const [name, setName] = useState("");
|
||||
const [baseUrl, setBaseUrl] = useState("");
|
||||
const [apiKey, setApiKey] = useState("");
|
||||
const [showApiKey, setShowApiKey] = useState(false);
|
||||
const [websiteUrl, setWebsiteUrl] = useState("");
|
||||
const [notes, setNotes] = useState("");
|
||||
|
||||
// 应用启用状态
|
||||
const [claudeEnabled, setClaudeEnabled] = useState(true);
|
||||
const [codexEnabled, setCodexEnabled] = useState(true);
|
||||
const [geminiEnabled, setGeminiEnabled] = useState(true);
|
||||
|
||||
// 模型配置
|
||||
const [models, setModels] = useState<UniversalProviderModels>({});
|
||||
|
||||
// 保存并同步确认弹窗
|
||||
const [syncConfirmOpen, setSyncConfirmOpen] = useState(false);
|
||||
const [pendingProvider, setPendingProvider] =
|
||||
useState<UniversalProvider | null>(null);
|
||||
|
||||
// 初始化表单
|
||||
useEffect(() => {
|
||||
if (editingProvider) {
|
||||
// 编辑模式:加载现有数据
|
||||
setName(editingProvider.name);
|
||||
setBaseUrl(editingProvider.baseUrl);
|
||||
setApiKey(editingProvider.apiKey);
|
||||
setWebsiteUrl(editingProvider.websiteUrl || "");
|
||||
setNotes(editingProvider.notes || "");
|
||||
setClaudeEnabled(editingProvider.apps.claude);
|
||||
setCodexEnabled(editingProvider.apps.codex);
|
||||
setGeminiEnabled(editingProvider.apps.gemini);
|
||||
setModels(editingProvider.models || {});
|
||||
|
||||
// 尝试匹配预设
|
||||
const preset = universalProviderPresets.find(
|
||||
(p) => p.providerType === editingProvider.providerType,
|
||||
);
|
||||
setSelectedPreset(preset || null);
|
||||
} else {
|
||||
// 新建模式:使用传入的预设或默认选择第一个预设
|
||||
const defaultPreset = initialPreset || universalProviderPresets[0];
|
||||
setSelectedPreset(defaultPreset);
|
||||
setName(defaultPreset.name);
|
||||
setBaseUrl("");
|
||||
setApiKey("");
|
||||
setWebsiteUrl(defaultPreset.websiteUrl || "");
|
||||
setNotes("");
|
||||
setClaudeEnabled(defaultPreset.defaultApps.claude);
|
||||
setCodexEnabled(defaultPreset.defaultApps.codex);
|
||||
setGeminiEnabled(defaultPreset.defaultApps.gemini);
|
||||
setModels(JSON.parse(JSON.stringify(defaultPreset.defaultModels)));
|
||||
}
|
||||
}, [editingProvider, initialPreset, isOpen]);
|
||||
|
||||
// 选择预设
|
||||
const handlePresetSelect = useCallback(
|
||||
(preset: UniversalProviderPreset) => {
|
||||
setSelectedPreset(preset);
|
||||
if (!isEditMode) {
|
||||
setName(preset.name);
|
||||
setClaudeEnabled(preset.defaultApps.claude);
|
||||
setCodexEnabled(preset.defaultApps.codex);
|
||||
setGeminiEnabled(preset.defaultApps.gemini);
|
||||
setModels(JSON.parse(JSON.stringify(preset.defaultModels)));
|
||||
}
|
||||
},
|
||||
[isEditMode],
|
||||
);
|
||||
|
||||
// 更新模型配置
|
||||
const updateModel = useCallback(
|
||||
(app: "claude" | "codex" | "gemini", field: string, value: string) => {
|
||||
setModels((prev) => ({
|
||||
...prev,
|
||||
[app]: {
|
||||
...(prev[app] || {}),
|
||||
[field]: value,
|
||||
},
|
||||
}));
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// 计算 Claude 配置 JSON 预览
|
||||
const claudeConfigJson = useMemo(() => {
|
||||
if (!claudeEnabled) return null;
|
||||
const model = models.claude?.model || "claude-sonnet-4-20250514";
|
||||
const haiku = models.claude?.haikuModel || "claude-haiku-4-20250514";
|
||||
const sonnet = models.claude?.sonnetModel || "claude-sonnet-4-20250514";
|
||||
const opus = models.claude?.opusModel || "claude-sonnet-4-20250514";
|
||||
return {
|
||||
env: {
|
||||
ANTHROPIC_BASE_URL: baseUrl,
|
||||
ANTHROPIC_AUTH_TOKEN: apiKey,
|
||||
ANTHROPIC_MODEL: model,
|
||||
ANTHROPIC_DEFAULT_HAIKU_MODEL: haiku,
|
||||
ANTHROPIC_DEFAULT_SONNET_MODEL: sonnet,
|
||||
ANTHROPIC_DEFAULT_OPUS_MODEL: opus,
|
||||
},
|
||||
};
|
||||
}, [claudeEnabled, baseUrl, apiKey, models.claude]);
|
||||
|
||||
// 计算 Codex 配置 JSON 预览
|
||||
const codexConfigJson = useMemo(() => {
|
||||
if (!codexEnabled) return null;
|
||||
const model = models.codex?.model || "gpt-4o";
|
||||
const reasoningEffort = models.codex?.reasoningEffort || "high";
|
||||
// 确保 base_url 以 /v1 结尾(Codex 使用 OpenAI 兼容 API)
|
||||
const codexBaseUrl = baseUrl.endsWith("/v1")
|
||||
? baseUrl
|
||||
: `${baseUrl.replace(/\/+$/, "")}/v1`;
|
||||
const configToml = `model_provider = "newapi"
|
||||
model = "${model}"
|
||||
model_reasoning_effort = "${reasoningEffort}"
|
||||
disable_response_storage = true
|
||||
|
||||
[model_providers.newapi]
|
||||
name = "NewAPI"
|
||||
base_url = "${codexBaseUrl}"
|
||||
wire_api = "responses"
|
||||
requires_openai_auth = true`;
|
||||
return {
|
||||
auth: {
|
||||
OPENAI_API_KEY: apiKey,
|
||||
},
|
||||
config: configToml,
|
||||
};
|
||||
}, [codexEnabled, baseUrl, apiKey, models.codex]);
|
||||
|
||||
// 计算 Gemini 配置 JSON 预览
|
||||
const geminiConfigJson = useMemo(() => {
|
||||
if (!geminiEnabled) return null;
|
||||
const model = models.gemini?.model || "gemini-2.5-pro";
|
||||
return {
|
||||
env: {
|
||||
GOOGLE_GEMINI_BASE_URL: baseUrl,
|
||||
GEMINI_API_KEY: apiKey,
|
||||
GEMINI_MODEL: model,
|
||||
},
|
||||
};
|
||||
}, [geminiEnabled, baseUrl, apiKey, models.gemini]);
|
||||
|
||||
// 提交表单
|
||||
const handleSubmit = useCallback(() => {
|
||||
if (!name.trim() || !baseUrl.trim() || !apiKey.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const provider: UniversalProvider = editingProvider
|
||||
? {
|
||||
...editingProvider,
|
||||
name: name.trim(),
|
||||
baseUrl: baseUrl.trim(),
|
||||
apiKey: apiKey.trim(),
|
||||
websiteUrl: websiteUrl.trim() || undefined,
|
||||
notes: notes.trim() || undefined,
|
||||
apps: {
|
||||
claude: claudeEnabled,
|
||||
codex: codexEnabled,
|
||||
gemini: geminiEnabled,
|
||||
},
|
||||
models,
|
||||
}
|
||||
: createUniversalProviderFromPreset(
|
||||
selectedPreset || universalProviderPresets[0],
|
||||
crypto.randomUUID(),
|
||||
baseUrl.trim(),
|
||||
apiKey.trim(),
|
||||
name.trim(),
|
||||
);
|
||||
|
||||
// 如果是新建,更新应用启用状态和模型
|
||||
if (!editingProvider) {
|
||||
provider.apps = {
|
||||
claude: claudeEnabled,
|
||||
codex: codexEnabled,
|
||||
gemini: geminiEnabled,
|
||||
};
|
||||
provider.models = models;
|
||||
provider.websiteUrl = websiteUrl.trim() || undefined;
|
||||
provider.notes = notes.trim() || undefined;
|
||||
}
|
||||
|
||||
onSave(provider);
|
||||
onClose();
|
||||
}, [
|
||||
editingProvider,
|
||||
name,
|
||||
baseUrl,
|
||||
apiKey,
|
||||
websiteUrl,
|
||||
notes,
|
||||
claudeEnabled,
|
||||
codexEnabled,
|
||||
geminiEnabled,
|
||||
models,
|
||||
selectedPreset,
|
||||
onSave,
|
||||
onClose,
|
||||
]);
|
||||
|
||||
// 构建 provider 对象的辅助函数
|
||||
const buildProvider = useCallback((): UniversalProvider | null => {
|
||||
if (!name.trim() || !baseUrl.trim() || !apiKey.trim()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const provider: UniversalProvider = editingProvider
|
||||
? {
|
||||
...editingProvider,
|
||||
name: name.trim(),
|
||||
baseUrl: baseUrl.trim(),
|
||||
apiKey: apiKey.trim(),
|
||||
websiteUrl: websiteUrl.trim() || undefined,
|
||||
notes: notes.trim() || undefined,
|
||||
apps: {
|
||||
claude: claudeEnabled,
|
||||
codex: codexEnabled,
|
||||
gemini: geminiEnabled,
|
||||
},
|
||||
models,
|
||||
}
|
||||
: createUniversalProviderFromPreset(
|
||||
selectedPreset || universalProviderPresets[0],
|
||||
crypto.randomUUID(),
|
||||
baseUrl.trim(),
|
||||
apiKey.trim(),
|
||||
name.trim(),
|
||||
);
|
||||
|
||||
// 如果是新建,更新应用启用状态和模型
|
||||
if (!editingProvider) {
|
||||
provider.apps = {
|
||||
claude: claudeEnabled,
|
||||
codex: codexEnabled,
|
||||
gemini: geminiEnabled,
|
||||
};
|
||||
provider.models = models;
|
||||
provider.websiteUrl = websiteUrl.trim() || undefined;
|
||||
provider.notes = notes.trim() || undefined;
|
||||
}
|
||||
|
||||
return provider;
|
||||
}, [
|
||||
editingProvider,
|
||||
name,
|
||||
baseUrl,
|
||||
apiKey,
|
||||
websiteUrl,
|
||||
notes,
|
||||
claudeEnabled,
|
||||
codexEnabled,
|
||||
geminiEnabled,
|
||||
models,
|
||||
selectedPreset,
|
||||
]);
|
||||
|
||||
// 打开保存并同步确认弹窗
|
||||
const handleSaveAndSyncClick = useCallback(() => {
|
||||
const provider = buildProvider();
|
||||
if (!provider || !onSaveAndSync) return;
|
||||
|
||||
setPendingProvider(provider);
|
||||
setSyncConfirmOpen(true);
|
||||
}, [buildProvider, onSaveAndSync]);
|
||||
|
||||
// 确认保存并同步
|
||||
const confirmSaveAndSync = useCallback(() => {
|
||||
if (!pendingProvider || !onSaveAndSync) return;
|
||||
|
||||
onSaveAndSync(pendingProvider);
|
||||
setSyncConfirmOpen(false);
|
||||
setPendingProvider(null);
|
||||
onClose();
|
||||
}, [pendingProvider, onSaveAndSync, onClose]);
|
||||
|
||||
const footer = (
|
||||
<>
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
{t("common.cancel", { defaultValue: "取消" })}
|
||||
</Button>
|
||||
{isEditMode && onSaveAndSync ? (
|
||||
<Button
|
||||
onClick={handleSaveAndSyncClick}
|
||||
disabled={!name.trim() || !baseUrl.trim() || !apiKey.trim()}
|
||||
>
|
||||
<RefreshCw className="mr-1.5 h-4 w-4" />
|
||||
{t("universalProvider.saveAndSync", { defaultValue: "保存并同步" })}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={!name.trim() || !baseUrl.trim() || !apiKey.trim()}
|
||||
>
|
||||
{t("common.add", { defaultValue: "添加" })}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<FullScreenPanel
|
||||
isOpen={isOpen}
|
||||
title={
|
||||
isEditMode
|
||||
? t("universalProvider.edit", { defaultValue: "编辑统一供应商" })
|
||||
: t("universalProvider.add", { defaultValue: "添加统一供应商" })
|
||||
}
|
||||
onClose={onClose}
|
||||
footer={footer}
|
||||
>
|
||||
<div className="space-y-6">
|
||||
{/* 预设选择(仅新建模式) */}
|
||||
{!isEditMode && (
|
||||
<div className="space-y-3">
|
||||
<Label>
|
||||
{t("universalProvider.selectPreset", {
|
||||
defaultValue: "选择预设类型",
|
||||
})}
|
||||
</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{universalProviderPresets.map((preset) => (
|
||||
<button
|
||||
key={preset.providerType}
|
||||
type="button"
|
||||
onClick={() => handlePresetSelect(preset)}
|
||||
className={`inline-flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-colors ${
|
||||
selectedPreset?.providerType === preset.providerType
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-accent text-muted-foreground hover:bg-accent/80"
|
||||
}`}
|
||||
>
|
||||
<ProviderIcon
|
||||
icon={preset.icon}
|
||||
name={preset.name}
|
||||
size={16}
|
||||
/>
|
||||
{preset.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{selectedPreset?.description && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{selectedPreset.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 基本信息 */}
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">
|
||||
{t("universalProvider.name", { defaultValue: "名称" })}
|
||||
</Label>
|
||||
<Input
|
||||
id="name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder={t("universalProvider.namePlaceholder", {
|
||||
defaultValue: "例如:我的 NewAPI",
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="baseUrl">
|
||||
{t("universalProvider.baseUrl", { defaultValue: "API 地址" })}
|
||||
</Label>
|
||||
<Input
|
||||
id="baseUrl"
|
||||
value={baseUrl}
|
||||
onChange={(e) => setBaseUrl(e.target.value)}
|
||||
placeholder="https://api.example.com"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="apiKey">
|
||||
{t("universalProvider.apiKey", { defaultValue: "API Key" })}
|
||||
</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="apiKey"
|
||||
type={showApiKey ? "text" : "password"}
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
placeholder="sk-..."
|
||||
className="pr-10"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="absolute right-0 top-0 h-full px-3"
|
||||
onClick={() => setShowApiKey(!showApiKey)}
|
||||
>
|
||||
{showApiKey ? (
|
||||
<EyeOff className="h-4 w-4" />
|
||||
) : (
|
||||
<Eye className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="websiteUrl">
|
||||
{t("universalProvider.websiteUrl", { defaultValue: "官网地址" })}
|
||||
</Label>
|
||||
<Input
|
||||
id="websiteUrl"
|
||||
value={websiteUrl}
|
||||
onChange={(e) => setWebsiteUrl(e.target.value)}
|
||||
placeholder={t("universalProvider.websiteUrlPlaceholder", {
|
||||
defaultValue: "https://example.com(可选,用于在列表中显示)",
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="notes">
|
||||
{t("universalProvider.notes", { defaultValue: "备注" })}
|
||||
</Label>
|
||||
<Input
|
||||
id="notes"
|
||||
value={notes}
|
||||
onChange={(e) => setNotes(e.target.value)}
|
||||
placeholder={t("universalProvider.notesPlaceholder", {
|
||||
defaultValue: "可选:添加备注信息",
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 应用启用 */}
|
||||
<div className="space-y-3">
|
||||
<Label>
|
||||
{t("universalProvider.enabledApps", { defaultValue: "启用的应用" })}
|
||||
</Label>
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-center justify-between rounded-lg border p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<ProviderIcon icon="claude" name="Claude" size={20} />
|
||||
<span className="font-medium">Claude Code</span>
|
||||
</div>
|
||||
<Switch
|
||||
checked={claudeEnabled}
|
||||
onCheckedChange={setClaudeEnabled}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between rounded-lg border p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<ProviderIcon icon="openai" name="Codex" size={20} />
|
||||
<span className="font-medium">OpenAI Codex</span>
|
||||
</div>
|
||||
<Switch
|
||||
checked={codexEnabled}
|
||||
onCheckedChange={setCodexEnabled}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between rounded-lg border p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<ProviderIcon icon="gemini" name="Gemini" size={20} />
|
||||
<span className="font-medium">Gemini CLI</span>
|
||||
</div>
|
||||
<Switch
|
||||
checked={geminiEnabled}
|
||||
onCheckedChange={setGeminiEnabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 模型配置 */}
|
||||
<div className="space-y-4">
|
||||
<Label>
|
||||
{t("universalProvider.modelConfig", { defaultValue: "模型配置" })}
|
||||
</Label>
|
||||
|
||||
{/* Claude 模型 */}
|
||||
{claudeEnabled && (
|
||||
<div className="space-y-3 rounded-lg border p-4">
|
||||
<div className="flex items-center gap-2 font-medium">
|
||||
<ProviderIcon icon="claude" name="Claude" size={16} />
|
||||
Claude
|
||||
</div>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">
|
||||
{t("universalProvider.model", { defaultValue: "主模型" })}
|
||||
</Label>
|
||||
<Input
|
||||
value={models.claude?.model || ""}
|
||||
onChange={(e) =>
|
||||
updateModel("claude", "model", e.target.value)
|
||||
}
|
||||
placeholder="claude-sonnet-4-20250514"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Haiku</Label>
|
||||
<Input
|
||||
value={models.claude?.haikuModel || ""}
|
||||
onChange={(e) =>
|
||||
updateModel("claude", "haikuModel", e.target.value)
|
||||
}
|
||||
placeholder="claude-haiku-4-20250514"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Sonnet</Label>
|
||||
<Input
|
||||
value={models.claude?.sonnetModel || ""}
|
||||
onChange={(e) =>
|
||||
updateModel("claude", "sonnetModel", e.target.value)
|
||||
}
|
||||
placeholder="claude-sonnet-4-20250514"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Opus</Label>
|
||||
<Input
|
||||
value={models.claude?.opusModel || ""}
|
||||
onChange={(e) =>
|
||||
updateModel("claude", "opusModel", e.target.value)
|
||||
}
|
||||
placeholder="claude-sonnet-4-20250514"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Codex 模型 */}
|
||||
{codexEnabled && (
|
||||
<div className="space-y-3 rounded-lg border p-4">
|
||||
<div className="flex items-center gap-2 font-medium">
|
||||
<ProviderIcon icon="openai" name="Codex" size={16} />
|
||||
Codex
|
||||
</div>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">
|
||||
{t("universalProvider.model", { defaultValue: "模型" })}
|
||||
</Label>
|
||||
<Input
|
||||
value={models.codex?.model || ""}
|
||||
onChange={(e) =>
|
||||
updateModel("codex", "model", e.target.value)
|
||||
}
|
||||
placeholder="gpt-4o"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Reasoning Effort</Label>
|
||||
<Input
|
||||
value={models.codex?.reasoningEffort || ""}
|
||||
onChange={(e) =>
|
||||
updateModel("codex", "reasoningEffort", e.target.value)
|
||||
}
|
||||
placeholder="high"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Gemini 模型 */}
|
||||
{geminiEnabled && (
|
||||
<div className="space-y-3 rounded-lg border p-4">
|
||||
<div className="flex items-center gap-2 font-medium">
|
||||
<ProviderIcon icon="gemini" name="Gemini" size={16} />
|
||||
Gemini
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">
|
||||
{t("universalProvider.model", { defaultValue: "模型" })}
|
||||
</Label>
|
||||
<Input
|
||||
value={models.gemini?.model || ""}
|
||||
onChange={(e) =>
|
||||
updateModel("gemini", "model", e.target.value)
|
||||
}
|
||||
placeholder="gemini-2.5-pro"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 配置 JSON 预览 */}
|
||||
{isEditMode && (claudeEnabled || codexEnabled || geminiEnabled) && (
|
||||
<div className="space-y-4">
|
||||
<Label>
|
||||
{t("universalProvider.configJsonPreview", {
|
||||
defaultValue: "配置 JSON 预览",
|
||||
})}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("universalProvider.configJsonPreviewHint", {
|
||||
defaultValue:
|
||||
"以下是将要同步到各应用的配置内容(仅覆盖显示的字段,保留其他自定义配置)",
|
||||
})}
|
||||
</p>
|
||||
|
||||
{/* Claude JSON */}
|
||||
{claudeConfigJson && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2 text-sm font-medium">
|
||||
<ProviderIcon icon="claude" name="Claude" size={16} />
|
||||
Claude
|
||||
</div>
|
||||
<JsonEditor
|
||||
value={JSON.stringify(claudeConfigJson, null, 2)}
|
||||
onChange={() => {}}
|
||||
height={180}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Codex JSON */}
|
||||
{codexConfigJson && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2 text-sm font-medium">
|
||||
<ProviderIcon icon="openai" name="Codex" size={16} />
|
||||
Codex
|
||||
</div>
|
||||
<JsonEditor
|
||||
value={JSON.stringify(codexConfigJson, null, 2)}
|
||||
onChange={() => {}}
|
||||
height={280}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Gemini JSON */}
|
||||
{geminiConfigJson && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2 text-sm font-medium">
|
||||
<ProviderIcon icon="gemini" name="Gemini" size={16} />
|
||||
Gemini
|
||||
</div>
|
||||
<JsonEditor
|
||||
value={JSON.stringify(geminiConfigJson, null, 2)}
|
||||
onChange={() => {}}
|
||||
height={140}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 保存并同步确认弹窗 */}
|
||||
<ConfirmDialog
|
||||
isOpen={syncConfirmOpen}
|
||||
title={t("universalProvider.syncConfirmTitle", {
|
||||
defaultValue: "同步统一供应商",
|
||||
})}
|
||||
message={t("universalProvider.syncConfirmDescription", {
|
||||
defaultValue: `同步 "${name}" 将会覆盖 Claude、Codex 和 Gemini 中关联的供应商配置。确定要继续吗?`,
|
||||
name: name,
|
||||
})}
|
||||
confirmText={t("universalProvider.saveAndSync", {
|
||||
defaultValue: "保存并同步",
|
||||
})}
|
||||
onConfirm={confirmSaveAndSync}
|
||||
onCancel={() => {
|
||||
setSyncConfirmOpen(false);
|
||||
setPendingProvider(null);
|
||||
}}
|
||||
/>
|
||||
</FullScreenPanel>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
import { useState, useCallback, useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Layers } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { ConfirmDialog } from "@/components/ConfirmDialog";
|
||||
import { UniversalProviderCard } from "./UniversalProviderCard";
|
||||
import { UniversalProviderFormModal } from "./UniversalProviderFormModal";
|
||||
import { universalProvidersApi } from "@/lib/api";
|
||||
import type { UniversalProvider, UniversalProvidersMap } from "@/types";
|
||||
|
||||
export function UniversalProviderPanel() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// 状态
|
||||
const [providers, setProviders] = useState<UniversalProvidersMap>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [isFormOpen, setIsFormOpen] = useState(false);
|
||||
const [editingProvider, setEditingProvider] =
|
||||
useState<UniversalProvider | null>(null);
|
||||
const [deleteConfirm, setDeleteConfirm] = useState<{
|
||||
open: boolean;
|
||||
id: string;
|
||||
name: string;
|
||||
}>({ open: false, id: "", name: "" });
|
||||
const [syncConfirm, setSyncConfirm] = useState<{
|
||||
open: boolean;
|
||||
id: string;
|
||||
name: string;
|
||||
}>({ open: false, id: "", name: "" });
|
||||
|
||||
// 加载数据
|
||||
const loadProviders = useCallback(async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const data = await universalProvidersApi.getAll();
|
||||
setProviders(data);
|
||||
} catch (error) {
|
||||
console.error("Failed to load universal providers:", error);
|
||||
toast.error(
|
||||
t("universalProvider.loadError", {
|
||||
defaultValue: "加载统一供应商失败",
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [t]);
|
||||
|
||||
useEffect(() => {
|
||||
loadProviders();
|
||||
}, [loadProviders]);
|
||||
|
||||
// 添加/编辑供应商
|
||||
const handleSave = useCallback(
|
||||
async (provider: UniversalProvider) => {
|
||||
try {
|
||||
await universalProvidersApi.upsert(provider);
|
||||
|
||||
// 新建模式下自动同步到各应用
|
||||
if (!editingProvider) {
|
||||
await universalProvidersApi.sync(provider.id);
|
||||
}
|
||||
|
||||
toast.success(
|
||||
editingProvider
|
||||
? t("universalProvider.updated", {
|
||||
defaultValue: "统一供应商已更新",
|
||||
})
|
||||
: t("universalProvider.addedAndSynced", {
|
||||
defaultValue: "统一供应商已添加并同步",
|
||||
}),
|
||||
);
|
||||
loadProviders();
|
||||
setEditingProvider(null);
|
||||
} catch (error) {
|
||||
console.error("Failed to save universal provider:", error);
|
||||
toast.error(
|
||||
t("universalProvider.saveError", {
|
||||
defaultValue: "保存统一供应商失败",
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
[editingProvider, loadProviders, t],
|
||||
);
|
||||
|
||||
// 保存并同步供应商
|
||||
const handleSaveAndSync = useCallback(
|
||||
async (provider: UniversalProvider) => {
|
||||
try {
|
||||
await universalProvidersApi.upsert(provider);
|
||||
await universalProvidersApi.sync(provider.id);
|
||||
toast.success(
|
||||
t("universalProvider.savedAndSynced", {
|
||||
defaultValue: "已保存并同步到所有应用",
|
||||
}),
|
||||
);
|
||||
loadProviders();
|
||||
setEditingProvider(null);
|
||||
} catch (error) {
|
||||
console.error("Failed to save and sync universal provider:", error);
|
||||
toast.error(
|
||||
t("universalProvider.saveAndSyncError", {
|
||||
defaultValue: "保存并同步失败",
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
[loadProviders, t],
|
||||
);
|
||||
|
||||
// 删除供应商
|
||||
const handleDelete = useCallback(async () => {
|
||||
if (!deleteConfirm.id) return;
|
||||
|
||||
try {
|
||||
await universalProvidersApi.delete(deleteConfirm.id);
|
||||
toast.success(
|
||||
t("universalProvider.deleted", { defaultValue: "统一供应商已删除" }),
|
||||
);
|
||||
loadProviders();
|
||||
} catch (error) {
|
||||
console.error("Failed to delete universal provider:", error);
|
||||
toast.error(
|
||||
t("universalProvider.deleteError", {
|
||||
defaultValue: "删除统一供应商失败",
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setDeleteConfirm({ open: false, id: "", name: "" });
|
||||
}
|
||||
}, [deleteConfirm.id, loadProviders, t]);
|
||||
|
||||
// 同步供应商
|
||||
const handleSync = useCallback(async () => {
|
||||
if (!syncConfirm.id) return;
|
||||
|
||||
try {
|
||||
await universalProvidersApi.sync(syncConfirm.id);
|
||||
toast.success(
|
||||
t("universalProvider.synced", { defaultValue: "已同步到所有应用" }),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Failed to sync universal provider:", error);
|
||||
toast.error(
|
||||
t("universalProvider.syncError", {
|
||||
defaultValue: "同步统一供应商失败",
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setSyncConfirm({ open: false, id: "", name: "" });
|
||||
}
|
||||
}, [syncConfirm.id, t]);
|
||||
|
||||
// 打开同步确认
|
||||
const handleSyncClick = useCallback(
|
||||
(id: string) => {
|
||||
const provider = providers[id];
|
||||
setSyncConfirm({
|
||||
open: true,
|
||||
id,
|
||||
name: provider?.name || id,
|
||||
});
|
||||
},
|
||||
[providers],
|
||||
);
|
||||
|
||||
// 打开编辑
|
||||
const handleEdit = useCallback((provider: UniversalProvider) => {
|
||||
setEditingProvider(provider);
|
||||
setIsFormOpen(true);
|
||||
}, []);
|
||||
|
||||
// 打开删除确认
|
||||
const handleDeleteClick = useCallback(
|
||||
(id: string) => {
|
||||
const provider = providers[id];
|
||||
setDeleteConfirm({
|
||||
open: true,
|
||||
id,
|
||||
name: provider?.name || id,
|
||||
});
|
||||
},
|
||||
[providers],
|
||||
);
|
||||
|
||||
const providerList = Object.values(providers);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* 头部 */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Layers className="h-5 w-5 text-primary" />
|
||||
<h2 className="text-lg font-semibold">
|
||||
{t("universalProvider.title", { defaultValue: "统一供应商" })}
|
||||
</h2>
|
||||
<span className="rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">
|
||||
{providerList.length}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* 描述 */}
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("universalProvider.description", {
|
||||
defaultValue:
|
||||
"统一供应商可以同时管理 Claude、Codex 和 Gemini 的配置。修改后会自动同步到所有启用的应用。",
|
||||
})}
|
||||
</p>
|
||||
|
||||
{/* 供应商列表 */}
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />
|
||||
</div>
|
||||
) : providerList.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center rounded-xl border border-dashed py-12 text-center">
|
||||
<Layers className="mb-3 h-10 w-10 text-muted-foreground/50" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("universalProvider.empty", {
|
||||
defaultValue: "还没有统一供应商",
|
||||
})}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground/70">
|
||||
{t("universalProvider.emptyHint", {
|
||||
defaultValue: "点击下方「添加统一供应商」按钮创建一个",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{providerList.map((provider) => (
|
||||
<UniversalProviderCard
|
||||
key={provider.id}
|
||||
provider={provider}
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDeleteClick}
|
||||
onSync={handleSyncClick}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 表单模态框 */}
|
||||
<UniversalProviderFormModal
|
||||
isOpen={isFormOpen}
|
||||
onClose={() => {
|
||||
setIsFormOpen(false);
|
||||
setEditingProvider(null);
|
||||
}}
|
||||
onSave={handleSave}
|
||||
onSaveAndSync={handleSaveAndSync}
|
||||
editingProvider={editingProvider}
|
||||
/>
|
||||
|
||||
{/* 删除确认对话框 */}
|
||||
<ConfirmDialog
|
||||
isOpen={deleteConfirm.open}
|
||||
title={t("universalProvider.deleteConfirmTitle", {
|
||||
defaultValue: "删除统一供应商",
|
||||
})}
|
||||
message={t("universalProvider.deleteConfirmDescription", {
|
||||
defaultValue: `确定要删除 "${deleteConfirm.name}" 吗?这将同时删除它在各应用中生成的供应商配置。`,
|
||||
name: deleteConfirm.name,
|
||||
})}
|
||||
confirmText={t("common.delete", { defaultValue: "删除" })}
|
||||
onConfirm={handleDelete}
|
||||
onCancel={() => setDeleteConfirm({ open: false, id: "", name: "" })}
|
||||
/>
|
||||
|
||||
{/* 同步确认对话框 */}
|
||||
<ConfirmDialog
|
||||
isOpen={syncConfirm.open}
|
||||
title={t("universalProvider.syncConfirmTitle", {
|
||||
defaultValue: "同步统一供应商",
|
||||
})}
|
||||
message={t("universalProvider.syncConfirmDescription", {
|
||||
defaultValue: `同步 "${syncConfirm.name}" 将会覆盖 Claude、Codex 和 Gemini 中关联的供应商配置。确定要继续吗?`,
|
||||
name: syncConfirm.name,
|
||||
})}
|
||||
confirmText={t("universalProvider.syncConfirm", {
|
||||
defaultValue: "同步",
|
||||
})}
|
||||
onConfirm={handleSync}
|
||||
onCancel={() => setSyncConfirm({ open: false, id: "", name: "" })}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export { UniversalProviderPanel } from "./UniversalProviderPanel";
|
||||
export { UniversalProviderCard } from "./UniversalProviderCard";
|
||||
export { UniversalProviderFormModal } from "./UniversalProviderFormModal";
|
||||
@@ -391,4 +391,22 @@ export const providerPresets: ProviderPreset[] = [
|
||||
icon: "openrouter",
|
||||
iconColor: "#6566F1",
|
||||
},
|
||||
{
|
||||
name: "Xiaomi MiMo",
|
||||
websiteUrl: "https://platform.xiaomimimo.com",
|
||||
apiKeyUrl: "https://platform.xiaomimimo.com/#/console/api-keys",
|
||||
settingsConfig: {
|
||||
env: {
|
||||
ANTHROPIC_BASE_URL: "https://api.xiaomimimo.com/anthropic",
|
||||
ANTHROPIC_AUTH_TOKEN: "",
|
||||
ANTHROPIC_MODEL: "mimo-v2-flash",
|
||||
ANTHROPIC_DEFAULT_HAIKU_MODEL: "mimo-v2-flash",
|
||||
ANTHROPIC_DEFAULT_SONNET_MODEL: "mimo-v2-flash",
|
||||
ANTHROPIC_DEFAULT_OPUS_MODEL: "mimo-v2-flash",
|
||||
},
|
||||
},
|
||||
category: "cn_official",
|
||||
icon: "xiaomimimo",
|
||||
iconColor: "#000000",
|
||||
},
|
||||
];
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* 统一供应商(Universal Provider)预设配置
|
||||
*
|
||||
* 统一供应商是跨应用共享的配置,修改后会自动同步到 Claude、Codex、Gemini 三个应用。
|
||||
* 适用于 NewAPI 等支持多种协议的 API 网关。
|
||||
*/
|
||||
|
||||
import type {
|
||||
UniversalProvider,
|
||||
UniversalProviderApps,
|
||||
UniversalProviderModels,
|
||||
} from "@/types";
|
||||
|
||||
/**
|
||||
* 统一供应商预设接口
|
||||
*/
|
||||
export interface UniversalProviderPreset {
|
||||
/** 预设名称 */
|
||||
name: string;
|
||||
/** 供应商类型标识 */
|
||||
providerType: string;
|
||||
/** 默认启用的应用 */
|
||||
defaultApps: UniversalProviderApps;
|
||||
/** 默认模型配置 */
|
||||
defaultModels: UniversalProviderModels;
|
||||
/** 网站链接 */
|
||||
websiteUrl?: string;
|
||||
/** 图标名称 */
|
||||
icon?: string;
|
||||
/** 图标颜色 */
|
||||
iconColor?: string;
|
||||
/** 描述 */
|
||||
description?: string;
|
||||
/** 是否为自定义模板(允许用户完全自定义) */
|
||||
isCustomTemplate?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* NewAPI 默认模型配置
|
||||
*/
|
||||
const NEWAPI_DEFAULT_MODELS: UniversalProviderModels = {
|
||||
claude: {
|
||||
model: "claude-sonnet-4-20250514",
|
||||
haikuModel: "claude-haiku-4-20250514",
|
||||
sonnetModel: "claude-sonnet-4-20250514",
|
||||
opusModel: "claude-sonnet-4-20250514",
|
||||
},
|
||||
codex: {
|
||||
model: "gpt-4o",
|
||||
reasoningEffort: "high",
|
||||
},
|
||||
gemini: {
|
||||
model: "gemini-2.5-pro",
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* 统一供应商预设列表
|
||||
*/
|
||||
export const universalProviderPresets: UniversalProviderPreset[] = [
|
||||
{
|
||||
name: "NewAPI",
|
||||
providerType: "newapi",
|
||||
defaultApps: {
|
||||
claude: true,
|
||||
codex: true,
|
||||
gemini: true,
|
||||
},
|
||||
defaultModels: NEWAPI_DEFAULT_MODELS,
|
||||
websiteUrl: "https://www.newapi.pro",
|
||||
icon: "newapi",
|
||||
iconColor: "#00A67E",
|
||||
description:
|
||||
"NewAPI 是一个可自部署的 API 网关,支持 Anthropic、OpenAI、Gemini 等多种协议",
|
||||
},
|
||||
{
|
||||
name: "自定义网关",
|
||||
providerType: "custom_gateway",
|
||||
defaultApps: {
|
||||
claude: true,
|
||||
codex: true,
|
||||
gemini: true,
|
||||
},
|
||||
defaultModels: NEWAPI_DEFAULT_MODELS,
|
||||
icon: "openai",
|
||||
iconColor: "#6366F1",
|
||||
description: "自定义配置的 API 网关",
|
||||
isCustomTemplate: true,
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* 根据预设创建统一供应商
|
||||
*/
|
||||
export function createUniversalProviderFromPreset(
|
||||
preset: UniversalProviderPreset,
|
||||
id: string,
|
||||
baseUrl: string,
|
||||
apiKey: string,
|
||||
customName?: string,
|
||||
): UniversalProvider {
|
||||
return {
|
||||
id,
|
||||
name: customName || preset.name,
|
||||
providerType: preset.providerType,
|
||||
apps: { ...preset.defaultApps },
|
||||
baseUrl,
|
||||
apiKey,
|
||||
models: JSON.parse(JSON.stringify(preset.defaultModels)), // Deep copy
|
||||
websiteUrl: preset.websiteUrl,
|
||||
icon: preset.icon,
|
||||
iconColor: preset.iconColor,
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取预设的显示名称(用于 UI)
|
||||
*/
|
||||
export function getPresetDisplayName(preset: UniversalProviderPreset): string {
|
||||
return preset.name;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据类型查找预设
|
||||
*/
|
||||
export function findPresetByType(
|
||||
providerType: string,
|
||||
): UniversalProviderPreset | undefined {
|
||||
return universalProviderPresets.find((p) => p.providerType === providerType);
|
||||
}
|
||||
@@ -75,6 +75,11 @@ export function useDragSort(providers: Record<string, Provider>, appId: AppId) {
|
||||
queryKey: ["providers", appId],
|
||||
});
|
||||
|
||||
// 刷新故障转移队列(因为队列顺序依赖 sort_index)
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: ["failoverQueue", appId],
|
||||
});
|
||||
|
||||
// 更新托盘菜单以反映新的排序(失败不影响主操作)
|
||||
try {
|
||||
await providersApi.updateTrayMenu();
|
||||
|
||||
@@ -73,8 +73,11 @@ export function useProxyStatus() {
|
||||
);
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyStatus"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyTakeoverStatus"] });
|
||||
// 清除所有供应商健康状态缓存(后端已清空数据库记录)
|
||||
queryClient.invalidateQueries({ queryKey: ["providerHealth"] });
|
||||
// 彻底删除所有供应商健康状态缓存(后端已清空数据库记录)
|
||||
queryClient.removeQueries({ queryKey: ["providerHealth"] });
|
||||
// 彻底删除所有熔断器统计缓存(代理停止后熔断器状态已重置)
|
||||
queryClient.removeQueries({ queryKey: ["circuitBreakerStats"] });
|
||||
// 注意:故障转移队列和开关状态会保留,不需要刷新
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
const detail =
|
||||
|
||||
@@ -6,10 +6,12 @@ import {
|
||||
type StreamCheckResult,
|
||||
} from "@/lib/api/model-test";
|
||||
import type { AppId } from "@/lib/api";
|
||||
import { useResetCircuitBreaker } from "@/lib/query/failover";
|
||||
|
||||
export function useStreamCheck(appId: AppId) {
|
||||
const { t } = useTranslation();
|
||||
const [checkingIds, setCheckingIds] = useState<Set<string>>(new Set());
|
||||
const resetCircuitBreaker = useResetCircuitBreaker();
|
||||
|
||||
const checkProvider = useCallback(
|
||||
async (
|
||||
@@ -30,6 +32,9 @@ export function useStreamCheck(appId: AppId) {
|
||||
}),
|
||||
{ closeButton: true },
|
||||
);
|
||||
|
||||
// 测试通过后重置熔断器状态
|
||||
resetCircuitBreaker.mutate({ providerId, appType: appId });
|
||||
} else if (result.status === "degraded") {
|
||||
toast.warning(
|
||||
t("streamCheck.degraded", {
|
||||
@@ -38,6 +43,9 @@ export function useStreamCheck(appId: AppId) {
|
||||
defaultValue: `${providerName} 响应较慢 (${result.responseTimeMs}ms)`,
|
||||
}),
|
||||
);
|
||||
|
||||
// 降级状态也重置熔断器,因为至少能通信
|
||||
resetCircuitBreaker.mutate({ providerId, appType: appId });
|
||||
} else {
|
||||
toast.error(
|
||||
t("streamCheck.failed", {
|
||||
@@ -66,7 +74,7 @@ export function useStreamCheck(appId: AppId) {
|
||||
});
|
||||
}
|
||||
},
|
||||
[appId, t],
|
||||
[appId, t, resetCircuitBreaker],
|
||||
);
|
||||
|
||||
const isChecking = useCallback(
|
||||
|
||||
@@ -66,6 +66,8 @@
|
||||
"exitEditMode": "Exit Edit Mode"
|
||||
},
|
||||
"provider": {
|
||||
"tabProvider": "Provider",
|
||||
"tabUniversal": "Universal",
|
||||
"noProviders": "No providers added yet",
|
||||
"noProvidersDescription": "Click the \"Add Provider\" button in the top right to configure your first API provider",
|
||||
"currentlyUsing": "Currently Using",
|
||||
@@ -340,6 +342,10 @@
|
||||
"visitWebsite": "Visit {{url}}",
|
||||
"anthropicModel": "Main Model",
|
||||
"anthropicSmallFastModel": "Fast Model",
|
||||
"anthropicReasoningModel": "Reasoning Model (Thinking)",
|
||||
"reasoningModelPlaceholder": "e.g. claude-sonnet-4-20250514",
|
||||
"openrouterCompatMode": "OpenRouter Compatibility Mode",
|
||||
"openrouterCompatModeHint": "Use OpenAI Chat Completions interface and convert to Anthropic SSE.",
|
||||
"anthropicDefaultHaikuModel": "Default Haiku Model",
|
||||
"anthropicDefaultSonnetModel": "Default Sonnet Model",
|
||||
"anthropicDefaultOpusModel": "Default Opus Model",
|
||||
@@ -981,12 +987,85 @@
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"title": "Proxy Service Settings",
|
||||
"description": "Configure local proxy server listening address, port and runtime parameters. Changes take effect immediately after saving.",
|
||||
"alert": {
|
||||
"autoApply": "Changes will be automatically synced to the running proxy service without manual restart."
|
||||
},
|
||||
"basic": {
|
||||
"title": "Basic Settings",
|
||||
"description": "Configure proxy service listening address and port."
|
||||
},
|
||||
"advanced": {
|
||||
"title": "Advanced Parameters",
|
||||
"description": "Control request stability and logging."
|
||||
},
|
||||
"timeout": {
|
||||
"title": "Timeout Settings",
|
||||
"description": "Configure timeout for streaming and non-streaming requests."
|
||||
},
|
||||
"fields": {
|
||||
"listenAddress": {
|
||||
"label": "Listen Address",
|
||||
"placeholder": "127.0.0.1",
|
||||
"description": "IP address the proxy server listens on (recommended: 127.0.0.1)"
|
||||
},
|
||||
"listenPort": {
|
||||
"label": "Listen Port",
|
||||
"placeholder": "5000",
|
||||
"description": "Port number the proxy server listens on (1024 ~ 65535)"
|
||||
},
|
||||
"maxRetries": {
|
||||
"label": "Max Retries",
|
||||
"placeholder": "3",
|
||||
"description": "Number of retries on request failure (0 ~ 10)"
|
||||
},
|
||||
"requestTimeout": {
|
||||
"label": "Request Timeout (sec)",
|
||||
"placeholder": "0 (unlimited) or 300",
|
||||
"description": "Maximum wait time for a single request (0 = unlimited, or 10 ~ 600 seconds)"
|
||||
},
|
||||
"enableLogging": {
|
||||
"label": "Enable Logging",
|
||||
"description": "Log all proxy requests for troubleshooting"
|
||||
},
|
||||
"streamingFirstByteTimeout": {
|
||||
"label": "Streaming First Byte Timeout (sec)",
|
||||
"description": "Maximum time to wait for the first data chunk"
|
||||
},
|
||||
"streamingIdleTimeout": {
|
||||
"label": "Streaming Idle Timeout (sec)",
|
||||
"description": "Maximum interval between data chunks"
|
||||
},
|
||||
"nonStreamingTimeout": {
|
||||
"label": "Non-Streaming Timeout (sec)",
|
||||
"description": "Total timeout for non-streaming requests"
|
||||
}
|
||||
},
|
||||
"validation": {
|
||||
"addressInvalid": "Please enter a valid IP address",
|
||||
"portMin": "Port must be greater than 1024",
|
||||
"portMax": "Port must be less than 65535",
|
||||
"retryMin": "Retry count cannot be negative",
|
||||
"retryMax": "Retry count cannot exceed 10",
|
||||
"timeoutNonNegative": "Timeout cannot be negative",
|
||||
"timeoutMax": "Timeout cannot exceed 600 seconds",
|
||||
"timeoutRange": "Please enter 0 or a value between 10-600",
|
||||
"streamingTimeoutMin": "Timeout must be at least 5 seconds",
|
||||
"streamingTimeoutMax": "Timeout cannot exceed 300 seconds"
|
||||
},
|
||||
"actions": {
|
||||
"save": "Save Configuration"
|
||||
},
|
||||
"toast": {
|
||||
"saved": "Proxy configuration saved",
|
||||
"saveFailed": "Save failed: {{error}}"
|
||||
}
|
||||
},
|
||||
"switchFailed": "Switch failed: {{error}}",
|
||||
"failover": {
|
||||
"proxyRequired": "Proxy service must be started to configure failover"
|
||||
},
|
||||
"failoverQueue": {
|
||||
"title": "Failover Queue",
|
||||
"description": "Manage failover order for each app's providers",
|
||||
@@ -1013,7 +1092,7 @@
|
||||
"failureThresholdHint": "Open circuit breaker after this many consecutive failures (recommended: 3-10)",
|
||||
"timeout": "Recovery Wait Time (seconds)",
|
||||
"timeoutHint": "Wait this long before trying to recover after circuit opens (recommended: 30-120)",
|
||||
"circuitBreakerSettings": "Circuit Breaker Advanced Settings",
|
||||
"circuitBreakerSettings": "Circuit Breaker Settings",
|
||||
"successThreshold": "Recovery Success Threshold",
|
||||
"successThresholdHint": "Close circuit breaker after this many successes in half-open state",
|
||||
"errorRate": "Error Rate Threshold (%)",
|
||||
@@ -1042,5 +1121,65 @@
|
||||
"timeout": "Timeout (seconds)",
|
||||
"maxRetries": "Max Retries",
|
||||
"degradedThreshold": "Degraded Threshold (ms)"
|
||||
},
|
||||
"proxyConfig": {
|
||||
"proxyEnabled": "Proxy Enabled",
|
||||
"appTakeover": "Proxy Enabled",
|
||||
"perAppConfig": "Per-App Config",
|
||||
"circuitBreaker": "Circuit Breaker",
|
||||
"circuitBreakerSettings": "Circuit Breaker Settings",
|
||||
"failureThreshold": "Failure Threshold",
|
||||
"successThreshold": "Success Threshold",
|
||||
"recoveryTimeout": "Recovery Timeout",
|
||||
"errorRateThreshold": "Error Rate Threshold",
|
||||
"minRequests": "Min Requests",
|
||||
"timeoutConfig": "Timeout Config",
|
||||
"streamingFirstByte": "Streaming First Byte Timeout",
|
||||
"streamingIdle": "Streaming Idle Timeout",
|
||||
"nonStreaming": "Non-Streaming Timeout"
|
||||
},
|
||||
"universalProvider": {
|
||||
"title": "Universal Provider",
|
||||
"description": "Universal providers manage Claude, Codex, and Gemini configurations simultaneously. Changes are automatically synced to all enabled apps.",
|
||||
"add": "Add Universal Provider",
|
||||
"edit": "Edit Universal Provider",
|
||||
"empty": "No universal providers yet",
|
||||
"emptyHint": "Click the \"Add Universal Provider\" button below to create one",
|
||||
"selectPreset": "Select Preset Type",
|
||||
"name": "Name",
|
||||
"namePlaceholder": "e.g., My NewAPI",
|
||||
"baseUrl": "API URL",
|
||||
"apiKey": "API Key",
|
||||
"websiteUrl": "Website URL",
|
||||
"websiteUrlPlaceholder": "https://example.com (optional, displayed in the list)",
|
||||
"notes": "Notes",
|
||||
"notesPlaceholder": "Optional: Add notes",
|
||||
"enabledApps": "Enabled Apps",
|
||||
"modelConfig": "Model Configuration",
|
||||
"model": "Model",
|
||||
"sync": "Sync to Apps",
|
||||
"synced": "Synced to all apps",
|
||||
"syncError": "Sync failed",
|
||||
"noAppsEnabled": "No apps enabled",
|
||||
"added": "Universal provider added",
|
||||
"addedAndSynced": "Universal provider added and synced",
|
||||
"updated": "Universal provider updated",
|
||||
"deleted": "Universal provider deleted",
|
||||
"addSuccess": "Universal provider added successfully",
|
||||
"addFailed": "Failed to add universal provider",
|
||||
"manage": "Manage",
|
||||
"loadError": "Failed to load universal providers",
|
||||
"saveError": "Failed to save universal provider",
|
||||
"deleteError": "Failed to delete universal provider",
|
||||
"deleteConfirmTitle": "Delete Universal Provider",
|
||||
"deleteConfirmDescription": "Are you sure you want to delete \"{{name}}\"? This will also delete its generated provider configurations in each app.",
|
||||
"syncConfirmTitle": "Sync Universal Provider",
|
||||
"syncConfirmDescription": "Syncing \"{{name}}\" will overwrite the associated provider configurations in Claude, Codex, and Gemini. Do you want to continue?",
|
||||
"syncConfirm": "Sync",
|
||||
"saveAndSync": "Save & Sync",
|
||||
"savedAndSynced": "Saved and synced to all apps",
|
||||
"saveAndSyncError": "Failed to save and sync",
|
||||
"configJsonPreview": "Config JSON Preview",
|
||||
"configJsonPreviewHint": "The following configurations will be synced to each app (only the displayed fields will be overwritten, other custom settings will be preserved)"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,6 +66,8 @@
|
||||
"exitEditMode": "編集モードを終了"
|
||||
},
|
||||
"provider": {
|
||||
"tabProvider": "プロバイダー",
|
||||
"tabUniversal": "統一プロバイダー",
|
||||
"noProviders": "まだプロバイダーがありません",
|
||||
"noProvidersDescription": "右上の「プロバイダーを追加」を押して最初の API プロバイダーを登録してください",
|
||||
"currentlyUsing": "現在使用中",
|
||||
@@ -340,6 +342,10 @@
|
||||
"visitWebsite": "{{url}} を開く",
|
||||
"anthropicModel": "メインモデル",
|
||||
"anthropicSmallFastModel": "高速モデル",
|
||||
"anthropicReasoningModel": "推論モデル(Thinking)",
|
||||
"reasoningModelPlaceholder": "例: claude-sonnet-4-20250514",
|
||||
"openrouterCompatMode": "OpenRouter 互換モード",
|
||||
"openrouterCompatModeHint": "OpenAI Chat Completions インターフェースを使用し、Anthropic SSE に変換します。",
|
||||
"anthropicDefaultHaikuModel": "既定 Haiku モデル",
|
||||
"anthropicDefaultSonnetModel": "既定 Sonnet モデル",
|
||||
"anthropicDefaultOpusModel": "既定 Opus モデル",
|
||||
@@ -981,12 +987,85 @@
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"title": "プロキシサービス設定",
|
||||
"description": "ローカルプロキシサーバーのリッスンアドレス、ポート、実行パラメータを設定します。保存後すぐに反映されます。",
|
||||
"alert": {
|
||||
"autoApply": "変更は実行中のプロキシサービスに自動的に同期され、手動での再起動は不要です。"
|
||||
},
|
||||
"basic": {
|
||||
"title": "基本設定",
|
||||
"description": "プロキシサービスのリッスンアドレスとポートを設定します。"
|
||||
},
|
||||
"advanced": {
|
||||
"title": "詳細パラメータ",
|
||||
"description": "リクエストの安定性とログ記録を制御します。"
|
||||
},
|
||||
"timeout": {
|
||||
"title": "タイムアウト設定",
|
||||
"description": "ストリーミングと非ストリーミングリクエストのタイムアウトを設定します。"
|
||||
},
|
||||
"fields": {
|
||||
"listenAddress": {
|
||||
"label": "リッスンアドレス",
|
||||
"placeholder": "127.0.0.1",
|
||||
"description": "プロキシサーバーがリッスンするIPアドレス(推奨: 127.0.0.1)"
|
||||
},
|
||||
"listenPort": {
|
||||
"label": "リッスンポート",
|
||||
"placeholder": "5000",
|
||||
"description": "プロキシサーバーがリッスンするポート番号(1024 ~ 65535)"
|
||||
},
|
||||
"maxRetries": {
|
||||
"label": "最大リトライ回数",
|
||||
"placeholder": "3",
|
||||
"description": "リクエスト失敗時のリトライ回数(0 ~ 10)"
|
||||
},
|
||||
"requestTimeout": {
|
||||
"label": "リクエストタイムアウト(秒)",
|
||||
"placeholder": "0(無制限)または 300",
|
||||
"description": "単一リクエストの最大待機時間(0 = 無制限、または 10 ~ 600 秒)"
|
||||
},
|
||||
"enableLogging": {
|
||||
"label": "ログ記録を有効化",
|
||||
"description": "トラブルシューティングのためにすべてのプロキシリクエストを記録"
|
||||
},
|
||||
"streamingFirstByteTimeout": {
|
||||
"label": "ストリーミング初回バイトタイムアウト(秒)",
|
||||
"description": "最初のデータチャンクを待つ最大時間"
|
||||
},
|
||||
"streamingIdleTimeout": {
|
||||
"label": "ストリーミングアイドルタイムアウト(秒)",
|
||||
"description": "データチャンク間の最大間隔"
|
||||
},
|
||||
"nonStreamingTimeout": {
|
||||
"label": "非ストリーミングタイムアウト(秒)",
|
||||
"description": "非ストリーミングリクエストの総タイムアウト"
|
||||
}
|
||||
},
|
||||
"validation": {
|
||||
"addressInvalid": "有効なIPアドレスを入力してください",
|
||||
"portMin": "ポートは1024より大きい必要があります",
|
||||
"portMax": "ポートは65535より小さい必要があります",
|
||||
"retryMin": "リトライ回数は負の値にできません",
|
||||
"retryMax": "リトライ回数は10を超えることはできません",
|
||||
"timeoutNonNegative": "タイムアウトは負の値にできません",
|
||||
"timeoutMax": "タイムアウトは600秒を超えることはできません",
|
||||
"timeoutRange": "0または10-600の間の値を入力してください",
|
||||
"streamingTimeoutMin": "タイムアウトは少なくとも5秒必要です",
|
||||
"streamingTimeoutMax": "タイムアウトは300秒を超えることはできません"
|
||||
},
|
||||
"actions": {
|
||||
"save": "設定を保存"
|
||||
},
|
||||
"toast": {
|
||||
"saved": "プロキシ設定を保存しました",
|
||||
"saveFailed": "保存に失敗しました: {{error}}"
|
||||
}
|
||||
},
|
||||
"switchFailed": "切り替えに失敗しました: {{error}}",
|
||||
"failover": {
|
||||
"proxyRequired": "フェイルオーバーを設定するには、プロキシサービスを先に起動する必要があります"
|
||||
},
|
||||
"failoverQueue": {
|
||||
"title": "フェイルオーバーキュー",
|
||||
"description": "各アプリのプロバイダーのフェイルオーバー順序を管理します",
|
||||
@@ -1013,7 +1092,7 @@
|
||||
"failureThresholdHint": "この回数連続で失敗するとサーキットブレーカーが開きます(推奨: 3-10)",
|
||||
"timeout": "回復待ち時間(秒)",
|
||||
"timeoutHint": "サーキットが開いた後、回復を試みるまでの待ち時間(推奨: 30-120)",
|
||||
"circuitBreakerSettings": "サーキットブレーカー詳細設定",
|
||||
"circuitBreakerSettings": "サーキットブレーカー設定",
|
||||
"successThreshold": "回復成功しきい値",
|
||||
"successThresholdHint": "半開状態でこの回数成功するとサーキットブレーカーが閉じます",
|
||||
"errorRate": "エラー率しきい値 (%)",
|
||||
@@ -1042,5 +1121,64 @@
|
||||
"timeout": "タイムアウト(秒)",
|
||||
"maxRetries": "最大リトライ回数",
|
||||
"degradedThreshold": "劣化しきい値(ミリ秒)"
|
||||
},
|
||||
"proxyConfig": {
|
||||
"proxyEnabled": "プロキシ有効",
|
||||
"appTakeover": "プロキシ有効",
|
||||
"perAppConfig": "アプリ別設定",
|
||||
"circuitBreaker": "サーキットブレーカー",
|
||||
"circuitBreakerSettings": "サーキットブレーカー設定",
|
||||
"failureThreshold": "失敗閾値",
|
||||
"successThreshold": "回復閾値",
|
||||
"recoveryTimeout": "回復待機時間",
|
||||
"errorRateThreshold": "エラー率閾値",
|
||||
"minRequests": "最小リクエスト数",
|
||||
"timeoutConfig": "タイムアウト設定",
|
||||
"streamingFirstByte": "ストリーミング初回バイトタイムアウト",
|
||||
"streamingIdle": "ストリーミングアイドルタイムアウト",
|
||||
"nonStreaming": "非ストリーミングタイムアウト"
|
||||
},
|
||||
"universalProvider": {
|
||||
"title": "統合プロバイダー",
|
||||
"description": "統合プロバイダーは Claude、Codex、Gemini の設定を同時に管理します。変更は有効なすべてのアプリに自動的に同期されます。",
|
||||
"add": "統合プロバイダーを追加",
|
||||
"edit": "統合プロバイダーを編集",
|
||||
"empty": "統合プロバイダーがありません",
|
||||
"emptyHint": "下の「統合プロバイダーを追加」ボタンをクリックして作成してください",
|
||||
"selectPreset": "プリセットタイプを選択",
|
||||
"name": "名前",
|
||||
"namePlaceholder": "例:私の NewAPI",
|
||||
"baseUrl": "API URL",
|
||||
"apiKey": "API キー",
|
||||
"websiteUrl": "ウェブサイト URL",
|
||||
"websiteUrlPlaceholder": "https://example.com(オプション、リストに表示されます)",
|
||||
"notes": "メモ",
|
||||
"notesPlaceholder": "オプション:メモを追加",
|
||||
"enabledApps": "有効なアプリ",
|
||||
"modelConfig": "モデル設定",
|
||||
"model": "モデル",
|
||||
"sync": "アプリに同期",
|
||||
"synced": "すべてのアプリに同期しました",
|
||||
"syncError": "同期に失敗しました",
|
||||
"noAppsEnabled": "有効なアプリがありません",
|
||||
"added": "統合プロバイダーを追加しました",
|
||||
"updated": "統合プロバイダーを更新しました",
|
||||
"deleted": "統合プロバイダーを削除しました",
|
||||
"addSuccess": "統合プロバイダーを追加しました",
|
||||
"addFailed": "統合プロバイダーの追加に失敗しました",
|
||||
"manage": "管理",
|
||||
"loadError": "統合プロバイダーの読み込みに失敗しました",
|
||||
"saveError": "統合プロバイダーの保存に失敗しました",
|
||||
"deleteError": "統合プロバイダーの削除に失敗しました",
|
||||
"deleteConfirmTitle": "統合プロバイダーを削除",
|
||||
"deleteConfirmDescription": "「{{name}}」を削除してもよろしいですか?各アプリで生成されたプロバイダー設定も削除されます。",
|
||||
"syncConfirmTitle": "統合プロバイダーを同期",
|
||||
"syncConfirmDescription": "「{{name}}」を同期すると、Claude、Codex、Gemini の関連プロバイダー設定が上書きされます。続行しますか?",
|
||||
"syncConfirm": "同期",
|
||||
"saveAndSync": "保存して同期",
|
||||
"savedAndSynced": "すべてのアプリに保存・同期されました",
|
||||
"saveAndSyncError": "保存と同期に失敗しました",
|
||||
"configJsonPreview": "設定 JSON プレビュー",
|
||||
"configJsonPreviewHint": "以下は各アプリに同期される設定内容です(表示されているフィールドのみ上書きされ、他のカスタム設定は保持されます)"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,6 +66,8 @@
|
||||
"exitEditMode": "退出编辑模式"
|
||||
},
|
||||
"provider": {
|
||||
"tabProvider": "供应商",
|
||||
"tabUniversal": "统一供应商",
|
||||
"noProviders": "还没有添加任何供应商",
|
||||
"noProvidersDescription": "点击右上角的\"添加供应商\"按钮开始配置您的第一个API供应商",
|
||||
"currentlyUsing": "当前使用",
|
||||
@@ -340,6 +342,10 @@
|
||||
"visitWebsite": "访问 {{url}}",
|
||||
"anthropicModel": "主模型",
|
||||
"anthropicSmallFastModel": "快速模型",
|
||||
"anthropicReasoningModel": "推理模型 (Thinking)",
|
||||
"reasoningModelPlaceholder": "如 claude-sonnet-4-20250514",
|
||||
"openrouterCompatMode": "OpenRouter 兼容模式",
|
||||
"openrouterCompatModeHint": "使用 OpenAI Chat Completions 接口并转换为 Anthropic SSE。",
|
||||
"anthropicDefaultHaikuModel": "Haiku 默认模型",
|
||||
"anthropicDefaultSonnetModel": "Sonnet 默认模型",
|
||||
"anthropicDefaultOpusModel": "Opus 默认模型",
|
||||
@@ -981,12 +987,85 @@
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"title": "代理服务设置",
|
||||
"description": "配置本地代理服务器的监听地址、端口和运行参数,保存后立即生效。",
|
||||
"alert": {
|
||||
"autoApply": "保存后将自动同步到正在运行的代理服务,无需手动重启。"
|
||||
},
|
||||
"basic": {
|
||||
"title": "基础设置",
|
||||
"description": "配置代理服务监听的地址与端口。"
|
||||
},
|
||||
"advanced": {
|
||||
"title": "高级参数",
|
||||
"description": "控制请求的稳定性和日志记录。"
|
||||
},
|
||||
"timeout": {
|
||||
"title": "超时设置",
|
||||
"description": "配置流式和非流式请求的超时时间。"
|
||||
},
|
||||
"fields": {
|
||||
"listenAddress": {
|
||||
"label": "监听地址",
|
||||
"placeholder": "127.0.0.1",
|
||||
"description": "代理服务器监听的 IP 地址(推荐 127.0.0.1)"
|
||||
},
|
||||
"listenPort": {
|
||||
"label": "监听端口",
|
||||
"placeholder": "5000",
|
||||
"description": "代理服务器监听的端口号(1024 ~ 65535)"
|
||||
},
|
||||
"maxRetries": {
|
||||
"label": "最大重试次数",
|
||||
"placeholder": "3",
|
||||
"description": "请求失败时的重试次数(0 ~ 10)"
|
||||
},
|
||||
"requestTimeout": {
|
||||
"label": "请求超时(秒)",
|
||||
"placeholder": "0(不限)或 300",
|
||||
"description": "单个请求的最大等待时间(0 表示不限制,或设置 10 ~ 600 秒)"
|
||||
},
|
||||
"enableLogging": {
|
||||
"label": "启用日志记录",
|
||||
"description": "记录所有代理请求,便于排查问题"
|
||||
},
|
||||
"streamingFirstByteTimeout": {
|
||||
"label": "流式首字超时(秒)",
|
||||
"description": "等待首个数据块的最大时间"
|
||||
},
|
||||
"streamingIdleTimeout": {
|
||||
"label": "流式静默超时(秒)",
|
||||
"description": "数据块之间的最大间隔"
|
||||
},
|
||||
"nonStreamingTimeout": {
|
||||
"label": "非流式超时(秒)",
|
||||
"description": "非流式请求的总超时时间"
|
||||
}
|
||||
},
|
||||
"validation": {
|
||||
"addressInvalid": "请输入有效的IP地址",
|
||||
"portMin": "端口必须大于1024",
|
||||
"portMax": "端口必须小于65535",
|
||||
"retryMin": "重试次数不能为负",
|
||||
"retryMax": "重试次数不能超过10",
|
||||
"timeoutNonNegative": "超时时间不能为负数",
|
||||
"timeoutMax": "超时时间最多600秒",
|
||||
"timeoutRange": "请输入 0 或 10-600 之间的数值",
|
||||
"streamingTimeoutMin": "超时时间至少5秒",
|
||||
"streamingTimeoutMax": "超时时间最多300秒"
|
||||
},
|
||||
"actions": {
|
||||
"save": "保存配置"
|
||||
},
|
||||
"toast": {
|
||||
"saved": "代理配置已保存",
|
||||
"saveFailed": "保存失败: {{error}}"
|
||||
}
|
||||
},
|
||||
"switchFailed": "切换失败: {{error}}",
|
||||
"failover": {
|
||||
"proxyRequired": "需要先启动代理服务才能配置故障转移"
|
||||
},
|
||||
"failoverQueue": {
|
||||
"title": "故障转移队列",
|
||||
"description": "管理各应用的供应商故障转移顺序",
|
||||
@@ -1013,7 +1092,7 @@
|
||||
"failureThresholdHint": "连续失败多少次后打开熔断器(建议: 3-10)",
|
||||
"timeout": "恢复等待时间(秒)",
|
||||
"timeoutHint": "熔断器打开后,等待多久后尝试恢复(建议: 30-120)",
|
||||
"circuitBreakerSettings": "熔断器高级设置",
|
||||
"circuitBreakerSettings": "熔断器设置",
|
||||
"successThreshold": "恢复成功阈值",
|
||||
"successThresholdHint": "半开状态下成功多少次后关闭熔断器",
|
||||
"errorRate": "错误率阈值 (%)",
|
||||
@@ -1042,5 +1121,65 @@
|
||||
"timeout": "超时时间(秒)",
|
||||
"maxRetries": "最大重试次数",
|
||||
"degradedThreshold": "降级阈值(毫秒)"
|
||||
},
|
||||
"proxyConfig": {
|
||||
"proxyEnabled": "代理总开关",
|
||||
"appTakeover": "代理启用",
|
||||
"perAppConfig": "应用配置",
|
||||
"circuitBreaker": "熔断器配置",
|
||||
"circuitBreakerSettings": "熔断器设置",
|
||||
"failureThreshold": "失败阈值",
|
||||
"successThreshold": "恢复阈值",
|
||||
"recoveryTimeout": "恢复等待时间",
|
||||
"errorRateThreshold": "错误率阈值",
|
||||
"minRequests": "最小请求数",
|
||||
"timeoutConfig": "超时配置",
|
||||
"streamingFirstByte": "流式首字节超时",
|
||||
"streamingIdle": "流式静默超时",
|
||||
"nonStreaming": "非流式超时"
|
||||
},
|
||||
"universalProvider": {
|
||||
"title": "统一供应商",
|
||||
"description": "统一供应商可以同时管理 Claude、Codex 和 Gemini 的配置。修改后会自动同步到所有启用的应用。",
|
||||
"add": "添加统一供应商",
|
||||
"edit": "编辑统一供应商",
|
||||
"empty": "还没有统一供应商",
|
||||
"emptyHint": "点击下方「添加统一供应商」按钮创建一个",
|
||||
"selectPreset": "选择预设类型",
|
||||
"name": "名称",
|
||||
"namePlaceholder": "例如:我的 NewAPI",
|
||||
"baseUrl": "API 地址",
|
||||
"apiKey": "API Key",
|
||||
"websiteUrl": "官网地址",
|
||||
"websiteUrlPlaceholder": "https://example.com(可选,用于在列表中显示)",
|
||||
"notes": "备注",
|
||||
"notesPlaceholder": "可选:添加备注信息",
|
||||
"enabledApps": "启用的应用",
|
||||
"modelConfig": "模型配置",
|
||||
"model": "模型",
|
||||
"sync": "同步到应用",
|
||||
"synced": "已同步到所有应用",
|
||||
"syncError": "同步失败",
|
||||
"noAppsEnabled": "未启用任何应用",
|
||||
"added": "统一供应商已添加",
|
||||
"addedAndSynced": "统一供应商已添加并同步",
|
||||
"updated": "统一供应商已更新",
|
||||
"deleted": "统一供应商已删除",
|
||||
"addSuccess": "统一供应商添加成功",
|
||||
"addFailed": "统一供应商添加失败",
|
||||
"manage": "管理",
|
||||
"loadError": "加载统一供应商失败",
|
||||
"saveError": "保存统一供应商失败",
|
||||
"deleteError": "删除统一供应商失败",
|
||||
"deleteConfirmTitle": "删除统一供应商",
|
||||
"deleteConfirmDescription": "确定要删除 \"{{name}}\" 吗?这将同时删除它在各应用中生成的供应商配置。",
|
||||
"syncConfirmTitle": "同步统一供应商",
|
||||
"syncConfirmDescription": "同步 \"{{name}}\" 将会覆盖 Claude、Codex 和 Gemini 中关联的供应商配置。确定要继续吗?",
|
||||
"syncConfirm": "同步",
|
||||
"saveAndSync": "保存并同步",
|
||||
"savedAndSynced": "已保存并同步到所有应用",
|
||||
"saveAndSyncError": "保存并同步失败",
|
||||
"configJsonPreview": "配置 JSON 预览",
|
||||
"configJsonPreviewHint": "以下是将要同步到各应用的配置内容(仅覆盖显示的字段,保留其他自定义配置)"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,6 +198,13 @@ export const iconMetadata: Record<string, IconMetadata> = {
|
||||
keywords: ["mistral"],
|
||||
defaultColor: "#FF7000",
|
||||
},
|
||||
newapi: {
|
||||
name: "newapi",
|
||||
displayName: "newapi",
|
||||
category: "other",
|
||||
keywords: [],
|
||||
defaultColor: "currentColor",
|
||||
},
|
||||
notion: {
|
||||
name: "notion",
|
||||
displayName: "notion",
|
||||
@@ -331,6 +338,13 @@ export const iconMetadata: Record<string, IconMetadata> = {
|
||||
keywords: ["aihubmix", "hub", "mix", "aggregator"],
|
||||
defaultColor: "#006FFB",
|
||||
},
|
||||
xiaomimimo: {
|
||||
name: "xiaomimimo",
|
||||
displayName: "Xiaomi MiMo",
|
||||
category: "ai-provider",
|
||||
keywords: ["xiaomimimo", "xiaomi", "mimo"],
|
||||
defaultColor: "#000000",
|
||||
},
|
||||
};
|
||||
|
||||
export function getIconMetadata(name: string): IconMetadata | undefined {
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>NewAPI</title><path d="M23.078 16.34c-.506 1.323-1.198 2.519-2.117 3.562-2.378 2.696-5.374 4.057-8.971 4.098a.037.037 0 01-.024-.01.041.041 0 01-.013-.023.041.041 0 01.003-.025.037.037 0 01.019-.019c1.886-.779 3.454-1.973 4.625-3.639a10.148 10.148 0 001.626-3.677c.217-.98.33-1.955.282-2.942-.048-1.018-.152-1.601-.484-2.565-.386-1.12-.915-2.16-1.627-3.089-.883-1.154-1.876-1.87-2.9-2.779-.995-.88-2.19-2.623-1.059-3.754.384-.384.997-.59 1.838-.621 2.478-.09 5.011 1.636 6.597 3.453.75.86 1.38 1.798 1.865 2.837.486 1.041.814 2.122.978 3.246.133.915.117 1.441.092 2.365a10.82 10.82 0 01-.73 3.582z" fill="url(#lobe-icons-new-api-fill-0)"></path><path d="M11.86.01a.041.041 0 01.009.049.038.038 0 01-.018.018C9.964.856 8.396 2.05 7.225 3.716a10.148 10.148 0 00-1.626 3.678c-.217.979-.33 1.955-.283 2.941.049 1.018.154 1.601.486 2.565.385 1.12.914 2.16 1.626 3.088.883 1.154 1.876 1.872 2.9 2.78.995.88 2.19 2.622 1.059 3.753-.385.385-.997.591-1.838.622-2.478.089-5.011-1.636-6.597-3.454-.75-.86-1.38-1.797-1.865-2.837a11.591 11.591 0 01-.978-3.246c-.133-.914-.117-1.44-.091-2.364.034-1.225.284-2.416.73-3.582.504-1.323 1.197-2.52 2.116-3.562C5.241 1.402 8.238.04 11.835 0c.009 0 .018.004.024.01z" fill="url(#lobe-icons-new-api-fill-1)"></path><path d="M8.721 11.903l2.455-.708.72-2.48a.066.066 0 01.127.002l.58 2.26c.776.437 1.65.755 2.622.956a.05.05 0 01.028.075.05.05 0 01-.024.019l-2.382.709a.163.163 0 00-.109.108l-.72 2.444a.034.034 0 01-.031.027.034.034 0 01-.034-.024l-.713-2.395a.183.183 0 00-.128-.128l-2.39-.705a.084.084 0 01-.044-.13.084.084 0 01.043-.03z" fill="url(#lobe-icons-new-api-fill-2)"></path><defs><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-new-api-fill-0" x1="17.889" x2="17.889" y1=".854" y2="24"><stop stop-color="#F85EAD"></stop><stop offset="1" stop-color="#FD75FD"></stop></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-new-api-fill-1" x1="5.936" x2="5.936" y1="0" y2="23.146"><stop offset=".332" stop-color="#11F5EF"></stop><stop offset="1" stop-color="#C738FB"></stop></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-new-api-fill-2" x1="11.961" x2="11.961" y1="8.666" y2="15.315"><stop offset=".332" stop-color="#11F5EF"></stop><stop offset="1" stop-color="#C738FB"></stop></linearGradient></defs></svg>
|
||||
|
After Width: | Height: | Size: 2.4 KiB |
|
After Width: | Height: | Size: 9.2 KiB |
@@ -84,34 +84,16 @@ export const failoverApi = {
|
||||
return invoke("remove_from_failover_queue", { appType, providerId });
|
||||
},
|
||||
|
||||
// 重新排序故障转移队列
|
||||
async reorderFailoverQueue(
|
||||
appType: string,
|
||||
providerIds: string[],
|
||||
): Promise<void> {
|
||||
return invoke("reorder_failover_queue", { appType, providerIds });
|
||||
// 获取指定应用的自动故障转移开关状态
|
||||
async getAutoFailoverEnabled(appType: string): Promise<boolean> {
|
||||
return invoke("get_auto_failover_enabled", { appType });
|
||||
},
|
||||
|
||||
// 设置故障转移队列项的启用状态
|
||||
async setFailoverItemEnabled(
|
||||
// 设置指定应用的自动故障转移开关状态
|
||||
async setAutoFailoverEnabled(
|
||||
appType: string,
|
||||
providerId: string,
|
||||
enabled: boolean,
|
||||
): Promise<void> {
|
||||
return invoke("set_failover_item_enabled", {
|
||||
appType,
|
||||
providerId,
|
||||
enabled,
|
||||
});
|
||||
},
|
||||
|
||||
// 获取自动故障转移总开关状态
|
||||
async getAutoFailoverEnabled(): Promise<boolean> {
|
||||
return invoke("get_auto_failover_enabled");
|
||||
},
|
||||
|
||||
// 设置自动故障转移总开关状态
|
||||
async setAutoFailoverEnabled(enabled: boolean): Promise<void> {
|
||||
return invoke("set_auto_failover_enabled", { enabled });
|
||||
return invoke("set_auto_failover_enabled", { appType, enabled });
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
export type { AppId } from "./types";
|
||||
export { providersApi } from "./providers";
|
||||
export { providersApi, universalProvidersApi } from "./providers";
|
||||
export { settingsApi } from "./settings";
|
||||
export { mcpApi } from "./mcp";
|
||||
export { promptsApi } from "./prompts";
|
||||
export { usageApi } from "./usage";
|
||||
export { vscodeApi } from "./vscode";
|
||||
export { proxyApi } from "./proxy";
|
||||
export * as configApi from "./config";
|
||||
export type { ProviderSwitchEvent } from "./providers";
|
||||
export type { Prompt } from "./prompts";
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
|
||||
import type { Provider } from "@/types";
|
||||
import type {
|
||||
Provider,
|
||||
UniversalProvider,
|
||||
UniversalProvidersMap,
|
||||
} from "@/types";
|
||||
import type { AppId } from "./types";
|
||||
|
||||
export interface ProviderSortUpdate {
|
||||
@@ -62,3 +66,44 @@ export const providersApi = {
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// 统一供应商(Universal Provider)API
|
||||
// ============================================================================
|
||||
|
||||
export const universalProvidersApi = {
|
||||
/**
|
||||
* 获取所有统一供应商
|
||||
*/
|
||||
async getAll(): Promise<UniversalProvidersMap> {
|
||||
return await invoke("get_universal_providers");
|
||||
},
|
||||
|
||||
/**
|
||||
* 获取单个统一供应商
|
||||
*/
|
||||
async get(id: string): Promise<UniversalProvider | null> {
|
||||
return await invoke("get_universal_provider", { id });
|
||||
},
|
||||
|
||||
/**
|
||||
* 添加或更新统一供应商
|
||||
*/
|
||||
async upsert(provider: UniversalProvider): Promise<boolean> {
|
||||
return await invoke("upsert_universal_provider", { provider });
|
||||
},
|
||||
|
||||
/**
|
||||
* 删除统一供应商
|
||||
*/
|
||||
async delete(id: string): Promise<boolean> {
|
||||
return await invoke("delete_universal_provider", { id });
|
||||
},
|
||||
|
||||
/**
|
||||
* 手动同步统一供应商到各应用
|
||||
*/
|
||||
async sync(id: string): Promise<boolean> {
|
||||
return await invoke("sync_universal_provider", { id });
|
||||
},
|
||||
};
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import type {
|
||||
ProxyConfig,
|
||||
ProxyStatus,
|
||||
ProxyServerInfo,
|
||||
ProxyTakeoverStatus,
|
||||
GlobalProxyConfig,
|
||||
AppProxyConfig,
|
||||
} from "@/types/proxy";
|
||||
|
||||
export const proxyApi = {
|
||||
// ========== 代理服务器控制 API ==========
|
||||
|
||||
// 启动代理服务器
|
||||
async startProxyServer(): Promise<ProxyServerInfo> {
|
||||
return invoke("start_proxy_server");
|
||||
},
|
||||
|
||||
// 停止代理服务器并恢复配置
|
||||
async stopProxyWithRestore(): Promise<void> {
|
||||
return invoke("stop_proxy_with_restore");
|
||||
},
|
||||
|
||||
// 获取代理服务器状态
|
||||
async getProxyStatus(): Promise<ProxyStatus> {
|
||||
return invoke("get_proxy_status");
|
||||
},
|
||||
|
||||
// 检查代理服务器是否正在运行
|
||||
async isProxyRunning(): Promise<boolean> {
|
||||
return invoke("is_proxy_running");
|
||||
},
|
||||
|
||||
// 检查是否处于接管模式
|
||||
async isLiveTakeoverActive(): Promise<boolean> {
|
||||
return invoke("is_live_takeover_active");
|
||||
},
|
||||
|
||||
// 代理模式下切换供应商
|
||||
async switchProxyProvider(
|
||||
appType: string,
|
||||
providerId: string,
|
||||
): Promise<void> {
|
||||
return invoke("switch_proxy_provider", { appType, providerId });
|
||||
},
|
||||
|
||||
// ========== 接管状态 API ==========
|
||||
|
||||
// 获取各应用接管状态
|
||||
async getProxyTakeoverStatus(): Promise<ProxyTakeoverStatus> {
|
||||
return invoke("get_proxy_takeover_status");
|
||||
},
|
||||
|
||||
// 为指定应用开启/关闭接管
|
||||
async setProxyTakeoverForApp(
|
||||
appType: string,
|
||||
enabled: boolean,
|
||||
): Promise<void> {
|
||||
return invoke("set_proxy_takeover_for_app", { appType, enabled });
|
||||
},
|
||||
|
||||
// ========== Legacy 代理配置 API (兼容) ==========
|
||||
|
||||
// 获取代理配置(旧版 v2 兼容接口)
|
||||
async getProxyConfig(): Promise<ProxyConfig> {
|
||||
return invoke("get_proxy_config");
|
||||
},
|
||||
|
||||
// 更新代理配置(旧版 v2 兼容接口)
|
||||
async updateProxyConfig(config: ProxyConfig): Promise<void> {
|
||||
return invoke("update_proxy_config", { config });
|
||||
},
|
||||
|
||||
// ========== v3+ 全局/应用级配置 API ==========
|
||||
|
||||
// 获取全局代理配置
|
||||
async getGlobalProxyConfig(): Promise<GlobalProxyConfig> {
|
||||
return invoke("get_global_proxy_config");
|
||||
},
|
||||
|
||||
// 更新全局代理配置
|
||||
async updateGlobalProxyConfig(config: GlobalProxyConfig): Promise<void> {
|
||||
return invoke("update_global_proxy_config", { config });
|
||||
},
|
||||
|
||||
// 获取指定应用的代理配置
|
||||
async getProxyConfigForApp(appType: string): Promise<AppProxyConfig> {
|
||||
return invoke("get_proxy_config_for_app", { appType });
|
||||
},
|
||||
|
||||
// 更新指定应用的代理配置
|
||||
async updateProxyConfigForApp(config: AppProxyConfig): Promise<void> {
|
||||
return invoke("update_proxy_config_for_app", { config });
|
||||
},
|
||||
};
|
||||
@@ -18,6 +18,9 @@ export function useProviderHealth(providerId: string, appType: string) {
|
||||
|
||||
/**
|
||||
* 重置熔断器
|
||||
*
|
||||
* 重置后后端会检查是否应该切回优先级更高的供应商,
|
||||
* 因此需要同时刷新供应商列表和代理状态。
|
||||
*/
|
||||
export function useResetCircuitBreaker() {
|
||||
const queryClient = useQueryClient();
|
||||
@@ -35,6 +38,14 @@ export function useResetCircuitBreaker() {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["providerHealth", variables.providerId, variables.appType],
|
||||
});
|
||||
// 刷新供应商列表(因为可能发生了自动恢复切换)
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["providers", variables.appType],
|
||||
});
|
||||
// 刷新代理状态(更新 active_targets)
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["proxyStatus"],
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -120,6 +131,9 @@ export function useAddToFailoverQueue() {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["availableProvidersForFailover", variables.appType],
|
||||
});
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["providers", variables.appType],
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -145,146 +159,79 @@ export function useRemoveFromFailoverQueue() {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["availableProvidersForFailover", variables.appType],
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 重新排序故障转移队列
|
||||
*/
|
||||
export function useReorderFailoverQueue() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({
|
||||
appType,
|
||||
providerIds,
|
||||
}: {
|
||||
appType: string;
|
||||
providerIds: string[];
|
||||
}) => failoverApi.reorderFailoverQueue(appType, providerIds),
|
||||
onSuccess: (_, variables) => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["failoverQueue", variables.appType],
|
||||
queryKey: ["providers", variables.appType],
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置故障转移队列项的启用状态
|
||||
* 使用乐观更新(Optimistic Update)以提供即时反馈
|
||||
*/
|
||||
export function useSetFailoverItemEnabled() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({
|
||||
appType,
|
||||
providerId,
|
||||
enabled,
|
||||
}: {
|
||||
appType: string;
|
||||
providerId: string;
|
||||
enabled: boolean;
|
||||
}) => failoverApi.setFailoverItemEnabled(appType, providerId, enabled),
|
||||
|
||||
// 乐观更新:立即更新缓存中的数据
|
||||
onMutate: async (variables) => {
|
||||
// 取消正在进行的查询,防止覆盖乐观更新
|
||||
await queryClient.cancelQueries({
|
||||
queryKey: ["failoverQueue", variables.appType],
|
||||
});
|
||||
|
||||
// 保存之前的数据以便回滚
|
||||
const previousQueue = queryClient.getQueryData<
|
||||
import("@/types/proxy").FailoverQueueItem[]
|
||||
>(["failoverQueue", variables.appType]);
|
||||
|
||||
// 乐观地更新缓存
|
||||
if (previousQueue) {
|
||||
queryClient.setQueryData<import("@/types/proxy").FailoverQueueItem[]>(
|
||||
["failoverQueue", variables.appType],
|
||||
previousQueue.map((item) =>
|
||||
item.providerId === variables.providerId
|
||||
? { ...item, enabled: variables.enabled }
|
||||
: item,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 返回上下文供 onError 使用
|
||||
return { previousQueue };
|
||||
},
|
||||
|
||||
// 错误时回滚
|
||||
onError: (_error, variables, context) => {
|
||||
if (context?.previousQueue) {
|
||||
queryClient.setQueryData(
|
||||
["failoverQueue", variables.appType],
|
||||
context.previousQueue,
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
// 无论成功失败,都重新获取最新数据以确保一致性
|
||||
onSettled: (_, __, variables) => {
|
||||
// 清除该供应商的健康状态缓存(退出队列后不再需要健康监控)
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["failoverQueue", variables.appType],
|
||||
queryKey: ["providerHealth", variables.providerId, variables.appType],
|
||||
});
|
||||
// 清除该供应商的熔断器统计缓存
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: [
|
||||
"circuitBreakerStats",
|
||||
variables.providerId,
|
||||
variables.appType,
|
||||
],
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ========== 自动故障转移总开关 Hooks ==========
|
||||
// ========== 自动故障转移开关 Hooks ==========
|
||||
|
||||
/**
|
||||
* 获取自动故障转移总开关状态
|
||||
* 获取指定应用的自动故障转移开关状态
|
||||
*/
|
||||
export function useAutoFailoverEnabled() {
|
||||
export function useAutoFailoverEnabled(appType: string) {
|
||||
return useQuery({
|
||||
queryKey: ["autoFailoverEnabled"],
|
||||
queryFn: () => failoverApi.getAutoFailoverEnabled(),
|
||||
queryKey: ["autoFailoverEnabled", appType],
|
||||
queryFn: () => failoverApi.getAutoFailoverEnabled(appType),
|
||||
// 默认值为 false(与后端保持一致)
|
||||
placeholderData: false,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置自动故障转移总开关状态
|
||||
* 设置指定应用的自动故障转移开关状态
|
||||
*/
|
||||
export function useSetAutoFailoverEnabled() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (enabled: boolean) =>
|
||||
failoverApi.setAutoFailoverEnabled(enabled),
|
||||
mutationFn: ({ appType, enabled }: { appType: string; enabled: boolean }) =>
|
||||
failoverApi.setAutoFailoverEnabled(appType, enabled),
|
||||
|
||||
// 乐观更新
|
||||
onMutate: async (enabled) => {
|
||||
await queryClient.cancelQueries({ queryKey: ["autoFailoverEnabled"] });
|
||||
onMutate: async ({ appType, enabled }) => {
|
||||
await queryClient.cancelQueries({
|
||||
queryKey: ["autoFailoverEnabled", appType],
|
||||
});
|
||||
const previousValue = queryClient.getQueryData<boolean>([
|
||||
"autoFailoverEnabled",
|
||||
appType,
|
||||
]);
|
||||
|
||||
queryClient.setQueryData(["autoFailoverEnabled"], enabled);
|
||||
queryClient.setQueryData(["autoFailoverEnabled", appType], enabled);
|
||||
|
||||
return { previousValue };
|
||||
return { previousValue, appType };
|
||||
},
|
||||
|
||||
// 错误时回滚
|
||||
onError: (_error, _enabled, context) => {
|
||||
onError: (_error, _variables, context) => {
|
||||
if (context?.previousValue !== undefined) {
|
||||
queryClient.setQueryData(
|
||||
["autoFailoverEnabled"],
|
||||
["autoFailoverEnabled", context.appType],
|
||||
context.previousValue,
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
// 无论成功失败,都重新获取
|
||||
onSettled: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["autoFailoverEnabled"] });
|
||||
onSettled: (_, __, variables) => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["autoFailoverEnabled", variables.appType],
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
export * from "./queryClient";
|
||||
export * from "./queries";
|
||||
export * from "./mutations";
|
||||
export * from "./proxy";
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { proxyApi } from "@/lib/api/proxy";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { GlobalProxyConfig, AppProxyConfig } from "@/types/proxy";
|
||||
|
||||
// ========== 代理服务器状态 Hooks ==========
|
||||
|
||||
/**
|
||||
* 获取代理服务器状态
|
||||
*/
|
||||
export function useProxyStatus() {
|
||||
return useQuery({
|
||||
queryKey: ["proxyStatus"],
|
||||
queryFn: () => proxyApi.getProxyStatus(),
|
||||
refetchInterval: 5000, // 每 5 秒刷新一次
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查代理服务器是否运行
|
||||
*/
|
||||
export function useIsProxyRunning() {
|
||||
return useQuery({
|
||||
queryKey: ["proxyRunning"],
|
||||
queryFn: () => proxyApi.isProxyRunning(),
|
||||
refetchInterval: 2000,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否处于接管模式
|
||||
*/
|
||||
export function useIsLiveTakeoverActive() {
|
||||
return useQuery({
|
||||
queryKey: ["liveTakeoverActive"],
|
||||
queryFn: () => proxyApi.isLiveTakeoverActive(),
|
||||
refetchInterval: 2000,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取各应用接管状态
|
||||
*/
|
||||
export function useProxyTakeoverStatus() {
|
||||
return useQuery({
|
||||
queryKey: ["proxyTakeoverStatus"],
|
||||
queryFn: () => proxyApi.getProxyTakeoverStatus(),
|
||||
refetchInterval: 2000,
|
||||
});
|
||||
}
|
||||
|
||||
// ========== 代理服务器控制 Hooks ==========
|
||||
|
||||
/**
|
||||
* 启动代理服务器
|
||||
*/
|
||||
export function useStartProxyServer() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: () => proxyApi.startProxyServer(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyStatus"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyRunning"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["liveTakeoverActive"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyTakeoverStatus"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止代理服务器
|
||||
*/
|
||||
export function useStopProxyServer() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: () => proxyApi.stopProxyWithRestore(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyStatus"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyRunning"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["liveTakeoverActive"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyTakeoverStatus"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置应用接管状态
|
||||
*/
|
||||
export function useSetProxyTakeoverForApp() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ appType, enabled }: { appType: string; enabled: boolean }) =>
|
||||
proxyApi.setProxyTakeoverForApp(appType, enabled),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyTakeoverStatus"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["liveTakeoverActive"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 代理模式下切换供应商
|
||||
*/
|
||||
export function useSwitchProxyProvider() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({
|
||||
appType,
|
||||
providerId,
|
||||
}: {
|
||||
appType: string;
|
||||
providerId: string;
|
||||
}) => proxyApi.switchProxyProvider(appType, providerId),
|
||||
onSuccess: (_, variables) => {
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyStatus"] });
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["providers", variables.appType],
|
||||
});
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(t("proxy.switchFailed", { error: error.message }));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ========== Legacy 代理配置 Hooks (兼容) ==========
|
||||
|
||||
/**
|
||||
* 获取代理配置(旧版)
|
||||
*/
|
||||
export function useProxyConfig() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { data: config, isLoading } = useQuery({
|
||||
queryKey: ["proxyConfig"],
|
||||
queryFn: () => proxyApi.getProxyConfig(),
|
||||
});
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: proxyApi.updateProxyConfig,
|
||||
onSuccess: () => {
|
||||
toast.success(t("proxy.settings.toast.saved"), { closeButton: true });
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyConfig"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyStatus"] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(
|
||||
t("proxy.settings.toast.saveFailed", { error: error.message }),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
config,
|
||||
isLoading,
|
||||
updateConfig: updateMutation.mutateAsync,
|
||||
isUpdating: updateMutation.isPending,
|
||||
};
|
||||
}
|
||||
|
||||
// ========== v3+ 全局/应用级配置 Hooks ==========
|
||||
|
||||
/**
|
||||
* 获取全局代理配置
|
||||
*/
|
||||
export function useGlobalProxyConfig() {
|
||||
return useQuery({
|
||||
queryKey: ["globalProxyConfig"],
|
||||
queryFn: () => proxyApi.getGlobalProxyConfig(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新全局代理配置
|
||||
*/
|
||||
export function useUpdateGlobalProxyConfig() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (config: GlobalProxyConfig) =>
|
||||
proxyApi.updateGlobalProxyConfig(config),
|
||||
onSuccess: () => {
|
||||
toast.success(t("proxy.settings.toast.saved"), { closeButton: true });
|
||||
queryClient.invalidateQueries({ queryKey: ["globalProxyConfig"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyConfig"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyStatus"] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(
|
||||
t("proxy.settings.toast.saveFailed", { error: error.message }),
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定应用的代理配置
|
||||
*/
|
||||
export function useAppProxyConfig(appType: string) {
|
||||
return useQuery({
|
||||
queryKey: ["appProxyConfig", appType],
|
||||
queryFn: () => proxyApi.getProxyConfigForApp(appType),
|
||||
enabled: !!appType,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新指定应用的代理配置
|
||||
*/
|
||||
export function useUpdateAppProxyConfig() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (config: AppProxyConfig) =>
|
||||
proxyApi.updateProxyConfigForApp(config),
|
||||
onSuccess: (_, variables) => {
|
||||
toast.success(t("proxy.settings.toast.saved"), { closeButton: true });
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["appProxyConfig", variables.appType],
|
||||
});
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyConfig"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["circuitBreakerConfig"] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(
|
||||
t("proxy.settings.toast.saveFailed", { error: error.message }),
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -23,6 +23,8 @@ export interface Provider {
|
||||
// 图标配置
|
||||
icon?: string; // 图标名称(如 "openai", "anthropic")
|
||||
iconColor?: string; // 图标颜色(Hex 格式,如 "#00A67E")
|
||||
// 是否加入故障转移队列
|
||||
inFailoverQueue?: boolean;
|
||||
}
|
||||
|
||||
export interface AppConfig {
|
||||
@@ -184,3 +186,61 @@ export interface McpConfigResponse {
|
||||
configPath: string;
|
||||
servers: Record<string, McpServer>;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 统一供应商(Universal Provider)- 跨应用共享配置
|
||||
// ============================================================================
|
||||
|
||||
// 统一供应商的应用启用状态
|
||||
export interface UniversalProviderApps {
|
||||
claude: boolean;
|
||||
codex: boolean;
|
||||
gemini: boolean;
|
||||
}
|
||||
|
||||
// Claude 模型配置
|
||||
export interface ClaudeModelConfig {
|
||||
model?: string;
|
||||
haikuModel?: string;
|
||||
sonnetModel?: string;
|
||||
opusModel?: string;
|
||||
}
|
||||
|
||||
// Codex 模型配置
|
||||
export interface CodexModelConfig {
|
||||
model?: string;
|
||||
reasoningEffort?: string;
|
||||
}
|
||||
|
||||
// Gemini 模型配置
|
||||
export interface GeminiModelConfig {
|
||||
model?: string;
|
||||
}
|
||||
|
||||
// 各应用的模型配置
|
||||
export interface UniversalProviderModels {
|
||||
claude?: ClaudeModelConfig;
|
||||
codex?: CodexModelConfig;
|
||||
gemini?: GeminiModelConfig;
|
||||
}
|
||||
|
||||
// 统一供应商(跨应用共享配置)
|
||||
export interface UniversalProvider {
|
||||
id: string;
|
||||
name: string;
|
||||
providerType: string; // "newapi" | "custom" 等
|
||||
apps: UniversalProviderApps;
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
models: UniversalProviderModels;
|
||||
websiteUrl?: string;
|
||||
notes?: string;
|
||||
icon?: string;
|
||||
iconColor?: string;
|
||||
meta?: ProviderMeta;
|
||||
createdAt?: number;
|
||||
sortIndex?: number;
|
||||
}
|
||||
|
||||
// 统一供应商映射(id -> UniversalProvider)
|
||||
export type UniversalProvidersMap = Record<string, UniversalProvider>;
|
||||
|
||||
@@ -5,6 +5,10 @@ export interface ProxyConfig {
|
||||
request_timeout: number;
|
||||
enable_logging: boolean;
|
||||
live_takeover_active?: boolean;
|
||||
// 超时配置
|
||||
streaming_first_byte_timeout: number;
|
||||
streaming_idle_timeout: number;
|
||||
non_streaming_timeout: number;
|
||||
}
|
||||
|
||||
export interface ProxyStatus {
|
||||
@@ -103,7 +107,29 @@ export interface ProxyUsageRecord {
|
||||
export interface FailoverQueueItem {
|
||||
providerId: string;
|
||||
providerName: string;
|
||||
queueOrder: number;
|
||||
enabled: boolean;
|
||||
createdAt: number;
|
||||
sortIndex?: number;
|
||||
}
|
||||
|
||||
// 全局代理配置(统一字段,三行镜像)
|
||||
export interface GlobalProxyConfig {
|
||||
proxyEnabled: boolean;
|
||||
listenAddress: string;
|
||||
listenPort: number;
|
||||
enableLogging: boolean;
|
||||
}
|
||||
|
||||
// 应用级代理配置(每个 app 独立)
|
||||
export interface AppProxyConfig {
|
||||
appType: string;
|
||||
enabled: boolean;
|
||||
autoFailoverEnabled: boolean;
|
||||
maxRetries: number;
|
||||
streamingFirstByteTimeout: number;
|
||||
streamingIdleTimeout: number;
|
||||
nonStreamingTimeout: number;
|
||||
circuitFailureThreshold: number;
|
||||
circuitSuccessThreshold: number;
|
||||
circuitTimeoutSeconds: number;
|
||||
circuitErrorRateThreshold: number;
|
||||
circuitMinRequests: number;
|
||||
}
|
||||
|
||||