mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-07-26 06:07:29 +08:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 80c61a7fc7 |
@@ -3,6 +3,7 @@
|
||||
# All-in-One Assistant for Claude Code, Codex & Gemini CLI
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/trending/typescript)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://tauri.app/)
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
@@ -11,13 +12,21 @@
|
||||
|
||||
English | [中文](README_ZH.md) | [日本語](README_JA.md) | [Changelog](CHANGELOG.md)
|
||||
|
||||
**From Provider Switcher to All-in-One AI CLI Management Platform**
|
||||
|
||||
Unified management for Claude Code, Codex & Gemini CLI provider configurations, MCP servers, Skills extensions, and system prompts.
|
||||
|
||||
</div>
|
||||
|
||||
## ❤️Sponsor
|
||||
|
||||

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

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

|
||||
|
||||
感谢智谱AI的 GLM CODING PLAN 赞助了本项目!GLM CODING PLAN 是专为AI编码打造的订阅套餐,每月最低仅需20元,即可在十余款主流AI编码工具如 Claude Code、Cline 中畅享智谱旗舰模型 GLM-4.6,为开发者提供顶尖、高速、稳定的编码体验。CC Switch 已经预设了智谱GLM,只需要填写 key 即可一键导入编程工具。智谱AI为本软件的用户提供了特别优惠,使用[此链接](https://www.bigmodel.cn/claude-code?ic=RRVJPB5SII)购买可以享受九折优惠。
|
||||
感谢智谱AI的 GLM CODING PLAN 赞助了本项目!
|
||||
|
||||
GLM CODING PLAN 是专为AI编码打造的订阅套餐,每月最低仅需20元,即可在十余款主流AI编码工具如 Claude Code、Cline 中畅享智谱旗舰模型 GLM-4.6,为开发者提供顶尖、高速、稳定的编码体验。
|
||||
|
||||
CC Switch 已经预设了智谱GLM,只需要填写 key 即可一键导入编程工具。智谱AI为本软件的用户提供了特别优惠,使用[此链接](https://www.bigmodel.cn/claude-code?ic=RRVJPB5SII)购买可以享受九折优惠。
|
||||
|
||||
---
|
||||
|
||||
@@ -32,11 +41,6 @@
|
||||
<td>感谢闪电说赞助了本项目!闪电说是本地优先的 AI 语音输入法:毫秒级响应,数据不离设备;打字速度提升 4 倍,AI 智能纠错;绝对隐私安全,完全免费,配合 Claude Code 写代码效率翻倍!支持 Mac/Win 双平台,<a href="https://www.shandianshuo.cn">免费下载</a></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></td>
|
||||
<td>感谢 AIGoCode 赞助了本项目!AIGoCode 是一个集成了 Claude Code、Codex 以及 Gemini 最新模型的一站式平台,为你提供稳定、高效且高性价比的AI编程服务。本站提供灵活的订阅计划,零封号风险,国内直连,无需魔法,极速响应。AIGoCode 为 CC Switch 的用户提供了特别福利,通过<a href="https://aigocode.com/invite/CC-SWITCH">此链接</a>注册的用户首次充值可以获得额外10%奖励额度!</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
## 界面预览
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 33 KiB |
@@ -50,7 +50,6 @@
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@hookform/resolvers": "^5.2.2",
|
||||
"@lobehub/icons-static-svg": "^1.73.0",
|
||||
"@radix-ui/react-accordion": "^1.2.12",
|
||||
"@radix-ui/react-checkbox": "^1.3.3",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||
@@ -68,9 +67,7 @@
|
||||
"@tauri-apps/plugin-updater": "^2.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"codemirror": "^6.0.2",
|
||||
"framer-motion": "^12.23.25",
|
||||
"i18next": "^25.5.2",
|
||||
"jsonc-parser": "^3.2.1",
|
||||
"lucide-react": "^0.542.0",
|
||||
|
||||
Generated
-121
@@ -44,9 +44,6 @@ importers:
|
||||
'@lobehub/icons-static-svg':
|
||||
specifier: ^1.73.0
|
||||
version: 1.73.0
|
||||
'@radix-ui/react-accordion':
|
||||
specifier: ^1.2.12
|
||||
version: 1.2.12(@types/react-dom@18.3.7(@types/react@18.3.23))(@types/react@18.3.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
||||
'@radix-ui/react-checkbox':
|
||||
specifier: ^1.3.3
|
||||
version: 1.3.3(@types/react-dom@18.3.7(@types/react@18.3.23))(@types/react@18.3.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
||||
@@ -98,15 +95,9 @@ importers:
|
||||
clsx:
|
||||
specifier: ^2.1.1
|
||||
version: 2.1.1
|
||||
cmdk:
|
||||
specifier: ^1.1.1
|
||||
version: 1.1.1(@types/react-dom@18.3.7(@types/react@18.3.23))(@types/react@18.3.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
||||
codemirror:
|
||||
specifier: ^6.0.2
|
||||
version: 6.0.2
|
||||
framer-motion:
|
||||
specifier: ^12.23.25
|
||||
version: 12.23.25(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
||||
i18next:
|
||||
specifier: ^25.5.2
|
||||
version: 25.5.2(typescript@5.9.2)
|
||||
@@ -661,19 +652,6 @@ packages:
|
||||
'@radix-ui/primitive@1.1.3':
|
||||
resolution: {integrity: sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==}
|
||||
|
||||
'@radix-ui/react-accordion@1.2.12':
|
||||
resolution: {integrity: sha512-T4nygeh9YE9dLRPhAHSeOZi7HBXo+0kYIPJXayZfvWOWA0+n3dESrZbjfDPUABkUNym6Hd+f2IR113To8D2GPA==}
|
||||
peerDependencies:
|
||||
'@types/react': '*'
|
||||
'@types/react-dom': '*'
|
||||
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
|
||||
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
|
||||
peerDependenciesMeta:
|
||||
'@types/react':
|
||||
optional: true
|
||||
'@types/react-dom':
|
||||
optional: true
|
||||
|
||||
'@radix-ui/react-arrow@1.1.7':
|
||||
resolution: {integrity: sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w==}
|
||||
peerDependencies:
|
||||
@@ -700,19 +678,6 @@ packages:
|
||||
'@types/react-dom':
|
||||
optional: true
|
||||
|
||||
'@radix-ui/react-collapsible@1.1.12':
|
||||
resolution: {integrity: sha512-Uu+mSh4agx2ib1uIGPP4/CKNULyajb3p92LsVXmH2EHVMTfZWpll88XJ0j4W0z3f8NK1eYl1+Mf/szHPmcHzyA==}
|
||||
peerDependencies:
|
||||
'@types/react': '*'
|
||||
'@types/react-dom': '*'
|
||||
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
|
||||
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
|
||||
peerDependenciesMeta:
|
||||
'@types/react':
|
||||
optional: true
|
||||
'@types/react-dom':
|
||||
optional: true
|
||||
|
||||
'@radix-ui/react-collection@1.1.7':
|
||||
resolution: {integrity: sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw==}
|
||||
peerDependencies:
|
||||
@@ -1562,12 +1527,6 @@ packages:
|
||||
resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
cmdk@1.1.1:
|
||||
resolution: {integrity: sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg==}
|
||||
peerDependencies:
|
||||
react: ^18 || ^19 || ^19.0.0-rc
|
||||
react-dom: ^18 || ^19 || ^19.0.0-rc
|
||||
|
||||
codemirror@6.0.2:
|
||||
resolution: {integrity: sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==}
|
||||
|
||||
@@ -1793,20 +1752,6 @@ packages:
|
||||
fraction.js@5.3.4:
|
||||
resolution: {integrity: sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==}
|
||||
|
||||
framer-motion@12.23.25:
|
||||
resolution: {integrity: sha512-gUHGl2e4VG66jOcH0JHhuJQr6ZNwrET9g31ZG0xdXzT0CznP7fHX4P8Bcvuc4MiUB90ysNnWX2ukHRIggkl6hQ==}
|
||||
peerDependencies:
|
||||
'@emotion/is-prop-valid': '*'
|
||||
react: ^18.0.0 || ^19.0.0
|
||||
react-dom: ^18.0.0 || ^19.0.0
|
||||
peerDependenciesMeta:
|
||||
'@emotion/is-prop-valid':
|
||||
optional: true
|
||||
react:
|
||||
optional: true
|
||||
react-dom:
|
||||
optional: true
|
||||
|
||||
fsevents@2.3.3:
|
||||
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
|
||||
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
|
||||
@@ -2090,12 +2035,6 @@ packages:
|
||||
resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==}
|
||||
engines: {node: '>=4'}
|
||||
|
||||
motion-dom@12.23.23:
|
||||
resolution: {integrity: sha512-n5yolOs0TQQBRUFImrRfs/+6X4p3Q4n1dUEqt/H58Vx7OW6RF+foWEgmTVDhIWJIMXOuNNL0apKH2S16en9eiA==}
|
||||
|
||||
motion-utils@12.23.6:
|
||||
resolution: {integrity: sha512-eAWoPgr4eFEOFfg2WjIsMoqJTW6Z8MTUCgn/GZ3VRpClWBdnbjryiA3ZSNLyxCTmCQx4RmYX6jX1iWHbenUPNQ==}
|
||||
|
||||
ms@2.1.3:
|
||||
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
|
||||
|
||||
@@ -3244,23 +3183,6 @@ snapshots:
|
||||
|
||||
'@radix-ui/primitive@1.1.3': {}
|
||||
|
||||
'@radix-ui/react-accordion@1.2.12(@types/react-dom@18.3.7(@types/react@18.3.23))(@types/react@18.3.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)':
|
||||
dependencies:
|
||||
'@radix-ui/primitive': 1.1.3
|
||||
'@radix-ui/react-collapsible': 1.1.12(@types/react-dom@18.3.7(@types/react@18.3.23))(@types/react@18.3.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
||||
'@radix-ui/react-collection': 1.1.7(@types/react-dom@18.3.7(@types/react@18.3.23))(@types/react@18.3.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
||||
'@radix-ui/react-compose-refs': 1.1.2(@types/react@18.3.23)(react@18.3.1)
|
||||
'@radix-ui/react-context': 1.1.2(@types/react@18.3.23)(react@18.3.1)
|
||||
'@radix-ui/react-direction': 1.1.1(@types/react@18.3.23)(react@18.3.1)
|
||||
'@radix-ui/react-id': 1.1.1(@types/react@18.3.23)(react@18.3.1)
|
||||
'@radix-ui/react-primitive': 2.1.3(@types/react-dom@18.3.7(@types/react@18.3.23))(@types/react@18.3.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
||||
'@radix-ui/react-use-controllable-state': 1.2.2(@types/react@18.3.23)(react@18.3.1)
|
||||
react: 18.3.1
|
||||
react-dom: 18.3.1(react@18.3.1)
|
||||
optionalDependencies:
|
||||
'@types/react': 18.3.23
|
||||
'@types/react-dom': 18.3.7(@types/react@18.3.23)
|
||||
|
||||
'@radix-ui/react-arrow@1.1.7(@types/react-dom@18.3.7(@types/react@18.3.23))(@types/react@18.3.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)':
|
||||
dependencies:
|
||||
'@radix-ui/react-primitive': 2.1.3(@types/react-dom@18.3.7(@types/react@18.3.23))(@types/react@18.3.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
||||
@@ -3286,22 +3208,6 @@ snapshots:
|
||||
'@types/react': 18.3.23
|
||||
'@types/react-dom': 18.3.7(@types/react@18.3.23)
|
||||
|
||||
'@radix-ui/react-collapsible@1.1.12(@types/react-dom@18.3.7(@types/react@18.3.23))(@types/react@18.3.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)':
|
||||
dependencies:
|
||||
'@radix-ui/primitive': 1.1.3
|
||||
'@radix-ui/react-compose-refs': 1.1.2(@types/react@18.3.23)(react@18.3.1)
|
||||
'@radix-ui/react-context': 1.1.2(@types/react@18.3.23)(react@18.3.1)
|
||||
'@radix-ui/react-id': 1.1.1(@types/react@18.3.23)(react@18.3.1)
|
||||
'@radix-ui/react-presence': 1.1.5(@types/react-dom@18.3.7(@types/react@18.3.23))(@types/react@18.3.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
||||
'@radix-ui/react-primitive': 2.1.3(@types/react-dom@18.3.7(@types/react@18.3.23))(@types/react@18.3.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
||||
'@radix-ui/react-use-controllable-state': 1.2.2(@types/react@18.3.23)(react@18.3.1)
|
||||
'@radix-ui/react-use-layout-effect': 1.1.1(@types/react@18.3.23)(react@18.3.1)
|
||||
react: 18.3.1
|
||||
react-dom: 18.3.1(react@18.3.1)
|
||||
optionalDependencies:
|
||||
'@types/react': 18.3.23
|
||||
'@types/react-dom': 18.3.7(@types/react@18.3.23)
|
||||
|
||||
'@radix-ui/react-collection@1.1.7(@types/react-dom@18.3.7(@types/react@18.3.23))(@types/react@18.3.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)':
|
||||
dependencies:
|
||||
'@radix-ui/react-compose-refs': 1.1.2(@types/react@18.3.23)(react@18.3.1)
|
||||
@@ -4082,18 +3988,6 @@ snapshots:
|
||||
|
||||
clsx@2.1.1: {}
|
||||
|
||||
cmdk@1.1.1(@types/react-dom@18.3.7(@types/react@18.3.23))(@types/react@18.3.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1):
|
||||
dependencies:
|
||||
'@radix-ui/react-compose-refs': 1.1.2(@types/react@18.3.23)(react@18.3.1)
|
||||
'@radix-ui/react-dialog': 1.1.15(@types/react-dom@18.3.7(@types/react@18.3.23))(@types/react@18.3.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
||||
'@radix-ui/react-id': 1.1.1(@types/react@18.3.23)(react@18.3.1)
|
||||
'@radix-ui/react-primitive': 2.1.4(@types/react-dom@18.3.7(@types/react@18.3.23))(@types/react@18.3.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
||||
react: 18.3.1
|
||||
react-dom: 18.3.1(react@18.3.1)
|
||||
transitivePeerDependencies:
|
||||
- '@types/react'
|
||||
- '@types/react-dom'
|
||||
|
||||
codemirror@6.0.2:
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.18.7
|
||||
@@ -4308,15 +4202,6 @@ snapshots:
|
||||
|
||||
fraction.js@5.3.4: {}
|
||||
|
||||
framer-motion@12.23.25(react-dom@18.3.1(react@18.3.1))(react@18.3.1):
|
||||
dependencies:
|
||||
motion-dom: 12.23.23
|
||||
motion-utils: 12.23.6
|
||||
tslib: 2.8.1
|
||||
optionalDependencies:
|
||||
react: 18.3.1
|
||||
react-dom: 18.3.1(react@18.3.1)
|
||||
|
||||
fsevents@2.3.3:
|
||||
optional: true
|
||||
|
||||
@@ -4559,12 +4444,6 @@ snapshots:
|
||||
|
||||
min-indent@1.0.1: {}
|
||||
|
||||
motion-dom@12.23.23:
|
||||
dependencies:
|
||||
motion-utils: 12.23.6
|
||||
|
||||
motion-utils@12.23.6: {}
|
||||
|
||||
ms@2.1.3: {}
|
||||
|
||||
msw@2.11.6(@types/node@20.19.9)(typescript@5.9.2):
|
||||
|
||||
@@ -58,194 +58,3 @@ pub async fn get_init_error() -> Result<Option<InitErrorPayload>, String> {
|
||||
pub async fn get_migration_result() -> Result<bool, String> {
|
||||
Ok(crate::init_status::take_migration_success())
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
pub struct ToolVersion {
|
||||
name: String,
|
||||
version: Option<String>,
|
||||
latest_version: Option<String>, // 新增字段:最新版本
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_tool_versions() -> Result<Vec<ToolVersion>, String> {
|
||||
let tools = vec!["claude", "codex", "gemini"];
|
||||
let mut results = Vec::new();
|
||||
|
||||
// 用于获取远程版本的 client
|
||||
let client = reqwest::Client::builder()
|
||||
.user_agent("cc-switch/1.0")
|
||||
.build()
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
for tool in tools {
|
||||
// 1. 获取本地版本 - 先尝试直接执行,失败则扫描常见路径
|
||||
let (local_version, local_error) = {
|
||||
// 先尝试直接执行
|
||||
let direct_result = try_get_version(tool);
|
||||
|
||||
if direct_result.0.is_some() {
|
||||
direct_result
|
||||
} else {
|
||||
// 扫描常见的 npm 全局安装路径
|
||||
scan_cli_version(tool)
|
||||
}
|
||||
};
|
||||
|
||||
// 2. 获取远程最新版本
|
||||
let latest_version = match tool {
|
||||
"claude" => fetch_npm_latest_version(&client, "@anthropic-ai/claude-code").await,
|
||||
"codex" => fetch_npm_latest_version(&client, "@openai/codex").await,
|
||||
"gemini" => fetch_npm_latest_version(&client, "@google/gemini-cli").await,
|
||||
_ => None,
|
||||
};
|
||||
|
||||
results.push(ToolVersion {
|
||||
name: tool.to_string(),
|
||||
version: local_version,
|
||||
latest_version,
|
||||
error: local_error,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
/// Helper function to fetch latest version from npm registry
|
||||
async fn fetch_npm_latest_version(client: &reqwest::Client, package: &str) -> Option<String> {
|
||||
let url = format!("https://registry.npmjs.org/{package}");
|
||||
match client.get(&url).send().await {
|
||||
Ok(resp) => {
|
||||
if let Ok(json) = resp.json::<serde_json::Value>().await {
|
||||
json.get("dist-tags")
|
||||
.and_then(|tags| tags.get("latest"))
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 从版本输出中提取纯版本号
|
||||
fn extract_version(raw: &str) -> String {
|
||||
// 匹配 semver 格式: x.y.z 或 x.y.z-xxx
|
||||
let re = regex::Regex::new(r"\d+\.\d+\.\d+(-[\w.]+)?").unwrap();
|
||||
re.find(raw)
|
||||
.map(|m| m.as_str().to_string())
|
||||
.unwrap_or_else(|| raw.to_string())
|
||||
}
|
||||
|
||||
/// 尝试直接执行命令获取版本
|
||||
fn try_get_version(tool: &str) -> (Option<String>, Option<String>) {
|
||||
use std::process::Command;
|
||||
|
||||
let output = if cfg!(target_os = "windows") {
|
||||
Command::new("cmd")
|
||||
.args(["/C", &format!("{tool} --version")])
|
||||
.output()
|
||||
} else {
|
||||
Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(format!("{tool} --version"))
|
||||
.output()
|
||||
};
|
||||
|
||||
match output {
|
||||
Ok(out) => {
|
||||
if out.status.success() {
|
||||
let raw = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
(Some(extract_version(&raw)), None)
|
||||
} else {
|
||||
let err = String::from_utf8_lossy(&out.stderr).trim().to_string();
|
||||
(
|
||||
None,
|
||||
Some(if err.is_empty() {
|
||||
"未安装或无法执行".to_string()
|
||||
} else {
|
||||
err
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
Err(e) => (None, Some(e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// 扫描常见路径查找 CLI
|
||||
fn scan_cli_version(tool: &str) -> (Option<String>, Option<String>) {
|
||||
use std::process::Command;
|
||||
|
||||
let home = dirs::home_dir().unwrap_or_default();
|
||||
|
||||
// 常见的 npm 全局安装路径
|
||||
let mut search_paths: Vec<std::path::PathBuf> = vec![
|
||||
home.join(".npm-global/bin"),
|
||||
home.join(".local/bin"),
|
||||
home.join("n/bin"), // n version manager
|
||||
];
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
search_paths.push(std::path::PathBuf::from("/opt/homebrew/bin"));
|
||||
search_paths.push(std::path::PathBuf::from("/usr/local/bin"));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
search_paths.push(std::path::PathBuf::from("/usr/local/bin"));
|
||||
search_paths.push(std::path::PathBuf::from("/usr/bin"));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
if let Some(appdata) = dirs::data_dir() {
|
||||
search_paths.push(appdata.join("npm"));
|
||||
}
|
||||
search_paths.push(std::path::PathBuf::from("C:\\Program Files\\nodejs"));
|
||||
}
|
||||
|
||||
// 扫描 nvm 目录下的所有 node 版本
|
||||
let nvm_base = home.join(".nvm/versions/node");
|
||||
if nvm_base.exists() {
|
||||
if let Ok(entries) = std::fs::read_dir(&nvm_base) {
|
||||
for entry in entries.flatten() {
|
||||
let bin_path = entry.path().join("bin");
|
||||
if bin_path.exists() {
|
||||
search_paths.push(bin_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 在每个路径中查找工具
|
||||
for path in &search_paths {
|
||||
let tool_path = if cfg!(target_os = "windows") {
|
||||
path.join(format!("{tool}.cmd"))
|
||||
} else {
|
||||
path.join(tool)
|
||||
};
|
||||
|
||||
if tool_path.exists() {
|
||||
// 构建 PATH 环境变量,确保 node 可被找到
|
||||
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();
|
||||
|
||||
if let Ok(out) = output {
|
||||
if out.status.success() {
|
||||
let raw = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
return (Some(extract_version(&raw)), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(None, Some("未安装或无法执行".to_string()))
|
||||
}
|
||||
|
||||
@@ -6,13 +6,13 @@ mod env;
|
||||
mod import_export;
|
||||
mod mcp;
|
||||
mod misc;
|
||||
mod model_test;
|
||||
mod plugin;
|
||||
mod prompt;
|
||||
mod provider;
|
||||
mod proxy;
|
||||
mod settings;
|
||||
pub mod skill;
|
||||
mod stream_check;
|
||||
mod usage;
|
||||
|
||||
pub use config::*;
|
||||
@@ -21,11 +21,11 @@ pub use env::*;
|
||||
pub use import_export::*;
|
||||
pub use mcp::*;
|
||||
pub use misc::*;
|
||||
pub use model_test::*;
|
||||
pub use plugin::*;
|
||||
pub use prompt::*;
|
||||
pub use provider::*;
|
||||
pub use proxy::*;
|
||||
pub use settings::*;
|
||||
pub use skill::*;
|
||||
pub use stream_check::*;
|
||||
pub use usage::*;
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
//! 模型测试相关命令
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::error::AppError;
|
||||
use crate::services::model_test::{
|
||||
ModelTestConfig, ModelTestLog, ModelTestResult, ModelTestService,
|
||||
};
|
||||
use crate::store::AppState;
|
||||
use tauri::State;
|
||||
|
||||
/// 测试单个供应商的模型可用性
|
||||
#[tauri::command]
|
||||
pub async fn test_provider_model(
|
||||
state: State<'_, AppState>,
|
||||
app_type: AppType,
|
||||
provider_id: String,
|
||||
) -> Result<ModelTestResult, AppError> {
|
||||
// 获取测试配置
|
||||
let config = state.db.get_model_test_config()?;
|
||||
|
||||
// 获取供应商
|
||||
let providers = state.db.get_all_providers(app_type.as_str())?;
|
||||
let provider = providers
|
||||
.get(&provider_id)
|
||||
.ok_or_else(|| AppError::Message(format!("供应商 {provider_id} 不存在")))?;
|
||||
|
||||
// 执行测试
|
||||
let result = ModelTestService::test_provider(&app_type, provider, &config).await?;
|
||||
|
||||
// 记录日志
|
||||
let _ = state.db.save_model_test_log(
|
||||
&provider_id,
|
||||
&provider.name,
|
||||
app_type.as_str(),
|
||||
&result.model_used,
|
||||
&config.test_prompt,
|
||||
&result,
|
||||
);
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// 批量测试所有供应商
|
||||
#[tauri::command]
|
||||
pub async fn test_all_providers_model(
|
||||
state: State<'_, AppState>,
|
||||
app_type: AppType,
|
||||
proxy_targets_only: bool,
|
||||
) -> Result<Vec<(String, ModelTestResult)>, AppError> {
|
||||
let config = state.db.get_model_test_config()?;
|
||||
let providers = state.db.get_all_providers(app_type.as_str())?;
|
||||
|
||||
let mut results = Vec::new();
|
||||
|
||||
for (id, provider) in providers {
|
||||
// 如果只测试代理目标,跳过非代理目标
|
||||
if proxy_targets_only && !provider.is_proxy_target.unwrap_or(false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
match ModelTestService::test_provider(&app_type, &provider, &config).await {
|
||||
Ok(result) => {
|
||||
// 记录日志
|
||||
let _ = state.db.save_model_test_log(
|
||||
&id,
|
||||
&provider.name,
|
||||
app_type.as_str(),
|
||||
&result.model_used,
|
||||
&config.test_prompt,
|
||||
&result,
|
||||
);
|
||||
results.push((id, result));
|
||||
}
|
||||
Err(e) => {
|
||||
let error_result = ModelTestResult {
|
||||
success: false,
|
||||
message: e.to_string(),
|
||||
response_time_ms: None,
|
||||
http_status: None,
|
||||
model_used: String::new(),
|
||||
tested_at: chrono::Utc::now().timestamp(),
|
||||
};
|
||||
results.push((id, error_result));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
/// 获取模型测试配置
|
||||
#[tauri::command]
|
||||
pub fn get_model_test_config(state: State<'_, AppState>) -> Result<ModelTestConfig, AppError> {
|
||||
state.db.get_model_test_config()
|
||||
}
|
||||
|
||||
/// 保存模型测试配置
|
||||
#[tauri::command]
|
||||
pub fn save_model_test_config(
|
||||
state: State<'_, AppState>,
|
||||
config: ModelTestConfig,
|
||||
) -> Result<(), AppError> {
|
||||
state.db.save_model_test_config(&config)
|
||||
}
|
||||
|
||||
/// 获取模型测试日志
|
||||
#[tauri::command]
|
||||
pub fn get_model_test_logs(
|
||||
state: State<'_, AppState>,
|
||||
app_type: Option<String>,
|
||||
provider_id: Option<String>,
|
||||
limit: Option<u32>,
|
||||
) -> Result<Vec<ModelTestLog>, AppError> {
|
||||
state.db.get_model_test_logs(
|
||||
app_type.as_deref(),
|
||||
provider_id.as_deref(),
|
||||
limit.unwrap_or(50),
|
||||
)
|
||||
}
|
||||
|
||||
/// 清理旧的测试日志
|
||||
#[tauri::command]
|
||||
pub fn cleanup_model_test_logs(
|
||||
state: State<'_, AppState>,
|
||||
keep_count: Option<u32>,
|
||||
) -> Result<u64, AppError> {
|
||||
state.db.cleanup_model_test_logs(keep_count.unwrap_or(100))
|
||||
}
|
||||
@@ -2,23 +2,21 @@
|
||||
//!
|
||||
//! 提供前端调用的 API 接口
|
||||
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::types::*;
|
||||
use crate::proxy::{CircuitBreakerConfig, CircuitBreakerStats};
|
||||
use crate::store::AppState;
|
||||
|
||||
/// 启动代理服务器(带 Live 配置接管)
|
||||
/// 启动代理服务器
|
||||
#[tauri::command]
|
||||
pub async fn start_proxy_with_takeover(
|
||||
pub async fn start_proxy_server(
|
||||
state: tauri::State<'_, AppState>,
|
||||
) -> Result<ProxyServerInfo, String> {
|
||||
state.proxy_service.start_with_takeover().await
|
||||
state.proxy_service.start().await
|
||||
}
|
||||
|
||||
/// 停止代理服务器(恢复 Live 配置)
|
||||
/// 停止代理服务器
|
||||
#[tauri::command]
|
||||
pub async fn stop_proxy_with_restore(state: tauri::State<'_, AppState>) -> Result<(), String> {
|
||||
state.proxy_service.stop_with_restore().await
|
||||
pub async fn stop_proxy_server(state: tauri::State<'_, AppState>) -> Result<(), String> {
|
||||
state.proxy_service.stop().await
|
||||
}
|
||||
|
||||
/// 获取代理服务器状态
|
||||
@@ -47,134 +45,3 @@ pub async fn update_proxy_config(
|
||||
pub async fn is_proxy_running(state: tauri::State<'_, AppState>) -> Result<bool, String> {
|
||||
Ok(state.proxy_service.is_running().await)
|
||||
}
|
||||
|
||||
/// 检查是否处于 Live 接管模式
|
||||
#[tauri::command]
|
||||
pub async fn is_live_takeover_active(state: tauri::State<'_, AppState>) -> Result<bool, String> {
|
||||
state.proxy_service.is_takeover_active().await
|
||||
}
|
||||
|
||||
/// 代理模式下切换供应商(热切换)
|
||||
#[tauri::command]
|
||||
pub async fn switch_proxy_provider(
|
||||
state: tauri::State<'_, AppState>,
|
||||
app_type: String,
|
||||
provider_id: String,
|
||||
) -> Result<(), String> {
|
||||
state
|
||||
.proxy_service
|
||||
.switch_proxy_target(&app_type, &provider_id)
|
||||
.await
|
||||
}
|
||||
|
||||
// ==================== 故障转移相关命令 ====================
|
||||
|
||||
/// 获取代理目标列表
|
||||
#[tauri::command]
|
||||
pub async fn get_proxy_targets(
|
||||
state: tauri::State<'_, AppState>,
|
||||
app_type: String,
|
||||
) -> Result<Vec<Provider>, String> {
|
||||
let db = &state.db;
|
||||
db.get_proxy_targets(&app_type)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
.map(|providers| providers.into_values().collect())
|
||||
}
|
||||
|
||||
/// 设置代理目标
|
||||
#[tauri::command]
|
||||
pub async fn set_proxy_target(
|
||||
state: tauri::State<'_, AppState>,
|
||||
provider_id: String,
|
||||
app_type: String,
|
||||
enabled: bool,
|
||||
) -> Result<(), String> {
|
||||
let db = &state.db;
|
||||
|
||||
// 设置代理目标状态
|
||||
db.set_proxy_target(&provider_id, &app_type, enabled)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
// 如果是禁用代理目标,重置健康状态
|
||||
if !enabled {
|
||||
log::info!(
|
||||
"Resetting health status for provider {provider_id} (app: {app_type}) after disabling proxy target"
|
||||
);
|
||||
if let Err(e) = db.reset_provider_health(&provider_id, &app_type).await {
|
||||
log::warn!("Failed to reset provider health: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 获取供应商健康状态
|
||||
#[tauri::command]
|
||||
pub async fn get_provider_health(
|
||||
state: tauri::State<'_, AppState>,
|
||||
provider_id: String,
|
||||
app_type: String,
|
||||
) -> Result<ProviderHealth, String> {
|
||||
let db = &state.db;
|
||||
db.get_provider_health(&provider_id, &app_type)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 重置熔断器
|
||||
#[tauri::command]
|
||||
pub async fn reset_circuit_breaker(
|
||||
state: tauri::State<'_, AppState>,
|
||||
provider_id: String,
|
||||
app_type: String,
|
||||
) -> Result<(), String> {
|
||||
// 重置数据库健康状态
|
||||
let db = &state.db;
|
||||
db.update_provider_health(&provider_id, &app_type, true, None)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
// 注意:熔断器状态在内存中,重启代理服务器后会重置
|
||||
// 如果代理服务器正在运行,需要通知它重置熔断器
|
||||
// 目前先通过数据库重置健康状态,熔断器会在下次超时后自动尝试半开
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 获取熔断器配置
|
||||
#[tauri::command]
|
||||
pub async fn get_circuit_breaker_config(
|
||||
state: tauri::State<'_, AppState>,
|
||||
) -> Result<CircuitBreakerConfig, String> {
|
||||
let db = &state.db;
|
||||
db.get_circuit_breaker_config()
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 更新熔断器配置
|
||||
#[tauri::command]
|
||||
pub async fn update_circuit_breaker_config(
|
||||
state: tauri::State<'_, AppState>,
|
||||
config: CircuitBreakerConfig,
|
||||
) -> Result<(), String> {
|
||||
let db = &state.db;
|
||||
db.update_circuit_breaker_config(&config)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 获取熔断器统计信息(仅当代理服务器运行时)
|
||||
#[tauri::command]
|
||||
pub async fn get_circuit_breaker_stats(
|
||||
state: tauri::State<'_, AppState>,
|
||||
provider_id: String,
|
||||
app_type: String,
|
||||
) -> Result<Option<CircuitBreakerStats>, String> {
|
||||
// 这个功能需要访问运行中的代理服务器的内存状态
|
||||
// 目前先返回 None,后续可以通过 ProxyService 暴露接口来实现
|
||||
let _ = (state, provider_id, app_type);
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use crate::app_config::AppType;
|
||||
use crate::error::format_skill_error;
|
||||
use crate::services::skill::SkillState;
|
||||
use crate::services::{Skill, SkillRepo, SkillService};
|
||||
@@ -9,46 +8,15 @@ use tauri::State;
|
||||
|
||||
pub struct SkillServiceState(pub Arc<SkillService>);
|
||||
|
||||
/// 解析 app 参数为 AppType
|
||||
fn parse_app_type(app: &str) -> Result<AppType, String> {
|
||||
match app.to_lowercase().as_str() {
|
||||
"claude" => Ok(AppType::Claude),
|
||||
"codex" => Ok(AppType::Codex),
|
||||
"gemini" => Ok(AppType::Gemini),
|
||||
_ => Err(format!("不支持的 app 类型: {app}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// 根据 app_type 生成带前缀的 skill key
|
||||
fn get_skill_key(app_type: &AppType, directory: &str) -> String {
|
||||
let prefix = match app_type {
|
||||
AppType::Claude => "claude",
|
||||
AppType::Codex => "codex",
|
||||
AppType::Gemini => "gemini",
|
||||
};
|
||||
format!("{prefix}:{directory}")
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_skills(
|
||||
service: State<'_, SkillServiceState>,
|
||||
app_state: State<'_, AppState>,
|
||||
) -> Result<Vec<Skill>, String> {
|
||||
get_skills_for_app("claude".to_string(), service, app_state).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_skills_for_app(
|
||||
app: String,
|
||||
_service: State<'_, SkillServiceState>,
|
||||
app_state: State<'_, AppState>,
|
||||
) -> Result<Vec<Skill>, String> {
|
||||
let app_type = parse_app_type(&app)?;
|
||||
let service = SkillService::new_for_app(app_type.clone()).map_err(|e| e.to_string())?;
|
||||
|
||||
let repos = app_state.db.get_skill_repos().map_err(|e| e.to_string())?;
|
||||
|
||||
let skills = service
|
||||
.0
|
||||
.list_skills(repos)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
@@ -58,19 +26,16 @@ pub async fn get_skills_for_app(
|
||||
let existing_states = app_state.db.get_skills().unwrap_or_default();
|
||||
|
||||
for skill in &skills {
|
||||
if skill.installed {
|
||||
let key = get_skill_key(&app_type, &skill.directory);
|
||||
if !existing_states.contains_key(&key) {
|
||||
// 本地有该 skill,但数据库中没有记录,自动添加
|
||||
if let Err(e) = app_state.db.update_skill_state(
|
||||
&key,
|
||||
&SkillState {
|
||||
installed: true,
|
||||
installed_at: Utc::now(),
|
||||
},
|
||||
) {
|
||||
log::warn!("同步本地 skill {key} 状态到数据库失败: {e}");
|
||||
}
|
||||
if skill.installed && !existing_states.contains_key(&skill.directory) {
|
||||
// 本地有该 skill,但数据库中没有记录,自动添加
|
||||
if let Err(e) = app_state.db.update_skill_state(
|
||||
&skill.directory,
|
||||
&SkillState {
|
||||
installed: true,
|
||||
installed_at: Utc::now(),
|
||||
},
|
||||
) {
|
||||
log::warn!("同步本地 skill {} 状态到数据库失败: {}", skill.directory, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -84,23 +49,11 @@ pub async fn install_skill(
|
||||
service: State<'_, SkillServiceState>,
|
||||
app_state: State<'_, AppState>,
|
||||
) -> Result<bool, String> {
|
||||
install_skill_for_app("claude".to_string(), directory, service, app_state).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn install_skill_for_app(
|
||||
app: String,
|
||||
directory: String,
|
||||
_service: State<'_, SkillServiceState>,
|
||||
app_state: State<'_, AppState>,
|
||||
) -> Result<bool, String> {
|
||||
let app_type = parse_app_type(&app)?;
|
||||
let service = SkillService::new_for_app(app_type.clone()).map_err(|e| e.to_string())?;
|
||||
|
||||
// 先在不持有写锁的情况下收集仓库与技能信息
|
||||
let repos = app_state.db.get_skill_repos().map_err(|e| e.to_string())?;
|
||||
|
||||
let skills = service
|
||||
.0
|
||||
.list_skills(repos)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
@@ -140,16 +93,16 @@ pub async fn install_skill_for_app(
|
||||
};
|
||||
|
||||
service
|
||||
.0
|
||||
.install_skill(directory.clone(), repo)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
|
||||
let key = get_skill_key(&app_type, &directory);
|
||||
app_state
|
||||
.db
|
||||
.update_skill_state(
|
||||
&key,
|
||||
&directory,
|
||||
&SkillState {
|
||||
installed: true,
|
||||
installed_at: Utc::now(),
|
||||
@@ -166,29 +119,16 @@ pub fn uninstall_skill(
|
||||
service: State<'_, SkillServiceState>,
|
||||
app_state: State<'_, AppState>,
|
||||
) -> Result<bool, String> {
|
||||
uninstall_skill_for_app("claude".to_string(), directory, service, app_state)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn uninstall_skill_for_app(
|
||||
app: String,
|
||||
directory: String,
|
||||
_service: State<'_, SkillServiceState>,
|
||||
app_state: State<'_, AppState>,
|
||||
) -> Result<bool, String> {
|
||||
let app_type = parse_app_type(&app)?;
|
||||
let service = SkillService::new_for_app(app_type.clone()).map_err(|e| e.to_string())?;
|
||||
|
||||
service
|
||||
.0
|
||||
.uninstall_skill(directory.clone())
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
// Remove from database by setting installed = false
|
||||
let key = get_skill_key(&app_type, &directory);
|
||||
app_state
|
||||
.db
|
||||
.update_skill_state(
|
||||
&key,
|
||||
&directory,
|
||||
&SkillState {
|
||||
installed: false,
|
||||
installed_at: Utc::now(),
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
//! 流式健康检查命令
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::error::AppError;
|
||||
use crate::services::stream_check::{
|
||||
HealthStatus, StreamCheckConfig, StreamCheckResult, StreamCheckService,
|
||||
};
|
||||
use crate::store::AppState;
|
||||
use tauri::State;
|
||||
|
||||
/// 流式健康检查(单个供应商)
|
||||
#[tauri::command]
|
||||
pub async fn stream_check_provider(
|
||||
state: State<'_, AppState>,
|
||||
app_type: AppType,
|
||||
provider_id: String,
|
||||
) -> Result<StreamCheckResult, AppError> {
|
||||
let config = state.db.get_stream_check_config()?;
|
||||
|
||||
let providers = state.db.get_all_providers(app_type.as_str())?;
|
||||
let provider = providers
|
||||
.get(&provider_id)
|
||||
.ok_or_else(|| AppError::Message(format!("供应商 {provider_id} 不存在")))?;
|
||||
|
||||
let result = StreamCheckService::check_with_retry(&app_type, provider, &config).await?;
|
||||
|
||||
// 记录日志
|
||||
let _ =
|
||||
state
|
||||
.db
|
||||
.save_stream_check_log(&provider_id, &provider.name, app_type.as_str(), &result);
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// 批量流式健康检查
|
||||
#[tauri::command]
|
||||
pub async fn stream_check_all_providers(
|
||||
state: State<'_, AppState>,
|
||||
app_type: AppType,
|
||||
proxy_targets_only: bool,
|
||||
) -> Result<Vec<(String, StreamCheckResult)>, AppError> {
|
||||
let config = state.db.get_stream_check_config()?;
|
||||
let providers = state.db.get_all_providers(app_type.as_str())?;
|
||||
|
||||
let mut results = Vec::new();
|
||||
|
||||
for (id, provider) in providers {
|
||||
if proxy_targets_only && !provider.is_proxy_target.unwrap_or(false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let result = StreamCheckService::check_with_retry(&app_type, &provider, &config)
|
||||
.await
|
||||
.unwrap_or_else(|e| StreamCheckResult {
|
||||
status: HealthStatus::Failed,
|
||||
success: false,
|
||||
message: e.to_string(),
|
||||
response_time_ms: None,
|
||||
http_status: None,
|
||||
model_used: String::new(),
|
||||
tested_at: chrono::Utc::now().timestamp(),
|
||||
retry_count: 0,
|
||||
});
|
||||
|
||||
let _ = state
|
||||
.db
|
||||
.save_stream_check_log(&id, &provider.name, app_type.as_str(), &result);
|
||||
|
||||
results.push((id, result));
|
||||
}
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
/// 获取流式检查配置
|
||||
#[tauri::command]
|
||||
pub fn get_stream_check_config(state: State<'_, AppState>) -> Result<StreamCheckConfig, AppError> {
|
||||
state.db.get_stream_check_config()
|
||||
}
|
||||
|
||||
/// 保存流式检查配置
|
||||
#[tauri::command]
|
||||
pub fn save_stream_check_config(
|
||||
state: State<'_, AppState>,
|
||||
config: StreamCheckConfig,
|
||||
) -> Result<(), AppError> {
|
||||
state.db.save_stream_check_config(&config)
|
||||
}
|
||||
@@ -8,6 +8,5 @@ pub mod providers;
|
||||
pub mod proxy;
|
||||
pub mod settings;
|
||||
pub mod skills;
|
||||
pub mod stream_check;
|
||||
|
||||
// 所有 DAO 方法都通过 Database impl 提供,无需单独导出
|
||||
|
||||
@@ -357,116 +357,6 @@ impl Database {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 设置单个供应商的代理目标状态(支持多个代理目标)
|
||||
pub async fn set_proxy_target(
|
||||
&self,
|
||||
provider_id: &str,
|
||||
app_type: &str,
|
||||
enabled: bool,
|
||||
) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
conn.execute(
|
||||
"UPDATE providers SET is_proxy_target = ?1
|
||||
WHERE id = ?2 AND app_type = ?3",
|
||||
params![if enabled { 1 } else { 0 }, provider_id, app_type],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 获取指定应用类型的所有代理目标供应商(按 sort_index 排序)
|
||||
pub async fn get_proxy_targets(
|
||||
&self,
|
||||
app_type: &str,
|
||||
) -> 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, is_proxy_target
|
||||
FROM providers WHERE app_type = ?1 AND is_proxy_target = 1
|
||||
ORDER BY COALESCE(sort_index, 999999), created_at ASC, id ASC"
|
||||
).map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
let provider_iter = stmt
|
||||
.query_map(params![app_type], |row| {
|
||||
let id: String = row.get(0)?;
|
||||
let name: String = row.get(1)?;
|
||||
let settings_config_str: String = row.get(2)?;
|
||||
let website_url: Option<String> = row.get(3)?;
|
||||
let category: Option<String> = row.get(4)?;
|
||||
let created_at: Option<i64> = row.get(5)?;
|
||||
let sort_index: Option<usize> = row.get(6)?;
|
||||
let notes: Option<String> = row.get(7)?;
|
||||
let icon: Option<String> = row.get(8)?;
|
||||
let icon_color: Option<String> = row.get(9)?;
|
||||
let meta_str: String = row.get(10)?;
|
||||
let is_proxy_target: bool = row.get(11)?;
|
||||
|
||||
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();
|
||||
|
||||
Ok((
|
||||
id,
|
||||
Provider {
|
||||
id: "".to_string(),
|
||||
name,
|
||||
settings_config,
|
||||
website_url,
|
||||
category,
|
||||
created_at,
|
||||
sort_index,
|
||||
notes,
|
||||
meta: Some(meta),
|
||||
icon,
|
||||
icon_color,
|
||||
is_proxy_target: Some(is_proxy_target),
|
||||
},
|
||||
))
|
||||
})
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
let mut providers = IndexMap::new();
|
||||
for provider_res in provider_iter {
|
||||
let (id, mut provider) = provider_res.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
provider.id = id.clone();
|
||||
|
||||
// 加载 endpoints
|
||||
let mut stmt_endpoints = conn.prepare(
|
||||
"SELECT url, added_at FROM provider_endpoints WHERE provider_id = ?1 AND app_type = ?2 ORDER BY added_at ASC, url ASC"
|
||||
).map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
let endpoints_iter = stmt_endpoints
|
||||
.query_map(params![id, app_type], |row| {
|
||||
let url: String = row.get(0)?;
|
||||
let added_at: Option<i64> = row.get(1)?;
|
||||
Ok((
|
||||
url,
|
||||
crate::settings::CustomEndpoint {
|
||||
url: "".to_string(),
|
||||
added_at: added_at.unwrap_or(0),
|
||||
last_used: None,
|
||||
},
|
||||
))
|
||||
})
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
let mut custom_endpoints = HashMap::new();
|
||||
for ep_res in endpoints_iter {
|
||||
let (url, mut ep) = ep_res.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
ep.url = url.clone();
|
||||
custom_endpoints.insert(url, ep);
|
||||
}
|
||||
|
||||
if let Some(meta) = &mut provider.meta {
|
||||
meta.custom_endpoints = custom_endpoints;
|
||||
}
|
||||
|
||||
providers.insert(id, provider);
|
||||
}
|
||||
|
||||
Ok(providers)
|
||||
}
|
||||
|
||||
/// 获取所有活跃的代理目标
|
||||
pub fn get_all_proxy_targets(&self) -> Result<Vec<(String, String, String)>, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
@@ -483,26 +373,6 @@ impl Database {
|
||||
Ok(targets)
|
||||
}
|
||||
|
||||
/// 更新供应商的 settings_config(仅更新配置,不改变其他字段)
|
||||
pub fn update_provider_settings_config(
|
||||
&self,
|
||||
app_type: &str,
|
||||
provider_id: &str,
|
||||
settings_config: &serde_json::Value,
|
||||
) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
conn.execute(
|
||||
"UPDATE providers SET settings_config = ?1 WHERE id = ?2 AND app_type = ?3",
|
||||
params![
|
||||
serde_json::to_string(settings_config).unwrap(),
|
||||
provider_id,
|
||||
app_type
|
||||
],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 添加自定义端点
|
||||
pub fn add_custom_endpoint(
|
||||
&self,
|
||||
|
||||
@@ -17,7 +17,7 @@ impl Database {
|
||||
let conn = lock_conn!(self.conn);
|
||||
conn.query_row(
|
||||
"SELECT enabled, listen_address, listen_port, max_retries,
|
||||
request_timeout, enable_logging, live_takeover_active
|
||||
request_timeout, enable_logging
|
||||
FROM proxy_config WHERE id = 1",
|
||||
[],
|
||||
|row| {
|
||||
@@ -28,7 +28,6 @@ impl Database {
|
||||
max_retries: row.get::<_, i32>(3)? as u8,
|
||||
request_timeout: row.get::<_, i32>(4)? as u64,
|
||||
enable_logging: row.get::<_, i32>(5)? != 0,
|
||||
live_takeover_active: row.get::<_, i32>(6).unwrap_or(0) != 0,
|
||||
})
|
||||
},
|
||||
)
|
||||
@@ -52,8 +51,8 @@ impl Database {
|
||||
|
||||
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,
|
||||
(id, enabled, listen_address, listen_port, max_retries, request_timeout, enable_logging, target_app, created_at, updated_at)
|
||||
VALUES (1, ?1, ?2, ?3, ?4, ?5, ?6, ?7,
|
||||
COALESCE((SELECT created_at FROM proxy_config WHERE id = 1), datetime('now')),
|
||||
datetime('now'))",
|
||||
rusqlite::params![
|
||||
@@ -63,7 +62,6 @@ impl Database {
|
||||
config.max_retries as i32,
|
||||
config.request_timeout as i32,
|
||||
if config.enable_logging { 1 } else { 0 },
|
||||
if config.live_takeover_active { 1 } else { 0 },
|
||||
"claude", // 兼容旧字段,写入默认值
|
||||
],
|
||||
)
|
||||
@@ -72,30 +70,6 @@ impl Database {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 设置 Live 接管状态
|
||||
pub async fn set_live_takeover_active(&self, active: bool) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
conn.execute(
|
||||
"UPDATE proxy_config SET live_takeover_active = ?1, updated_at = datetime('now') WHERE id = 1",
|
||||
rusqlite::params![if active { 1 } else { 0 }],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 检查是否处于 Live 接管模式
|
||||
pub async fn is_live_takeover_active(&self) -> Result<bool, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
let active: i32 = conn
|
||||
.query_row(
|
||||
"SELECT COALESCE(live_takeover_active, 0) FROM proxy_config WHERE id = 1",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.unwrap_or(0);
|
||||
Ok(active != 0)
|
||||
}
|
||||
|
||||
// ==================== Provider Health ====================
|
||||
|
||||
/// 获取Provider健康状态
|
||||
@@ -191,76 +165,28 @@ impl Database {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 重置Provider健康状态
|
||||
pub async fn reset_provider_health(
|
||||
&self,
|
||||
provider_id: &str,
|
||||
app_type: &str,
|
||||
) -> Result<(), AppError> {
|
||||
// ==================== Proxy Usage (可选) ====================
|
||||
|
||||
/// 记录代理使用统计
|
||||
#[allow(dead_code)]
|
||||
pub async fn record_proxy_usage(&self, record: &ProxyUsageRecord) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
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()))?;
|
||||
|
||||
log::debug!("Reset health status for provider {provider_id} (app: {app_type})");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ==================== Circuit Breaker Config ====================
|
||||
|
||||
/// 获取熔断器配置
|
||||
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",
|
||||
[],
|
||||
|row| {
|
||||
Ok(crate::proxy::circuit_breaker::CircuitBreakerConfig {
|
||||
failure_threshold: row.get::<_, i32>(0)? as u32,
|
||||
success_threshold: row.get::<_, i32>(1)? as u32,
|
||||
timeout_seconds: row.get::<_, i64>(2)? as u64,
|
||||
error_rate_threshold: row.get(3)?,
|
||||
min_requests: row.get::<_, i32>(4)? as u32,
|
||||
})
|
||||
},
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// 更新熔断器配置
|
||||
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",
|
||||
"INSERT INTO proxy_usage
|
||||
(provider_id, app_type, endpoint, request_tokens, response_tokens,
|
||||
status_code, latency_ms, error, timestamp)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
|
||||
rusqlite::params![
|
||||
config.failure_threshold as i32,
|
||||
config.success_threshold as i32,
|
||||
config.timeout_seconds as i64,
|
||||
config.error_rate_threshold,
|
||||
config.min_requests as i32,
|
||||
&record.provider_id,
|
||||
&record.app_type,
|
||||
&record.endpoint,
|
||||
record.request_tokens,
|
||||
record.response_tokens,
|
||||
record.status_code as i64,
|
||||
record.latency_ms as i64,
|
||||
&record.error,
|
||||
&record.timestamp,
|
||||
],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
@@ -268,73 +194,51 @@ impl Database {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ==================== Live Backup ====================
|
||||
|
||||
/// 保存 Live 配置备份
|
||||
pub async fn save_live_backup(
|
||||
/// 查询最近的使用统计
|
||||
#[allow(dead_code)]
|
||||
pub async fn get_recent_usage(
|
||||
&self,
|
||||
provider_id: &str,
|
||||
app_type: &str,
|
||||
config_json: &str,
|
||||
) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO proxy_live_backup (app_type, original_config, backed_up_at)
|
||||
VALUES (?1, ?2, ?3)",
|
||||
rusqlite::params![app_type, config_json, now],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
log::info!("已备份 {app_type} Live 配置");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 获取 Live 配置备份
|
||||
pub async fn get_live_backup(&self, app_type: &str) -> Result<Option<LiveBackup>, AppError> {
|
||||
limit: usize,
|
||||
) -> Result<Vec<ProxyUsageRecord>, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
let result = conn.query_row(
|
||||
"SELECT app_type, original_config, backed_up_at FROM proxy_live_backup WHERE app_type = ?1",
|
||||
rusqlite::params![app_type],
|
||||
|row| {
|
||||
Ok(LiveBackup {
|
||||
app_type: row.get(0)?,
|
||||
original_config: row.get(1)?,
|
||||
backed_up_at: row.get(2)?,
|
||||
})
|
||||
},
|
||||
);
|
||||
|
||||
match result {
|
||||
Ok(backup) => Ok(Some(backup)),
|
||||
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
|
||||
Err(e) => Err(AppError::Database(e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// 删除 Live 配置备份
|
||||
pub async fn delete_live_backup(&self, app_type: &str) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
conn.execute(
|
||||
"DELETE FROM proxy_live_backup WHERE app_type = ?1",
|
||||
rusqlite::params![app_type],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
log::info!("已删除 {app_type} Live 配置备份");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 删除所有 Live 配置备份
|
||||
pub async fn delete_all_live_backups(&self) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
conn.execute("DELETE FROM proxy_live_backup", [])
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT provider_id, app_type, endpoint, request_tokens, response_tokens,
|
||||
status_code, latency_ms, error, timestamp
|
||||
FROM proxy_usage
|
||||
WHERE provider_id = ?1 AND app_type = ?2
|
||||
ORDER BY timestamp DESC
|
||||
LIMIT ?3",
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
log::info!("已删除所有 Live 配置备份");
|
||||
Ok(())
|
||||
let rows = stmt
|
||||
.query_map(
|
||||
rusqlite::params![provider_id, app_type, limit as i64],
|
||||
|row| {
|
||||
Ok(ProxyUsageRecord {
|
||||
provider_id: row.get(0)?,
|
||||
app_type: row.get(1)?,
|
||||
endpoint: row.get(2)?,
|
||||
request_tokens: row.get(3)?,
|
||||
response_tokens: row.get(4)?,
|
||||
status_code: row.get::<_, i64>(5)? as u16,
|
||||
latency_ms: row.get::<_, i64>(6)? as u64,
|
||||
error: row.get(7)?,
|
||||
timestamp: row.get(8)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
let mut records = Vec::new();
|
||||
for row in rows {
|
||||
records.push(row.map_err(|e| AppError::Database(e.to_string()))?);
|
||||
}
|
||||
|
||||
Ok(records)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,22 +13,18 @@ impl Database {
|
||||
pub fn get_skills(&self) -> Result<IndexMap<String, SkillState>, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT directory, app_type, installed, installed_at FROM skills ORDER BY directory ASC, app_type ASC")
|
||||
.prepare("SELECT key, installed, installed_at FROM skills ORDER BY key ASC")
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
let skill_iter = stmt
|
||||
.query_map([], |row| {
|
||||
let directory: String = row.get(0)?;
|
||||
let app_type: String = row.get(1)?;
|
||||
let installed: bool = row.get(2)?;
|
||||
let installed_at_ts: i64 = row.get(3)?;
|
||||
let key: String = row.get(0)?;
|
||||
let installed: bool = row.get(1)?;
|
||||
let installed_at_ts: i64 = row.get(2)?;
|
||||
|
||||
let installed_at =
|
||||
chrono::DateTime::from_timestamp(installed_at_ts, 0).unwrap_or_default();
|
||||
|
||||
// 构建复合 key:"app_type:directory"
|
||||
let key = format!("{app_type}:{directory}");
|
||||
|
||||
Ok((
|
||||
key,
|
||||
SkillState {
|
||||
@@ -48,21 +44,11 @@ impl Database {
|
||||
}
|
||||
|
||||
/// 更新 Skill 状态
|
||||
/// key 格式为 "app_type:directory"
|
||||
pub fn update_skill_state(&self, key: &str, state: &SkillState) -> Result<(), AppError> {
|
||||
// 解析 key
|
||||
let (app_type, directory) = if let Some(idx) = key.find(':') {
|
||||
let (app, dir) = key.split_at(idx);
|
||||
(app, &dir[1..]) // 跳过冒号
|
||||
} else {
|
||||
// 向后兼容:如果没有前缀,默认为 claude
|
||||
("claude", key)
|
||||
};
|
||||
|
||||
let conn = lock_conn!(self.conn);
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO skills (directory, app_type, installed, installed_at) VALUES (?1, ?2, ?3, ?4)",
|
||||
params![directory, app_type, state.installed, state.installed_at.timestamp()],
|
||||
"INSERT OR REPLACE INTO skills (key, installed, installed_at) VALUES (?1, ?2, ?3)",
|
||||
params![key, state.installed, state.installed_at.timestamp()],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
Ok(())
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
//! 流式健康检查日志 DAO
|
||||
|
||||
use crate::database::{lock_conn, Database};
|
||||
use crate::error::AppError;
|
||||
use crate::services::stream_check::{StreamCheckConfig, StreamCheckResult};
|
||||
|
||||
impl Database {
|
||||
/// 保存流式检查日志
|
||||
pub fn save_stream_check_log(
|
||||
&self,
|
||||
provider_id: &str,
|
||||
provider_name: &str,
|
||||
app_type: &str,
|
||||
result: &StreamCheckResult,
|
||||
) -> Result<i64, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO stream_check_logs
|
||||
(provider_id, provider_name, app_type, status, success, message,
|
||||
response_time_ms, http_status, model_used, retry_count, tested_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
|
||||
rusqlite::params![
|
||||
provider_id,
|
||||
provider_name,
|
||||
app_type,
|
||||
format!("{:?}", result.status).to_lowercase(),
|
||||
result.success,
|
||||
result.message,
|
||||
result.response_time_ms.map(|t| t as i64),
|
||||
result.http_status.map(|s| s as i64),
|
||||
result.model_used,
|
||||
result.retry_count as i64,
|
||||
result.tested_at,
|
||||
],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
Ok(conn.last_insert_rowid())
|
||||
}
|
||||
|
||||
/// 获取流式检查配置
|
||||
pub fn get_stream_check_config(&self) -> Result<StreamCheckConfig, AppError> {
|
||||
match self.get_setting("stream_check_config")? {
|
||||
Some(json) => serde_json::from_str(&json)
|
||||
.map_err(|e| AppError::Message(format!("解析配置失败: {e}"))),
|
||||
None => Ok(StreamCheckConfig::default()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 保存流式检查配置
|
||||
pub fn save_stream_check_config(&self, config: &StreamCheckConfig) -> Result<(), AppError> {
|
||||
let json = serde_json::to_string(config)
|
||||
.map_err(|e| AppError::Message(format!("序列化配置失败: {e}")))?;
|
||||
self.set_setting("stream_check_config", &json)
|
||||
}
|
||||
}
|
||||
@@ -96,11 +96,9 @@ impl Database {
|
||||
// 5. Skills 表
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS skills (
|
||||
directory TEXT NOT NULL,
|
||||
app_type TEXT NOT NULL,
|
||||
key TEXT PRIMARY KEY,
|
||||
installed BOOLEAN NOT NULL DEFAULT 0,
|
||||
installed_at INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (directory, app_type)
|
||||
installed_at INTEGER NOT NULL DEFAULT 0
|
||||
)",
|
||||
[],
|
||||
)
|
||||
@@ -173,7 +171,40 @@ impl Database {
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 10. Proxy Request Logs 表 (详细请求日志)
|
||||
// 10. Proxy Usage 表 (代理使用统计,可选)
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS proxy_usage (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
provider_id TEXT NOT NULL,
|
||||
app_type TEXT NOT NULL,
|
||||
endpoint TEXT NOT NULL,
|
||||
request_tokens INTEGER,
|
||||
response_tokens INTEGER,
|
||||
status_code INTEGER NOT NULL,
|
||||
latency_ms INTEGER NOT NULL,
|
||||
error TEXT,
|
||||
timestamp TEXT NOT NULL
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 为 proxy_usage 创建索引
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_proxy_usage_timestamp
|
||||
ON proxy_usage(timestamp)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_proxy_usage_provider
|
||||
ON proxy_usage(provider_id, app_type)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 11. Proxy Request Logs 表 (详细请求日志)
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS proxy_request_logs (
|
||||
request_id TEXT PRIMARY KEY,
|
||||
@@ -239,7 +270,7 @@ impl Database {
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 11. Model Pricing 表 (模型定价)
|
||||
// 12. Model Pricing 表 (模型定价)
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS model_pricing (
|
||||
model_id TEXT PRIMARY KEY,
|
||||
@@ -253,20 +284,38 @@ impl Database {
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 12. Stream Check Logs 表 (流式健康检查日志)
|
||||
// 13. Usage Daily Stats 表 (每日聚合统计)
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS stream_check_logs (
|
||||
"CREATE TABLE IF NOT EXISTS usage_daily_stats (
|
||||
date TEXT NOT NULL,
|
||||
provider_id TEXT NOT NULL,
|
||||
app_type TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
request_count INTEGER NOT NULL DEFAULT 0,
|
||||
total_input_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
total_output_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
total_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
success_count INTEGER NOT NULL DEFAULT 0,
|
||||
error_count INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (date, provider_id, app_type, model)
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 14. Model Test Logs 表 (模型测试日志,独立于代理使用统计)
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS model_test_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
provider_id TEXT NOT NULL,
|
||||
provider_name TEXT NOT NULL,
|
||||
app_type TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
prompt 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
|
||||
)",
|
||||
[],
|
||||
@@ -274,51 +323,19 @@ impl Database {
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_stream_check_logs_provider
|
||||
ON stream_check_logs(app_type, provider_id, tested_at DESC)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_model_test_logs_provider
|
||||
ON model_test_logs(provider_id, app_type)",
|
||||
[],
|
||||
)
|
||||
.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
|
||||
)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_model_test_logs_tested_at
|
||||
ON model_test_logs(tested_at DESC)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 插入默认熔断器配置
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO circuit_breaker_config (id) VALUES (1)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 16. Proxy Live Backup 表 (Live 配置备份)
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS proxy_live_backup (
|
||||
app_type TEXT PRIMARY KEY,
|
||||
original_config TEXT NOT NULL,
|
||||
backed_up_at TEXT NOT NULL
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 尝试添加 live_takeover_active 列到 proxy_config 表
|
||||
let _ = conn.execute(
|
||||
"ALTER TABLE proxy_config ADD COLUMN live_takeover_active INTEGER NOT NULL DEFAULT 0",
|
||||
[],
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -352,9 +369,7 @@ impl Database {
|
||||
Self::set_user_version(conn, 1)?;
|
||||
}
|
||||
1 => {
|
||||
log::info!(
|
||||
"迁移数据库从 v1 到 v2(添加使用统计表和完整字段,重构 skills 表)"
|
||||
);
|
||||
log::info!("迁移数据库从 v1 到 v2(添加使用统计表和完整字段)");
|
||||
Self::migrate_v1_to_v2(conn)?;
|
||||
Self::set_user_version(conn, 2)?;
|
||||
}
|
||||
@@ -443,7 +458,7 @@ impl Database {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// v1 -> v2 迁移:添加使用统计表和完整字段,重构 skills 表
|
||||
/// v1 -> v2 迁移:添加使用统计表和完整字段
|
||||
fn migrate_v1_to_v2(conn: &Connection) -> Result<(), AppError> {
|
||||
// providers 表字段
|
||||
Self::add_column_if_missing(
|
||||
@@ -516,87 +531,29 @@ impl Database {
|
||||
[],
|
||||
)?;
|
||||
|
||||
// usage_daily_stats 表
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS usage_daily_stats (
|
||||
date TEXT NOT NULL,
|
||||
provider_id TEXT NOT NULL,
|
||||
app_type TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
request_count INTEGER NOT NULL DEFAULT 0,
|
||||
total_input_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
total_output_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
total_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
success_count INTEGER NOT NULL DEFAULT 0,
|
||||
error_count INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (date, provider_id, app_type, model)
|
||||
)",
|
||||
[],
|
||||
)?;
|
||||
|
||||
// 清空并重新插入模型定价
|
||||
conn.execute("DELETE FROM model_pricing", [])
|
||||
.map_err(|e| AppError::Database(format!("清空模型定价失败: {e}")))?;
|
||||
Self::seed_model_pricing(conn)?;
|
||||
|
||||
// 重构 skills 表(添加 app_type 字段)
|
||||
Self::migrate_skills_table(conn)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 迁移 skills 表:从单 key 主键改为 (directory, app_type) 复合主键
|
||||
fn migrate_skills_table(conn: &Connection) -> Result<(), AppError> {
|
||||
// 检查是否已经是新表结构
|
||||
if Self::has_column(conn, "skills", "app_type")? {
|
||||
log::info!("skills 表已经包含 app_type 字段,跳过迁移");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
log::info!("开始迁移 skills 表...");
|
||||
|
||||
// 1. 重命名旧表
|
||||
conn.execute("ALTER TABLE skills RENAME TO skills_old", [])
|
||||
.map_err(|e| AppError::Database(format!("重命名旧 skills 表失败: {e}")))?;
|
||||
|
||||
// 2. 创建新表
|
||||
conn.execute(
|
||||
"CREATE TABLE 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)
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(format!("创建新 skills 表失败: {e}")))?;
|
||||
|
||||
// 3. 迁移数据:解析 key 格式(如 "claude:my-skill" 或 "codex:foo")
|
||||
// 旧数据如果没有前缀,默认为 claude
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT key, installed, installed_at FROM skills_old")
|
||||
.map_err(|e| AppError::Database(format!("查询旧 skills 数据失败: {e}")))?;
|
||||
|
||||
let old_skills: Vec<(String, bool, i64)> = stmt
|
||||
.query_map([], |row| {
|
||||
Ok((
|
||||
row.get::<_, String>(0)?,
|
||||
row.get::<_, bool>(1)?,
|
||||
row.get::<_, i64>(2)?,
|
||||
))
|
||||
})
|
||||
.map_err(|e| AppError::Database(format!("读取旧 skills 数据失败: {e}")))?
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|e| AppError::Database(format!("解析旧 skills 数据失败: {e}")))?;
|
||||
|
||||
let count = old_skills.len();
|
||||
|
||||
for (key, installed, installed_at) in old_skills {
|
||||
// 解析 key: "app:directory" 或 "directory"(默认 claude)
|
||||
let (app_type, directory) = if let Some(idx) = key.find(':') {
|
||||
let (app, dir) = key.split_at(idx);
|
||||
(app.to_string(), dir[1..].to_string()) // 跳过冒号
|
||||
} else {
|
||||
("claude".to_string(), key.clone())
|
||||
};
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO skills (directory, app_type, installed, installed_at) VALUES (?1, ?2, ?3, ?4)",
|
||||
rusqlite::params![directory, app_type, installed, installed_at],
|
||||
)
|
||||
.map_err(|e| {
|
||||
AppError::Database(format!("迁移 skill {key} 到新表失败: {e}"))
|
||||
})?;
|
||||
}
|
||||
|
||||
// 4. 删除旧表
|
||||
conn.execute("DROP TABLE skills_old", [])
|
||||
.map_err(|e| AppError::Database(format!("删除旧 skills 表失败: {e}")))?;
|
||||
|
||||
log::info!("skills 表迁移完成,共迁移 {count} 条记录");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
+10
-76
@@ -530,7 +530,7 @@ pub fn run() {
|
||||
Ok(config) => {
|
||||
if config.enabled {
|
||||
log::info!("代理服务配置为启用,正在启动...");
|
||||
match state.proxy_service.start_with_takeover().await {
|
||||
match state.proxy_service.start().await {
|
||||
Ok(info) => log::info!(
|
||||
"代理服务器自动启动成功: {}:{}",
|
||||
info.address,
|
||||
@@ -635,11 +635,8 @@ pub fn run() {
|
||||
commands::restore_env_backup,
|
||||
// Skill management
|
||||
commands::get_skills,
|
||||
commands::get_skills_for_app,
|
||||
commands::install_skill,
|
||||
commands::install_skill_for_app,
|
||||
commands::uninstall_skill,
|
||||
commands::uninstall_skill_for_app,
|
||||
commands::get_skill_repos,
|
||||
commands::add_skill_repo,
|
||||
commands::remove_skill_repo,
|
||||
@@ -647,22 +644,12 @@ pub fn run() {
|
||||
commands::set_auto_launch,
|
||||
commands::get_auto_launch_status,
|
||||
// Proxy server management
|
||||
commands::start_proxy_with_takeover,
|
||||
commands::stop_proxy_with_restore,
|
||||
commands::start_proxy_server,
|
||||
commands::stop_proxy_server,
|
||||
commands::get_proxy_status,
|
||||
commands::get_proxy_config,
|
||||
commands::update_proxy_config,
|
||||
commands::is_proxy_running,
|
||||
commands::is_live_takeover_active,
|
||||
commands::switch_proxy_provider,
|
||||
// Proxy failover commands
|
||||
commands::get_proxy_targets,
|
||||
commands::set_proxy_target,
|
||||
commands::get_provider_health,
|
||||
commands::reset_circuit_breaker,
|
||||
commands::get_circuit_breaker_config,
|
||||
commands::update_circuit_breaker_config,
|
||||
commands::get_circuit_breaker_stats,
|
||||
// Usage statistics
|
||||
commands::get_usage_summary,
|
||||
commands::get_usage_trends,
|
||||
@@ -674,12 +661,13 @@ pub fn run() {
|
||||
commands::update_model_pricing,
|
||||
commands::delete_model_pricing,
|
||||
commands::check_provider_limits,
|
||||
// Stream health check
|
||||
commands::stream_check_provider,
|
||||
commands::stream_check_all_providers,
|
||||
commands::get_stream_check_config,
|
||||
commands::save_stream_check_config,
|
||||
commands::get_tool_versions,
|
||||
// Model testing
|
||||
commands::test_provider_model,
|
||||
commands::test_all_providers_model,
|
||||
commands::get_model_test_config,
|
||||
commands::save_model_test_config,
|
||||
commands::get_model_test_logs,
|
||||
commands::cleanup_model_test_logs,
|
||||
]);
|
||||
|
||||
let app = builder
|
||||
@@ -687,22 +675,6 @@ pub fn run() {
|
||||
.expect("error while running tauri application");
|
||||
|
||||
app.run(|app_handle, event| {
|
||||
// 处理退出请求(所有平台)
|
||||
if let RunEvent::ExitRequested { api, .. } = &event {
|
||||
log::info!("收到退出请求,开始清理...");
|
||||
// 阻止立即退出,执行清理
|
||||
api.prevent_exit();
|
||||
|
||||
let app_handle = app_handle.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
cleanup_before_exit(&app_handle).await;
|
||||
log::info!("清理完成,退出应用");
|
||||
// 使用 std::process::exit 避免再次触发 ExitRequested
|
||||
std::process::exit(0);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
match event {
|
||||
@@ -782,44 +754,6 @@ pub fn run() {
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 应用退出清理
|
||||
// ============================================================
|
||||
|
||||
/// 应用退出前的清理工作
|
||||
///
|
||||
/// 在应用退出前检查代理服务器状态,如果正在运行则停止代理并恢复 Live 配置。
|
||||
/// 确保 Claude Code/Codex/Gemini 的配置不会处于损坏状态。
|
||||
pub async fn cleanup_before_exit(app_handle: &tauri::AppHandle) {
|
||||
if let Some(state) = app_handle.try_state::<store::AppState>() {
|
||||
let proxy_service = &state.proxy_service;
|
||||
|
||||
// 检查代理是否在运行
|
||||
if proxy_service.is_running().await {
|
||||
log::info!("检测到代理服务器正在运行,开始清理...");
|
||||
|
||||
// 检查是否处于 Live 接管模式
|
||||
if let Ok(is_takeover) = state.db.is_live_takeover_active().await {
|
||||
if is_takeover {
|
||||
// 接管模式:停止并恢复配置
|
||||
if let Err(e) = proxy_service.stop_with_restore().await {
|
||||
log::error!("退出时恢复 Live 配置失败: {e}");
|
||||
} else {
|
||||
log::info!("已恢复 Live 配置");
|
||||
}
|
||||
} else {
|
||||
// 非接管模式:仅停止代理
|
||||
if let Err(e) = proxy_service.stop().await {
|
||||
log::error!("退出时停止代理失败: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log::info!("代理服务器清理完成");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 迁移错误对话框辅助函数
|
||||
// ============================================================
|
||||
|
||||
@@ -1,334 +0,0 @@
|
||||
//! 熔断器模块
|
||||
//!
|
||||
//! 实现熔断器模式,用于防止向不健康的供应商发送请求
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
/// 熔断器状态
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CircuitState {
|
||||
/// 关闭状态 - 正常工作
|
||||
Closed,
|
||||
/// 打开状态 - 熔断激活,拒绝请求
|
||||
Open,
|
||||
/// 半开状态 - 尝试恢复,允许部分请求通过
|
||||
HalfOpen,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for CircuitState {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
CircuitState::Closed => write!(f, "closed"),
|
||||
CircuitState::Open => write!(f, "open"),
|
||||
CircuitState::HalfOpen => write!(f, "half_open"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 熔断器配置
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CircuitBreakerConfig {
|
||||
/// 失败阈值 - 连续失败多少次后打开熔断器
|
||||
pub failure_threshold: u32,
|
||||
/// 成功阈值 - 半开状态下成功多少次后关闭熔断器
|
||||
pub success_threshold: u32,
|
||||
/// 超时时间 - 熔断器打开后多久尝试半开(秒)
|
||||
pub timeout_seconds: u64,
|
||||
/// 错误率阈值 - 错误率超过此值时打开熔断器 (0.0-1.0)
|
||||
pub error_rate_threshold: f64,
|
||||
/// 最小请求数 - 计算错误率前的最小请求数
|
||||
pub min_requests: u32,
|
||||
}
|
||||
|
||||
impl Default for CircuitBreakerConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
failure_threshold: 5,
|
||||
success_threshold: 2,
|
||||
timeout_seconds: 60,
|
||||
error_rate_threshold: 0.5,
|
||||
min_requests: 10,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 熔断器实例
|
||||
pub struct CircuitBreaker {
|
||||
/// 当前状态
|
||||
state: Arc<RwLock<CircuitState>>,
|
||||
/// 连续失败计数
|
||||
consecutive_failures: Arc<AtomicU32>,
|
||||
/// 连续成功计数(半开状态)
|
||||
consecutive_successes: Arc<AtomicU32>,
|
||||
/// 总请求计数
|
||||
total_requests: Arc<AtomicU32>,
|
||||
/// 失败请求计数
|
||||
failed_requests: Arc<AtomicU32>,
|
||||
/// 上次打开时间
|
||||
last_opened_at: Arc<RwLock<Option<Instant>>>,
|
||||
/// 配置
|
||||
config: CircuitBreakerConfig,
|
||||
}
|
||||
|
||||
impl CircuitBreaker {
|
||||
/// 创建新的熔断器
|
||||
pub fn new(config: CircuitBreakerConfig) -> Self {
|
||||
Self {
|
||||
state: Arc::new(RwLock::new(CircuitState::Closed)),
|
||||
consecutive_failures: Arc::new(AtomicU32::new(0)),
|
||||
consecutive_successes: Arc::new(AtomicU32::new(0)),
|
||||
total_requests: Arc::new(AtomicU32::new(0)),
|
||||
failed_requests: Arc::new(AtomicU32::new(0)),
|
||||
last_opened_at: Arc::new(RwLock::new(None)),
|
||||
config,
|
||||
}
|
||||
}
|
||||
|
||||
/// 检查是否允许请求通过
|
||||
pub async fn allow_request(&self) -> bool {
|
||||
let state = *self.state.read().await;
|
||||
|
||||
match state {
|
||||
CircuitState::Closed => true,
|
||||
CircuitState::Open => {
|
||||
// 检查是否应该尝试半开
|
||||
if let Some(opened_at) = *self.last_opened_at.read().await {
|
||||
if opened_at.elapsed().as_secs() >= self.config.timeout_seconds {
|
||||
log::info!(
|
||||
"Circuit breaker transitioning from Open to HalfOpen (timeout reached)"
|
||||
);
|
||||
self.transition_to_half_open().await;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
CircuitState::HalfOpen => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// 记录成功
|
||||
pub async fn record_success(&self) {
|
||||
let state = *self.state.read().await;
|
||||
|
||||
// 重置失败计数
|
||||
self.consecutive_failures.store(0, Ordering::SeqCst);
|
||||
self.total_requests.fetch_add(1, Ordering::SeqCst);
|
||||
|
||||
match state {
|
||||
CircuitState::HalfOpen => {
|
||||
let successes = self.consecutive_successes.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
log::debug!(
|
||||
"Circuit breaker HalfOpen: {} consecutive successes (threshold: {})",
|
||||
successes,
|
||||
self.config.success_threshold
|
||||
);
|
||||
|
||||
if successes >= self.config.success_threshold {
|
||||
log::info!("Circuit breaker transitioning from HalfOpen to Closed (success threshold reached)");
|
||||
self.transition_to_closed().await;
|
||||
}
|
||||
}
|
||||
CircuitState::Closed => {
|
||||
log::debug!("Circuit breaker Closed: request succeeded");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// 记录失败
|
||||
pub async fn record_failure(&self) {
|
||||
let state = *self.state.read().await;
|
||||
|
||||
// 更新计数器
|
||||
let failures = self.consecutive_failures.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
self.total_requests.fetch_add(1, Ordering::SeqCst);
|
||||
self.failed_requests.fetch_add(1, Ordering::SeqCst);
|
||||
|
||||
// 重置成功计数
|
||||
self.consecutive_successes.store(0, Ordering::SeqCst);
|
||||
|
||||
log::debug!(
|
||||
"Circuit breaker {:?}: {} consecutive failures (threshold: {})",
|
||||
state,
|
||||
failures,
|
||||
self.config.failure_threshold
|
||||
);
|
||||
|
||||
// 检查是否应该打开熔断器
|
||||
match state {
|
||||
CircuitState::Closed | CircuitState::HalfOpen => {
|
||||
// 检查连续失败次数
|
||||
if failures >= self.config.failure_threshold {
|
||||
log::warn!(
|
||||
"Circuit breaker opening due to {} consecutive failures (threshold: {})",
|
||||
failures,
|
||||
self.config.failure_threshold
|
||||
);
|
||||
self.transition_to_open().await;
|
||||
} else {
|
||||
// 检查错误率
|
||||
let total = self.total_requests.load(Ordering::SeqCst);
|
||||
let failed = self.failed_requests.load(Ordering::SeqCst);
|
||||
|
||||
if total >= self.config.min_requests {
|
||||
let error_rate = failed as f64 / total as f64;
|
||||
log::debug!(
|
||||
"Circuit breaker error rate: {:.2}% ({}/{} requests)",
|
||||
error_rate * 100.0,
|
||||
failed,
|
||||
total
|
||||
);
|
||||
|
||||
if error_rate >= self.config.error_rate_threshold {
|
||||
log::warn!(
|
||||
"Circuit breaker opening due to high error rate: {:.2}% (threshold: {:.2}%)",
|
||||
error_rate * 100.0,
|
||||
self.config.error_rate_threshold * 100.0
|
||||
);
|
||||
self.transition_to_open().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取当前状态
|
||||
pub async fn get_state(&self) -> CircuitState {
|
||||
*self.state.read().await
|
||||
}
|
||||
|
||||
/// 获取统计信息
|
||||
#[allow(dead_code)]
|
||||
pub async fn get_stats(&self) -> CircuitBreakerStats {
|
||||
CircuitBreakerStats {
|
||||
state: *self.state.read().await,
|
||||
consecutive_failures: self.consecutive_failures.load(Ordering::SeqCst),
|
||||
consecutive_successes: self.consecutive_successes.load(Ordering::SeqCst),
|
||||
total_requests: self.total_requests.load(Ordering::SeqCst),
|
||||
failed_requests: self.failed_requests.load(Ordering::SeqCst),
|
||||
}
|
||||
}
|
||||
|
||||
/// 重置熔断器(手动恢复)
|
||||
#[allow(dead_code)]
|
||||
pub async fn reset(&self) {
|
||||
log::info!("Circuit breaker manually reset to Closed state");
|
||||
self.transition_to_closed().await;
|
||||
}
|
||||
|
||||
/// 转换到打开状态
|
||||
async fn transition_to_open(&self) {
|
||||
*self.state.write().await = CircuitState::Open;
|
||||
*self.last_opened_at.write().await = Some(Instant::now());
|
||||
self.consecutive_failures.store(0, Ordering::SeqCst);
|
||||
self.consecutive_successes.store(0, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// 转换到半开状态
|
||||
async fn transition_to_half_open(&self) {
|
||||
*self.state.write().await = CircuitState::HalfOpen;
|
||||
self.consecutive_successes.store(0, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// 转换到关闭状态
|
||||
async fn transition_to_closed(&self) {
|
||||
*self.state.write().await = CircuitState::Closed;
|
||||
self.consecutive_failures.store(0, Ordering::SeqCst);
|
||||
self.consecutive_successes.store(0, Ordering::SeqCst);
|
||||
// 重置计数器
|
||||
self.total_requests.store(0, Ordering::SeqCst);
|
||||
self.failed_requests.store(0, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
/// 熔断器统计信息
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CircuitBreakerStats {
|
||||
pub state: CircuitState,
|
||||
pub consecutive_failures: u32,
|
||||
pub consecutive_successes: u32,
|
||||
pub total_requests: u32,
|
||||
pub failed_requests: u32,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_circuit_breaker_closed_to_open() {
|
||||
let config = CircuitBreakerConfig {
|
||||
failure_threshold: 3,
|
||||
..Default::default()
|
||||
};
|
||||
let breaker = CircuitBreaker::new(config);
|
||||
|
||||
// 初始状态应该是关闭
|
||||
assert_eq!(breaker.get_state().await, CircuitState::Closed);
|
||||
assert!(breaker.allow_request().await);
|
||||
|
||||
// 记录 3 次失败
|
||||
for _ in 0..3 {
|
||||
breaker.record_failure().await;
|
||||
}
|
||||
|
||||
// 应该转换到打开状态
|
||||
assert_eq!(breaker.get_state().await, CircuitState::Open);
|
||||
assert!(!breaker.allow_request().await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_circuit_breaker_half_open_to_closed() {
|
||||
let config = CircuitBreakerConfig {
|
||||
failure_threshold: 2,
|
||||
success_threshold: 2,
|
||||
..Default::default()
|
||||
};
|
||||
let breaker = CircuitBreaker::new(config);
|
||||
|
||||
// 打开熔断器
|
||||
breaker.record_failure().await;
|
||||
breaker.record_failure().await;
|
||||
assert_eq!(breaker.get_state().await, CircuitState::Open);
|
||||
|
||||
// 手动转换到半开状态
|
||||
breaker.transition_to_half_open().await;
|
||||
assert_eq!(breaker.get_state().await, CircuitState::HalfOpen);
|
||||
|
||||
// 记录 2 次成功
|
||||
breaker.record_success().await;
|
||||
breaker.record_success().await;
|
||||
|
||||
// 应该转换到关闭状态
|
||||
assert_eq!(breaker.get_state().await, CircuitState::Closed);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_circuit_breaker_reset() {
|
||||
let config = CircuitBreakerConfig {
|
||||
failure_threshold: 2,
|
||||
..Default::default()
|
||||
};
|
||||
let breaker = CircuitBreaker::new(config);
|
||||
|
||||
// 打开熔断器
|
||||
breaker.record_failure().await;
|
||||
breaker.record_failure().await;
|
||||
assert_eq!(breaker.get_state().await, CircuitState::Open);
|
||||
|
||||
// 重置
|
||||
breaker.reset().await;
|
||||
assert_eq!(breaker.get_state().await, CircuitState::Closed);
|
||||
assert!(breaker.allow_request().await);
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,8 @@
|
||||
|
||||
use super::{
|
||||
error::*,
|
||||
provider_router::ProviderRouter as NewProviderRouter,
|
||||
providers::{get_adapter, ProviderAdapter},
|
||||
router::ProviderRouter,
|
||||
types::ProxyStatus,
|
||||
ProxyError,
|
||||
};
|
||||
@@ -18,11 +18,9 @@ use tokio::sync::RwLock;
|
||||
|
||||
pub struct RequestForwarder {
|
||||
client: Client,
|
||||
router: Arc<NewProviderRouter>,
|
||||
#[allow(dead_code)]
|
||||
router: ProviderRouter,
|
||||
max_retries: u8,
|
||||
status: Arc<RwLock<ProxyStatus>>,
|
||||
current_providers: Arc<RwLock<std::collections::HashMap<String, (String, String)>>>,
|
||||
}
|
||||
|
||||
impl RequestForwarder {
|
||||
@@ -31,7 +29,6 @@ impl RequestForwarder {
|
||||
timeout_secs: u64,
|
||||
max_retries: u8,
|
||||
status: Arc<RwLock<ProxyStatus>>,
|
||||
current_providers: Arc<RwLock<std::collections::HashMap<String, (String, String)>>>,
|
||||
) -> Self {
|
||||
let mut client_builder = Client::builder();
|
||||
if timeout_secs > 0 {
|
||||
@@ -44,14 +41,13 @@ impl RequestForwarder {
|
||||
|
||||
Self {
|
||||
client,
|
||||
router: Arc::new(NewProviderRouter::new(db)),
|
||||
router: ProviderRouter::new(db),
|
||||
max_retries,
|
||||
status,
|
||||
current_providers,
|
||||
}
|
||||
}
|
||||
|
||||
/// 转发请求(带故障转移)
|
||||
/// 转发请求(带重试和故障转移)
|
||||
pub async fn forward_with_retry(
|
||||
&self,
|
||||
app_type: &AppType,
|
||||
@@ -59,39 +55,21 @@ impl RequestForwarder {
|
||||
body: Value,
|
||||
headers: axum::http::HeaderMap,
|
||||
) -> Result<Response, ProxyError> {
|
||||
// 获取适配器
|
||||
let adapter = get_adapter(app_type);
|
||||
let app_type_str = app_type.as_str();
|
||||
|
||||
// 使用新的 ProviderRouter 选择所有可用供应商
|
||||
let providers = self
|
||||
.router
|
||||
.select_providers(app_type_str)
|
||||
.await
|
||||
.map_err(|e| ProxyError::DatabaseError(e.to_string()))?;
|
||||
|
||||
if providers.is_empty() {
|
||||
return Err(ProxyError::NoAvailableProvider);
|
||||
}
|
||||
|
||||
log::info!(
|
||||
"[{}] 故障转移链: {} 个可用供应商",
|
||||
app_type_str,
|
||||
providers.len()
|
||||
);
|
||||
|
||||
let mut last_error = None;
|
||||
let mut failed_ids = Vec::new();
|
||||
let mut failover_happened = false;
|
||||
|
||||
// 依次尝试每个供应商
|
||||
for (attempt, provider) in providers.iter().enumerate() {
|
||||
log::info!(
|
||||
"[{}] 尝试 {}/{} - 使用Provider: {} (sort_index: {})",
|
||||
app_type_str,
|
||||
// 获取适配器
|
||||
let adapter = get_adapter(app_type);
|
||||
|
||||
for attempt in 0..self.max_retries {
|
||||
// 选择Provider
|
||||
let provider = self.router.select_provider(app_type, &failed_ids).await?;
|
||||
|
||||
log::debug!(
|
||||
"尝试 {} - 使用Provider: {} ({})",
|
||||
attempt + 1,
|
||||
providers.len(),
|
||||
provider.name,
|
||||
provider.sort_index.unwrap_or(999999)
|
||||
provider.id
|
||||
);
|
||||
|
||||
// 更新状态中的当前Provider信息
|
||||
@@ -110,29 +88,16 @@ impl RequestForwarder {
|
||||
|
||||
// 转发请求
|
||||
match self
|
||||
.forward(provider, endpoint, &body, &headers, adapter.as_ref())
|
||||
.forward(&provider, endpoint, &body, &headers, adapter.as_ref())
|
||||
.await
|
||||
{
|
||||
Ok(response) => {
|
||||
let latency = start.elapsed().as_millis() as u64;
|
||||
let _latency = start.elapsed().as_millis() as u64;
|
||||
|
||||
// 成功:记录成功并更新熔断器
|
||||
if let Err(e) = self
|
||||
.router
|
||||
.record_result(&provider.id, app_type_str, true, None)
|
||||
.await
|
||||
{
|
||||
log::warn!("Failed to record success: {e}");
|
||||
}
|
||||
|
||||
// 更新当前应用类型使用的 provider
|
||||
{
|
||||
let mut current_providers = self.current_providers.write().await;
|
||||
current_providers.insert(
|
||||
app_type_str.to_string(),
|
||||
(provider.id.clone(), provider.name.clone()),
|
||||
);
|
||||
}
|
||||
// 成功:更新健康状态
|
||||
self.router
|
||||
.update_health(&provider, app_type, true, None)
|
||||
.await;
|
||||
|
||||
// 更新成功统计
|
||||
{
|
||||
@@ -141,12 +106,6 @@ impl RequestForwarder {
|
||||
status.last_error = None;
|
||||
if failover_happened {
|
||||
status.failover_count += 1;
|
||||
log::info!(
|
||||
"[{}] 故障转移成功!切换到 Provider: {} (耗时: {}ms)",
|
||||
app_type_str,
|
||||
provider.name,
|
||||
latency
|
||||
);
|
||||
}
|
||||
// 重新计算成功率
|
||||
if status.total_requests > 0 {
|
||||
@@ -156,33 +115,23 @@ impl RequestForwarder {
|
||||
}
|
||||
}
|
||||
|
||||
log::info!(
|
||||
"[{}] 请求成功 - Provider: {} - {}ms",
|
||||
app_type_str,
|
||||
provider.name,
|
||||
latency
|
||||
);
|
||||
|
||||
return Ok(response);
|
||||
}
|
||||
Err(e) => {
|
||||
let latency = start.elapsed().as_millis() as u64;
|
||||
|
||||
// 失败:记录失败并更新熔断器
|
||||
if let Err(record_err) = self
|
||||
.router
|
||||
.record_result(&provider.id, app_type_str, false, Some(e.to_string()))
|
||||
.await
|
||||
{
|
||||
log::warn!("Failed to record failure: {record_err}");
|
||||
}
|
||||
|
||||
// 分类错误
|
||||
// 失败:分类错误
|
||||
let category = self.categorize_proxy_error(&e);
|
||||
|
||||
match category {
|
||||
ErrorCategory::Retryable => {
|
||||
// 可重试:更新错误信息,继续尝试下一个供应商
|
||||
// 可重试:更新健康状态,添加到失败列表
|
||||
self.router
|
||||
.update_health(&provider, app_type, false, Some(e.to_string()))
|
||||
.await;
|
||||
failed_ids.push(provider.id.clone());
|
||||
|
||||
// 更新错误信息
|
||||
{
|
||||
let mut status = self.status.write().await;
|
||||
status.last_error =
|
||||
@@ -190,19 +139,15 @@ impl RequestForwarder {
|
||||
}
|
||||
|
||||
log::warn!(
|
||||
"[{}] Provider {} 失败(可重试): {} - {}ms",
|
||||
app_type_str,
|
||||
"请求失败(可重试): Provider {} - {} - {}ms",
|
||||
provider.name,
|
||||
e,
|
||||
latency
|
||||
);
|
||||
|
||||
last_error = Some(e);
|
||||
// 继续尝试下一个供应商
|
||||
continue;
|
||||
}
|
||||
ErrorCategory::NonRetryable | ErrorCategory::ClientAbort => {
|
||||
// 不可重试:直接返回错误
|
||||
// 不可重试:更新失败统计并返回
|
||||
{
|
||||
let mut status = self.status.write().await;
|
||||
status.failed_requests += 1;
|
||||
@@ -213,12 +158,7 @@ impl RequestForwarder {
|
||||
* 100.0;
|
||||
}
|
||||
}
|
||||
log::error!(
|
||||
"[{}] Provider {} 失败(不可重试): {}",
|
||||
app_type_str,
|
||||
provider.name,
|
||||
e
|
||||
);
|
||||
log::error!("请求失败(不可重试): {e}");
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
@@ -226,24 +166,18 @@ impl RequestForwarder {
|
||||
}
|
||||
}
|
||||
|
||||
// 所有供应商都失败了
|
||||
// 所有重试都失败
|
||||
{
|
||||
let mut status = self.status.write().await;
|
||||
status.failed_requests += 1;
|
||||
status.last_error = Some("所有供应商都失败".to_string());
|
||||
status.last_error = Some("已达到最大重试次数".to_string());
|
||||
if status.total_requests > 0 {
|
||||
status.success_rate =
|
||||
(status.success_requests as f32 / status.total_requests as f32) * 100.0;
|
||||
}
|
||||
}
|
||||
|
||||
log::error!(
|
||||
"[{}] 所有 {} 个供应商都失败了",
|
||||
app_type_str,
|
||||
providers.len()
|
||||
);
|
||||
|
||||
Err(last_error.unwrap_or(ProxyError::MaxRetriesExceeded))
|
||||
Err(ProxyError::MaxRetriesExceeded)
|
||||
}
|
||||
|
||||
/// 转发单个请求(使用适配器)
|
||||
|
||||
@@ -322,7 +322,6 @@ pub async fn handle_messages(
|
||||
config.request_timeout,
|
||||
config.max_retries,
|
||||
state.status.clone(),
|
||||
state.current_providers.clone(),
|
||||
);
|
||||
|
||||
let response = forwarder
|
||||
@@ -642,7 +641,6 @@ pub async fn handle_gemini(
|
||||
config.request_timeout,
|
||||
config.max_retries,
|
||||
state.status.clone(),
|
||||
state.current_providers.clone(),
|
||||
);
|
||||
|
||||
// 提取完整的路径和查询参数
|
||||
@@ -808,7 +806,6 @@ pub async fn handle_responses(
|
||||
config.request_timeout,
|
||||
config.max_retries,
|
||||
state.status.clone(),
|
||||
state.current_providers.clone(),
|
||||
);
|
||||
|
||||
let response = forwarder
|
||||
@@ -988,7 +985,6 @@ pub async fn handle_chat_completions(
|
||||
config.request_timeout,
|
||||
config.max_retries,
|
||||
state.status.clone(),
|
||||
state.current_providers.clone(),
|
||||
);
|
||||
|
||||
let response = forwarder
|
||||
|
||||
@@ -2,12 +2,10 @@
|
||||
//!
|
||||
//! 提供本地HTTP代理服务,支持多Provider故障转移和请求透传
|
||||
|
||||
pub mod circuit_breaker;
|
||||
pub mod error;
|
||||
mod forwarder;
|
||||
mod handlers;
|
||||
mod health;
|
||||
pub mod provider_router;
|
||||
pub mod providers;
|
||||
pub mod response_handler;
|
||||
mod router;
|
||||
@@ -18,14 +16,8 @@ pub mod usage;
|
||||
|
||||
// 公开导出给外部使用(commands, services等模块需要)
|
||||
#[allow(unused_imports)]
|
||||
pub use circuit_breaker::{
|
||||
CircuitBreaker, CircuitBreakerConfig, CircuitBreakerStats, CircuitState,
|
||||
};
|
||||
#[allow(unused_imports)]
|
||||
pub use error::ProxyError;
|
||||
#[allow(unused_imports)]
|
||||
pub use provider_router::ProviderRouter;
|
||||
#[allow(unused_imports)]
|
||||
pub use response_handler::{NonStreamHandler, ResponseType, StreamHandler};
|
||||
#[allow(unused_imports)]
|
||||
pub use session::{ClientFormat, ProxySession};
|
||||
|
||||
@@ -1,200 +0,0 @@
|
||||
//! 供应商路由器模块
|
||||
//!
|
||||
//! 负责选择和管理代理目标供应商,实现智能故障转移
|
||||
|
||||
use crate::database::Database;
|
||||
use crate::error::AppError;
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::circuit_breaker::CircuitBreaker;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
/// 供应商路由器
|
||||
pub struct ProviderRouter {
|
||||
/// 数据库连接
|
||||
db: Arc<Database>,
|
||||
/// 熔断器管理器 - key 格式: "app_type:provider_id"
|
||||
circuit_breakers: Arc<RwLock<HashMap<String, Arc<CircuitBreaker>>>>,
|
||||
}
|
||||
|
||||
impl ProviderRouter {
|
||||
/// 创建新的供应商路由器
|
||||
pub fn new(db: Arc<Database>) -> Self {
|
||||
Self {
|
||||
db,
|
||||
circuit_breakers: Arc::new(RwLock::new(HashMap::new())),
|
||||
}
|
||||
}
|
||||
|
||||
/// 选择可用的供应商(支持故障转移)
|
||||
/// 返回按优先级排序的可用供应商列表
|
||||
pub async fn select_providers(&self, app_type: &str) -> Result<Vec<Provider>, AppError> {
|
||||
// 直接获取当前选中的供应商(基于 is_current 字段)
|
||||
let current_id = self
|
||||
.db
|
||||
.get_current_provider(app_type)?
|
||||
.ok_or_else(|| AppError::Config(format!("No current provider for {}", app_type)))?;
|
||||
|
||||
let providers = self.db.get_all_providers(app_type)?;
|
||||
let provider = providers
|
||||
.get(¤t_id)
|
||||
.ok_or_else(|| AppError::Config(format!("Current provider {} not found", current_id)))?
|
||||
.clone();
|
||||
|
||||
log::info!(
|
||||
"[{}] Selected current provider: {} ({})",
|
||||
app_type,
|
||||
provider.name,
|
||||
provider.id
|
||||
);
|
||||
|
||||
// 检查熔断器状态
|
||||
let circuit_key = format!("{}:{}", app_type, provider.id);
|
||||
let breaker = self.get_or_create_circuit_breaker(&circuit_key).await;
|
||||
|
||||
if !breaker.allow_request().await {
|
||||
log::warn!(
|
||||
"Provider {} is unavailable (circuit breaker open)",
|
||||
provider.id
|
||||
);
|
||||
return Err(AppError::Config(format!(
|
||||
"Current provider {} is unavailable (circuit breaker open)",
|
||||
provider.name
|
||||
)));
|
||||
}
|
||||
|
||||
// 返回单个供应商(保留 Vec 接口以兼容现有代码)
|
||||
Ok(vec![provider])
|
||||
}
|
||||
|
||||
/// 记录供应商请求结果
|
||||
pub async fn record_result(
|
||||
&self,
|
||||
provider_id: &str,
|
||||
app_type: &str,
|
||||
success: bool,
|
||||
error_msg: Option<String>,
|
||||
) -> Result<(), AppError> {
|
||||
// 1. 更新熔断器状态
|
||||
let circuit_key = format!("{app_type}:{provider_id}");
|
||||
let breaker = self.get_or_create_circuit_breaker(&circuit_key).await;
|
||||
|
||||
if success {
|
||||
breaker.record_success().await;
|
||||
log::debug!("Provider {provider_id} request succeeded");
|
||||
} else {
|
||||
breaker.record_failure().await;
|
||||
log::warn!(
|
||||
"Provider {} request failed: {}",
|
||||
provider_id,
|
||||
error_msg.as_deref().unwrap_or("Unknown error")
|
||||
);
|
||||
}
|
||||
|
||||
// 2. 更新数据库健康状态
|
||||
self.db
|
||||
.update_provider_health(provider_id, app_type, success, error_msg.clone())
|
||||
.await?;
|
||||
|
||||
// 3. 如果连续失败达到熔断阈值,自动禁用代理目标
|
||||
if !success {
|
||||
let health = self.db.get_provider_health(provider_id, app_type).await?;
|
||||
|
||||
// 获取熔断器配置
|
||||
let config = self.db.get_circuit_breaker_config().await.ok();
|
||||
let failure_threshold = config.map(|c| c.failure_threshold).unwrap_or(5);
|
||||
|
||||
// 如果连续失败达到阈值,自动关闭该供应商的代理开关
|
||||
if health.consecutive_failures >= failure_threshold {
|
||||
log::warn!(
|
||||
"Provider {} has failed {} times (threshold: {}), auto-disabling proxy target",
|
||||
provider_id,
|
||||
health.consecutive_failures,
|
||||
failure_threshold
|
||||
);
|
||||
self.db
|
||||
.set_proxy_target(provider_id, app_type, false)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 重置熔断器(手动恢复)
|
||||
#[allow(dead_code)]
|
||||
pub async fn reset_circuit_breaker(&self, circuit_key: &str) {
|
||||
let breakers = self.circuit_breakers.read().await;
|
||||
if let Some(breaker) = breakers.get(circuit_key) {
|
||||
log::info!("Manually resetting circuit breaker for {circuit_key}");
|
||||
breaker.reset().await;
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取熔断器状态
|
||||
#[allow(dead_code)]
|
||||
pub async fn get_circuit_breaker_stats(
|
||||
&self,
|
||||
provider_id: &str,
|
||||
app_type: &str,
|
||||
) -> Option<crate::proxy::circuit_breaker::CircuitBreakerStats> {
|
||||
let circuit_key = format!("{app_type}:{provider_id}");
|
||||
let breakers = self.circuit_breakers.read().await;
|
||||
|
||||
if let Some(breaker) = breakers.get(&circuit_key) {
|
||||
Some(breaker.get_stats().await)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取或创建熔断器
|
||||
async fn get_or_create_circuit_breaker(&self, key: &str) -> Arc<CircuitBreaker> {
|
||||
// 先尝试读锁获取
|
||||
{
|
||||
let breakers = self.circuit_breakers.read().await;
|
||||
if let Some(breaker) = breakers.get(key) {
|
||||
return breaker.clone();
|
||||
}
|
||||
}
|
||||
|
||||
// 如果不存在,获取写锁创建
|
||||
let mut breakers = self.circuit_breakers.write().await;
|
||||
|
||||
// 双重检查,防止竞争条件
|
||||
if let Some(breaker) = breakers.get(key) {
|
||||
return breaker.clone();
|
||||
}
|
||||
|
||||
// 从数据库加载配置
|
||||
let config = self
|
||||
.db
|
||||
.get_circuit_breaker_config()
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
log::debug!("Creating new circuit breaker for {key} with config: {config:?}");
|
||||
|
||||
let breaker = Arc::new(CircuitBreaker::new(config));
|
||||
breakers.insert(key.to_string(), breaker.clone());
|
||||
|
||||
breaker
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::database::Database;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_provider_router_creation() {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,6 @@ impl ProviderRouter {
|
||||
}
|
||||
|
||||
/// 更新Provider健康状态(保留接口但不影响选择)
|
||||
#[allow(dead_code)]
|
||||
pub async fn update_health(
|
||||
&self,
|
||||
_provider: &Provider,
|
||||
|
||||
@@ -20,8 +20,6 @@ pub struct ProxyState {
|
||||
pub config: Arc<RwLock<ProxyConfig>>,
|
||||
pub status: Arc<RwLock<ProxyStatus>>,
|
||||
pub start_time: Arc<RwLock<Option<std::time::Instant>>>,
|
||||
/// 每个应用类型当前使用的 provider (app_type -> (provider_id, provider_name))
|
||||
pub current_providers: Arc<RwLock<std::collections::HashMap<String, (String, String)>>>,
|
||||
}
|
||||
|
||||
/// 代理HTTP服务器
|
||||
@@ -38,7 +36,6 @@ impl ProxyServer {
|
||||
config: Arc::new(RwLock::new(config.clone())),
|
||||
status: Arc::new(RwLock::new(ProxyStatus::default())),
|
||||
start_time: Arc::new(RwLock::new(None)),
|
||||
current_providers: Arc::new(RwLock::new(std::collections::HashMap::new())),
|
||||
};
|
||||
|
||||
Self {
|
||||
@@ -124,16 +121,17 @@ impl ProxyServer {
|
||||
status.uptime_seconds = start.elapsed().as_secs();
|
||||
}
|
||||
|
||||
// 从 current_providers HashMap 获取每个应用类型当前正在使用的 provider
|
||||
let current_providers = self.state.current_providers.read().await;
|
||||
status.active_targets = current_providers
|
||||
.iter()
|
||||
.map(|(app_type, (provider_id, provider_name))| ActiveTarget {
|
||||
app_type: app_type.clone(),
|
||||
provider_id: provider_id.clone(),
|
||||
provider_name: provider_name.clone(),
|
||||
})
|
||||
.collect();
|
||||
// 获取所有活跃的代理目标
|
||||
if let Ok(targets) = self.state.db.get_all_proxy_targets() {
|
||||
status.active_targets = targets
|
||||
.into_iter()
|
||||
.map(|(app_type, name, id)| ActiveTarget {
|
||||
app_type,
|
||||
provider_name: name,
|
||||
provider_id: id,
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
status
|
||||
}
|
||||
@@ -148,24 +146,17 @@ impl ProxyServer {
|
||||
// 健康检查
|
||||
.route("/health", get(handlers::health_check))
|
||||
.route("/status", get(handlers::get_status))
|
||||
// Claude API (支持带前缀和不带前缀两种格式)
|
||||
// Claude API
|
||||
.route("/v1/messages", post(handlers::handle_messages))
|
||||
.route("/claude/v1/messages", post(handlers::handle_messages))
|
||||
// OpenAI Chat Completions API (Codex CLI,支持带前缀和不带前缀)
|
||||
// OpenAI Chat Completions API (Codex CLI)
|
||||
.route(
|
||||
"/v1/chat/completions",
|
||||
post(handlers::handle_chat_completions),
|
||||
)
|
||||
.route(
|
||||
"/codex/v1/chat/completions",
|
||||
post(handlers::handle_chat_completions),
|
||||
)
|
||||
// OpenAI Responses API (Codex CLI,支持带前缀和不带前缀)
|
||||
// OpenAI Responses API (Codex CLI)
|
||||
.route("/v1/responses", post(handlers::handle_responses))
|
||||
.route("/codex/v1/responses", post(handlers::handle_responses))
|
||||
// Gemini API (支持带前缀和不带前缀)
|
||||
// Gemini API
|
||||
.route("/v1beta/*path", post(handlers::handle_gemini))
|
||||
.route("/gemini/v1beta/*path", post(handlers::handle_gemini))
|
||||
.layer(cors)
|
||||
.with_state(self.state.clone())
|
||||
}
|
||||
|
||||
@@ -15,9 +15,6 @@ pub struct ProxyConfig {
|
||||
pub request_timeout: u64,
|
||||
/// 是否启用日志
|
||||
pub enable_logging: bool,
|
||||
/// 是否正在接管 Live 配置
|
||||
#[serde(default)]
|
||||
pub live_takeover_active: bool,
|
||||
}
|
||||
|
||||
impl Default for ProxyConfig {
|
||||
@@ -29,7 +26,6 @@ impl Default for ProxyConfig {
|
||||
max_retries: 3,
|
||||
request_timeout: 300,
|
||||
enable_logging: true,
|
||||
live_takeover_active: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -108,13 +104,16 @@ pub struct ProviderHealth {
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
/// Live 配置备份记录
|
||||
/// 使用统计记录
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct LiveBackup {
|
||||
/// 应用类型 (claude/codex/gemini)
|
||||
pub struct ProxyUsageRecord {
|
||||
pub provider_id: String,
|
||||
pub app_type: String,
|
||||
/// 原始配置 JSON
|
||||
pub original_config: String,
|
||||
/// 备份时间
|
||||
pub backed_up_at: String,
|
||||
pub endpoint: String,
|
||||
pub request_tokens: Option<i32>,
|
||||
pub response_tokens: Option<i32>,
|
||||
pub status_code: u16,
|
||||
pub latency_ms: u64,
|
||||
pub error: Option<String>,
|
||||
pub timestamp: String,
|
||||
}
|
||||
|
||||
@@ -2,16 +2,18 @@ pub mod config;
|
||||
pub mod env_checker;
|
||||
pub mod env_manager;
|
||||
pub mod mcp;
|
||||
pub mod model_test;
|
||||
pub mod prompt;
|
||||
pub mod provider;
|
||||
pub mod proxy;
|
||||
pub mod skill;
|
||||
pub mod speedtest;
|
||||
pub mod stream_check;
|
||||
pub mod usage_stats;
|
||||
|
||||
pub use config::ConfigService;
|
||||
pub use mcp::McpService;
|
||||
#[allow(unused_imports)]
|
||||
pub use model_test::{ModelTestConfig, ModelTestLog, ModelTestResult, ModelTestService};
|
||||
pub use prompt::PromptService;
|
||||
pub use provider::{ProviderService, ProviderSortUpdate};
|
||||
pub use proxy::ProxyService;
|
||||
|
||||
@@ -0,0 +1,510 @@
|
||||
//! 模型测试服务
|
||||
//!
|
||||
//! 提供独立的模型可用性测试功能,复用现有 Provider 适配器逻辑,
|
||||
//! 但不影响正常代理数据流程。测试结果记录到独立的日志表。
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::database::Database;
|
||||
use crate::error::AppError;
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::providers::{get_adapter, AuthInfo, ProviderAdapter};
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// 模型测试配置
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ModelTestConfig {
|
||||
/// 默认测试模型(Claude)
|
||||
pub claude_model: String,
|
||||
/// 默认测试模型(Codex/OpenAI)
|
||||
pub codex_model: String,
|
||||
/// 默认测试模型(Gemini)
|
||||
pub gemini_model: String,
|
||||
/// 测试提示词
|
||||
pub test_prompt: String,
|
||||
/// 超时时间(秒)
|
||||
pub timeout_secs: u64,
|
||||
}
|
||||
|
||||
impl Default for ModelTestConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
claude_model: "claude-haiku-4-5-20251001".to_string(),
|
||||
codex_model: "gpt-5.1-low".to_string(),
|
||||
gemini_model: "gemini-3-pro-low".to_string(),
|
||||
test_prompt: "ping".to_string(),
|
||||
timeout_secs: 15,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 模型测试结果
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ModelTestResult {
|
||||
pub success: bool,
|
||||
pub message: String,
|
||||
pub response_time_ms: Option<u64>,
|
||||
pub http_status: Option<u16>,
|
||||
pub model_used: String,
|
||||
pub tested_at: i64,
|
||||
}
|
||||
|
||||
/// 模型测试日志记录
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ModelTestLog {
|
||||
pub id: i64,
|
||||
pub provider_id: String,
|
||||
pub provider_name: String,
|
||||
pub app_type: String,
|
||||
pub model: String,
|
||||
pub prompt: String,
|
||||
pub success: bool,
|
||||
pub message: String,
|
||||
pub response_time_ms: Option<i64>,
|
||||
pub http_status: Option<i64>,
|
||||
pub tested_at: i64,
|
||||
}
|
||||
|
||||
/// 模型测试服务
|
||||
pub struct ModelTestService;
|
||||
|
||||
impl ModelTestService {
|
||||
/// 测试单个供应商的模型可用性
|
||||
pub async fn test_provider(
|
||||
app_type: &AppType,
|
||||
provider: &Provider,
|
||||
config: &ModelTestConfig,
|
||||
) -> Result<ModelTestResult, AppError> {
|
||||
let start = Instant::now();
|
||||
let adapter = get_adapter(app_type);
|
||||
|
||||
// 构建 HTTP 客户端(独立于代理服务)
|
||||
let client = Client::builder()
|
||||
.timeout(Duration::from_secs(config.timeout_secs))
|
||||
.build()
|
||||
.map_err(|e| AppError::Message(format!("创建 HTTP 客户端失败: {e}")))?;
|
||||
|
||||
// 根据 AppType 选择测试模型
|
||||
let model = match app_type {
|
||||
AppType::Claude => &config.claude_model,
|
||||
AppType::Codex => &config.codex_model,
|
||||
AppType::Gemini => &config.gemini_model,
|
||||
};
|
||||
|
||||
let result = match app_type {
|
||||
AppType::Claude => {
|
||||
Self::test_claude(
|
||||
&client,
|
||||
provider,
|
||||
adapter.as_ref(),
|
||||
model,
|
||||
&config.test_prompt,
|
||||
)
|
||||
.await
|
||||
}
|
||||
AppType::Codex => {
|
||||
Self::test_codex(
|
||||
&client,
|
||||
provider,
|
||||
adapter.as_ref(),
|
||||
model,
|
||||
&config.test_prompt,
|
||||
)
|
||||
.await
|
||||
}
|
||||
AppType::Gemini => {
|
||||
Self::test_gemini(
|
||||
&client,
|
||||
provider,
|
||||
adapter.as_ref(),
|
||||
model,
|
||||
&config.test_prompt,
|
||||
)
|
||||
.await
|
||||
}
|
||||
};
|
||||
|
||||
let response_time = start.elapsed().as_millis() as u64;
|
||||
let tested_at = chrono::Utc::now().timestamp();
|
||||
|
||||
match result {
|
||||
Ok((status, msg)) => Ok(ModelTestResult {
|
||||
success: true,
|
||||
message: msg,
|
||||
response_time_ms: Some(response_time),
|
||||
http_status: Some(status),
|
||||
model_used: model.clone(),
|
||||
tested_at,
|
||||
}),
|
||||
Err(e) => Ok(ModelTestResult {
|
||||
success: false,
|
||||
message: e.to_string(),
|
||||
response_time_ms: Some(response_time),
|
||||
http_status: None,
|
||||
model_used: model.clone(),
|
||||
tested_at,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// 测试 Claude (Anthropic Messages API)
|
||||
async fn test_claude(
|
||||
client: &Client,
|
||||
provider: &Provider,
|
||||
adapter: &dyn ProviderAdapter,
|
||||
model: &str,
|
||||
prompt: &str,
|
||||
) -> Result<(u16, String), AppError> {
|
||||
let base_url = adapter
|
||||
.extract_base_url(provider)
|
||||
.map_err(|e| AppError::Message(format!("提取 base_url 失败: {e}")))?;
|
||||
|
||||
let auth = adapter
|
||||
.extract_auth(provider)
|
||||
.ok_or_else(|| AppError::Message("未找到 API Key".to_string()))?;
|
||||
|
||||
// 智能拼接 URL,避免重复 /v1
|
||||
let base = base_url.trim_end_matches('/');
|
||||
let url = if base.ends_with("/v1") {
|
||||
format!("{base}/messages")
|
||||
} else {
|
||||
format!("{base}/v1/messages")
|
||||
};
|
||||
|
||||
let body = json!({
|
||||
"model": model,
|
||||
"max_tokens": 1,
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": prompt
|
||||
}]
|
||||
});
|
||||
|
||||
let mut request = client.post(&url).json(&body);
|
||||
request = Self::add_claude_auth(request, &auth);
|
||||
|
||||
let response = request.send().await.map_err(|e| {
|
||||
if e.is_timeout() {
|
||||
AppError::Message("请求超时".to_string())
|
||||
} else if e.is_connect() {
|
||||
AppError::Message(format!("连接失败: {e}"))
|
||||
} else {
|
||||
AppError::Message(e.to_string())
|
||||
}
|
||||
})?;
|
||||
|
||||
let status = response.status().as_u16();
|
||||
|
||||
if response.status().is_success() {
|
||||
// 先获取文本,再尝试解析 JSON(兼容流式响应)
|
||||
let text = response.text().await.unwrap_or_default();
|
||||
|
||||
// 尝试解析 JSON
|
||||
if let Ok(data) = serde_json::from_str::<Value>(&text) {
|
||||
if data.get("type").is_some()
|
||||
|| data.get("content").is_some()
|
||||
|| data.get("id").is_some()
|
||||
{
|
||||
return Ok((status, "模型测试成功".to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
// 即使无法解析 JSON,只要状态码是 200 就认为成功
|
||||
Ok((status, "模型测试成功".to_string()))
|
||||
} else {
|
||||
let error_text = response.text().await.unwrap_or_default();
|
||||
Err(AppError::Message(format!("HTTP {status}: {error_text}")))
|
||||
}
|
||||
}
|
||||
|
||||
/// 测试 Codex (OpenAI Chat Completions API)
|
||||
async fn test_codex(
|
||||
client: &Client,
|
||||
provider: &Provider,
|
||||
adapter: &dyn ProviderAdapter,
|
||||
model: &str,
|
||||
prompt: &str,
|
||||
) -> Result<(u16, String), AppError> {
|
||||
let base_url = adapter
|
||||
.extract_base_url(provider)
|
||||
.map_err(|e| AppError::Message(format!("提取 base_url 失败: {e}")))?;
|
||||
|
||||
let auth = adapter
|
||||
.extract_auth(provider)
|
||||
.ok_or_else(|| AppError::Message("未找到 API Key".to_string()))?;
|
||||
|
||||
// 智能拼接 URL,避免重复 /v1
|
||||
let base = base_url.trim_end_matches('/');
|
||||
let url = if base.ends_with("/v1") {
|
||||
format!("{base}/chat/completions")
|
||||
} else {
|
||||
format!("{base}/v1/chat/completions")
|
||||
};
|
||||
|
||||
let body = json!({
|
||||
"model": model,
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": prompt
|
||||
}],
|
||||
"max_tokens": 1,
|
||||
"stream": false
|
||||
});
|
||||
|
||||
let request = client
|
||||
.post(&url)
|
||||
.header("Authorization", format!("Bearer {}", auth.api_key))
|
||||
.header("Content-Type", "application/json")
|
||||
.json(&body);
|
||||
|
||||
let response = request.send().await.map_err(|e| {
|
||||
if e.is_timeout() {
|
||||
AppError::Message("请求超时".to_string())
|
||||
} else if e.is_connect() {
|
||||
AppError::Message(format!("连接失败: {e}"))
|
||||
} else {
|
||||
AppError::Message(e.to_string())
|
||||
}
|
||||
})?;
|
||||
|
||||
let status = response.status().as_u16();
|
||||
|
||||
if response.status().is_success() {
|
||||
// 先获取文本,再尝试解析 JSON
|
||||
let text = response.text().await.unwrap_or_default();
|
||||
|
||||
if let Ok(data) = serde_json::from_str::<Value>(&text) {
|
||||
if data.get("choices").is_some() || data.get("id").is_some() {
|
||||
return Ok((status, "模型测试成功".to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
// 即使无法解析 JSON,只要状态码是 200 就认为成功
|
||||
Ok((status, "模型测试成功".to_string()))
|
||||
} else {
|
||||
let error_text = response.text().await.unwrap_or_default();
|
||||
Err(AppError::Message(format!("HTTP {status}: {error_text}")))
|
||||
}
|
||||
}
|
||||
|
||||
/// 测试 Gemini (Google Generative AI API)
|
||||
async fn test_gemini(
|
||||
client: &Client,
|
||||
provider: &Provider,
|
||||
adapter: &dyn ProviderAdapter,
|
||||
model: &str,
|
||||
prompt: &str,
|
||||
) -> Result<(u16, String), AppError> {
|
||||
let base_url = adapter
|
||||
.extract_base_url(provider)
|
||||
.map_err(|e| AppError::Message(format!("提取 base_url 失败: {e}")))?;
|
||||
|
||||
let auth = adapter
|
||||
.extract_auth(provider)
|
||||
.ok_or_else(|| AppError::Message("未找到 API Key".to_string()))?;
|
||||
|
||||
let url = format!(
|
||||
"{}/v1beta/models/{}:generateContent?key={}",
|
||||
base_url.trim_end_matches('/'),
|
||||
model,
|
||||
auth.api_key
|
||||
);
|
||||
|
||||
let body = json!({
|
||||
"contents": [{
|
||||
"parts": [{
|
||||
"text": prompt
|
||||
}]
|
||||
}],
|
||||
"generationConfig": {
|
||||
"maxOutputTokens": 1
|
||||
}
|
||||
});
|
||||
|
||||
let request = client
|
||||
.post(&url)
|
||||
.header("Content-Type", "application/json")
|
||||
.json(&body);
|
||||
|
||||
let response = request.send().await.map_err(|e| {
|
||||
if e.is_timeout() {
|
||||
AppError::Message("请求超时".to_string())
|
||||
} else if e.is_connect() {
|
||||
AppError::Message(format!("连接失败: {e}"))
|
||||
} else {
|
||||
AppError::Message(e.to_string())
|
||||
}
|
||||
})?;
|
||||
|
||||
let status = response.status().as_u16();
|
||||
|
||||
if response.status().is_success() {
|
||||
let data: Value = response
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| AppError::Message(format!("解析响应失败: {e}")))?;
|
||||
|
||||
if data.get("candidates").is_some() {
|
||||
Ok((status, "模型测试成功".to_string()))
|
||||
} else {
|
||||
Err(AppError::Message("响应格式异常".to_string()))
|
||||
}
|
||||
} else {
|
||||
let error_text = response.text().await.unwrap_or_default();
|
||||
Err(AppError::Message(format!("HTTP {status}: {error_text}")))
|
||||
}
|
||||
}
|
||||
|
||||
/// 添加 Claude 认证头
|
||||
fn add_claude_auth(
|
||||
request: reqwest::RequestBuilder,
|
||||
auth: &AuthInfo,
|
||||
) -> reqwest::RequestBuilder {
|
||||
request
|
||||
.header("x-api-key", &auth.api_key)
|
||||
.header("anthropic-version", "2023-06-01")
|
||||
.header("Content-Type", "application/json")
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 数据库操作 =====
|
||||
|
||||
impl Database {
|
||||
/// 保存模型测试日志
|
||||
pub fn save_model_test_log(
|
||||
&self,
|
||||
provider_id: &str,
|
||||
provider_name: &str,
|
||||
app_type: &str,
|
||||
model: &str,
|
||||
prompt: &str,
|
||||
result: &ModelTestResult,
|
||||
) -> Result<i64, AppError> {
|
||||
let conn = self
|
||||
.conn
|
||||
.lock()
|
||||
.map_err(|e| AppError::Database(format!("获取数据库连接失败: {e}")))?;
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO model_test_logs
|
||||
(provider_id, provider_name, app_type, model, prompt, success, message, response_time_ms, http_status, tested_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
rusqlite::params![
|
||||
provider_id,
|
||||
provider_name,
|
||||
app_type,
|
||||
model,
|
||||
prompt,
|
||||
result.success,
|
||||
result.message,
|
||||
result.response_time_ms.map(|t| t as i64),
|
||||
result.http_status.map(|s| s as i64),
|
||||
result.tested_at,
|
||||
],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
Ok(conn.last_insert_rowid())
|
||||
}
|
||||
|
||||
/// 获取模型测试日志
|
||||
pub fn get_model_test_logs(
|
||||
&self,
|
||||
app_type: Option<&str>,
|
||||
provider_id: Option<&str>,
|
||||
limit: u32,
|
||||
) -> Result<Vec<ModelTestLog>, AppError> {
|
||||
let conn = self
|
||||
.conn
|
||||
.lock()
|
||||
.map_err(|e| AppError::Database(format!("获取数据库连接失败: {e}")))?;
|
||||
|
||||
let mut sql = String::from(
|
||||
"SELECT id, provider_id, provider_name, app_type, model, prompt, success, message, response_time_ms, http_status, tested_at
|
||||
FROM model_test_logs WHERE 1=1"
|
||||
);
|
||||
|
||||
let mut params: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
|
||||
|
||||
if let Some(at) = app_type {
|
||||
sql.push_str(" AND app_type = ?");
|
||||
params.push(Box::new(at.to_string()));
|
||||
}
|
||||
|
||||
if let Some(pid) = provider_id {
|
||||
sql.push_str(" AND provider_id = ?");
|
||||
params.push(Box::new(pid.to_string()));
|
||||
}
|
||||
|
||||
sql.push_str(" ORDER BY tested_at DESC LIMIT ?");
|
||||
params.push(Box::new(limit as i64));
|
||||
|
||||
let params_refs: Vec<&dyn rusqlite::ToSql> = params.iter().map(|p| p.as_ref()).collect();
|
||||
|
||||
let mut stmt = conn
|
||||
.prepare(&sql)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
let logs = stmt
|
||||
.query_map(params_refs.as_slice(), |row| {
|
||||
Ok(ModelTestLog {
|
||||
id: row.get(0)?,
|
||||
provider_id: row.get(1)?,
|
||||
provider_name: row.get(2)?,
|
||||
app_type: row.get(3)?,
|
||||
model: row.get(4)?,
|
||||
prompt: row.get(5)?,
|
||||
success: row.get(6)?,
|
||||
message: row.get(7)?,
|
||||
response_time_ms: row.get(8)?,
|
||||
http_status: row.get(9)?,
|
||||
tested_at: row.get(10)?,
|
||||
})
|
||||
})
|
||||
.map_err(|e| AppError::Database(e.to_string()))?
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
Ok(logs)
|
||||
}
|
||||
|
||||
/// 获取模型测试配置
|
||||
pub fn get_model_test_config(&self) -> Result<ModelTestConfig, AppError> {
|
||||
match self.get_setting("model_test_config")? {
|
||||
Some(json) => serde_json::from_str(&json)
|
||||
.map_err(|e| AppError::Message(format!("解析模型测试配置失败: {e}"))),
|
||||
None => Ok(ModelTestConfig::default()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 保存模型测试配置
|
||||
pub fn save_model_test_config(&self, config: &ModelTestConfig) -> Result<(), AppError> {
|
||||
let json = serde_json::to_string(config)
|
||||
.map_err(|e| AppError::Message(format!("序列化模型测试配置失败: {e}")))?;
|
||||
self.set_setting("model_test_config", &json)
|
||||
}
|
||||
|
||||
/// 清理旧的测试日志(保留最近 N 条)
|
||||
pub fn cleanup_model_test_logs(&self, keep_count: u32) -> Result<u64, AppError> {
|
||||
let conn = self
|
||||
.conn
|
||||
.lock()
|
||||
.map_err(|e| AppError::Database(format!("获取数据库连接失败: {e}")))?;
|
||||
|
||||
let deleted = conn
|
||||
.execute(
|
||||
"DELETE FROM model_test_logs WHERE id NOT IN (
|
||||
SELECT id FROM model_test_logs ORDER BY tested_at DESC LIMIT ?
|
||||
)",
|
||||
rusqlite::params![keep_count as i64],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
Ok(deleted as u64)
|
||||
}
|
||||
}
|
||||
@@ -173,71 +173,14 @@ impl ProviderService {
|
||||
///
|
||||
/// Switch flow:
|
||||
/// 1. Validate target provider exists
|
||||
/// 2. Check if proxy takeover mode is active AND proxy server is running
|
||||
/// 3. If takeover mode active: hot-switch proxy target only (no Live config write)
|
||||
/// 4. If normal mode:
|
||||
/// a. **Backfill mechanism**: Backfill current live config to current provider
|
||||
/// b. Update local settings current_provider_xxx (device-level)
|
||||
/// c. Update database is_current (as default for new devices)
|
||||
/// d. Write target provider config to live files
|
||||
/// e. Sync MCP configuration
|
||||
/// 2. **Backfill mechanism**: Backfill current live config to current provider, protect user manual modifications
|
||||
/// 3. Update local settings current_provider_xxx (device-level)
|
||||
/// 4. Update database is_current (as default for new devices)
|
||||
/// 5. Write target provider config to live files
|
||||
/// 6. Sync MCP configuration
|
||||
pub fn switch(state: &AppState, app_type: AppType, id: &str) -> Result<(), AppError> {
|
||||
// Check if provider exists
|
||||
let providers = state.db.get_all_providers(app_type.as_str())?;
|
||||
let _provider = providers
|
||||
.get(id)
|
||||
.ok_or_else(|| AppError::Message(format!("供应商 {id} 不存在")))?;
|
||||
|
||||
// Check if proxy takeover mode is active AND proxy server is actually running
|
||||
// Both conditions must be true to use hot-switch mode
|
||||
// Use blocking wait since this is a sync function
|
||||
let is_takeover_flag =
|
||||
futures::executor::block_on(state.db.is_live_takeover_active()).unwrap_or(false);
|
||||
let is_proxy_running = futures::executor::block_on(state.proxy_service.is_running());
|
||||
|
||||
// Hot-switch only when BOTH: takeover flag is set AND proxy server is actually running
|
||||
let should_hot_switch = is_takeover_flag && is_proxy_running;
|
||||
|
||||
if should_hot_switch {
|
||||
// Proxy takeover mode: hot-switch only, don't write Live config
|
||||
log::info!(
|
||||
"代理接管模式:热切换 {} 的目标供应商为 {}",
|
||||
app_type.as_str(),
|
||||
id
|
||||
);
|
||||
|
||||
// Update database is_current
|
||||
state.db.set_current_provider(app_type.as_str(), id)?;
|
||||
|
||||
// 同时更新 is_proxy_target(代理路由器使用此字段选择供应商)
|
||||
state.db.set_proxy_target_provider(app_type.as_str(), id)?;
|
||||
|
||||
// Update local settings for consistency
|
||||
crate::settings::set_current_provider(&app_type, Some(id))?;
|
||||
|
||||
// Note: No Live config write, no MCP sync
|
||||
// The proxy server will route requests to the new provider via is_proxy_target
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Normal mode: full switch with Live config write
|
||||
// Also clear stale takeover flag if proxy is not running but flag was set
|
||||
if is_takeover_flag && !is_proxy_running {
|
||||
log::warn!("检测到代理接管标志残留(代理已停止),清除标志并执行正常切换");
|
||||
// Clear stale takeover flag
|
||||
let _ = futures::executor::block_on(state.db.set_live_takeover_active(false));
|
||||
}
|
||||
|
||||
Self::switch_normal(state, app_type, id, &providers)
|
||||
}
|
||||
|
||||
/// Normal switch flow (non-proxy mode)
|
||||
fn switch_normal(
|
||||
state: &AppState,
|
||||
app_type: AppType,
|
||||
id: &str,
|
||||
providers: &indexmap::IndexMap<String, Provider>,
|
||||
) -> Result<(), AppError> {
|
||||
let provider = providers
|
||||
.get(id)
|
||||
.ok_or_else(|| AppError::Message(format!("供应商 {id} 不存在")))?;
|
||||
|
||||
@@ -2,13 +2,9 @@
|
||||
//!
|
||||
//! 提供代理服务器的启动、停止和配置管理
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::config::{get_claude_settings_path, read_json_file, write_json_file};
|
||||
use crate::database::Database;
|
||||
use crate::proxy::server::ProxyServer;
|
||||
use crate::proxy::types::*;
|
||||
use serde_json::{json, Value};
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
@@ -63,196 +59,6 @@ impl ProxyService {
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
/// 启动代理服务器(带 Live 配置接管)
|
||||
pub async fn start_with_takeover(&self) -> Result<ProxyServerInfo, String> {
|
||||
// 1. 自动将各应用当前选中的供应商设置为代理目标
|
||||
self.setup_proxy_targets().await?;
|
||||
|
||||
// 2. 备份各应用的 Live 配置
|
||||
self.backup_live_configs().await?;
|
||||
|
||||
// 3. 同步 Live 配置中的 Token 到数据库(确保代理能读到最新的 Token)
|
||||
self.sync_live_to_providers().await?;
|
||||
|
||||
// 4. 接管各应用的 Live 配置(写入代理地址,清空 Token)
|
||||
self.takeover_live_configs().await?;
|
||||
|
||||
// 5. 设置接管状态
|
||||
self.db
|
||||
.set_live_takeover_active(true)
|
||||
.await
|
||||
.map_err(|e| format!("设置接管状态失败: {e}"))?;
|
||||
|
||||
// 6. 启动代理服务器
|
||||
match self.start().await {
|
||||
Ok(info) => Ok(info),
|
||||
Err(e) => {
|
||||
// 启动失败,恢复原始配置
|
||||
log::error!("代理启动失败,尝试恢复原始配置: {e}");
|
||||
let _ = self.restore_live_configs().await;
|
||||
let _ = self.db.set_live_takeover_active(false).await;
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 自动设置代理目标:将各应用当前选中的供应商设置为代理目标
|
||||
async fn setup_proxy_targets(&self) -> Result<(), String> {
|
||||
let app_types = ["claude", "codex", "gemini"];
|
||||
|
||||
for app_type in app_types {
|
||||
// 获取当前选中的供应商
|
||||
if let Ok(Some(provider_id)) = self.db.get_current_provider(app_type) {
|
||||
// 设置为代理目标
|
||||
if let Err(e) = self.db.set_proxy_target(&provider_id, app_type, true).await {
|
||||
log::warn!("设置 {} 的代理目标 {} 失败: {}", app_type, provider_id, e);
|
||||
} else {
|
||||
log::info!(
|
||||
"已将 {} 的当前供应商 {} 设置为代理目标",
|
||||
app_type,
|
||||
provider_id
|
||||
);
|
||||
}
|
||||
} else {
|
||||
log::debug!("{} 没有当前供应商,跳过代理目标设置", app_type);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 同步 Live 配置中的 Token 到数据库
|
||||
///
|
||||
/// 在清空 Live Token 之前调用,确保数据库中的 Provider 配置有最新的 Token。
|
||||
/// 这样代理才能从数据库读取到正确的认证信息。
|
||||
async fn sync_live_to_providers(&self) -> Result<(), String> {
|
||||
// Claude: 同步 ANTHROPIC_AUTH_TOKEN
|
||||
if let Ok(live_config) = self.read_claude_live() {
|
||||
if let Some(provider_id) = self.db.get_current_provider("claude").ok().flatten() {
|
||||
if let Ok(Some(mut provider)) = self.db.get_provider_by_id(&provider_id, "claude") {
|
||||
// 从 live 配置提取 token
|
||||
if let Some(env) = live_config.get("env") {
|
||||
if let Some(token) =
|
||||
env.get("ANTHROPIC_AUTH_TOKEN").and_then(|v| v.as_str())
|
||||
{
|
||||
if !token.is_empty() {
|
||||
// 更新 provider 的 settings_config
|
||||
if let Some(env_obj) = provider
|
||||
.settings_config
|
||||
.get_mut("env")
|
||||
.and_then(|v| v.as_object_mut())
|
||||
{
|
||||
env_obj
|
||||
.insert("ANTHROPIC_AUTH_TOKEN".to_string(), json!(token));
|
||||
} else {
|
||||
provider.settings_config["env"] = json!({
|
||||
"ANTHROPIC_AUTH_TOKEN": token
|
||||
});
|
||||
}
|
||||
// 保存到数据库
|
||||
if let Err(e) = self.db.update_provider_settings_config(
|
||||
"claude",
|
||||
&provider_id,
|
||||
&provider.settings_config,
|
||||
) {
|
||||
log::warn!("同步 Claude Token 到数据库失败: {e}");
|
||||
} else {
|
||||
log::info!(
|
||||
"已同步 Claude Token 到数据库 (provider: {})",
|
||||
provider_id
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Codex: 同步 OPENAI_API_KEY
|
||||
if let Ok(live_config) = self.read_codex_live() {
|
||||
if let Some(provider_id) = self.db.get_current_provider("codex").ok().flatten() {
|
||||
if let Ok(Some(mut provider)) = self.db.get_provider_by_id(&provider_id, "codex") {
|
||||
// 从 live 配置提取 token
|
||||
if let Some(auth) = live_config.get("auth") {
|
||||
if let Some(token) = auth.get("OPENAI_API_KEY").and_then(|v| v.as_str()) {
|
||||
if !token.is_empty() {
|
||||
// 更新 provider 的 settings_config
|
||||
if let Some(auth_obj) = provider
|
||||
.settings_config
|
||||
.get_mut("auth")
|
||||
.and_then(|v| v.as_object_mut())
|
||||
{
|
||||
auth_obj.insert("OPENAI_API_KEY".to_string(), json!(token));
|
||||
} else {
|
||||
provider.settings_config["auth"] = json!({
|
||||
"OPENAI_API_KEY": token
|
||||
});
|
||||
}
|
||||
// 保存到数据库
|
||||
if let Err(e) = self.db.update_provider_settings_config(
|
||||
"codex",
|
||||
&provider_id,
|
||||
&provider.settings_config,
|
||||
) {
|
||||
log::warn!("同步 Codex Token 到数据库失败: {e}");
|
||||
} else {
|
||||
log::info!(
|
||||
"已同步 Codex Token 到数据库 (provider: {})",
|
||||
provider_id
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Gemini: 同步 GOOGLE_API_KEY
|
||||
if let Ok(live_config) = self.read_gemini_live() {
|
||||
if let Some(provider_id) = self.db.get_current_provider("gemini").ok().flatten() {
|
||||
if let Ok(Some(mut provider)) = self.db.get_provider_by_id(&provider_id, "gemini") {
|
||||
// 从 live 配置提取 token
|
||||
if let Some(env) = live_config.get("env") {
|
||||
if let Some(token) = env.get("GOOGLE_API_KEY").and_then(|v| v.as_str()) {
|
||||
if !token.is_empty() {
|
||||
// 更新 provider 的 settings_config
|
||||
if let Some(env_obj) = provider
|
||||
.settings_config
|
||||
.get_mut("env")
|
||||
.and_then(|v| v.as_object_mut())
|
||||
{
|
||||
env_obj.insert("GOOGLE_API_KEY".to_string(), json!(token));
|
||||
} else {
|
||||
provider.settings_config["env"] = json!({
|
||||
"GOOGLE_API_KEY": token
|
||||
});
|
||||
}
|
||||
// 保存到数据库
|
||||
if let Err(e) = self.db.update_provider_settings_config(
|
||||
"gemini",
|
||||
&provider_id,
|
||||
&provider.settings_config,
|
||||
) {
|
||||
log::warn!("同步 Gemini Token 到数据库失败: {e}");
|
||||
} else {
|
||||
log::info!(
|
||||
"已同步 Gemini Token 到数据库 (provider: {})",
|
||||
provider_id
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log::info!("Live 配置 Token 同步完成");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 停止代理服务器
|
||||
pub async fn stop(&self) -> Result<(), String> {
|
||||
if let Some(server) = self.server.write().await.take() {
|
||||
@@ -260,13 +66,6 @@ impl ProxyService {
|
||||
.stop()
|
||||
.await
|
||||
.map_err(|e| format!("停止代理服务器失败: {e}"))?;
|
||||
|
||||
// 将 enabled 设为 false,避免下次启动时自动开启
|
||||
if let Ok(mut config) = self.db.get_proxy_config().await {
|
||||
config.enabled = false;
|
||||
let _ = self.db.update_proxy_config(config).await;
|
||||
}
|
||||
|
||||
log::info!("代理服务器已停止");
|
||||
Ok(())
|
||||
} else {
|
||||
@@ -274,267 +73,6 @@ impl ProxyService {
|
||||
}
|
||||
}
|
||||
|
||||
/// 停止代理服务器(恢复 Live 配置)
|
||||
pub async fn stop_with_restore(&self) -> Result<(), String> {
|
||||
// 1. 停止代理服务器
|
||||
self.stop().await?;
|
||||
|
||||
// 2. 恢复原始 Live 配置
|
||||
self.restore_live_configs().await?;
|
||||
|
||||
// 3. 清除接管状态
|
||||
self.db
|
||||
.set_live_takeover_active(false)
|
||||
.await
|
||||
.map_err(|e| format!("清除接管状态失败: {e}"))?;
|
||||
|
||||
// 4. 删除备份
|
||||
self.db
|
||||
.delete_all_live_backups()
|
||||
.await
|
||||
.map_err(|e| format!("删除备份失败: {e}"))?;
|
||||
|
||||
log::info!("代理已停止,Live 配置已恢复");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 备份各应用的 Live 配置
|
||||
async fn backup_live_configs(&self) -> Result<(), String> {
|
||||
// Claude
|
||||
if let Ok(config) = self.read_claude_live() {
|
||||
let json_str = serde_json::to_string(&config)
|
||||
.map_err(|e| format!("序列化 Claude 配置失败: {e}"))?;
|
||||
self.db
|
||||
.save_live_backup("claude", &json_str)
|
||||
.await
|
||||
.map_err(|e| format!("备份 Claude 配置失败: {e}"))?;
|
||||
}
|
||||
|
||||
// Codex
|
||||
if let Ok(config) = self.read_codex_live() {
|
||||
let json_str = serde_json::to_string(&config)
|
||||
.map_err(|e| format!("序列化 Codex 配置失败: {e}"))?;
|
||||
self.db
|
||||
.save_live_backup("codex", &json_str)
|
||||
.await
|
||||
.map_err(|e| format!("备份 Codex 配置失败: {e}"))?;
|
||||
}
|
||||
|
||||
// Gemini
|
||||
if let Ok(config) = self.read_gemini_live() {
|
||||
let json_str = serde_json::to_string(&config)
|
||||
.map_err(|e| format!("序列化 Gemini 配置失败: {e}"))?;
|
||||
self.db
|
||||
.save_live_backup("gemini", &json_str)
|
||||
.await
|
||||
.map_err(|e| format!("备份 Gemini 配置失败: {e}"))?;
|
||||
}
|
||||
|
||||
log::info!("已备份所有应用的 Live 配置");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 接管各应用的 Live 配置(写入代理地址)
|
||||
///
|
||||
/// 代理服务器的路由已经根据 API 端点自动区分应用类型:
|
||||
/// - `/v1/messages` → Claude
|
||||
/// - `/v1/chat/completions`, `/v1/responses` → Codex
|
||||
/// - `/v1beta/*` → Gemini
|
||||
///
|
||||
/// 因此不需要在 URL 中添加应用前缀。
|
||||
async fn takeover_live_configs(&self) -> Result<(), String> {
|
||||
let config = self
|
||||
.db
|
||||
.get_proxy_config()
|
||||
.await
|
||||
.map_err(|e| format!("获取代理配置失败: {e}"))?;
|
||||
|
||||
let proxy_url = format!("http://{}:{}", config.listen_address, config.listen_port);
|
||||
|
||||
// Claude: 修改 ANTHROPIC_BASE_URL,使用占位符替代真实 Token(代理会注入真实 Token)
|
||||
if let Ok(mut live_config) = self.read_claude_live() {
|
||||
if let Some(env) = live_config.get_mut("env").and_then(|v| v.as_object_mut()) {
|
||||
env.insert("ANTHROPIC_BASE_URL".to_string(), json!(&proxy_url));
|
||||
// 使用占位符,避免 Claude Code 显示缺少 key 的警告
|
||||
env.insert("ANTHROPIC_AUTH_TOKEN".to_string(), json!("PROXY_MANAGED"));
|
||||
} else {
|
||||
live_config["env"] = json!({
|
||||
"ANTHROPIC_BASE_URL": &proxy_url,
|
||||
"ANTHROPIC_AUTH_TOKEN": "PROXY_MANAGED"
|
||||
});
|
||||
}
|
||||
self.write_claude_live(&live_config)?;
|
||||
log::info!("Claude Live 配置已接管,代理地址: {}", proxy_url);
|
||||
}
|
||||
|
||||
// Codex: 修改 OPENAI_BASE_URL,使用占位符替代真实 Token(代理会注入真实 Token)
|
||||
if let Ok(mut live_config) = self.read_codex_live() {
|
||||
if let Some(auth) = live_config.get_mut("auth").and_then(|v| v.as_object_mut()) {
|
||||
auth.insert("OPENAI_BASE_URL".to_string(), json!(&proxy_url));
|
||||
// 使用占位符,避免显示缺少 key 的警告
|
||||
auth.insert("OPENAI_API_KEY".to_string(), json!("PROXY_MANAGED"));
|
||||
}
|
||||
self.write_codex_live(&live_config)?;
|
||||
log::info!("Codex Live 配置已接管,代理地址: {}", proxy_url);
|
||||
}
|
||||
|
||||
// Gemini: 修改 GEMINI_API_BASE,使用占位符替代真实 Token(代理会注入真实 Token)
|
||||
if let Ok(mut live_config) = self.read_gemini_live() {
|
||||
if let Some(env) = live_config.get_mut("env").and_then(|v| v.as_object_mut()) {
|
||||
env.insert("GEMINI_API_BASE".to_string(), json!(&proxy_url));
|
||||
// 使用占位符,避免显示缺少 key 的警告
|
||||
env.insert("GOOGLE_API_KEY".to_string(), json!("PROXY_MANAGED"));
|
||||
} else {
|
||||
live_config["env"] = json!({
|
||||
"GEMINI_API_BASE": &proxy_url,
|
||||
"GOOGLE_API_KEY": "PROXY_MANAGED"
|
||||
});
|
||||
}
|
||||
self.write_gemini_live(&live_config)?;
|
||||
log::info!("Gemini Live 配置已接管,代理地址: {}", proxy_url);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 恢复原始 Live 配置
|
||||
async fn restore_live_configs(&self) -> Result<(), String> {
|
||||
// Claude
|
||||
if let Ok(Some(backup)) = self.db.get_live_backup("claude").await {
|
||||
let config: Value = serde_json::from_str(&backup.original_config)
|
||||
.map_err(|e| format!("解析 Claude 备份失败: {e}"))?;
|
||||
self.write_claude_live(&config)?;
|
||||
log::info!("Claude Live 配置已恢复");
|
||||
}
|
||||
|
||||
// Codex
|
||||
if let Ok(Some(backup)) = self.db.get_live_backup("codex").await {
|
||||
let config: Value = serde_json::from_str(&backup.original_config)
|
||||
.map_err(|e| format!("解析 Codex 备份失败: {e}"))?;
|
||||
self.write_codex_live(&config)?;
|
||||
log::info!("Codex Live 配置已恢复");
|
||||
}
|
||||
|
||||
// Gemini
|
||||
if let Ok(Some(backup)) = self.db.get_live_backup("gemini").await {
|
||||
let config: Value = serde_json::from_str(&backup.original_config)
|
||||
.map_err(|e| format!("解析 Gemini 备份失败: {e}"))?;
|
||||
self.write_gemini_live(&config)?;
|
||||
log::info!("Gemini Live 配置已恢复");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 检查是否处于 Live 接管模式
|
||||
pub async fn is_takeover_active(&self) -> Result<bool, String> {
|
||||
self.db
|
||||
.is_live_takeover_active()
|
||||
.await
|
||||
.map_err(|e| format!("检查接管状态失败: {e}"))
|
||||
}
|
||||
|
||||
/// 代理模式下切换供应商(热切换,不写 Live)
|
||||
pub async fn switch_proxy_target(
|
||||
&self,
|
||||
app_type: &str,
|
||||
provider_id: &str,
|
||||
) -> Result<(), String> {
|
||||
// 更新数据库中的 is_current 标记
|
||||
let app_type_enum =
|
||||
AppType::from_str(app_type).map_err(|_| format!("无效的应用类型: {app_type}"))?;
|
||||
|
||||
self.db
|
||||
.set_current_provider(app_type_enum.as_str(), provider_id)
|
||||
.map_err(|e| format!("更新当前供应商失败: {e}"))?;
|
||||
|
||||
log::info!(
|
||||
"代理模式:已切换 {} 的目标供应商为 {}",
|
||||
app_type,
|
||||
provider_id
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ==================== Live 配置读写辅助方法 ====================
|
||||
|
||||
fn read_claude_live(&self) -> Result<Value, String> {
|
||||
let path = get_claude_settings_path();
|
||||
if !path.exists() {
|
||||
return Err("Claude 配置文件不存在".to_string());
|
||||
}
|
||||
read_json_file(&path).map_err(|e| format!("读取 Claude 配置失败: {e}"))
|
||||
}
|
||||
|
||||
fn write_claude_live(&self, config: &Value) -> Result<(), String> {
|
||||
let path = get_claude_settings_path();
|
||||
write_json_file(&path, config).map_err(|e| format!("写入 Claude 配置失败: {e}"))
|
||||
}
|
||||
|
||||
fn read_codex_live(&self) -> Result<Value, String> {
|
||||
use crate::codex_config::{get_codex_auth_path, get_codex_config_path};
|
||||
|
||||
let auth_path = get_codex_auth_path();
|
||||
if !auth_path.exists() {
|
||||
return Err("Codex auth.json 不存在".to_string());
|
||||
}
|
||||
|
||||
let auth: Value =
|
||||
read_json_file(&auth_path).map_err(|e| format!("读取 Codex auth 失败: {e}"))?;
|
||||
|
||||
let config_path = get_codex_config_path();
|
||||
let config_str = if config_path.exists() {
|
||||
std::fs::read_to_string(&config_path)
|
||||
.map_err(|e| format!("读取 Codex config 失败: {e}"))?
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
Ok(json!({
|
||||
"auth": auth,
|
||||
"config": config_str
|
||||
}))
|
||||
}
|
||||
|
||||
fn write_codex_live(&self, config: &Value) -> Result<(), String> {
|
||||
use crate::codex_config::{get_codex_auth_path, get_codex_config_path};
|
||||
|
||||
if let Some(auth) = config.get("auth") {
|
||||
let auth_path = get_codex_auth_path();
|
||||
write_json_file(&auth_path, auth).map_err(|e| format!("写入 Codex auth 失败: {e}"))?;
|
||||
}
|
||||
|
||||
if let Some(config_str) = config.get("config").and_then(|v| v.as_str()) {
|
||||
let config_path = get_codex_config_path();
|
||||
std::fs::write(&config_path, config_str)
|
||||
.map_err(|e| format!("写入 Codex config 失败: {e}"))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_gemini_live(&self) -> Result<Value, String> {
|
||||
use crate::gemini_config::{env_to_json, get_gemini_env_path, read_gemini_env};
|
||||
|
||||
let env_path = get_gemini_env_path();
|
||||
if !env_path.exists() {
|
||||
return Err("Gemini .env 文件不存在".to_string());
|
||||
}
|
||||
|
||||
let env_map = read_gemini_env().map_err(|e| format!("读取 Gemini env 失败: {e}"))?;
|
||||
Ok(env_to_json(&env_map))
|
||||
}
|
||||
|
||||
fn write_gemini_live(&self, config: &Value) -> Result<(), String> {
|
||||
use crate::gemini_config::{json_to_env, write_gemini_env_atomic};
|
||||
|
||||
let env_map = json_to_env(config).map_err(|e| format!("转换 Gemini 配置失败: {e}"))?;
|
||||
write_gemini_env_atomic(&env_map).map_err(|e| format!("写入 Gemini env 失败: {e}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ==================== 原有方法 ====================
|
||||
|
||||
/// 获取服务器状态
|
||||
pub async fn get_status(&self) -> Result<ProxyStatus, String> {
|
||||
if let Some(server) = self.server.read().await.as_ref() {
|
||||
@@ -565,10 +103,9 @@ impl ProxyService {
|
||||
.await
|
||||
.map_err(|e| format!("获取代理配置失败: {e}"))?;
|
||||
|
||||
// 保存到数据库(保持 enabled 和 live_takeover_active 状态不变)
|
||||
// 保存到数据库(保持 enabled 状态不变)
|
||||
let mut new_config = config.clone();
|
||||
new_config.enabled = previous.enabled;
|
||||
new_config.live_takeover_active = previous.live_takeover_active;
|
||||
|
||||
self.db
|
||||
.update_proxy_config(new_config.clone())
|
||||
|
||||
@@ -7,7 +7,6 @@ use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use tokio::time::timeout;
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::error::format_skill_error;
|
||||
|
||||
/// 技能对象
|
||||
@@ -107,16 +106,11 @@ pub struct SkillMetadata {
|
||||
pub struct SkillService {
|
||||
http_client: Client,
|
||||
install_dir: PathBuf,
|
||||
app_type: AppType,
|
||||
}
|
||||
|
||||
impl SkillService {
|
||||
pub fn new() -> Result<Self> {
|
||||
Self::new_for_app(AppType::Claude)
|
||||
}
|
||||
|
||||
pub fn new_for_app(app_type: AppType) -> Result<Self> {
|
||||
let install_dir = Self::get_install_dir_for_app(&app_type)?;
|
||||
let install_dir = Self::get_install_dir()?;
|
||||
|
||||
// 确保目录存在
|
||||
fs::create_dir_all(&install_dir)?;
|
||||
@@ -128,38 +122,16 @@ impl SkillService {
|
||||
.timeout(std::time::Duration::from_secs(10))
|
||||
.build()?,
|
||||
install_dir,
|
||||
app_type,
|
||||
})
|
||||
}
|
||||
|
||||
fn get_install_dir_for_app(app_type: &AppType) -> Result<PathBuf> {
|
||||
fn get_install_dir() -> Result<PathBuf> {
|
||||
let home = dirs::home_dir().context(format_skill_error(
|
||||
"GET_HOME_DIR_FAILED",
|
||||
&[],
|
||||
Some("checkPermission"),
|
||||
))?;
|
||||
|
||||
let dir = match app_type {
|
||||
AppType::Claude => home.join(".claude").join("skills"),
|
||||
AppType::Codex => {
|
||||
// 检查是否有自定义 Codex 配置目录
|
||||
if let Some(custom) = crate::settings::get_codex_override_dir() {
|
||||
custom.join("skills")
|
||||
} else {
|
||||
home.join(".codex").join("skills")
|
||||
}
|
||||
}
|
||||
AppType::Gemini => {
|
||||
// 为 Gemini 预留,暂时使用默认路径
|
||||
home.join(".gemini").join("skills")
|
||||
}
|
||||
};
|
||||
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
pub fn app_type(&self) -> &AppType {
|
||||
&self.app_type
|
||||
Ok(home.join(".claude").join("skills"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,436 +0,0 @@
|
||||
//! 流式健康检查服务
|
||||
//!
|
||||
//! 使用流式 API 进行快速健康检查,只需接收首个 chunk 即判定成功。
|
||||
|
||||
use futures::StreamExt;
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::error::AppError;
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::providers::{get_adapter, AuthInfo};
|
||||
|
||||
/// 健康状态枚举
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum HealthStatus {
|
||||
Operational,
|
||||
Degraded,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// 流式检查配置
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StreamCheckConfig {
|
||||
pub timeout_secs: u64,
|
||||
pub max_retries: u32,
|
||||
pub degraded_threshold_ms: u64,
|
||||
/// Claude 测试模型
|
||||
pub claude_model: String,
|
||||
/// Codex 测试模型
|
||||
pub codex_model: String,
|
||||
/// Gemini 测试模型
|
||||
pub gemini_model: String,
|
||||
}
|
||||
|
||||
impl Default for StreamCheckConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
timeout_secs: 45,
|
||||
max_retries: 2,
|
||||
degraded_threshold_ms: 6000,
|
||||
claude_model: "claude-haiku-4-5-20251001".to_string(),
|
||||
codex_model: "gpt-5.1-codex@low".to_string(),
|
||||
gemini_model: "gemini-3-pro-preview".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 流式检查结果
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StreamCheckResult {
|
||||
pub status: HealthStatus,
|
||||
pub success: bool,
|
||||
pub message: String,
|
||||
pub response_time_ms: Option<u64>,
|
||||
pub http_status: Option<u16>,
|
||||
pub model_used: String,
|
||||
pub tested_at: i64,
|
||||
pub retry_count: u32,
|
||||
}
|
||||
|
||||
/// 流式健康检查服务
|
||||
pub struct StreamCheckService;
|
||||
|
||||
impl StreamCheckService {
|
||||
/// 执行流式健康检查(带重试)
|
||||
pub async fn check_with_retry(
|
||||
app_type: &AppType,
|
||||
provider: &Provider,
|
||||
config: &StreamCheckConfig,
|
||||
) -> Result<StreamCheckResult, AppError> {
|
||||
let mut last_result = None;
|
||||
|
||||
for attempt in 0..=config.max_retries {
|
||||
let result = Self::check_once(app_type, provider, config).await;
|
||||
|
||||
match &result {
|
||||
Ok(r) if r.success => {
|
||||
return Ok(StreamCheckResult {
|
||||
retry_count: attempt,
|
||||
..r.clone()
|
||||
});
|
||||
}
|
||||
Ok(r) => {
|
||||
// 失败但非异常,判断是否重试
|
||||
if Self::should_retry(&r.message) && attempt < config.max_retries {
|
||||
last_result = Some(r.clone());
|
||||
continue;
|
||||
}
|
||||
return Ok(StreamCheckResult {
|
||||
retry_count: attempt,
|
||||
..r.clone()
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
if Self::should_retry(&e.to_string()) && attempt < config.max_retries {
|
||||
continue;
|
||||
}
|
||||
return Err(AppError::Message(e.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(last_result.unwrap_or_else(|| StreamCheckResult {
|
||||
status: HealthStatus::Failed,
|
||||
success: false,
|
||||
message: "检查失败".to_string(),
|
||||
response_time_ms: None,
|
||||
http_status: None,
|
||||
model_used: String::new(),
|
||||
tested_at: chrono::Utc::now().timestamp(),
|
||||
retry_count: config.max_retries,
|
||||
}))
|
||||
}
|
||||
|
||||
/// 单次流式检查
|
||||
async fn check_once(
|
||||
app_type: &AppType,
|
||||
provider: &Provider,
|
||||
config: &StreamCheckConfig,
|
||||
) -> Result<StreamCheckResult, AppError> {
|
||||
let start = Instant::now();
|
||||
let adapter = get_adapter(app_type);
|
||||
|
||||
let base_url = adapter
|
||||
.extract_base_url(provider)
|
||||
.map_err(|e| AppError::Message(format!("提取 base_url 失败: {e}")))?;
|
||||
|
||||
let auth = adapter
|
||||
.extract_auth(provider)
|
||||
.ok_or_else(|| AppError::Message("未找到 API Key".to_string()))?;
|
||||
|
||||
let client = Client::builder()
|
||||
.timeout(Duration::from_secs(config.timeout_secs))
|
||||
.user_agent("cc-switch/1.0")
|
||||
.build()
|
||||
.map_err(|e| AppError::Message(format!("创建客户端失败: {e}")))?;
|
||||
|
||||
let result = match app_type {
|
||||
AppType::Claude => {
|
||||
Self::check_claude_stream(&client, &base_url, &auth, &config.claude_model).await
|
||||
}
|
||||
AppType::Codex => {
|
||||
Self::check_codex_stream(&client, &base_url, &auth, &config.codex_model).await
|
||||
}
|
||||
AppType::Gemini => {
|
||||
Self::check_gemini_stream(&client, &base_url, &auth, &config.gemini_model).await
|
||||
}
|
||||
};
|
||||
|
||||
let response_time = start.elapsed().as_millis() as u64;
|
||||
let tested_at = chrono::Utc::now().timestamp();
|
||||
|
||||
match result {
|
||||
Ok((status_code, model)) => {
|
||||
let health_status =
|
||||
Self::determine_status(response_time, config.degraded_threshold_ms);
|
||||
Ok(StreamCheckResult {
|
||||
status: health_status,
|
||||
success: true,
|
||||
message: "检查成功".to_string(),
|
||||
response_time_ms: Some(response_time),
|
||||
http_status: Some(status_code),
|
||||
model_used: model,
|
||||
tested_at,
|
||||
retry_count: 0,
|
||||
})
|
||||
}
|
||||
Err(e) => Ok(StreamCheckResult {
|
||||
status: HealthStatus::Failed,
|
||||
success: false,
|
||||
message: e.to_string(),
|
||||
response_time_ms: Some(response_time),
|
||||
http_status: None,
|
||||
model_used: String::new(),
|
||||
tested_at,
|
||||
retry_count: 0,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Claude 流式检查
|
||||
async fn check_claude_stream(
|
||||
client: &Client,
|
||||
base_url: &str,
|
||||
auth: &AuthInfo,
|
||||
model: &str,
|
||||
) -> Result<(u16, String), AppError> {
|
||||
let base = base_url.trim_end_matches('/');
|
||||
let url = if base.ends_with("/v1") {
|
||||
format!("{base}/messages")
|
||||
} else {
|
||||
format!("{base}/v1/messages")
|
||||
};
|
||||
|
||||
let body = json!({
|
||||
"model": model,
|
||||
"max_tokens": 1,
|
||||
"messages": [{ "role": "user", "content": "hi" }],
|
||||
"stream": true
|
||||
});
|
||||
|
||||
let response = client
|
||||
.post(&url)
|
||||
.header("x-api-key", &auth.api_key)
|
||||
.header("anthropic-version", "2023-06-01")
|
||||
.header("Content-Type", "application/json")
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(Self::map_request_error)?;
|
||||
|
||||
let status = response.status().as_u16();
|
||||
|
||||
if !response.status().is_success() {
|
||||
let error_text = response.text().await.unwrap_or_default();
|
||||
return Err(AppError::Message(format!("HTTP {status}: {error_text}")));
|
||||
}
|
||||
|
||||
// 流式读取:只需首个 chunk
|
||||
let mut stream = response.bytes_stream();
|
||||
if let Some(chunk) = stream.next().await {
|
||||
match chunk {
|
||||
Ok(_) => Ok((status, model.to_string())),
|
||||
Err(e) => Err(AppError::Message(format!("读取流失败: {e}"))),
|
||||
}
|
||||
} else {
|
||||
Err(AppError::Message("未收到响应数据".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Codex 流式检查
|
||||
async fn check_codex_stream(
|
||||
client: &Client,
|
||||
base_url: &str,
|
||||
auth: &AuthInfo,
|
||||
model: &str,
|
||||
) -> Result<(u16, String), AppError> {
|
||||
let base = base_url.trim_end_matches('/');
|
||||
let url = if base.ends_with("/v1") {
|
||||
format!("{base}/chat/completions")
|
||||
} else {
|
||||
format!("{base}/v1/chat/completions")
|
||||
};
|
||||
|
||||
// 解析模型名和推理等级 (支持 model@level 或 model#level 格式)
|
||||
let (actual_model, reasoning_effort) = Self::parse_model_with_effort(model);
|
||||
|
||||
let mut body = json!({
|
||||
"model": actual_model,
|
||||
"messages": [
|
||||
{ "role": "system", "content": "" },
|
||||
{ "role": "assistant", "content": "" },
|
||||
{ "role": "user", "content": "hi" }
|
||||
],
|
||||
"max_tokens": 1,
|
||||
"temperature": 0,
|
||||
"stream": true
|
||||
});
|
||||
|
||||
// 如果是推理模型,添加 reasoning_effort
|
||||
if let Some(effort) = reasoning_effort {
|
||||
body["reasoning_effort"] = json!(effort);
|
||||
}
|
||||
|
||||
let response = client
|
||||
.post(&url)
|
||||
.header("Authorization", format!("Bearer {}", auth.api_key))
|
||||
.header("Content-Type", "application/json")
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(Self::map_request_error)?;
|
||||
|
||||
let status = response.status().as_u16();
|
||||
|
||||
if !response.status().is_success() {
|
||||
let error_text = response.text().await.unwrap_or_default();
|
||||
return Err(AppError::Message(format!("HTTP {status}: {error_text}")));
|
||||
}
|
||||
|
||||
let mut stream = response.bytes_stream();
|
||||
if let Some(chunk) = stream.next().await {
|
||||
match chunk {
|
||||
Ok(_) => Ok((status, model.to_string())),
|
||||
Err(e) => Err(AppError::Message(format!("读取流失败: {e}"))),
|
||||
}
|
||||
} else {
|
||||
Err(AppError::Message("未收到响应数据".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Gemini 流式检查
|
||||
async fn check_gemini_stream(
|
||||
client: &Client,
|
||||
base_url: &str,
|
||||
auth: &AuthInfo,
|
||||
model: &str,
|
||||
) -> Result<(u16, String), AppError> {
|
||||
let base = base_url.trim_end_matches('/');
|
||||
let url = format!("{base}/v1/chat/completions");
|
||||
|
||||
let body = json!({
|
||||
"model": model,
|
||||
"messages": [{ "role": "user", "content": "hi" }],
|
||||
"max_tokens": 1,
|
||||
"temperature": 0,
|
||||
"stream": true
|
||||
});
|
||||
|
||||
let response = client
|
||||
.post(&url)
|
||||
.header("Authorization", format!("Bearer {}", auth.api_key))
|
||||
.header("Content-Type", "application/json")
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(Self::map_request_error)?;
|
||||
|
||||
let status = response.status().as_u16();
|
||||
|
||||
if !response.status().is_success() {
|
||||
let error_text = response.text().await.unwrap_or_default();
|
||||
return Err(AppError::Message(format!("HTTP {status}: {error_text}")));
|
||||
}
|
||||
|
||||
let mut stream = response.bytes_stream();
|
||||
if let Some(chunk) = stream.next().await {
|
||||
match chunk {
|
||||
Ok(_) => Ok((status, model.to_string())),
|
||||
Err(e) => Err(AppError::Message(format!("读取流失败: {e}"))),
|
||||
}
|
||||
} else {
|
||||
Err(AppError::Message("未收到响应数据".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
fn determine_status(latency_ms: u64, threshold: u64) -> HealthStatus {
|
||||
if latency_ms <= threshold {
|
||||
HealthStatus::Operational
|
||||
} else {
|
||||
HealthStatus::Degraded
|
||||
}
|
||||
}
|
||||
|
||||
/// 解析模型名和推理等级 (支持 model@level 或 model#level 格式)
|
||||
/// 返回 (实际模型名, Option<推理等级>)
|
||||
fn parse_model_with_effort(model: &str) -> (String, Option<String>) {
|
||||
// 查找 @ 或 # 分隔符
|
||||
if let Some(pos) = model.find('@').or_else(|| model.find('#')) {
|
||||
let actual_model = model[..pos].to_string();
|
||||
let effort = model[pos + 1..].to_string();
|
||||
if !effort.is_empty() {
|
||||
return (actual_model, Some(effort));
|
||||
}
|
||||
}
|
||||
(model.to_string(), None)
|
||||
}
|
||||
|
||||
fn should_retry(msg: &str) -> bool {
|
||||
let lower = msg.to_lowercase();
|
||||
lower.contains("timeout")
|
||||
|| lower.contains("abort")
|
||||
|| lower.contains("中断")
|
||||
|| lower.contains("超时")
|
||||
}
|
||||
|
||||
fn map_request_error(e: reqwest::Error) -> AppError {
|
||||
if e.is_timeout() {
|
||||
AppError::Message("请求超时".to_string())
|
||||
} else if e.is_connect() {
|
||||
AppError::Message(format!("连接失败: {e}"))
|
||||
} else {
|
||||
AppError::Message(e.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_determine_status() {
|
||||
assert_eq!(
|
||||
StreamCheckService::determine_status(3000, 6000),
|
||||
HealthStatus::Operational
|
||||
);
|
||||
assert_eq!(
|
||||
StreamCheckService::determine_status(6000, 6000),
|
||||
HealthStatus::Operational
|
||||
);
|
||||
assert_eq!(
|
||||
StreamCheckService::determine_status(6001, 6000),
|
||||
HealthStatus::Degraded
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_should_retry() {
|
||||
assert!(StreamCheckService::should_retry("请求超时"));
|
||||
assert!(StreamCheckService::should_retry("request timeout"));
|
||||
assert!(!StreamCheckService::should_retry("API Key 无效"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_config() {
|
||||
let config = StreamCheckConfig::default();
|
||||
assert_eq!(config.timeout_secs, 45);
|
||||
assert_eq!(config.max_retries, 2);
|
||||
assert_eq!(config.degraded_threshold_ms, 6000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_model_with_effort() {
|
||||
// 带 @ 分隔符
|
||||
let (model, effort) = StreamCheckService::parse_model_with_effort("gpt-5.1-codex@low");
|
||||
assert_eq!(model, "gpt-5.1-codex");
|
||||
assert_eq!(effort, Some("low".to_string()));
|
||||
|
||||
// 带 # 分隔符
|
||||
let (model, effort) = StreamCheckService::parse_model_with_effort("o1-preview#high");
|
||||
assert_eq!(model, "o1-preview");
|
||||
assert_eq!(effort, Some("high".to_string()));
|
||||
|
||||
// 无分隔符
|
||||
let (model, effort) = StreamCheckService::parse_model_with_effort("gpt-4o-mini");
|
||||
assert_eq!(model, "gpt-4o-mini");
|
||||
assert_eq!(effort, None);
|
||||
}
|
||||
}
|
||||
@@ -652,6 +652,56 @@ impl Database {
|
||||
monthly_exceeded,
|
||||
})
|
||||
}
|
||||
|
||||
/// 更新每日统计聚合
|
||||
///
|
||||
/// 在请求完成后调用,更新 usage_daily_stats 表
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn update_daily_stats(
|
||||
&self,
|
||||
provider_id: &str,
|
||||
app_type: &str,
|
||||
model: &str,
|
||||
input_tokens: u32,
|
||||
output_tokens: u32,
|
||||
total_cost: &str,
|
||||
is_success: bool,
|
||||
) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
let date = Utc::now().format("%Y-%m-%d").to_string();
|
||||
|
||||
// 使用 UPSERT 更新或插入统计
|
||||
conn.execute(
|
||||
"INSERT INTO usage_daily_stats (
|
||||
date, provider_id, app_type, model,
|
||||
request_count, total_input_tokens, total_output_tokens,
|
||||
total_cost_usd, success_count, error_count
|
||||
) VALUES (?1, ?2, ?3, ?4, 1, ?5, ?6, ?7, ?8, ?9)
|
||||
ON CONFLICT(date, provider_id, app_type, model) DO UPDATE SET
|
||||
request_count = request_count + 1,
|
||||
total_input_tokens = total_input_tokens + ?5,
|
||||
total_output_tokens = total_output_tokens + ?6,
|
||||
total_cost_usd = CAST(
|
||||
CAST(total_cost_usd AS REAL) + CAST(?7 AS REAL) AS TEXT
|
||||
),
|
||||
success_count = success_count + ?8,
|
||||
error_count = error_count + ?9",
|
||||
params![
|
||||
date,
|
||||
provider_id,
|
||||
app_type,
|
||||
model,
|
||||
input_tokens,
|
||||
output_tokens,
|
||||
total_cost,
|
||||
if is_success { 1 } else { 0 },
|
||||
if is_success { 0 } else { 1 },
|
||||
],
|
||||
)
|
||||
.map_err(|e| AppError::Database(format!("更新每日统计失败: {e}")))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Provider 限额状态
|
||||
|
||||
+18
-492
@@ -3,7 +3,6 @@ use rquickjs::{Context, Function, Runtime};
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
use url::{Host, Url};
|
||||
|
||||
use crate::error::AppError;
|
||||
|
||||
@@ -16,14 +15,20 @@ pub async fn execute_usage_script(
|
||||
access_token: Option<&str>,
|
||||
user_id: Option<&str>,
|
||||
) -> Result<Value, AppError> {
|
||||
// 1. 替换模板变量,避免泄露敏感信息
|
||||
let script_with_vars =
|
||||
build_script_with_vars(script_code, api_key, base_url, access_token, user_id);
|
||||
// 1. 替换变量
|
||||
let mut replaced = script_code
|
||||
.replace("{{apiKey}}", api_key)
|
||||
.replace("{{baseUrl}}", base_url);
|
||||
|
||||
// 2. 验证 base_url 的安全性
|
||||
validate_base_url(base_url)?;
|
||||
// 替换 accessToken 和 userId
|
||||
if let Some(token) = access_token {
|
||||
replaced = replaced.replace("{{accessToken}}", token);
|
||||
}
|
||||
if let Some(uid) = user_id {
|
||||
replaced = replaced.replace("{{userId}}", uid);
|
||||
}
|
||||
|
||||
// 3. 在独立作用域中提取 request 配置(确保 Runtime/Context 在 await 前释放)
|
||||
// 2. 在独立作用域中提取 request 配置(确保 Runtime/Context 在 await 前释放)
|
||||
let request_config = {
|
||||
let runtime = Runtime::new().map_err(|e| {
|
||||
AppError::localized(
|
||||
@@ -42,7 +47,7 @@ pub async fn execute_usage_script(
|
||||
|
||||
context.with(|ctx| {
|
||||
// 执行用户代码,获取配置对象
|
||||
let config: rquickjs::Object = ctx.eval(script_with_vars.clone()).map_err(|e| {
|
||||
let config: rquickjs::Object = ctx.eval(replaced.clone()).map_err(|e| {
|
||||
AppError::localized(
|
||||
"usage_script.config_parse_failed",
|
||||
format!("解析配置失败: {e}"),
|
||||
@@ -89,7 +94,7 @@ pub async fn execute_usage_script(
|
||||
})?
|
||||
}; // Runtime 和 Context 在这里被 drop
|
||||
|
||||
// 4. 解析 request 配置
|
||||
// 3. 解析 request 配置
|
||||
let request: RequestConfig = serde_json::from_str(&request_config).map_err(|e| {
|
||||
AppError::localized(
|
||||
"usage_script.request_format_invalid",
|
||||
@@ -98,13 +103,10 @@ pub async fn execute_usage_script(
|
||||
)
|
||||
})?;
|
||||
|
||||
// 5. 验证请求 URL 是否安全(防止 SSRF)
|
||||
validate_request_url(&request.url, base_url)?;
|
||||
|
||||
// 6. 发送 HTTP 请求
|
||||
// 4. 发送 HTTP 请求
|
||||
let response_data = send_http_request(&request, timeout_secs).await?;
|
||||
|
||||
// 7. 在独立作用域中执行 extractor(确保 Runtime/Context 在函数结束前释放)
|
||||
// 5. 在独立作用域中执行 extractor(确保 Runtime/Context 在函数结束前释放)
|
||||
let result: Value = {
|
||||
let runtime = Runtime::new().map_err(|e| {
|
||||
AppError::localized(
|
||||
@@ -123,7 +125,7 @@ pub async fn execute_usage_script(
|
||||
|
||||
context.with(|ctx| {
|
||||
// 重新 eval 获取配置对象
|
||||
let config: rquickjs::Object = ctx.eval(script_with_vars.clone()).map_err(|e| {
|
||||
let config: rquickjs::Object = ctx.eval(replaced.clone()).map_err(|e| {
|
||||
AppError::localized(
|
||||
"usage_script.config_reparse_failed",
|
||||
format!("重新解析配置失败: {e}"),
|
||||
@@ -196,7 +198,7 @@ pub async fn execute_usage_script(
|
||||
})?
|
||||
}; // Runtime 和 Context 在这里被 drop
|
||||
|
||||
// 8. 验证返回值格式
|
||||
// 6. 验证返回值格式
|
||||
validate_result(&result)?;
|
||||
|
||||
Ok(result)
|
||||
@@ -392,479 +394,3 @@ fn validate_single_usage(result: &Value) -> Result<(), AppError> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 构建替换变量后的脚本,保持与旧版脚本的兼容性
|
||||
fn build_script_with_vars(
|
||||
script_code: &str,
|
||||
api_key: &str,
|
||||
base_url: &str,
|
||||
access_token: Option<&str>,
|
||||
user_id: Option<&str>,
|
||||
) -> String {
|
||||
let mut replaced = script_code
|
||||
.replace("{{apiKey}}", api_key)
|
||||
.replace("{{baseUrl}}", base_url);
|
||||
|
||||
if let Some(token) = access_token {
|
||||
replaced = replaced.replace("{{accessToken}}", token);
|
||||
}
|
||||
if let Some(uid) = user_id {
|
||||
replaced = replaced.replace("{{userId}}", uid);
|
||||
}
|
||||
|
||||
replaced
|
||||
}
|
||||
|
||||
/// 验证 base_url 的基本安全性
|
||||
fn validate_base_url(base_url: &str) -> Result<(), AppError> {
|
||||
if base_url.is_empty() {
|
||||
return Err(AppError::localized(
|
||||
"usage_script.base_url_empty",
|
||||
"base_url 不能为空",
|
||||
"base_url cannot be empty",
|
||||
));
|
||||
}
|
||||
|
||||
// 解析 URL
|
||||
let parsed_url = Url::parse(base_url).map_err(|e| {
|
||||
AppError::localized(
|
||||
"usage_script.base_url_invalid",
|
||||
format!("无效的 base_url: {e}"),
|
||||
format!("Invalid base_url: {e}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
let is_loopback = is_loopback_host(&parsed_url);
|
||||
|
||||
// 必须是 HTTPS(允许 localhost 用于开发)
|
||||
if parsed_url.scheme() != "https" && !is_loopback {
|
||||
return Err(AppError::localized(
|
||||
"usage_script.base_url_https_required",
|
||||
"base_url 必须使用 HTTPS 协议(localhost 除外)",
|
||||
"base_url must use HTTPS (localhost allowed)",
|
||||
));
|
||||
}
|
||||
|
||||
// 检查主机名格式有效性
|
||||
let hostname = parsed_url.host_str().ok_or_else(|| {
|
||||
AppError::localized(
|
||||
"usage_script.base_url_hostname_missing",
|
||||
"base_url 必须包含有效的主机名",
|
||||
"base_url must include a valid hostname",
|
||||
)
|
||||
})?;
|
||||
|
||||
// 基本的主机名格式检查
|
||||
if hostname.is_empty() {
|
||||
return Err(AppError::localized(
|
||||
"usage_script.base_url_hostname_empty",
|
||||
"base_url 主机名不能为空",
|
||||
"base_url hostname cannot be empty",
|
||||
));
|
||||
}
|
||||
|
||||
// 检查是否为明显的私有IP(但在 base_url 阶段不过于严格,主要在 request_url 阶段检查)
|
||||
if is_suspicious_hostname(hostname) {
|
||||
return Err(AppError::localized(
|
||||
"usage_script.base_url_suspicious",
|
||||
"base_url 包含可疑的主机名",
|
||||
"base_url contains a suspicious hostname",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 验证请求 URL 是否安全(防止 SSRF)
|
||||
fn validate_request_url(request_url: &str, base_url: &str) -> Result<(), AppError> {
|
||||
// 解析请求 URL
|
||||
let parsed_request = Url::parse(request_url).map_err(|e| {
|
||||
AppError::localized(
|
||||
"usage_script.request_url_invalid",
|
||||
format!("无效的请求 URL: {e}"),
|
||||
format!("Invalid request URL: {e}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
// 解析 base URL
|
||||
let parsed_base = Url::parse(base_url).map_err(|e| {
|
||||
AppError::localized(
|
||||
"usage_script.base_url_invalid",
|
||||
format!("无效的 base_url: {e}"),
|
||||
format!("Invalid base_url: {e}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
let is_request_loopback = is_loopback_host(&parsed_request);
|
||||
|
||||
// 必须使用 HTTPS(允许 localhost 用于开发)
|
||||
if parsed_request.scheme() != "https" && !is_request_loopback {
|
||||
return Err(AppError::localized(
|
||||
"usage_script.request_https_required",
|
||||
"请求 URL 必须使用 HTTPS 协议(localhost 除外)",
|
||||
"Request URL must use HTTPS (localhost allowed)",
|
||||
));
|
||||
}
|
||||
|
||||
// 核心安全检查:必须与 base_url 同源(相同域名和端口)
|
||||
if parsed_request.host_str() != parsed_base.host_str() {
|
||||
return Err(AppError::localized(
|
||||
"usage_script.request_host_mismatch",
|
||||
format!(
|
||||
"请求域名 {} 与 base_url 域名 {} 不匹配(必须是同源请求)",
|
||||
parsed_request.host_str().unwrap_or("unknown"),
|
||||
parsed_base.host_str().unwrap_or("unknown")
|
||||
),
|
||||
format!(
|
||||
"Request host {} must match base_url host {} (same-origin required)",
|
||||
parsed_request.host_str().unwrap_or("unknown"),
|
||||
parsed_base.host_str().unwrap_or("unknown")
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
// 检查端口是否匹配(考虑默认端口)
|
||||
// 使用 port_or_known_default() 会自动处理默认端口(http->80, https->443)
|
||||
match (
|
||||
parsed_request.port_or_known_default(),
|
||||
parsed_base.port_or_known_default(),
|
||||
) {
|
||||
(Some(request_port), Some(base_port)) if request_port == base_port => {
|
||||
// 端口匹配,继续执行
|
||||
}
|
||||
(Some(request_port), Some(base_port)) => {
|
||||
return Err(AppError::localized(
|
||||
"usage_script.request_port_mismatch",
|
||||
format!("请求端口 {request_port} 必须与 base_url 端口 {base_port} 匹配"),
|
||||
format!("Request port {request_port} must match base_url port {base_port}"),
|
||||
));
|
||||
}
|
||||
_ => {
|
||||
// 理论上不会发生,因为 port_or_known_default() 应该总是返回 Some
|
||||
return Err(AppError::localized(
|
||||
"usage_script.request_port_unknown",
|
||||
"无法确定端口号",
|
||||
"Unable to determine port number",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// 禁止私有 IP 地址访问(除非 base_url 本身就是私有地址,用于开发环境)
|
||||
if let Some(host) = parsed_request.host_str() {
|
||||
let base_host = parsed_base.host_str().unwrap_or("");
|
||||
|
||||
// 如果 base_url 不是私有地址,则禁止访问私有IP
|
||||
if !is_private_ip(base_host) && is_private_ip(host) {
|
||||
return Err(AppError::localized(
|
||||
"usage_script.private_ip_blocked",
|
||||
"禁止访问私有 IP 地址",
|
||||
"Access to private IP addresses is blocked",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 检查是否为私有 IP 地址
|
||||
fn is_private_ip(host: &str) -> bool {
|
||||
// localhost 检查
|
||||
if host.eq_ignore_ascii_case("localhost") {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 尝试解析为IP地址
|
||||
if let Ok(ip_addr) = host.parse::<std::net::IpAddr>() {
|
||||
return is_private_ip_addr(ip_addr);
|
||||
}
|
||||
|
||||
// 如果不是IP地址,不是私有IP
|
||||
false
|
||||
}
|
||||
|
||||
/// 使用标准库API检查IP地址是否为私有地址
|
||||
fn is_private_ip_addr(ip: std::net::IpAddr) -> bool {
|
||||
match ip {
|
||||
std::net::IpAddr::V4(ipv4) => {
|
||||
let octets = ipv4.octets();
|
||||
|
||||
// 0.0.0.0/8 (包括未指定地址)
|
||||
if octets[0] == 0 {
|
||||
return true;
|
||||
}
|
||||
|
||||
// RFC1918 私有地址范围
|
||||
// 10.0.0.0/8
|
||||
if octets[0] == 10 {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 172.16.0.0/12 (172.16.0.0 - 172.31.255.255)
|
||||
if octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31 {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 192.168.0.0/16
|
||||
if octets[0] == 192 && octets[1] == 168 {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 其他特殊地址
|
||||
// 169.254.0.0/16 (链路本地地址)
|
||||
if octets[0] == 169 && octets[1] == 254 {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 127.0.0.0/8 (环回地址)
|
||||
if octets[0] == 127 {
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
std::net::IpAddr::V6(ipv6) => {
|
||||
// IPv6 私有地址检查 - 使用标准库方法
|
||||
|
||||
// ::1 (环回地址)
|
||||
if ipv6.is_loopback() {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 唯一本地地址 (fc00::/7)
|
||||
// Rust 1.70+ 可以使用 ipv6.is_unique_local()
|
||||
// 但为了兼容性,我们手动检查
|
||||
let first_segment = ipv6.segments()[0];
|
||||
if (first_segment & 0xfe00) == 0xfc00 {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 链路本地地址 (fe80::/10)
|
||||
if (first_segment & 0xffc0) == 0xfe80 {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 未指定地址 ::
|
||||
if ipv6.is_unspecified() {
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 检查是否为可疑的主机名(只检查明显不安全的模式)
|
||||
fn is_suspicious_hostname(hostname: &str) -> bool {
|
||||
// 空主机名
|
||||
if hostname.is_empty() {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 检查明显的主机名格式问题
|
||||
if hostname.contains("..") || hostname.starts_with(".") || hostname.ends_with(".") {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 检查是否为纯IP地址但没有合理格式(过于宽松的检查在这里可能不够,但主要依赖后续的同源检查)
|
||||
if hostname.parse::<std::net::IpAddr>().is_ok() {
|
||||
// IP地址格式的,在这里不直接拒绝,让同源检查来处理
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查是否包含明显不当的字符
|
||||
let suspicious_chars = ['<', '>', '"', '\'', '\n', '\r', '\t', '\0'];
|
||||
if hostname.chars().any(|c| suspicious_chars.contains(&c)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
/// 判断 URL 是否指向本机(localhost / loopback)
|
||||
fn is_loopback_host(url: &Url) -> bool {
|
||||
match url.host() {
|
||||
Some(Host::Domain(d)) => d.eq_ignore_ascii_case("localhost"),
|
||||
Some(Host::Ipv4(ip)) => ip.is_loopback(),
|
||||
Some(Host::Ipv6(ip)) => ip.is_loopback(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_private_ip_validation() {
|
||||
// 测试IPv4私网地址
|
||||
|
||||
// RFC1918私网地址 - 应该返回true
|
||||
assert!(is_private_ip("10.0.0.1"));
|
||||
assert!(is_private_ip("10.255.255.254"));
|
||||
assert!(is_private_ip("172.16.0.1"));
|
||||
assert!(is_private_ip("172.31.255.255"));
|
||||
assert!(is_private_ip("192.168.0.1"));
|
||||
assert!(is_private_ip("192.168.255.255"));
|
||||
|
||||
// 链路本地地址 - 应该返回true
|
||||
assert!(is_private_ip("169.254.0.1"));
|
||||
assert!(is_private_ip("169.254.255.255"));
|
||||
|
||||
// 环回地址 - 应该返回true
|
||||
assert!(is_private_ip("127.0.0.1"));
|
||||
assert!(is_private_ip("localhost"));
|
||||
|
||||
// 公网172.x.x.x地址 - 应该返回false(这是修复的重点)
|
||||
assert!(!is_private_ip("172.0.0.1"));
|
||||
assert!(!is_private_ip("172.15.255.255"));
|
||||
assert!(!is_private_ip("172.32.0.1"));
|
||||
assert!(!is_private_ip("172.64.0.1"));
|
||||
assert!(!is_private_ip("172.67.0.1")); // Cloudflare CDN
|
||||
assert!(!is_private_ip("172.68.0.1"));
|
||||
assert!(!is_private_ip("172.100.50.25"));
|
||||
assert!(!is_private_ip("172.255.255.255"));
|
||||
|
||||
// 其他公网地址 - 应该返回false
|
||||
assert!(!is_private_ip("8.8.8.8")); // Google DNS
|
||||
assert!(!is_private_ip("1.1.1.1")); // Cloudflare DNS
|
||||
assert!(!is_private_ip("208.67.222.222")); // OpenDNS
|
||||
assert!(!is_private_ip("180.76.76.76")); // Baidu DNS
|
||||
|
||||
// 域名 - 应该返回false
|
||||
assert!(!is_private_ip("api.example.com"));
|
||||
assert!(!is_private_ip("www.google.com"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ipv6_private_validation() {
|
||||
// IPv6私网地址
|
||||
assert!(is_private_ip("::1")); // 环回地址
|
||||
assert!(is_private_ip("fc00::1")); // 唯一本地地址
|
||||
assert!(is_private_ip("fd00::1")); // 唯一本地地址
|
||||
assert!(is_private_ip("fe80::1")); // 链路本地地址
|
||||
assert!(is_private_ip("::")); // 未指定地址
|
||||
|
||||
// IPv6公网地址 - 应该返回false(修复的重点)
|
||||
assert!(!is_private_ip("2001:4860:4860::8888")); // Google DNS IPv6
|
||||
assert!(!is_private_ip("2606:4700:4700::1111")); // Cloudflare DNS IPv6
|
||||
assert!(!is_private_ip("2404:6800:4001:c01::67")); // Google DNS IPv6 (其他格式)
|
||||
assert!(!is_private_ip("2001:db8::1")); // 文档地址(非私网)
|
||||
|
||||
// 测试包含 ::1 子串但不是环回地址的公网地址
|
||||
assert!(!is_private_ip("2001:db8::1abc")); // 包含 ::1abc 但不是环回
|
||||
assert!(!is_private_ip("2606:4700::1")); // 包含 ::1 但不是环回
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hostname_bypass_prevention() {
|
||||
// 看起来像本地,但实际是域名
|
||||
assert!(!is_private_ip("127.0.0.1.evil.com"));
|
||||
assert!(!is_private_ip("localhost.evil.com"));
|
||||
|
||||
// 0.0.0.0 应该被视为本地/阻断
|
||||
assert!(is_private_ip("0.0.0.0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_https_bypass_prevention() {
|
||||
// 非本地域名的 HTTP 应该被拒绝
|
||||
let result = validate_base_url("http://127.0.0.1.evil.com/api");
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"Should reject HTTP for non-localhost domains"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edge_cases() {
|
||||
// 边界情况测试
|
||||
assert!(is_private_ip("172.16.0.0")); // RFC1918起始
|
||||
assert!(is_private_ip("172.31.255.255")); // RFC1918结束
|
||||
assert!(is_private_ip("10.0.0.0")); // 10.0.0.0/8起始
|
||||
assert!(is_private_ip("10.255.255.255")); // 10.0.0.0/8结束
|
||||
assert!(is_private_ip("192.168.0.0")); // 192.168.0.0/16起始
|
||||
assert!(is_private_ip("192.168.255.255")); // 192.168.0.0/16结束
|
||||
|
||||
// 紧邻RFC1918的公网地址 - 应该返回false
|
||||
assert!(!is_private_ip("172.15.255.255")); // 172.16.0.0的前一个
|
||||
assert!(!is_private_ip("172.32.0.0")); // 172.31.255.255的后一个
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ip_addr_parsing() {
|
||||
// 测试IP地址解析功能
|
||||
let ipv4_private = "10.0.0.1".parse::<std::net::IpAddr>().unwrap();
|
||||
assert!(is_private_ip_addr(ipv4_private));
|
||||
|
||||
let ipv4_public = "172.67.0.1".parse::<std::net::IpAddr>().unwrap();
|
||||
assert!(!is_private_ip_addr(ipv4_public));
|
||||
|
||||
let ipv6_private = "fc00::1".parse::<std::net::IpAddr>().unwrap();
|
||||
assert!(is_private_ip_addr(ipv6_private));
|
||||
|
||||
let ipv6_public = "2001:4860:4860::8888".parse::<std::net::IpAddr>().unwrap();
|
||||
assert!(!is_private_ip_addr(ipv6_public));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_port_comparison() {
|
||||
// 测试端口比较逻辑是否正确处理默认端口和显式端口
|
||||
|
||||
// 测试用例:(base_url, request_url, should_match)
|
||||
let test_cases = vec![
|
||||
// HTTPS默认端口测试
|
||||
(
|
||||
"https://api.example.com",
|
||||
"https://api.example.com/v1/test",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"https://api.example.com",
|
||||
"https://api.example.com:443/v1/test",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"https://api.example.com:443",
|
||||
"https://api.example.com/v1/test",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"https://api.example.com:443",
|
||||
"https://api.example.com:443/v1/test",
|
||||
true,
|
||||
),
|
||||
// 端口不匹配测试
|
||||
(
|
||||
"https://api.example.com",
|
||||
"https://api.example.com:8443/v1/test",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"https://api.example.com:443",
|
||||
"https://api.example.com:8443/v1/test",
|
||||
false,
|
||||
),
|
||||
];
|
||||
|
||||
for (base_url, request_url, should_match) in test_cases {
|
||||
let result = validate_request_url(request_url, base_url);
|
||||
|
||||
if should_match {
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
"应该匹配的URL被拒绝: base_url={}, request_url={}, error={}",
|
||||
base_url,
|
||||
request_url,
|
||||
result.unwrap_err()
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"应该不匹配的URL被允许: base_url={}, request_url={}",
|
||||
base_url,
|
||||
request_url
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+22
-35
@@ -23,7 +23,6 @@ import {
|
||||
} from "@/lib/api";
|
||||
import { checkAllEnvConflicts, checkEnvConflicts } from "@/lib/api/env";
|
||||
import { useProviderActions } from "@/hooks/useProviderActions";
|
||||
import { useProxyStatus } from "@/hooks/useProxyStatus";
|
||||
import { extractErrorMessage } from "@/utils/errorUtils";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { AppSwitcher } from "@/components/AppSwitcher";
|
||||
@@ -34,7 +33,6 @@ import { ConfirmDialog } from "@/components/ConfirmDialog";
|
||||
import { SettingsPage } from "@/components/settings/SettingsPage";
|
||||
import { UpdateBadge } from "@/components/UpdateBadge";
|
||||
import { EnvWarningBanner } from "@/components/env/EnvWarningBanner";
|
||||
import { ProxyToggle } from "@/components/proxy/ProxyToggle";
|
||||
import UsageScriptModal from "@/components/UsageScriptModal";
|
||||
import UnifiedMcpPanel from "@/components/mcp/UnifiedMcpPanel";
|
||||
import PromptPanel from "@/components/prompts/PromptPanel";
|
||||
@@ -64,17 +62,10 @@ function App() {
|
||||
const addActionButtonClass =
|
||||
"bg-orange-500 hover:bg-orange-600 dark:bg-orange-500 dark:hover:bg-orange-600 text-white shadow-lg shadow-orange-500/30 dark:shadow-orange-500/40 rounded-full w-8 h-8";
|
||||
|
||||
// 获取代理服务状态
|
||||
const { isRunning: isProxyRunning, isTakeoverActive } = useProxyStatus();
|
||||
|
||||
// 获取供应商列表,当代理服务运行时自动刷新
|
||||
const { data, isLoading, refetch } = useProvidersQuery(activeApp, {
|
||||
isProxyRunning,
|
||||
});
|
||||
const { data, isLoading, refetch } = useProvidersQuery(activeApp);
|
||||
const providers = useMemo(() => data?.providers ?? {}, [data]);
|
||||
const currentProviderId = data?.currentProviderId ?? "";
|
||||
// Skills 功能仅支持 Claude 和 Codex
|
||||
const hasSkillsSupport = activeApp === "claude" || activeApp === "codex";
|
||||
const isClaudeApp = activeApp === "claude";
|
||||
|
||||
// 🎯 使用 useProviderActions Hook 统一管理所有 Provider 操作
|
||||
const {
|
||||
@@ -83,6 +74,7 @@ function App() {
|
||||
switchProvider,
|
||||
deleteProvider,
|
||||
saveUsageScript,
|
||||
setProxyTarget,
|
||||
} = useProviderActions(activeApp);
|
||||
|
||||
// 监听来自托盘菜单的切换事件
|
||||
@@ -299,7 +291,6 @@ function App() {
|
||||
<SkillsPage
|
||||
ref={skillsPageRef}
|
||||
onClose={() => setCurrentView("providers")}
|
||||
initialApp={activeApp}
|
||||
/>
|
||||
);
|
||||
case "mcp":
|
||||
@@ -322,9 +313,8 @@ function App() {
|
||||
currentProviderId={currentProviderId}
|
||||
appId={activeApp}
|
||||
isLoading={isLoading}
|
||||
isProxyRunning={isProxyRunning}
|
||||
isProxyTakeover={isProxyRunning && isTakeoverActive}
|
||||
onSwitch={switchProvider}
|
||||
onSetProxyTarget={setProxyTarget}
|
||||
onEdit={setEditingProvider}
|
||||
onDelete={setConfirmDelete}
|
||||
onDuplicate={handleDuplicateProvider}
|
||||
@@ -378,7 +368,7 @@ function App() {
|
||||
)}
|
||||
|
||||
<header
|
||||
className="fixed top-0 z-50 w-full py-3 bg-background/80 backdrop-blur-md transition-all duration-300"
|
||||
className="glass-header fixed top-0 z-50 w-full py-3 transition-all duration-300"
|
||||
data-tauri-drag-region
|
||||
style={{ WebkitAppRegion: "drag" } as any}
|
||||
>
|
||||
@@ -418,12 +408,7 @@ function App() {
|
||||
href="https://github.com/farion1231/cc-switch"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className={cn(
|
||||
"text-xl font-semibold transition-colors",
|
||||
isProxyRunning && isTakeoverActive
|
||||
? "text-emerald-500 hover:text-emerald-600 dark:text-emerald-400 dark:hover:text-emerald-300"
|
||||
: "text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300"
|
||||
)}
|
||||
className="text-xl font-semibold text-blue-500 transition-colors hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300"
|
||||
>
|
||||
CC Switch
|
||||
</a>
|
||||
@@ -490,22 +475,24 @@ function App() {
|
||||
)}
|
||||
{currentView === "providers" && (
|
||||
<>
|
||||
<ProxyToggle />
|
||||
|
||||
<AppSwitcher activeApp={activeApp} onSwitch={setActiveApp} />
|
||||
|
||||
<div className="bg-muted p-1 rounded-xl flex items-center gap-1">
|
||||
{hasSkillsSupport && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setCurrentView("skills")}
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
|
||||
title={t("skills.manage")}
|
||||
>
|
||||
<Wrench className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<div className="glass p-1 rounded-xl flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setCurrentView("skills")}
|
||||
className={cn(
|
||||
"text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5",
|
||||
"transition-all duration-200 ease-in-out overflow-hidden",
|
||||
isClaudeApp
|
||||
? "opacity-100 w-8 scale-100 px-2"
|
||||
: "opacity-0 w-0 scale-75 pointer-events-none px-0 -ml-1",
|
||||
)}
|
||||
title={t("skills.manage")}
|
||||
>
|
||||
<Wrench className="h-4 w-4 flex-shrink-0" />
|
||||
</Button>
|
||||
{/* TODO: Agents 功能开发中,暂时隐藏入口 */}
|
||||
{/* {isClaudeApp && (
|
||||
<Button
|
||||
|
||||
@@ -24,14 +24,14 @@ export function AppSwitcher({ activeApp, onSwitch }: AppSwitcherProps) {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="inline-flex bg-muted rounded-lg p-1 gap-1">
|
||||
<div className="inline-flex bg-gray-100 dark:bg-gray-800 rounded-lg p-1 gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleSwitch("claude")}
|
||||
className={`group inline-flex items-center gap-2 px-3 py-2 rounded-md text-sm font-medium transition-all duration-200 ${
|
||||
activeApp === "claude"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-background/50"
|
||||
? "bg-white text-gray-900 shadow-sm dark:bg-gray-900 dark:text-gray-100"
|
||||
: "text-gray-500 hover:text-gray-900 hover:bg-white/50 dark:text-gray-400 dark:hover:text-gray-100 dark:hover:bg-gray-800/60"
|
||||
}`}
|
||||
>
|
||||
<ProviderIcon
|
||||
@@ -41,7 +41,7 @@ export function AppSwitcher({ activeApp, onSwitch }: AppSwitcherProps) {
|
||||
className={
|
||||
activeApp === "claude"
|
||||
? "text-foreground"
|
||||
: "text-muted-foreground group-hover:text-foreground transition-colors"
|
||||
: "text-gray-500 dark:text-gray-400 group-hover:text-foreground transition-colors"
|
||||
}
|
||||
/>
|
||||
<span>{appDisplayName.claude}</span>
|
||||
@@ -50,10 +50,10 @@ export function AppSwitcher({ activeApp, onSwitch }: AppSwitcherProps) {
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleSwitch("codex")}
|
||||
className={`group inline-flex items-center gap-2 px-3 py-2 rounded-md text-sm font-medium transition-all duration-200 ${
|
||||
className={`inline-flex items-center gap-2 px-3 py-2 rounded-md text-sm font-medium transition-all duration-200 ${
|
||||
activeApp === "codex"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-background/50"
|
||||
? "bg-white text-gray-900 shadow-sm dark:bg-gray-900 dark:text-gray-100"
|
||||
: "text-gray-500 hover:text-gray-900 hover:bg-white/50 dark:text-gray-400 dark:hover:text-gray-100 dark:hover:bg-gray-800/60"
|
||||
}`}
|
||||
>
|
||||
<ProviderIcon
|
||||
@@ -63,7 +63,7 @@ export function AppSwitcher({ activeApp, onSwitch }: AppSwitcherProps) {
|
||||
className={
|
||||
activeApp === "codex"
|
||||
? "text-foreground"
|
||||
: "text-muted-foreground group-hover:text-foreground transition-colors"
|
||||
: "text-gray-500 dark:text-gray-400 group-hover:text-foreground transition-colors"
|
||||
}
|
||||
/>
|
||||
<span>{appDisplayName.codex}</span>
|
||||
@@ -72,10 +72,10 @@ export function AppSwitcher({ activeApp, onSwitch }: AppSwitcherProps) {
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleSwitch("gemini")}
|
||||
className={`group inline-flex items-center gap-2 px-3 py-2 rounded-md text-sm font-medium transition-all duration-200 ${
|
||||
className={`inline-flex items-center gap-2 px-3 py-2 rounded-md text-sm font-medium transition-all duration-200 ${
|
||||
activeApp === "gemini"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-background/50"
|
||||
? "bg-white text-gray-900 shadow-sm dark:bg-gray-900 dark:text-gray-100"
|
||||
: "text-gray-500 hover:text-gray-900 hover:bg-white/50 dark:text-gray-400 dark:hover:text-gray-100 dark:hover:bg-gray-800/60"
|
||||
}`}
|
||||
>
|
||||
<ProviderIcon
|
||||
@@ -85,7 +85,7 @@ export function AppSwitcher({ activeApp, onSwitch }: AppSwitcherProps) {
|
||||
className={
|
||||
activeApp === "gemini"
|
||||
? "text-foreground"
|
||||
: "text-muted-foreground group-hover:text-foreground transition-colors"
|
||||
: "text-gray-500 dark:text-gray-400 group-hover:text-foreground transition-colors"
|
||||
}
|
||||
/>
|
||||
<span>{appDisplayName.gemini}</span>
|
||||
|
||||
@@ -14,7 +14,6 @@ interface ProviderIconProps {
|
||||
export const ProviderIcon: React.FC<ProviderIconProps> = ({
|
||||
icon,
|
||||
name,
|
||||
color,
|
||||
size = 32,
|
||||
className,
|
||||
showFallback = true,
|
||||
@@ -47,7 +46,7 @@ export const ProviderIcon: React.FC<ProviderIconProps> = ({
|
||||
"inline-flex items-center justify-center flex-shrink-0",
|
||||
className,
|
||||
)}
|
||||
style={{ ...sizeStyle, color }}
|
||||
style={sizeStyle}
|
||||
dangerouslySetInnerHTML={{ __html: iconSvg }}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -33,23 +33,13 @@ export function EditProviderDialog({
|
||||
unknown
|
||||
> | null>(null);
|
||||
|
||||
// 使用 ref 标记是否已经加载过,防止重复读取覆盖用户编辑
|
||||
const [hasLoadedLive, setHasLoadedLive] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const load = async () => {
|
||||
if (!open || !provider) {
|
||||
setLiveSettings(null);
|
||||
setHasLoadedLive(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// 关键修复:只在首次打开时加载一次
|
||||
if (hasLoadedLive) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const currentId = await providersApi.getCurrent(appId);
|
||||
if (currentId && provider.id === currentId) {
|
||||
@@ -59,20 +49,13 @@ export function EditProviderDialog({
|
||||
)) as Record<string, unknown>;
|
||||
if (!cancelled && live && typeof live === "object") {
|
||||
setLiveSettings(live);
|
||||
setHasLoadedLive(true);
|
||||
}
|
||||
} catch {
|
||||
// 读取实时配置失败则回退到 SSOT(不打断编辑流程)
|
||||
if (!cancelled) {
|
||||
setLiveSettings(null);
|
||||
setHasLoadedLive(true);
|
||||
}
|
||||
if (!cancelled) setLiveSettings(null);
|
||||
}
|
||||
} else {
|
||||
if (!cancelled) {
|
||||
setLiveSettings(null);
|
||||
setHasLoadedLive(true);
|
||||
}
|
||||
if (!cancelled) setLiveSettings(null);
|
||||
}
|
||||
} finally {
|
||||
// no-op
|
||||
@@ -82,33 +65,14 @@ export function EditProviderDialog({
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [open, provider?.id, appId, hasLoadedLive]); // 只依赖 provider.id,不依赖整个 provider 对象
|
||||
}, [open, provider, appId]);
|
||||
|
||||
const initialSettingsConfig = useMemo(() => {
|
||||
return (liveSettings ?? provider?.settingsConfig ?? {}) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
}, [liveSettings, provider?.settingsConfig]); // 只依赖 settingsConfig,不依赖整个 provider
|
||||
|
||||
// 固定 initialData,防止 provider 对象更新时重置表单
|
||||
const initialData = useMemo(() => {
|
||||
if (!provider) return null;
|
||||
return {
|
||||
name: provider.name,
|
||||
notes: provider.notes,
|
||||
websiteUrl: provider.websiteUrl,
|
||||
settingsConfig: initialSettingsConfig,
|
||||
category: provider.category,
|
||||
meta: provider.meta,
|
||||
icon: provider.icon,
|
||||
iconColor: provider.iconColor,
|
||||
};
|
||||
}, [
|
||||
provider?.id, // 只依赖 ID,provider 对象更新不会触发重新计算
|
||||
initialSettingsConfig,
|
||||
// 注意:不依赖 provider 的其他字段,防止表单重置
|
||||
]);
|
||||
}, [liveSettings, provider]);
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
async (values: ProviderFormValues) => {
|
||||
@@ -140,7 +104,7 @@ export function EditProviderDialog({
|
||||
[onSubmit, onOpenChange, provider],
|
||||
);
|
||||
|
||||
if (!provider || !initialData) {
|
||||
if (!provider) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -166,7 +130,17 @@ export function EditProviderDialog({
|
||||
submitLabel={t("common.save")}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => onOpenChange(false)}
|
||||
initialData={initialData}
|
||||
initialData={{
|
||||
name: provider.name,
|
||||
notes: provider.notes,
|
||||
websiteUrl: provider.websiteUrl,
|
||||
// 若读取到实时配置则优先使用
|
||||
settingsConfig: initialSettingsConfig,
|
||||
category: provider.category,
|
||||
meta: provider.meta,
|
||||
icon: provider.icon,
|
||||
iconColor: provider.iconColor,
|
||||
}}
|
||||
showButtons={false}
|
||||
/>
|
||||
</FullScreenPanel>
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
import React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { HealthStatus } from "@/lib/api/model-test";
|
||||
|
||||
interface HealthStatusIndicatorProps {
|
||||
status: HealthStatus;
|
||||
responseTimeMs?: number;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const statusConfig = {
|
||||
operational: {
|
||||
color: "bg-emerald-500",
|
||||
label: "正常",
|
||||
textColor: "text-emerald-600 dark:text-emerald-400",
|
||||
},
|
||||
degraded: {
|
||||
color: "bg-yellow-500",
|
||||
label: "降级",
|
||||
textColor: "text-yellow-600 dark:text-yellow-400",
|
||||
},
|
||||
failed: {
|
||||
color: "bg-red-500",
|
||||
label: "失败",
|
||||
textColor: "text-red-600 dark:text-red-400",
|
||||
},
|
||||
};
|
||||
|
||||
export const HealthStatusIndicator: React.FC<HealthStatusIndicatorProps> = ({
|
||||
status,
|
||||
responseTimeMs,
|
||||
className,
|
||||
}) => {
|
||||
const config = statusConfig[status];
|
||||
|
||||
return (
|
||||
<div className={cn("flex items-center gap-2", className)}>
|
||||
<div className={cn("w-2 h-2 rounded-full", config.color)} />
|
||||
<span className={cn("text-xs font-medium", config.textColor)}>
|
||||
{config.label}
|
||||
{responseTimeMs !== undefined && ` (${responseTimeMs}ms)`}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
Play,
|
||||
TestTube2,
|
||||
Trash2,
|
||||
RotateCcw,
|
||||
} from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -16,31 +15,23 @@ import { cn } from "@/lib/utils";
|
||||
interface ProviderActionsProps {
|
||||
isCurrent: boolean;
|
||||
isTesting?: boolean;
|
||||
isProxyTakeover?: boolean;
|
||||
onSwitch: () => void;
|
||||
onEdit: () => void;
|
||||
onDuplicate: () => void;
|
||||
onTest?: () => void;
|
||||
onConfigureUsage: () => void;
|
||||
onDelete: () => void;
|
||||
onResetCircuitBreaker?: () => void;
|
||||
isProxyTarget?: boolean;
|
||||
consecutiveFailures?: number;
|
||||
}
|
||||
|
||||
export function ProviderActions({
|
||||
isCurrent,
|
||||
isTesting,
|
||||
isProxyTakeover = false,
|
||||
onSwitch,
|
||||
onEdit,
|
||||
onDuplicate,
|
||||
onTest,
|
||||
onConfigureUsage,
|
||||
onDelete,
|
||||
onResetCircuitBreaker,
|
||||
isProxyTarget,
|
||||
consecutiveFailures = 0,
|
||||
}: ProviderActionsProps) {
|
||||
const { t } = useTranslation();
|
||||
const iconButtonClass = "h-8 w-8 p-1";
|
||||
@@ -56,10 +47,6 @@ export function ProviderActions({
|
||||
"w-[4.5rem] px-2.5",
|
||||
isCurrent &&
|
||||
"bg-gray-200 text-muted-foreground hover:bg-gray-200 hover:text-muted-foreground dark:bg-gray-700 dark:hover:bg-gray-700",
|
||||
// 代理接管模式下启用按钮使用绿色
|
||||
!isCurrent &&
|
||||
isProxyTakeover &&
|
||||
"bg-emerald-500 hover:bg-emerald-600 dark:bg-emerald-600 dark:hover:bg-emerald-700"
|
||||
)}
|
||||
>
|
||||
{isCurrent ? (
|
||||
@@ -123,33 +110,6 @@ export function ProviderActions({
|
||||
<BarChart3 className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
{/* 重置熔断器按钮 - 代理目标启用时显示 */}
|
||||
{/* TODO: 暂时隐藏,后续根据故障转移功能启用 */}
|
||||
{/* {onResetCircuitBreaker && isProxyTarget && (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
onClick={onResetCircuitBreaker}
|
||||
disabled={consecutiveFailures === 0}
|
||||
title={
|
||||
consecutiveFailures > 0
|
||||
? t("provider.resetCircuitBreaker", {
|
||||
defaultValue: "重置熔断器",
|
||||
})
|
||||
: t("provider.noFailures", {
|
||||
defaultValue: "当前无失败记录",
|
||||
})
|
||||
}
|
||||
className={cn(
|
||||
iconButtonClass,
|
||||
consecutiveFailures > 0 &&
|
||||
"hover:text-orange-500 dark:hover:text-orange-400",
|
||||
)}
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</Button>
|
||||
)} */}
|
||||
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
@@ -158,7 +118,7 @@ export function ProviderActions({
|
||||
className={cn(
|
||||
iconButtonClass,
|
||||
!isCurrent && "hover:text-red-500 dark:hover:text-red-400",
|
||||
isCurrent && "opacity-40 cursor-not-allowed text-muted-foreground"
|
||||
isCurrent && "opacity-40 cursor-not-allowed text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
|
||||
@@ -11,12 +11,8 @@ import { cn } from "@/lib/utils";
|
||||
import { ProviderActions } from "@/components/providers/ProviderActions";
|
||||
import { ProviderIcon } from "@/components/ProviderIcon";
|
||||
import UsageFooter from "@/components/UsageFooter";
|
||||
import { ProviderHealthBadge } from "@/components/providers/ProviderHealthBadge";
|
||||
import {
|
||||
useProviderHealth,
|
||||
useResetCircuitBreaker,
|
||||
} from "@/lib/query/failover";
|
||||
import { toast } from "sonner";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Label } from "@/components/ui/label";
|
||||
|
||||
interface DragHandleProps {
|
||||
attributes: DraggableAttributes;
|
||||
@@ -36,8 +32,8 @@ interface ProviderCardProps {
|
||||
onDuplicate: (provider: Provider) => void;
|
||||
onTest?: (provider: Provider) => void;
|
||||
isTesting?: boolean;
|
||||
onSetProxyTarget: (provider: Provider) => void;
|
||||
isProxyRunning: boolean;
|
||||
isProxyTakeover?: boolean; // 代理接管模式(Live配置已被接管,切换为热切换)
|
||||
dragHandleProps?: DragHandleProps;
|
||||
}
|
||||
|
||||
@@ -88,40 +84,12 @@ export function ProviderCard({
|
||||
onDuplicate,
|
||||
onTest,
|
||||
isTesting,
|
||||
onSetProxyTarget,
|
||||
isProxyRunning,
|
||||
isProxyTakeover = false,
|
||||
dragHandleProps,
|
||||
}: ProviderCardProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// 获取供应商健康状态
|
||||
const { data: health } = useProviderHealth(provider.id, appId);
|
||||
|
||||
// 重置熔断器
|
||||
const resetCircuitBreaker = useResetCircuitBreaker();
|
||||
|
||||
const handleResetCircuitBreaker = async () => {
|
||||
try {
|
||||
await resetCircuitBreaker.mutateAsync({
|
||||
providerId: provider.id,
|
||||
appType: appId,
|
||||
});
|
||||
toast.success(
|
||||
t("provider.circuitBreakerReset", {
|
||||
defaultValue: "熔断器已重置",
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
t("provider.circuitBreakerResetFailed", {
|
||||
defaultValue: "重置失败",
|
||||
}) +
|
||||
": " +
|
||||
String(error),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const fallbackUrlText = t("provider.notConfigured", {
|
||||
defaultValue: "未配置接口地址",
|
||||
});
|
||||
@@ -156,26 +124,14 @@ export function ProviderCard({
|
||||
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: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",
|
||||
"glass-card relative overflow-hidden rounded-xl p-4 transition-all duration-300",
|
||||
"group hover:bg-black/[0.02] dark:hover:bg-white/[0.02] hover:border-primary/50",
|
||||
isCurrent ? "glass-card-active" : "hover:scale-[1.01]",
|
||||
dragHandleProps?.isDragging &&
|
||||
"cursor-grabbing border-primary shadow-lg scale-105 z-10",
|
||||
)}
|
||||
>
|
||||
<div className={cn(
|
||||
"absolute inset-0 bg-gradient-to-r to-transparent transition-opacity duration-500 pointer-events-none",
|
||||
// 代理接管模式下使用绿色渐变,否则使用蓝色主色调
|
||||
isProxyTakeover && isCurrent ? "from-emerald-500/10" : "from-primary/10",
|
||||
isCurrent ? "opacity-100" : "opacity-0"
|
||||
)} />
|
||||
<div className="absolute inset-0 bg-gradient-to-r from-primary/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500 pointer-events-none" />
|
||||
<div className="relative flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex flex-1 items-center gap-2">
|
||||
<button
|
||||
@@ -193,7 +149,7 @@ export function ProviderCard({
|
||||
</button>
|
||||
|
||||
{/* 供应商图标 */}
|
||||
<div className="h-8 w-8 rounded-lg bg-muted flex items-center justify-center border border-border group-hover:scale-105 transition-transform duration-300">
|
||||
<div className="h-8 w-8 rounded-lg bg-white/5 flex items-center justify-center border border-gray-200 dark:border-white/10 group-hover:scale-105 transition-transform duration-300">
|
||||
<ProviderIcon
|
||||
icon={provider.icon}
|
||||
name={provider.name}
|
||||
@@ -207,14 +163,6 @@ export function ProviderCard({
|
||||
<h3 className="text-base font-semibold leading-none">
|
||||
{provider.name}
|
||||
</h3>
|
||||
|
||||
{/* 健康状态徽章和优先级 */}
|
||||
{isProxyRunning && health && (
|
||||
<ProviderHealthBadge
|
||||
consecutiveFailures={health.consecutive_failures}
|
||||
/>
|
||||
)}
|
||||
|
||||
{provider.category === "third_party" &&
|
||||
provider.meta?.isPartner && (
|
||||
<span
|
||||
@@ -226,6 +174,44 @@ export function ProviderCard({
|
||||
⭐
|
||||
</span>
|
||||
)}
|
||||
|
||||
{/* 代理目标开关 - 仅在代理服务运行时显示 */}
|
||||
{isProxyRunning && (
|
||||
<div
|
||||
className="flex items-center gap-2 ml-2"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Switch
|
||||
id={`proxy-target-switch-${provider.id}`}
|
||||
checked={provider.isProxyTarget || false}
|
||||
onCheckedChange={(checked) => {
|
||||
if (checked && !provider.isProxyTarget) {
|
||||
onSetProxyTarget(provider);
|
||||
}
|
||||
}}
|
||||
disabled={provider.isProxyTarget}
|
||||
className="scale-75 data-[state=checked]:bg-purple-500"
|
||||
/>
|
||||
{provider.isProxyTarget && (
|
||||
<Label
|
||||
htmlFor={`proxy-target-switch-${provider.id}`}
|
||||
className="text-xs font-medium text-purple-500 dark:text-purple-400 cursor-pointer"
|
||||
>
|
||||
{t("provider.proxyTarget", { defaultValue: "代理目标" })}
|
||||
</Label>
|
||||
)}
|
||||
{!provider.isProxyTarget && (
|
||||
<Label
|
||||
htmlFor={`proxy-target-switch-${provider.id}`}
|
||||
className="text-xs text-muted-foreground cursor-pointer opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
>
|
||||
{t("provider.setAsProxyTarget", {
|
||||
defaultValue: "设为代理",
|
||||
})}
|
||||
</Label>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{displayUrl && (
|
||||
@@ -248,7 +234,7 @@ export function ProviderCard({
|
||||
</div>
|
||||
|
||||
<div className="relative flex items-center ml-auto">
|
||||
<div className="ml-auto transition-transform duration-300 ease-out group-hover:-translate-x-[14.5rem] group-focus-within:-translate-x-[14.5rem] sm:group-hover:-translate-x-[16.5rem] sm:group-focus-within:-translate-x-[16.5rem]">
|
||||
<div className="ml-auto transition-transform duration-200 group-hover:-translate-x-[12.25rem] group-focus-within:-translate-x-[12.25rem] sm:group-hover:-translate-x-[14.25rem] sm:group-focus-within:-translate-x-[14.25rem]">
|
||||
<UsageFooter
|
||||
provider={provider}
|
||||
providerId={provider.id}
|
||||
@@ -259,24 +245,16 @@ export function ProviderCard({
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="absolute right-0 top-1/2 -translate-y-1/2 flex items-center gap-1.5 opacity-0 pointer-events-none group-hover:opacity-100 group-focus-within:opacity-100 group-hover:pointer-events-auto group-focus-within:pointer-events-auto transition-all duration-300 ease-out translate-x-2 group-hover:translate-x-0 group-focus-within:translate-x-0">
|
||||
<div className="absolute right-0 top-1/2 -translate-y-1/2 flex items-center gap-1.5 opacity-0 pointer-events-none group-hover:opacity-100 group-focus-within:opacity-100 group-hover:pointer-events-auto group-focus-within:pointer-events-auto transition-all duration-200 translate-x-2 group-hover:translate-x-0 group-focus-within:translate-x-0">
|
||||
<ProviderActions
|
||||
isCurrent={isCurrent}
|
||||
isTesting={isTesting}
|
||||
isProxyTakeover={isProxyTakeover}
|
||||
onSwitch={() => onSwitch(provider)}
|
||||
onEdit={() => onEdit(provider)}
|
||||
onDuplicate={() => onDuplicate(provider)}
|
||||
onTest={onTest ? () => onTest(provider) : undefined}
|
||||
onConfigureUsage={() => onConfigureUsage(provider)}
|
||||
onDelete={() => onDelete(provider)}
|
||||
onResetCircuitBreaker={
|
||||
isProxyRunning && provider.isProxyTarget
|
||||
? handleResetCircuitBreaker
|
||||
: undefined
|
||||
}
|
||||
isProxyTarget={provider.isProxyTarget}
|
||||
consecutiveFailures={health?.consecutive_failures ?? 0}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -10,7 +10,7 @@ export function ProviderEmptyState({ onCreate }: ProviderEmptyStateProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center rounded-lg border border-dashed border-border p-10 text-center">
|
||||
<div className="flex flex-col items-center justify-center rounded-lg border border-dashed border-muted-foreground/30 p-10 text-center">
|
||||
<div className="mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-muted">
|
||||
<Users className="h-7 w-7 text-muted-foreground" />
|
||||
</div>
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
import { ProviderHealthStatus } from "@/types/proxy";
|
||||
|
||||
interface ProviderHealthBadgeProps {
|
||||
consecutiveFailures: number;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 供应商健康状态徽章
|
||||
* 根据连续失败次数显示不同颜色的状态指示器
|
||||
*/
|
||||
export function ProviderHealthBadge({
|
||||
consecutiveFailures,
|
||||
className,
|
||||
}: ProviderHealthBadgeProps) {
|
||||
// 根据失败次数计算状态
|
||||
const getStatus = () => {
|
||||
if (consecutiveFailures === 0) {
|
||||
return {
|
||||
label: "正常",
|
||||
status: ProviderHealthStatus.Healthy,
|
||||
color: "bg-green-500",
|
||||
// 使用更深/柔和的背景色,去除可能的白色内容感
|
||||
bgColor: "bg-green-500/10",
|
||||
textColor: "text-green-600 dark:text-green-400",
|
||||
};
|
||||
} else if (consecutiveFailures < 5) {
|
||||
return {
|
||||
label: "降级",
|
||||
status: ProviderHealthStatus.Degraded,
|
||||
color: "bg-yellow-500",
|
||||
bgColor: "bg-yellow-500/10",
|
||||
textColor: "text-yellow-600 dark:text-yellow-400",
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
label: "熔断",
|
||||
status: ProviderHealthStatus.Failed,
|
||||
color: "bg-red-500",
|
||||
bgColor: "bg-red-500/10",
|
||||
textColor: "text-red-600 dark:text-red-400",
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const statusConfig = getStatus();
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-xs font-medium",
|
||||
statusConfig.bgColor,
|
||||
statusConfig.textColor,
|
||||
className,
|
||||
)}
|
||||
title={`连续失败 ${consecutiveFailures} 次`}
|
||||
>
|
||||
<div className={cn("w-2 h-2 rounded-full", statusConfig.color)} />
|
||||
<span>{statusConfig.label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -9,7 +9,8 @@ import type { CSSProperties } from "react";
|
||||
import type { Provider } from "@/types";
|
||||
import type { AppId } from "@/lib/api";
|
||||
import { useDragSort } from "@/hooks/useDragSort";
|
||||
import { useStreamCheck } from "@/hooks/useStreamCheck";
|
||||
import { useProxyStatus } from "@/hooks/useProxyStatus";
|
||||
import { useModelTest } from "@/hooks/useModelTest";
|
||||
import { ProviderCard } from "@/components/providers/ProviderCard";
|
||||
import { ProviderEmptyState } from "@/components/providers/ProviderEmptyState";
|
||||
|
||||
@@ -25,8 +26,7 @@ interface ProviderListProps {
|
||||
onOpenWebsite: (url: string) => void;
|
||||
onCreate?: () => void;
|
||||
isLoading?: boolean;
|
||||
isProxyRunning?: boolean; // 代理服务运行状态
|
||||
isProxyTakeover?: boolean; // 代理接管模式(Live配置已被接管)
|
||||
onSetProxyTarget: (provider: Provider) => void;
|
||||
}
|
||||
|
||||
export function ProviderList({
|
||||
@@ -41,19 +41,21 @@ export function ProviderList({
|
||||
onOpenWebsite,
|
||||
onCreate,
|
||||
isLoading = false,
|
||||
isProxyRunning = false, // 默认值为 false
|
||||
isProxyTakeover = false, // 默认值为 false
|
||||
onSetProxyTarget,
|
||||
}: ProviderListProps) {
|
||||
const { sortedProviders, sensors, handleDragEnd } = useDragSort(
|
||||
providers,
|
||||
appId,
|
||||
);
|
||||
|
||||
// 流式健康检查
|
||||
const { checkProvider, isChecking } = useStreamCheck(appId);
|
||||
// 获取代理服务运行状态
|
||||
const { isRunning: isProxyRunning } = useProxyStatus();
|
||||
|
||||
// 模型测试
|
||||
const { testProvider, isTesting } = useModelTest(appId);
|
||||
|
||||
const handleTest = (provider: Provider) => {
|
||||
checkProvider(provider.id, provider.name);
|
||||
testProvider(provider.id, provider.name);
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
@@ -100,9 +102,9 @@ export function ProviderList({
|
||||
onConfigureUsage={onConfigureUsage}
|
||||
onOpenWebsite={onOpenWebsite}
|
||||
onTest={handleTest}
|
||||
isTesting={isChecking(provider.id)}
|
||||
isTesting={isTesting(provider.id)}
|
||||
onSetProxyTarget={onSetProxyTarget}
|
||||
isProxyRunning={isProxyRunning}
|
||||
isProxyTakeover={isProxyTakeover}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -123,8 +125,8 @@ interface SortableProviderCardProps {
|
||||
onOpenWebsite: (url: string) => void;
|
||||
onTest: (provider: Provider) => void;
|
||||
isTesting: boolean;
|
||||
onSetProxyTarget: (provider: Provider) => void;
|
||||
isProxyRunning: boolean;
|
||||
isProxyTakeover: boolean;
|
||||
}
|
||||
|
||||
function SortableProviderCard({
|
||||
@@ -139,8 +141,8 @@ function SortableProviderCard({
|
||||
onOpenWebsite,
|
||||
onTest,
|
||||
isTesting,
|
||||
onSetProxyTarget,
|
||||
isProxyRunning,
|
||||
isProxyTakeover,
|
||||
}: SortableProviderCardProps) {
|
||||
const {
|
||||
setNodeRef,
|
||||
@@ -172,8 +174,8 @@ function SortableProviderCard({
|
||||
onOpenWebsite={onOpenWebsite}
|
||||
onTest={onTest}
|
||||
isTesting={isTesting}
|
||||
onSetProxyTarget={onSetProxyTarget}
|
||||
isProxyRunning={isProxyRunning}
|
||||
isProxyTakeover={isProxyTakeover}
|
||||
dragHandleProps={{
|
||||
attributes,
|
||||
listeners,
|
||||
|
||||
@@ -51,7 +51,7 @@ export function BasicFormFields({ form }: BasicFormFieldsProps) {
|
||||
<DialogTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="w-20 h-20 p-3 rounded-xl border-2 border-muted hover:border-primary transition-colors cursor-pointer bg-muted/30 hover:bg-muted/50 flex items-center justify-center"
|
||||
className="w-20 h-20 p-3 rounded-xl border-2 border-gray-300 dark:border-gray-600 hover:border-primary dark:hover:border-primary transition-colors cursor-pointer bg-gray-50 dark:bg-gray-800/50 flex items-center justify-center"
|
||||
title={currentIcon ? "点击更换图标" : "点击选择图标"}
|
||||
>
|
||||
<ProviderIcon
|
||||
|
||||
@@ -559,7 +559,7 @@ const EndpointSpeedTest: React.FC<EndpointSpeedTestProps> = ({
|
||||
<div
|
||||
key={entry.id}
|
||||
onClick={() => handleSelect(entry.url)}
|
||||
className={`group flex cursor-pointer items-center justify-between px-3 py-2.5 rounded-lg border transition text-foreground ${
|
||||
className={`group flex cursor-pointer items-center justify-between px-3 py-2.5 rounded-lg border transition ${
|
||||
isSelected
|
||||
? "border-primary/70 bg-primary/5 shadow-sm"
|
||||
: "border-border-default bg-background hover:bg-muted"
|
||||
@@ -577,7 +577,7 @@ const EndpointSpeedTest: React.FC<EndpointSpeedTestProps> = ({
|
||||
|
||||
{/* 内容 */}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm text-foreground">
|
||||
<div className="truncate text-sm text-gray-900 dark:text-gray-100">
|
||||
{entry.url}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,339 +0,0 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Save, Loader2, Info } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
useCircuitBreakerConfig,
|
||||
useUpdateCircuitBreakerConfig,
|
||||
} from "@/lib/query/failover";
|
||||
|
||||
export interface AutoFailoverConfigPanelProps {
|
||||
enabled: boolean;
|
||||
onEnabledChange: (enabled: boolean) => void;
|
||||
}
|
||||
|
||||
export function AutoFailoverConfigPanel({
|
||||
enabled,
|
||||
onEnabledChange: _onEnabledChange,
|
||||
}: AutoFailoverConfigPanelProps) {
|
||||
// Note: onEnabledChange is currently unused but kept in the interface
|
||||
// for potential future use by parent components
|
||||
void _onEnabledChange;
|
||||
const { t } = useTranslation();
|
||||
const { data: config, isLoading, error } = useCircuitBreakerConfig();
|
||||
const updateConfig = useUpdateCircuitBreakerConfig();
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
failureThreshold: 5,
|
||||
successThreshold: 2,
|
||||
timeoutSeconds: 60,
|
||||
errorRateThreshold: 0.5,
|
||||
minRequests: 10,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (config) {
|
||||
setFormData({
|
||||
...config,
|
||||
});
|
||||
}
|
||||
}, [config]);
|
||||
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
await updateConfig.mutateAsync({
|
||||
failureThreshold: formData.failureThreshold,
|
||||
successThreshold: formData.successThreshold,
|
||||
timeoutSeconds: formData.timeoutSeconds,
|
||||
errorRateThreshold: formData.errorRateThreshold,
|
||||
minRequests: formData.minRequests,
|
||||
});
|
||||
toast.success(
|
||||
t("proxy.autoFailover.configSaved", "自动故障转移配置已保存"),
|
||||
);
|
||||
} catch (e) {
|
||||
toast.error(
|
||||
t("proxy.autoFailover.configSaveFailed", "保存失败") + ": " + String(e),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
if (config) {
|
||||
setFormData({
|
||||
...config,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-4">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="border-0 rounded-none shadow-none bg-transparent">
|
||||
{/* Header Switch moved to parent accordion logic or kept here absolutely positioned if styling permits.
|
||||
Since we need it in the accordion header, and this component is inside the content, we can use a portal or
|
||||
absolute positioning trick similar to ProxyPanel, OR cleaner, just duplicate the switch logic in SettingsPage
|
||||
and pass it down. But for now, let's use the absolute positioning trick to "lift" it visually.
|
||||
Better yet, let's just render the content directly without the wrapping Card header/collapse logic
|
||||
since the user requested "click to expand is detailed info, no need to fold again" (implying the accordion handles folding).
|
||||
*/}
|
||||
|
||||
<div className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{String(error)}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Alert className="border-blue-500/40 bg-blue-500/10">
|
||||
<Info className="h-4 w-4" />
|
||||
<AlertDescription className="text-sm">
|
||||
{t(
|
||||
"proxy.autoFailover.info",
|
||||
"当启用多个代理目标时,系统会按优先级顺序依次尝试。当某个供应商连续失败达到阈值时,熔断器会自动打开,跳过该供应商。",
|
||||
)}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
{/* 重试与超时配置 */}
|
||||
<div className="space-y-4 rounded-lg border border-white/10 bg-muted/30 p-4">
|
||||
<h4 className="text-sm font-semibold">
|
||||
{t("proxy.autoFailover.retrySettings", "重试与超时设置")}
|
||||
</h4>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="failureThreshold">
|
||||
{t("proxy.autoFailover.failureThreshold", "失败阈值")}
|
||||
</Label>
|
||||
<Input
|
||||
id="failureThreshold"
|
||||
type="number"
|
||||
min="1"
|
||||
max="20"
|
||||
value={formData.failureThreshold}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
failureThreshold: parseInt(e.target.value) || 5,
|
||||
})
|
||||
}
|
||||
disabled={!enabled}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
"proxy.autoFailover.failureThresholdHint",
|
||||
"连续失败多少次后打开熔断器(建议: 3-10)",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="timeoutSeconds">
|
||||
{t("proxy.autoFailover.timeout", "恢复等待时间(秒)")}
|
||||
</Label>
|
||||
<Input
|
||||
id="timeoutSeconds"
|
||||
type="number"
|
||||
min="10"
|
||||
max="300"
|
||||
value={formData.timeoutSeconds}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
timeoutSeconds: parseInt(e.target.value) || 60,
|
||||
})
|
||||
}
|
||||
disabled={!enabled}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
"proxy.autoFailover.timeoutHint",
|
||||
"熔断器打开后,等待多久后尝试恢复(建议: 30-120)",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 熔断器高级配置 */}
|
||||
<div className="space-y-4 rounded-lg border border-white/10 bg-muted/30 p-4">
|
||||
<h4 className="text-sm font-semibold">
|
||||
{t("proxy.autoFailover.circuitBreakerSettings", "熔断器高级设置")}
|
||||
</h4>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="successThreshold">
|
||||
{t("proxy.autoFailover.successThreshold", "恢复成功阈值")}
|
||||
</Label>
|
||||
<Input
|
||||
id="successThreshold"
|
||||
type="number"
|
||||
min="1"
|
||||
max="10"
|
||||
value={formData.successThreshold}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
successThreshold: parseInt(e.target.value) || 2,
|
||||
})
|
||||
}
|
||||
disabled={!enabled}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
"proxy.autoFailover.successThresholdHint",
|
||||
"半开状态下成功多少次后关闭熔断器",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="errorRateThreshold">
|
||||
{t("proxy.autoFailover.errorRate", "错误率阈值 (%)")}
|
||||
</Label>
|
||||
<Input
|
||||
id="errorRateThreshold"
|
||||
type="number"
|
||||
min="0"
|
||||
max="100"
|
||||
step="5"
|
||||
value={Math.round(formData.errorRateThreshold * 100)}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
errorRateThreshold: (parseInt(e.target.value) || 50) / 100,
|
||||
})
|
||||
}
|
||||
disabled={!enabled}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
"proxy.autoFailover.errorRateHint",
|
||||
"错误率超过此值时打开熔断器",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="minRequests">
|
||||
{t("proxy.autoFailover.minRequests", "最小请求数")}
|
||||
</Label>
|
||||
<Input
|
||||
id="minRequests"
|
||||
type="number"
|
||||
min="5"
|
||||
max="100"
|
||||
value={formData.minRequests}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
minRequests: parseInt(e.target.value) || 10,
|
||||
})
|
||||
}
|
||||
disabled={!enabled}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
"proxy.autoFailover.minRequestsHint",
|
||||
"计算错误率前的最小请求数",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 操作按钮 */}
|
||||
<div className="flex justify-end gap-3 pt-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleReset}
|
||||
disabled={updateConfig.isPending || !enabled}
|
||||
>
|
||||
{t("common.reset", "重置")}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
disabled={updateConfig.isPending || !enabled}
|
||||
>
|
||||
{updateConfig.isPending ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t("common.saving", "保存中...")}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
{t("common.save", "保存")}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 说明信息 */}
|
||||
<div className="p-4 bg-muted/50 rounded-lg space-y-2 text-sm">
|
||||
<h4 className="font-medium">
|
||||
{t("proxy.autoFailover.explanationTitle", "工作原理")}
|
||||
</h4>
|
||||
<ul className="space-y-1 text-muted-foreground">
|
||||
<li>
|
||||
•{" "}
|
||||
<strong>
|
||||
{t("proxy.autoFailover.failureThresholdLabel", "失败阈值")}
|
||||
</strong>
|
||||
:
|
||||
{t(
|
||||
"proxy.autoFailover.failureThresholdExplain",
|
||||
"连续失败达到此次数时,熔断器打开,该供应商暂时不可用",
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
•{" "}
|
||||
<strong>
|
||||
{t("proxy.autoFailover.timeoutLabel", "恢复等待时间")}
|
||||
</strong>
|
||||
:
|
||||
{t(
|
||||
"proxy.autoFailover.timeoutExplain",
|
||||
"熔断器打开后,等待此时间后尝试半开状态",
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
•{" "}
|
||||
<strong>
|
||||
{t("proxy.autoFailover.successThresholdLabel", "恢复成功阈值")}
|
||||
</strong>
|
||||
:
|
||||
{t(
|
||||
"proxy.autoFailover.successThresholdExplain",
|
||||
"半开状态下,成功达到此次数时关闭熔断器,供应商恢复可用",
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
•{" "}
|
||||
<strong>
|
||||
{t("proxy.autoFailover.errorRateLabel", "错误率阈值")}
|
||||
</strong>
|
||||
:
|
||||
{t(
|
||||
"proxy.autoFailover.errorRateExplain",
|
||||
"错误率超过此值时,即使未达到失败阈值也会打开熔断器",
|
||||
)}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,208 +0,0 @@
|
||||
import {
|
||||
useCircuitBreakerConfig,
|
||||
useUpdateCircuitBreakerConfig,
|
||||
} from "@/lib/query/failover";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useState, useEffect } from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
/**
|
||||
* 熔断器配置面板
|
||||
* 允许用户调整熔断器参数
|
||||
*/
|
||||
export function CircuitBreakerConfigPanel() {
|
||||
const { data: config, isLoading } = useCircuitBreakerConfig();
|
||||
const updateConfig = useUpdateCircuitBreakerConfig();
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
failureThreshold: 5,
|
||||
successThreshold: 2,
|
||||
timeoutSeconds: 60,
|
||||
errorRateThreshold: 0.5,
|
||||
minRequests: 10,
|
||||
});
|
||||
|
||||
// 当配置加载完成时更新表单数据
|
||||
useEffect(() => {
|
||||
if (config) {
|
||||
setFormData(config);
|
||||
}
|
||||
}, [config]);
|
||||
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
await updateConfig.mutateAsync(formData);
|
||||
toast.success("熔断器配置已保存");
|
||||
} catch (error) {
|
||||
toast.error("保存失败: " + String(error));
|
||||
}
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
if (config) {
|
||||
setFormData(config);
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return <div className="text-sm text-muted-foreground">加载中...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold">熔断器配置</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
调整熔断器参数以控制故障检测和恢复行为
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="h-px bg-border my-4" />
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
{/* 失败阈值 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="failureThreshold">失败阈值</Label>
|
||||
<Input
|
||||
id="failureThreshold"
|
||||
type="number"
|
||||
min="1"
|
||||
max="20"
|
||||
value={formData.failureThreshold}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
failureThreshold: parseInt(e.target.value) || 5,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
连续失败多少次后打开熔断器
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 超时时间 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="timeoutSeconds">超时时间(秒)</Label>
|
||||
<Input
|
||||
id="timeoutSeconds"
|
||||
type="number"
|
||||
min="10"
|
||||
max="300"
|
||||
value={formData.timeoutSeconds}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
timeoutSeconds: parseInt(e.target.value) || 60,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
熔断器打开后多久尝试恢复(半开状态)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 成功阈值 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="successThreshold">成功阈值</Label>
|
||||
<Input
|
||||
id="successThreshold"
|
||||
type="number"
|
||||
min="1"
|
||||
max="10"
|
||||
value={formData.successThreshold}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
successThreshold: parseInt(e.target.value) || 2,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
半开状态下成功多少次后关闭熔断器
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 错误率阈值 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="errorRateThreshold">错误率阈值 (%)</Label>
|
||||
<Input
|
||||
id="errorRateThreshold"
|
||||
type="number"
|
||||
min="0"
|
||||
max="100"
|
||||
step="5"
|
||||
value={Math.round(formData.errorRateThreshold * 100)}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
errorRateThreshold: (parseInt(e.target.value) || 50) / 100,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
错误率超过此值时打开熔断器
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 最小请求数 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="minRequests">最小请求数</Label>
|
||||
<Input
|
||||
id="minRequests"
|
||||
type="number"
|
||||
min="5"
|
||||
max="100"
|
||||
value={formData.minRequests}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
minRequests: parseInt(e.target.value) || 10,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
计算错误率前的最小请求数
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3">
|
||||
<Button onClick={handleSave} disabled={updateConfig.isPending}>
|
||||
{updateConfig.isPending ? "保存中..." : "保存配置"}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleReset}
|
||||
disabled={updateConfig.isPending}
|
||||
>
|
||||
重置
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 说明信息 */}
|
||||
<div className="p-4 bg-muted/50 rounded-lg space-y-2 text-sm">
|
||||
<h4 className="font-medium">配置说明</h4>
|
||||
<ul className="space-y-1 text-muted-foreground">
|
||||
<li>
|
||||
• <strong>失败阈值</strong>:连续失败达到此次数时,熔断器打开
|
||||
</li>
|
||||
<li>
|
||||
• <strong>超时时间</strong>:熔断器打开后,等待此时间后尝试半开
|
||||
</li>
|
||||
<li>
|
||||
• <strong>成功阈值</strong>:半开状态下,成功达到此次数时关闭熔断器
|
||||
</li>
|
||||
<li>
|
||||
• <strong>错误率阈值</strong>:错误率超过此值时,熔断器打开
|
||||
</li>
|
||||
<li>
|
||||
• <strong>最小请求数</strong>:只有请求数达到此值后才计算错误率
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,22 +1,27 @@
|
||||
import { useState } from "react";
|
||||
import { Activity, Clock, TrendingUp, Server, ListOrdered } from "lucide-react";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useProxyStatus } from "@/hooks/useProxyStatus";
|
||||
import { Settings, Activity, Clock, TrendingUp, Server } from "lucide-react";
|
||||
import { ProxySettingsDialog } from "./ProxySettingsDialog";
|
||||
import { toast } from "sonner";
|
||||
import { useProxyTargets } from "@/lib/query/failover";
|
||||
import { ProviderHealthBadge } from "@/components/providers/ProviderHealthBadge";
|
||||
import { useProviderHealth } from "@/lib/query/failover";
|
||||
import type { ProxyStatus } from "@/types/proxy";
|
||||
|
||||
export function ProxyPanel() {
|
||||
const { status, isRunning } = useProxyStatus();
|
||||
const { status, isRunning, start, stop, isPending } = useProxyStatus();
|
||||
const [showSettings, setShowSettings] = useState(false);
|
||||
|
||||
// 获取所有三个应用类型的代理目标列表
|
||||
const { data: claudeTargets = [] } = useProxyTargets("claude");
|
||||
const { data: codexTargets = [] } = useProxyTargets("codex");
|
||||
const { data: geminiTargets = [] } = useProxyTargets("gemini");
|
||||
const handleToggle = async () => {
|
||||
try {
|
||||
if (isRunning) {
|
||||
await stop();
|
||||
} else {
|
||||
await start();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Toggle proxy failed:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const formatUptime = (seconds: number): string => {
|
||||
const hours = Math.floor(seconds / 3600);
|
||||
@@ -34,12 +39,58 @@ export function ProxyPanel() {
|
||||
|
||||
return (
|
||||
<>
|
||||
<section className="space-y-6">
|
||||
<section className="space-y-6 rounded-xl border border-white/10 glass-card p-6">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 rounded-lg bg-primary/10 text-primary">
|
||||
<Server className="h-5 w-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-base font-semibold text-foreground">
|
||||
本地代理服务
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{isRunning
|
||||
? `运行中 · ${status?.address}:${status?.port}`
|
||||
: "已停止"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge
|
||||
variant={isRunning ? "default" : "secondary"}
|
||||
className="gap-1.5"
|
||||
>
|
||||
<Activity
|
||||
className={`h-3 w-3 ${isRunning ? "animate-pulse" : ""}`}
|
||||
/>
|
||||
{isRunning ? "运行中" : "已停止"}
|
||||
</Badge>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setShowSettings(true)}
|
||||
disabled={isPending}
|
||||
aria-label="打开代理设置"
|
||||
>
|
||||
<Settings className="h-4 w-4" />
|
||||
</Button>
|
||||
<Switch
|
||||
checked={isRunning}
|
||||
onCheckedChange={handleToggle}
|
||||
disabled={isPending}
|
||||
aria-label={isRunning ? "停止代理服务" : "启动代理服务"}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isRunning && status ? (
|
||||
<div className="space-y-6">
|
||||
<div className="rounded-lg border border-border bg-muted/40 p-4 space-y-4">
|
||||
<div className="rounded-lg border border-white/10 bg-muted/40 p-4 space-y-4">
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">服务地址</p>
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
|
||||
服务地址
|
||||
</p>
|
||||
<div className="mt-2 flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<code className="flex-1 text-sm bg-background px-3 py-2 rounded border border-border/60">
|
||||
http://{status.address}:{status.port}
|
||||
@@ -59,14 +110,16 @@ export function ProxyPanel() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-3 border-t border-border space-y-2">
|
||||
<p className="text-xs text-muted-foreground">使用中</p>
|
||||
<div className="pt-3 border-t border-white/10 space-y-2">
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
|
||||
当前代理
|
||||
</p>
|
||||
{status.active_targets && status.active_targets.length > 0 ? (
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{status.active_targets.map((target) => (
|
||||
<div
|
||||
key={target.app_type}
|
||||
className="flex items-center justify-between rounded-md border border-border bg-background/60 px-2 py-1.5 text-xs"
|
||||
className="flex items-center justify-between rounded-md border border-white/10 bg-background/60 px-2 py-1.5 text-xs"
|
||||
>
|
||||
<span className="text-muted-foreground">
|
||||
{target.app_type}
|
||||
@@ -93,50 +146,6 @@ export function ProxyPanel() {
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 供应商队列 - 按应用类型分组展示 */}
|
||||
{(claudeTargets.length > 0 ||
|
||||
codexTargets.length > 0 ||
|
||||
geminiTargets.length > 0) && (
|
||||
<div className="pt-3 border-t border-border space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<ListOrdered className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<p className="text-xs text-muted-foreground">
|
||||
故障转移队列
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Claude 队列 */}
|
||||
{claudeTargets.length > 0 && (
|
||||
<ProviderQueueGroup
|
||||
appType="claude"
|
||||
appLabel="Claude"
|
||||
targets={claudeTargets}
|
||||
status={status}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Codex 队列 */}
|
||||
{codexTargets.length > 0 && (
|
||||
<ProviderQueueGroup
|
||||
appType="codex"
|
||||
appLabel="Codex"
|
||||
targets={codexTargets}
|
||||
status={status}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Gemini 队列 */}
|
||||
{geminiTargets.length > 0 && (
|
||||
<ProviderQueueGroup
|
||||
appType="gemini"
|
||||
appLabel="Gemini"
|
||||
targets={geminiTargets}
|
||||
status={status}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 md:grid-cols-4">
|
||||
@@ -199,113 +208,15 @@ function StatCard({ icon, label, value, variant = "default" }: StatCardProps) {
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`rounded-lg border border-border bg-card/60 p-4 text-sm text-muted-foreground ${variantStyles[variant]}`}
|
||||
className={`rounded-lg border border-white/10 bg-white/70 p-4 text-sm text-muted-foreground dark:bg-white/5 ${variantStyles[variant]}`}
|
||||
>
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-2">
|
||||
{icon}
|
||||
<span className="text-xs">{label}</span>
|
||||
<span className="text-xs font-medium uppercase tracking-wide">
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-xl font-semibold text-foreground">{value}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ProviderQueueGroupProps {
|
||||
appType: string;
|
||||
appLabel: string;
|
||||
targets: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
}>;
|
||||
status: ProxyStatus;
|
||||
}
|
||||
|
||||
function ProviderQueueGroup({
|
||||
appType,
|
||||
appLabel,
|
||||
targets,
|
||||
status,
|
||||
}: ProviderQueueGroupProps) {
|
||||
// 查找该应用类型的当前活跃目标
|
||||
const activeTarget = status.active_targets?.find(
|
||||
(t) => t.app_type === appType,
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{/* 应用类型标题 */}
|
||||
<div className="flex items-center gap-2 px-2">
|
||||
<span className="text-xs font-semibold text-foreground/80">
|
||||
{appLabel}
|
||||
</span>
|
||||
<div className="flex-1 h-px bg-border/50" />
|
||||
</div>
|
||||
|
||||
{/* 供应商列表 */}
|
||||
<div className="space-y-1.5">
|
||||
{targets.map((target, index) => (
|
||||
<ProviderQueueItem
|
||||
key={target.id}
|
||||
provider={target}
|
||||
priority={index + 1}
|
||||
appType={appType}
|
||||
isCurrent={activeTarget?.provider_id === target.id}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ProviderQueueItemProps {
|
||||
provider: {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
priority: number;
|
||||
appType: string;
|
||||
isCurrent: boolean;
|
||||
}
|
||||
|
||||
function ProviderQueueItem({
|
||||
provider,
|
||||
priority,
|
||||
appType,
|
||||
isCurrent,
|
||||
}: ProviderQueueItemProps) {
|
||||
const { data: health } = useProviderHealth(provider.id, appType);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`flex items-center justify-between rounded-md border px-3 py-2 text-sm transition-colors ${
|
||||
isCurrent
|
||||
? "border-primary/40 bg-primary/10 text-primary font-medium"
|
||||
: "border-border bg-background/60"
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<span
|
||||
className={`flex-shrink-0 flex items-center justify-center w-5 h-5 rounded-full text-xs font-bold ${
|
||||
isCurrent
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-muted text-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
{priority}
|
||||
</span>
|
||||
<span className={isCurrent ? "" : "text-foreground"}>
|
||||
{provider.name}
|
||||
</span>
|
||||
{isCurrent && (
|
||||
<span className="text-xs px-1.5 py-0.5 rounded bg-primary/20 text-primary">
|
||||
使用中
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{/* 健康徽章 */}
|
||||
<ProviderHealthBadge
|
||||
consecutiveFailures={health?.consecutive_failures ?? 0}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
/**
|
||||
* 代理模式切换开关组件
|
||||
*
|
||||
* 放置在主界面头部,用于一键启用/关闭代理模式
|
||||
* 启用时自动接管 Live 配置,关闭时恢复原始配置
|
||||
*/
|
||||
|
||||
import { Radio, Loader2 } from "lucide-react";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { useProxyStatus } from "@/hooks/useProxyStatus";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface ProxyToggleProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ProxyToggle({ className }: ProxyToggleProps) {
|
||||
const {
|
||||
isRunning,
|
||||
isTakeoverActive,
|
||||
startWithTakeover,
|
||||
stopWithRestore,
|
||||
isPending,
|
||||
status,
|
||||
} = useProxyStatus();
|
||||
|
||||
const handleToggle = async (checked: boolean) => {
|
||||
if (checked) {
|
||||
await startWithTakeover();
|
||||
} else {
|
||||
await stopWithRestore();
|
||||
}
|
||||
};
|
||||
|
||||
const isActive = isRunning && isTakeoverActive;
|
||||
|
||||
const tooltipText = isActive
|
||||
? `代理模式运行中 - ${status?.address}:${status?.port}\n切换供应商为热切换`
|
||||
: "开启代理模式\n启用后自动接管 Live 配置";
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-2 px-3 py-1.5 rounded-lg transition-all cursor-default",
|
||||
isActive
|
||||
? "bg-emerald-500/10 border border-emerald-500/30"
|
||||
: "bg-muted/50 hover:bg-muted",
|
||||
className,
|
||||
)}
|
||||
title={tooltipText}
|
||||
>
|
||||
{isPending ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : (
|
||||
<Radio
|
||||
className={cn(
|
||||
"h-4 w-4 transition-colors",
|
||||
isActive
|
||||
? "text-emerald-500 animate-pulse"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<span
|
||||
className={cn(
|
||||
"text-sm font-medium transition-colors select-none",
|
||||
isActive
|
||||
? "text-emerald-600 dark:text-emerald-400"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
Proxy
|
||||
</span>
|
||||
<Switch
|
||||
checked={isActive}
|
||||
onCheckedChange={handleToggle}
|
||||
disabled={isPending}
|
||||
className="ml-1"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +1,5 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import {
|
||||
Download,
|
||||
ExternalLink,
|
||||
Info,
|
||||
Loader2,
|
||||
RefreshCw,
|
||||
Terminal,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
} from "lucide-react";
|
||||
import { Download, ExternalLink, Info, Loader2, RefreshCw } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
@@ -16,27 +7,16 @@ import { getVersion } from "@tauri-apps/api/app";
|
||||
import { settingsApi } from "@/lib/api";
|
||||
import { useUpdate } from "@/contexts/UpdateContext";
|
||||
import { relaunchApp } from "@/lib/updater";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
interface AboutSectionProps {
|
||||
isPortable: boolean;
|
||||
}
|
||||
|
||||
interface ToolVersion {
|
||||
name: string;
|
||||
version: string | null;
|
||||
latest_version: string | null;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export function AboutSection({ isPortable }: AboutSectionProps) {
|
||||
// ... (use hooks as before) ...
|
||||
const { t } = useTranslation();
|
||||
const [version, setVersion] = useState<string | null>(null);
|
||||
const [isLoadingVersion, setIsLoadingVersion] = useState(true);
|
||||
const [isDownloading, setIsDownloading] = useState(false);
|
||||
const [toolVersions, setToolVersions] = useState<ToolVersion[]>([]);
|
||||
const [isLoadingTools, setIsLoadingTools] = useState(true);
|
||||
|
||||
const {
|
||||
hasUpdate,
|
||||
@@ -51,24 +31,18 @@ export function AboutSection({ isPortable }: AboutSectionProps) {
|
||||
let active = true;
|
||||
const load = async () => {
|
||||
try {
|
||||
const [appVersion, tools] = await Promise.all([
|
||||
getVersion(),
|
||||
settingsApi.getToolVersions(),
|
||||
]);
|
||||
|
||||
const loaded = await getVersion();
|
||||
if (active) {
|
||||
setVersion(appVersion);
|
||||
setToolVersions(tools);
|
||||
setVersion(loaded);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[AboutSection] Failed to load info", error);
|
||||
console.error("[AboutSection] Failed to get version", error);
|
||||
if (active) {
|
||||
setVersion(null);
|
||||
}
|
||||
} finally {
|
||||
if (active) {
|
||||
setIsLoadingVersion(false);
|
||||
setIsLoadingTools(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -79,8 +53,6 @@ export function AboutSection({ isPortable }: AboutSectionProps) {
|
||||
};
|
||||
}, []);
|
||||
|
||||
// ... (handlers like handleOpenReleaseNotes, handleCheckUpdate) ...
|
||||
|
||||
const handleOpenReleaseNotes = useCallback(async () => {
|
||||
try {
|
||||
const targetVersion = updateInfo?.availableVersion ?? version ?? "";
|
||||
@@ -153,7 +125,7 @@ export function AboutSection({ isPortable }: AboutSectionProps) {
|
||||
const displayVersion = version ?? t("common.unknown");
|
||||
|
||||
return (
|
||||
<section className="space-y-6">
|
||||
<section className="space-y-4">
|
||||
<header className="space-y-1">
|
||||
<h3 className="text-sm font-medium">{t("common.about")}</h3>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
@@ -161,28 +133,24 @@ export function AboutSection({ isPortable }: AboutSectionProps) {
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div className="rounded-xl border border-border bg-card/50 p-6 space-y-6">
|
||||
<div className="space-y-4 rounded-lg border border-border-default p-4">
|
||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-lg font-semibold text-foreground">CC Switch</h4>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="outline" className="gap-1.5 bg-background">
|
||||
<span className="text-muted-foreground">
|
||||
{t("common.version")}
|
||||
</span>
|
||||
{isLoadingVersion ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<span className="font-medium">{`v${displayVersion}`}</span>
|
||||
)}
|
||||
</Badge>
|
||||
{isPortable && (
|
||||
<Badge variant="secondary" className="gap-1.5">
|
||||
<Info className="h-3 w-3" />
|
||||
{t("settings.portableMode")}
|
||||
</Badge>
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium text-foreground">CC Switch</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("common.version")}{" "}
|
||||
{isLoadingVersion ? (
|
||||
<Loader2 className="inline h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
`v${displayVersion}`
|
||||
)}
|
||||
</div>
|
||||
</p>
|
||||
{isPortable ? (
|
||||
<p className="inline-flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<Info className="h-3 w-3" />
|
||||
{t("settings.portableMode")}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
@@ -191,7 +159,6 @@ export function AboutSection({ isPortable }: AboutSectionProps) {
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleOpenReleaseNotes}
|
||||
className="h-9"
|
||||
>
|
||||
<ExternalLink className="mr-2 h-4 w-4" />
|
||||
{t("settings.releaseNotes")}
|
||||
@@ -201,7 +168,7 @@ export function AboutSection({ isPortable }: AboutSectionProps) {
|
||||
size="sm"
|
||||
onClick={handleCheckUpdate}
|
||||
disabled={isChecking || isDownloading}
|
||||
className="min-w-[140px] h-9"
|
||||
className="min-w-[140px]"
|
||||
>
|
||||
{isDownloading ? (
|
||||
<span className="inline-flex items-center gap-2">
|
||||
@@ -227,71 +194,18 @@ export function AboutSection({ isPortable }: AboutSectionProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hasUpdate && updateInfo && (
|
||||
<div className="rounded-lg bg-primary/10 border border-primary/20 px-4 py-3 text-sm">
|
||||
<p className="font-medium text-primary mb-1">
|
||||
{hasUpdate && updateInfo ? (
|
||||
<div className="rounded-md bg-muted/40 px-3 py-2 text-xs text-muted-foreground">
|
||||
<p>
|
||||
{t("settings.updateAvailable", {
|
||||
version: updateInfo.availableVersion,
|
||||
})}
|
||||
</p>
|
||||
{updateInfo.notes && (
|
||||
<p className="text-muted-foreground line-clamp-3 leading-relaxed">
|
||||
{updateInfo.notes}
|
||||
</p>
|
||||
)}
|
||||
{updateInfo.notes ? (
|
||||
<p className="mt-1 line-clamp-3">{updateInfo.notes}</p>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<h4 className="text-sm font-medium text-muted-foreground px-1">
|
||||
本地环境检查
|
||||
</h4>
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
{isLoadingTools
|
||||
? Array.from({ length: 3 }).map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="h-20 rounded-xl border border-border bg-card/50 animate-pulse"
|
||||
/>
|
||||
))
|
||||
: toolVersions.map((tool) => (
|
||||
<div
|
||||
key={tool.name}
|
||||
className="flex flex-col gap-2 rounded-xl border border-border bg-card/50 p-4 transition-colors hover:bg-muted/50"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Terminal className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-sm font-medium capitalize">
|
||||
{tool.name}
|
||||
</span>
|
||||
</div>
|
||||
{tool.version ? (
|
||||
<div className="flex items-center gap-1.5">
|
||||
{tool.latest_version &&
|
||||
tool.version !== tool.latest_version && (
|
||||
<span className="text-[10px] px-1.5 py-0.5 rounded-full bg-yellow-500/10 text-yellow-600 dark:text-yellow-400 border border-yellow-500/20">
|
||||
Update: {tool.latest_version}
|
||||
</span>
|
||||
)}
|
||||
<CheckCircle2 className="h-4 w-4 text-green-500" />
|
||||
</div>
|
||||
) : (
|
||||
<AlertCircle className="h-4 w-4 text-yellow-500" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<div
|
||||
className="text-xs font-mono truncate"
|
||||
title={tool.version || tool.error || "Unknown"}
|
||||
>
|
||||
{tool.version ? tool.version : tool.error || "未安装"}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -50,7 +50,7 @@ export function DirectorySettings({
|
||||
<Input
|
||||
value={appConfigDir ?? resolvedDirs.appConfig ?? ""}
|
||||
placeholder={t("settings.browsePlaceholderApp")}
|
||||
className="text-xs"
|
||||
className="font-mono text-xs"
|
||||
onChange={(event) => onAppConfigChange(event.target.value)}
|
||||
/>
|
||||
<Button
|
||||
@@ -161,7 +161,7 @@ function DirectoryInput({
|
||||
<Input
|
||||
value={displayValue}
|
||||
placeholder={placeholder}
|
||||
className="text-xs"
|
||||
className="font-mono text-xs"
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
/>
|
||||
<Button
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
Loader2,
|
||||
Save,
|
||||
FolderSearch,
|
||||
Activity,
|
||||
Coins,
|
||||
Database,
|
||||
Server,
|
||||
} from "lucide-react";
|
||||
import { Loader2, Save } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
Dialog,
|
||||
@@ -16,12 +8,6 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from "@/components/ui/accordion";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { settingsApi } from "@/lib/api";
|
||||
@@ -34,15 +20,11 @@ import { AboutSection } from "@/components/settings/AboutSection";
|
||||
import { ProxyPanel } from "@/components/proxy";
|
||||
import { PricingConfigPanel } from "@/components/usage/PricingConfigPanel";
|
||||
import { ModelTestConfigPanel } from "@/components/usage/ModelTestConfigPanel";
|
||||
import { AutoFailoverConfigPanel } from "@/components/proxy/AutoFailoverConfigPanel";
|
||||
import { UsageDashboard } from "@/components/usage/UsageDashboard";
|
||||
import { useSettings } from "@/hooks/useSettings";
|
||||
import { useImportExport } from "@/hooks/useImportExport";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { SettingsFormState } from "@/hooks/useSettings";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { useProxyStatus } from "@/hooks/useProxyStatus";
|
||||
|
||||
interface SettingsDialogProps {
|
||||
open: boolean;
|
||||
@@ -172,26 +154,6 @@ export function SettingsPage({
|
||||
|
||||
const isBusy = useMemo(() => isLoading && !settings, [isLoading, settings]);
|
||||
|
||||
const {
|
||||
isRunning,
|
||||
startWithTakeover: startProxy,
|
||||
stopWithRestore: stopProxy,
|
||||
isPending: isProxyPending,
|
||||
} = useProxyStatus();
|
||||
const [failoverEnabled, setFailoverEnabled] = useState(true);
|
||||
|
||||
const handleToggleProxy = async (checked: boolean) => {
|
||||
try {
|
||||
if (!checked) {
|
||||
await stopProxy();
|
||||
} else {
|
||||
await startProxy();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Toggle proxy failed:", error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-[56rem] flex flex-col h-[calc(100vh-8rem)] overflow-hidden px-6">
|
||||
{isBusy ? (
|
||||
@@ -236,225 +198,61 @@ export function SettingsPage({
|
||||
|
||||
<TabsContent value="advanced" className="space-y-6 mt-0 pb-6">
|
||||
{settings ? (
|
||||
<div className="space-y-4">
|
||||
<Accordion
|
||||
type="multiple"
|
||||
defaultValue={[]}
|
||||
className="w-full space-y-4"
|
||||
>
|
||||
<AccordionItem
|
||||
value="directory"
|
||||
className="rounded-xl glass-card overflow-hidden"
|
||||
>
|
||||
<AccordionTrigger className="px-6 py-4 hover:no-underline hover:bg-muted/50 data-[state=open]:bg-muted/50">
|
||||
<div className="flex items-center gap-3">
|
||||
<FolderSearch className="h-5 w-5 text-primary" />
|
||||
<div className="text-left">
|
||||
<h3 className="text-base font-semibold">
|
||||
配置文件目录
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground font-normal">
|
||||
管理 Claude、Codex 和 Gemini 的配置存储路径
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-6 pb-6 pt-4 border-t border-border/50">
|
||||
<DirectorySettings
|
||||
appConfigDir={appConfigDir}
|
||||
resolvedDirs={resolvedDirs}
|
||||
onAppConfigChange={updateAppConfigDir}
|
||||
onBrowseAppConfig={browseAppConfigDir}
|
||||
onResetAppConfig={resetAppConfigDir}
|
||||
claudeDir={settings.claudeConfigDir}
|
||||
codexDir={settings.codexConfigDir}
|
||||
geminiDir={settings.geminiConfigDir}
|
||||
onDirectoryChange={updateDirectory}
|
||||
onBrowseDirectory={browseDirectory}
|
||||
onResetDirectory={resetDirectory}
|
||||
/>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
<>
|
||||
<DirectorySettings
|
||||
appConfigDir={appConfigDir}
|
||||
resolvedDirs={resolvedDirs}
|
||||
onAppConfigChange={updateAppConfigDir}
|
||||
onBrowseAppConfig={browseAppConfigDir}
|
||||
onResetAppConfig={resetAppConfigDir}
|
||||
claudeDir={settings.claudeConfigDir}
|
||||
codexDir={settings.codexConfigDir}
|
||||
geminiDir={settings.geminiConfigDir}
|
||||
onDirectoryChange={updateDirectory}
|
||||
onBrowseDirectory={browseDirectory}
|
||||
onResetDirectory={resetDirectory}
|
||||
/>
|
||||
|
||||
<AccordionItem
|
||||
value="proxy"
|
||||
className="rounded-xl glass-card overflow-hidden"
|
||||
>
|
||||
<AccordionTrigger className="px-6 py-4 hover:no-underline hover:bg-muted/50 data-[state=open]:bg-muted/50">
|
||||
<div className="flex flex-1 items-center justify-between pr-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<Server className="h-5 w-5 text-green-500" />
|
||||
<div className="text-left">
|
||||
<h3 className="text-base font-semibold">
|
||||
本地代理
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground font-normal">
|
||||
控制代理服务开关、查看状态与端口信息
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className="flex items-center gap-4"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Badge
|
||||
variant={isRunning ? "default" : "secondary"}
|
||||
className="gap-1.5 h-6"
|
||||
>
|
||||
<Activity
|
||||
className={`h-3 w-3 ${isRunning ? "animate-pulse" : ""}`}
|
||||
/>
|
||||
{isRunning ? "运行中" : "已停止"}
|
||||
</Badge>
|
||||
<Switch
|
||||
checked={isRunning}
|
||||
onCheckedChange={handleToggleProxy}
|
||||
disabled={isProxyPending}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-6 pb-6 pt-0 border-t border-border/50">
|
||||
<ProxyPanel />
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
{/* 代理服务面板 */}
|
||||
<ProxyPanel />
|
||||
|
||||
<AccordionItem
|
||||
value="test"
|
||||
className="rounded-xl glass-card overflow-hidden"
|
||||
>
|
||||
<AccordionTrigger className="px-6 py-4 hover:no-underline hover:bg-muted/50 data-[state=open]:bg-muted/50">
|
||||
<div className="flex items-center gap-3">
|
||||
<Activity className="h-5 w-5 text-indigo-500" />
|
||||
<div className="text-left">
|
||||
<h3 className="text-base font-semibold">
|
||||
模型测试配置
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground font-normal">
|
||||
配置模型测试使用的默认模型和提示词
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-6 pb-6 pt-4 border-t border-border/50">
|
||||
<ModelTestConfigPanel />
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
{/* 模型定价配置 */}
|
||||
<PricingConfigPanel />
|
||||
|
||||
<AccordionItem
|
||||
value="failover"
|
||||
className="rounded-xl glass-card overflow-hidden"
|
||||
>
|
||||
<AccordionTrigger className="px-6 py-4 hover:no-underline hover:bg-muted/50 data-[state=open]:bg-muted/50">
|
||||
<div className="flex flex-1 items-center justify-between pr-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<Activity className="h-5 w-5 text-orange-500" />
|
||||
<div className="text-left">
|
||||
<h3 className="text-base font-semibold">
|
||||
自动故障转移
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground font-normal">
|
||||
配置自动故障转移和熔断策略
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className="flex items-center gap-4"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
{/* Removed status text as requested */}
|
||||
<Switch
|
||||
checked={failoverEnabled}
|
||||
onCheckedChange={setFailoverEnabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-6 pb-6 pt-4 border-t border-border/50">
|
||||
<AutoFailoverConfigPanel
|
||||
enabled={failoverEnabled}
|
||||
onEnabledChange={setFailoverEnabled}
|
||||
/>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
{/* 模型测试配置 */}
|
||||
<ModelTestConfigPanel />
|
||||
|
||||
<AccordionItem
|
||||
value="pricing"
|
||||
className="rounded-xl glass-card overflow-hidden"
|
||||
>
|
||||
<AccordionTrigger className="px-6 py-4 hover:no-underline hover:bg-muted/50 data-[state=open]:bg-muted/50">
|
||||
<div className="flex items-center gap-3">
|
||||
<Coins className="h-5 w-5 text-yellow-500" />
|
||||
<div className="text-left">
|
||||
<h3 className="text-base font-semibold">
|
||||
成本定价
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground font-normal">
|
||||
管理各模型 Token 计费规则
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-6 pb-6 pt-4 border-t border-border/50">
|
||||
<PricingConfigPanel />
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
|
||||
<AccordionItem
|
||||
value="data"
|
||||
className="rounded-xl glass-card overflow-hidden"
|
||||
>
|
||||
<AccordionTrigger className="px-6 py-4 hover:no-underline hover:bg-muted/50 data-[state=open]:bg-muted/50">
|
||||
<div className="flex items-center gap-3">
|
||||
<Database className="h-5 w-5 text-blue-500" />
|
||||
<div className="text-left">
|
||||
<h3 className="text-base font-semibold">
|
||||
数据管理
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground font-normal">
|
||||
导入导出配置与备份恢复
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-6 pb-6 pt-4 border-t border-border/50">
|
||||
<ImportExportSection
|
||||
status={importStatus}
|
||||
selectedFile={selectedFile}
|
||||
errorMessage={errorMessage}
|
||||
backupId={backupId}
|
||||
isImporting={isImporting}
|
||||
onSelectFile={selectImportFile}
|
||||
onImport={importConfig}
|
||||
onExport={exportConfig}
|
||||
onClear={clearSelection}
|
||||
/>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
<div className="pt-4">
|
||||
<ImportExportSection
|
||||
status={importStatus}
|
||||
selectedFile={selectedFile}
|
||||
errorMessage={errorMessage}
|
||||
backupId={backupId}
|
||||
isImporting={isImporting}
|
||||
onSelectFile={selectImportFile}
|
||||
onImport={importConfig}
|
||||
onExport={exportConfig}
|
||||
onClear={clearSelection}
|
||||
/>
|
||||
<div className="pt-6 border-t border-gray-200 dark:border-white/10">
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
className="w-full h-12 text-base font-medium"
|
||||
className="w-full"
|
||||
disabled={isSaving}
|
||||
>
|
||||
{isSaving ? (
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<Loader2 className="h-5 w-5 animate-spin" />
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
{t("settings.saving")}
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<Save className="mr-2 h-5 w-5" />
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
{t("common.save")}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</TabsContent>
|
||||
|
||||
@@ -473,7 +271,10 @@ export function SettingsPage({
|
||||
open={showRestartPrompt}
|
||||
onOpenChange={(open) => !open && handleRestartLater()}
|
||||
>
|
||||
<DialogContent zIndex="alert" className="max-w-md glass border-border">
|
||||
<DialogContent
|
||||
zIndex="alert"
|
||||
className="max-w-md glass border-white/10"
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("settings.restartRequired")}</DialogTitle>
|
||||
</DialogHeader>
|
||||
@@ -486,7 +287,7 @@ export function SettingsPage({
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={handleRestartLater}
|
||||
className="hover:bg-muted/50"
|
||||
className="hover:bg-white/5"
|
||||
>
|
||||
{t("settings.restartLater")}
|
||||
</Button>
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { SettingsFormState } from "@/hooks/useSettings";
|
||||
import { AppWindow, MonitorUp, Power } from "lucide-react";
|
||||
|
||||
interface WindowSettingsProps {
|
||||
settings: SettingsFormState;
|
||||
@@ -13,46 +12,40 @@ export function WindowSettings({ settings, onChange }: WindowSettingsProps) {
|
||||
|
||||
return (
|
||||
<section className="space-y-4">
|
||||
<div className="flex items-center gap-2 pb-2 border-b border-border/40">
|
||||
<AppWindow className="h-4 w-4 text-primary" />
|
||||
<header className="space-y-1">
|
||||
<h3 className="text-sm font-medium">{t("settings.windowBehavior")}</h3>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("settings.windowBehaviorHint")}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div className="space-y-3">
|
||||
<ToggleRow
|
||||
icon={<Power className="h-4 w-4 text-orange-500" />}
|
||||
title={t("settings.launchOnStartup")}
|
||||
description={t("settings.launchOnStartupDescription")}
|
||||
checked={!!settings.launchOnStartup}
|
||||
onCheckedChange={(value) => onChange({ launchOnStartup: value })}
|
||||
/>
|
||||
<ToggleRow
|
||||
title={t("settings.launchOnStartup")}
|
||||
description={t("settings.launchOnStartupDescription")}
|
||||
checked={!!settings.launchOnStartup}
|
||||
onCheckedChange={(value) => onChange({ launchOnStartup: value })}
|
||||
/>
|
||||
|
||||
<ToggleRow
|
||||
icon={<AppWindow className="h-4 w-4 text-blue-500" />}
|
||||
title={t("settings.minimizeToTray")}
|
||||
description={t("settings.minimizeToTrayDescription")}
|
||||
checked={settings.minimizeToTrayOnClose}
|
||||
onCheckedChange={(value) =>
|
||||
onChange({ minimizeToTrayOnClose: value })
|
||||
}
|
||||
/>
|
||||
<ToggleRow
|
||||
title={t("settings.minimizeToTray")}
|
||||
description={t("settings.minimizeToTrayDescription")}
|
||||
checked={settings.minimizeToTrayOnClose}
|
||||
onCheckedChange={(value) => onChange({ minimizeToTrayOnClose: value })}
|
||||
/>
|
||||
|
||||
<ToggleRow
|
||||
icon={<MonitorUp className="h-4 w-4 text-purple-500" />}
|
||||
title={t("settings.enableClaudePluginIntegration")}
|
||||
description={t("settings.enableClaudePluginIntegrationDescription")}
|
||||
checked={!!settings.enableClaudePluginIntegration}
|
||||
onCheckedChange={(value) =>
|
||||
onChange({ enableClaudePluginIntegration: value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<ToggleRow
|
||||
title={t("settings.enableClaudePluginIntegration")}
|
||||
description={t("settings.enableClaudePluginIntegrationDescription")}
|
||||
checked={!!settings.enableClaudePluginIntegration}
|
||||
onCheckedChange={(value) =>
|
||||
onChange({ enableClaudePluginIntegration: value })
|
||||
}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
interface ToggleRowProps {
|
||||
icon: React.ReactNode;
|
||||
title: string;
|
||||
description?: string;
|
||||
checked: boolean;
|
||||
@@ -60,24 +53,18 @@ interface ToggleRowProps {
|
||||
}
|
||||
|
||||
function ToggleRow({
|
||||
icon,
|
||||
title,
|
||||
description,
|
||||
checked,
|
||||
onCheckedChange,
|
||||
}: ToggleRowProps) {
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-4 rounded-xl border border-border bg-card/50 p-4 transition-colors hover:bg-muted/50">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-background ring-1 ring-border">
|
||||
{icon}
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium leading-none">{title}</p>
|
||||
{description ? (
|
||||
<p className="text-xs text-muted-foreground">{description}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex items-start justify-between gap-4 rounded-lg border border-border-default p-4">
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium leading-none">{title}</p>
|
||||
{description ? (
|
||||
<p className="text-xs text-muted-foreground">{description}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<Switch
|
||||
checked={checked}
|
||||
|
||||
@@ -19,17 +19,11 @@ import { RefreshCw, Search } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { SkillCard } from "./SkillCard";
|
||||
import { RepoManagerPanel } from "./RepoManagerPanel";
|
||||
import {
|
||||
skillsApi,
|
||||
type Skill,
|
||||
type SkillRepo,
|
||||
type AppType,
|
||||
} from "@/lib/api/skills";
|
||||
import { skillsApi, type Skill, type SkillRepo } from "@/lib/api/skills";
|
||||
import { formatSkillError } from "@/lib/errors/skillErrorParser";
|
||||
|
||||
interface SkillsPageProps {
|
||||
onClose?: () => void;
|
||||
initialApp?: AppType;
|
||||
}
|
||||
|
||||
export interface SkillsPageHandle {
|
||||
@@ -38,7 +32,7 @@ export interface SkillsPageHandle {
|
||||
}
|
||||
|
||||
export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
({ onClose: _onClose, initialApp = "claude" }, ref) => {
|
||||
({ onClose: _onClose }, ref) => {
|
||||
const { t } = useTranslation();
|
||||
const [skills, setSkills] = useState<Skill[]>([]);
|
||||
const [repos, setRepos] = useState<SkillRepo[]>([]);
|
||||
@@ -48,13 +42,11 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
const [filterStatus, setFilterStatus] = useState<
|
||||
"all" | "installed" | "uninstalled"
|
||||
>("all");
|
||||
// 使用 initialApp,不允许切换
|
||||
const selectedApp = initialApp;
|
||||
|
||||
const loadSkills = async (afterLoad?: (data: Skill[]) => void) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const data = await skillsApi.getAll(selectedApp);
|
||||
const data = await skillsApi.getAll();
|
||||
setSkills(data);
|
||||
if (afterLoad) {
|
||||
afterLoad(data);
|
||||
@@ -92,7 +84,6 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([loadSkills(), loadRepos()]);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
@@ -102,7 +93,7 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
|
||||
const handleInstall = async (directory: string) => {
|
||||
try {
|
||||
await skillsApi.install(directory, selectedApp);
|
||||
await skillsApi.install(directory);
|
||||
toast.success(t("skills.installSuccess", { name: directory }));
|
||||
await loadSkills();
|
||||
} catch (error) {
|
||||
@@ -131,7 +122,7 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
|
||||
const handleUninstall = async (directory: string) => {
|
||||
try {
|
||||
await skillsApi.uninstall(directory, selectedApp);
|
||||
await skillsApi.uninstall(directory);
|
||||
toast.success(t("skills.uninstallSuccess", { name: directory }));
|
||||
await loadSkills();
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
import * as React from "react";
|
||||
import * as AccordionPrimitive from "@radix-ui/react-accordion";
|
||||
import { ChevronDown } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Accordion = AccordionPrimitive.Root;
|
||||
|
||||
const AccordionItem = React.forwardRef<
|
||||
React.ElementRef<typeof AccordionPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AccordionPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn("border-b", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
AccordionItem.displayName = "AccordionItem";
|
||||
|
||||
const AccordionTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof AccordionPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<AccordionPrimitive.Header className="flex">
|
||||
<AccordionPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-200" />
|
||||
</AccordionPrimitive.Trigger>
|
||||
</AccordionPrimitive.Header>
|
||||
));
|
||||
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName;
|
||||
|
||||
const AccordionContent = React.forwardRef<
|
||||
React.ElementRef<typeof AccordionPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<AccordionPrimitive.Content
|
||||
ref={ref}
|
||||
className="overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
|
||||
{...props}
|
||||
>
|
||||
<div className={cn("pb-4 pt-0", className)}>{children}</div>
|
||||
</AccordionPrimitive.Content>
|
||||
));
|
||||
|
||||
AccordionContent.displayName = AccordionPrimitive.Content.displayName;
|
||||
|
||||
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };
|
||||
@@ -9,7 +9,7 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
"flex h-9 w-full rounded-md border border-border-default bg-background text-foreground px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-blue-500/20 dark:focus:ring-blue-400/20 disabled:cursor-not-allowed disabled:opacity-50",
|
||||
"flex h-9 w-full rounded-md border border-border-default bg-background px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-blue-500/20 dark:focus:ring-blue-400/20 disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className,
|
||||
)}
|
||||
ref={ref}
|
||||
|
||||
@@ -18,7 +18,7 @@ export function ModelStatsTable() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-border/50 bg-card/40 backdrop-blur-sm overflow-hidden">
|
||||
<div className="rounded-md bg-card/60 shadow-sm">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
|
||||
@@ -1,29 +1,36 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Save, Loader2 } from "lucide-react";
|
||||
import { ChevronDown, ChevronRight, Save, Loader2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
getStreamCheckConfig,
|
||||
saveStreamCheckConfig,
|
||||
type StreamCheckConfig,
|
||||
getModelTestConfig,
|
||||
saveModelTestConfig,
|
||||
type ModelTestConfig,
|
||||
} from "@/lib/api/model-test";
|
||||
|
||||
export function ModelTestConfigPanel() {
|
||||
const { t } = useTranslation();
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [config, setConfig] = useState<StreamCheckConfig>({
|
||||
timeoutSecs: 45,
|
||||
maxRetries: 2,
|
||||
degradedThresholdMs: 6000,
|
||||
const [config, setConfig] = useState<ModelTestConfig>({
|
||||
claudeModel: "claude-haiku-4-5-20251001",
|
||||
codexModel: "gpt-5.1-codex@low",
|
||||
geminiModel: "gemini-3-pro-preview",
|
||||
codexModel: "gpt-5.1-low",
|
||||
geminiModel: "gemini-3-pro-low",
|
||||
testPrompt: "ping",
|
||||
timeoutSecs: 15,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
@@ -34,7 +41,7 @@ export function ModelTestConfigPanel() {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
const data = await getStreamCheckConfig();
|
||||
const data = await getModelTestConfig();
|
||||
setConfig(data);
|
||||
} catch (e) {
|
||||
setError(String(e));
|
||||
@@ -46,11 +53,11 @@ export function ModelTestConfigPanel() {
|
||||
async function handleSave() {
|
||||
try {
|
||||
setIsSaving(true);
|
||||
await saveStreamCheckConfig(config);
|
||||
toast.success(t("streamCheck.configSaved", "健康检查配置已保存"));
|
||||
await saveModelTestConfig(config);
|
||||
toast.success(t("modelTest.configSaved", "模型测试配置已保存"));
|
||||
} catch (e) {
|
||||
toast.error(
|
||||
t("streamCheck.configSaveFailed", "保存失败") + ": " + String(e),
|
||||
t("modelTest.configSaveFailed", "保存失败") + ": " + String(e),
|
||||
);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
@@ -59,151 +66,160 @@ export function ModelTestConfigPanel() {
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-4">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
<Card className="border rounded-lg">
|
||||
<CardHeader
|
||||
className="cursor-pointer"
|
||||
onClick={() => setIsExpanded(!isExpanded)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
<CardTitle className="text-base">
|
||||
{t("modelTest.configTitle", "模型测试配置")}
|
||||
</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* 测试模型配置 */}
|
||||
<div className="space-y-4">
|
||||
<h4 className="text-sm font-medium text-muted-foreground">
|
||||
{t("streamCheck.testModels", "测试模型")}
|
||||
</h4>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="claudeModel">
|
||||
{t("streamCheck.claudeModel", "Claude 模型")}
|
||||
</Label>
|
||||
<Input
|
||||
id="claudeModel"
|
||||
value={config.claudeModel}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, claudeModel: e.target.value })
|
||||
}
|
||||
placeholder="claude-3-5-haiku-latest"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="codexModel">
|
||||
{t("streamCheck.codexModel", "Codex 模型")}
|
||||
</Label>
|
||||
<Input
|
||||
id="codexModel"
|
||||
value={config.codexModel}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, codexModel: e.target.value })
|
||||
}
|
||||
placeholder="gpt-4o-mini"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="geminiModel">
|
||||
{t("streamCheck.geminiModel", "Gemini 模型")}
|
||||
</Label>
|
||||
<Input
|
||||
id="geminiModel"
|
||||
value={config.geminiModel}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, geminiModel: e.target.value })
|
||||
}
|
||||
placeholder="gemini-1.5-flash"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 检查参数配置 */}
|
||||
<div className="space-y-4">
|
||||
<h4 className="text-sm font-medium text-muted-foreground">
|
||||
{t("streamCheck.checkParams", "检查参数")}
|
||||
</h4>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="timeoutSecs">
|
||||
{t("streamCheck.timeout", "超时时间(秒)")}
|
||||
</Label>
|
||||
<Input
|
||||
id="timeoutSecs"
|
||||
type="number"
|
||||
min={10}
|
||||
max={120}
|
||||
value={config.timeoutSecs}
|
||||
onChange={(e) =>
|
||||
setConfig({
|
||||
...config,
|
||||
timeoutSecs: parseInt(e.target.value) || 45,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="maxRetries">
|
||||
{t("streamCheck.maxRetries", "最大重试次数")}
|
||||
</Label>
|
||||
<Input
|
||||
id="maxRetries"
|
||||
type="number"
|
||||
min={0}
|
||||
max={5}
|
||||
value={config.maxRetries}
|
||||
onChange={(e) =>
|
||||
setConfig({
|
||||
...config,
|
||||
maxRetries: parseInt(e.target.value) || 2,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="degradedThresholdMs">
|
||||
{t("streamCheck.degradedThreshold", "降级阈值(毫秒)")}
|
||||
</Label>
|
||||
<Input
|
||||
id="degradedThresholdMs"
|
||||
type="number"
|
||||
min={1000}
|
||||
max={30000}
|
||||
step={1000}
|
||||
value={config.degradedThresholdMs}
|
||||
onChange={(e) =>
|
||||
setConfig({
|
||||
...config,
|
||||
degradedThresholdMs: parseInt(e.target.value) || 6000,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={handleSave} disabled={isSaving}>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t("common.saving", "保存中...")}
|
||||
</>
|
||||
<Card className="border rounded-lg">
|
||||
<CardHeader
|
||||
className="cursor-pointer select-none"
|
||||
onClick={() => setIsExpanded(!isExpanded)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="h-4 w-4 text-muted-foreground" />
|
||||
) : (
|
||||
<>
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
{t("common.save", "保存")}
|
||||
</>
|
||||
<ChevronRight className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<CardTitle className="text-base">
|
||||
{t("modelTest.configTitle", "模型测试配置")}
|
||||
</CardTitle>
|
||||
{!isExpanded && (
|
||||
<CardDescription className="mt-1">
|
||||
{t(
|
||||
"modelTest.configDesc",
|
||||
"配置模型测试使用的默认模型和提示词",
|
||||
)}
|
||||
</CardDescription>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
{isExpanded && (
|
||||
<CardContent className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="claudeModel">
|
||||
{t("modelTest.claudeModel", "Claude 测试模型")}
|
||||
</Label>
|
||||
<Input
|
||||
id="claudeModel"
|
||||
value={config.claudeModel}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, claudeModel: e.target.value })
|
||||
}
|
||||
placeholder="claude-haiku-4-5-20251001"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="codexModel">
|
||||
{t("modelTest.codexModel", "Codex 测试模型")}
|
||||
</Label>
|
||||
<Input
|
||||
id="codexModel"
|
||||
value={config.codexModel}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, codexModel: e.target.value })
|
||||
}
|
||||
placeholder="gpt-5.1-low"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="geminiModel">
|
||||
{t("modelTest.geminiModel", "Gemini 测试模型")}
|
||||
</Label>
|
||||
<Input
|
||||
id="geminiModel"
|
||||
value={config.geminiModel}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, geminiModel: e.target.value })
|
||||
}
|
||||
placeholder="gemini-3-pro-low"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="testPrompt">
|
||||
{t("modelTest.testPrompt", "测试提示词")}
|
||||
</Label>
|
||||
<Input
|
||||
id="testPrompt"
|
||||
value={config.testPrompt}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, testPrompt: e.target.value })
|
||||
}
|
||||
placeholder="ping"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
"modelTest.testPromptHint",
|
||||
"发送给模型的测试消息,建议使用简短内容以减少 token 消耗",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="timeoutSecs">
|
||||
{t("modelTest.timeout", "超时时间(秒)")}
|
||||
</Label>
|
||||
<Input
|
||||
id="timeoutSecs"
|
||||
type="number"
|
||||
min={5}
|
||||
max={60}
|
||||
value={config.timeoutSecs}
|
||||
onChange={(e) =>
|
||||
setConfig({
|
||||
...config,
|
||||
timeoutSecs: parseInt(e.target.value) || 15,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={handleSave} disabled={isSaving}>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t("common.saving", "保存中...")}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
{t("common.save", "保存")}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
@@ -104,107 +110,136 @@ export function PricingConfigPanel() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h4 className="text-sm font-medium text-muted-foreground">
|
||||
{t("usage.modelPricingDesc", "配置各模型的 Token 成本")} (每百万)
|
||||
</h4>
|
||||
<Button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleAddNew();
|
||||
}}
|
||||
size="sm"
|
||||
>
|
||||
<Plus className="mr-1 h-4 w-4" />
|
||||
{t("common.add", "新增")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
{!pricing || pricing.length === 0 ? (
|
||||
<Alert>
|
||||
<AlertDescription>
|
||||
{t(
|
||||
"usage.noPricingData",
|
||||
'暂无定价数据。点击"新增"添加模型定价配置。',
|
||||
<Card className="border rounded-lg">
|
||||
<CardHeader
|
||||
className="cursor-pointer select-none"
|
||||
onClick={() => setIsExpanded(!isExpanded)}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="h-4 w-4 text-muted-foreground" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
<div>
|
||||
<CardTitle className="text-base">
|
||||
{t("usage.modelPricing", "模型定价")}
|
||||
{pricing && pricing.length > 0 && (
|
||||
<span className="ml-2 text-sm font-normal text-muted-foreground">
|
||||
({pricing.length})
|
||||
</span>
|
||||
)}
|
||||
</CardTitle>
|
||||
{!isExpanded && (
|
||||
<CardDescription className="mt-1">
|
||||
{t(
|
||||
"usage.modelPricingDesc",
|
||||
"配置各模型的 Token 成本(每百万 tokens 的 USD 价格,支持 * 与 ? 通配)",
|
||||
)}
|
||||
</CardDescription>
|
||||
)}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : (
|
||||
<div className="rounded-md bg-card/60 shadow-sm">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>{t("usage.model", "模型")}</TableHead>
|
||||
<TableHead>{t("usage.displayName", "显示名称")}</TableHead>
|
||||
<TableHead className="text-right">
|
||||
{t("usage.inputCost", "输入成本")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right">
|
||||
{t("usage.outputCost", "输出成本")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right">
|
||||
{t("usage.cacheReadCost", "缓存读取")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right">
|
||||
{t("usage.cacheWriteCost", "缓存写入")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right">
|
||||
{t("common.actions", "操作")}
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{pricing.map((model) => (
|
||||
<TableRow key={model.modelId}>
|
||||
<TableCell className="font-mono text-sm">
|
||||
{model.modelId}
|
||||
</TableCell>
|
||||
<TableCell>{model.displayName}</TableCell>
|
||||
<TableCell className="text-right font-mono text-sm">
|
||||
${model.inputCostPerMillion}
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-mono text-sm">
|
||||
${model.outputCostPerMillion}
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-mono text-sm">
|
||||
${model.cacheReadCostPerMillion}
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-mono text-sm">
|
||||
${model.cacheCreationCostPerMillion}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex justify-end gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => {
|
||||
setIsAddingNew(false);
|
||||
setEditingModel(model);
|
||||
}}
|
||||
title={t("common.edit", "编辑")}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setDeleteConfirm(model.modelId)}
|
||||
title={t("common.delete", "删除")}
|
||||
className="text-destructive hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleAddNew();
|
||||
}}
|
||||
size="sm"
|
||||
>
|
||||
<Plus className="mr-1 h-4 w-4" />
|
||||
{t("common.add", "新增")}
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
{isExpanded && (
|
||||
<CardContent>
|
||||
{!pricing || pricing.length === 0 ? (
|
||||
<Alert>
|
||||
<AlertDescription>
|
||||
{t(
|
||||
"usage.noPricingData",
|
||||
'暂无定价数据。点击"新增"添加模型定价配置。',
|
||||
)}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : (
|
||||
<div className="rounded-md bg-card/60 shadow-sm">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>{t("usage.model", "模型")}</TableHead>
|
||||
<TableHead>{t("usage.displayName", "显示名称")}</TableHead>
|
||||
<TableHead className="text-right">
|
||||
{t("usage.inputCost", "输入成本")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right">
|
||||
{t("usage.outputCost", "输出成本")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right">
|
||||
{t("usage.cacheReadCost", "缓存读取")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right">
|
||||
{t("usage.cacheWriteCost", "缓存写入")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right">
|
||||
{t("common.actions", "操作")}
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{pricing.map((model) => (
|
||||
<TableRow key={model.modelId}>
|
||||
<TableCell className="font-mono text-sm">
|
||||
{model.modelId}
|
||||
</TableCell>
|
||||
<TableCell>{model.displayName}</TableCell>
|
||||
<TableCell className="text-right font-mono text-sm">
|
||||
${model.inputCostPerMillion}
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-mono text-sm">
|
||||
${model.outputCostPerMillion}
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-mono text-sm">
|
||||
${model.cacheReadCostPerMillion}
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-mono text-sm">
|
||||
${model.cacheCreationCostPerMillion}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex justify-end gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => {
|
||||
setIsAddingNew(false);
|
||||
setEditingModel(model);
|
||||
}}
|
||||
title={t("common.edit", "编辑")}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setDeleteConfirm(model.modelId)}
|
||||
title={t("common.delete", "删除")}
|
||||
className="text-destructive hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
)}
|
||||
|
||||
{editingModel && (
|
||||
<PricingEditModal
|
||||
@@ -249,6 +284,6 @@ export function PricingConfigPanel() {
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ export function ProviderStatsTable() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-border/50 bg-card/40 backdrop-blur-sm overflow-hidden">
|
||||
<div className="rounded-md bg-card/60 shadow-sm">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
|
||||
@@ -65,151 +65,123 @@ export function RequestLogTable() {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* 筛选栏 */}
|
||||
<div className="flex flex-col gap-4 rounded-lg border bg-card/50 p-4 backdrop-blur-sm">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Select
|
||||
value={tempFilters.appType || "all"}
|
||||
onValueChange={(v) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
appType: v === "all" ? undefined : v,
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-[130px] bg-background">
|
||||
<SelectValue placeholder={t("usage.endpoint", "端点")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">{t("common.all", "全部端点")}</SelectItem>
|
||||
<SelectItem value="claude">Claude</SelectItem>
|
||||
<SelectItem value="codex">Codex</SelectItem>
|
||||
<SelectItem value="gemini">Gemini</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="flex flex-wrap items-center gap-2 rounded-md bg-card/60 p-3 shadow-sm">
|
||||
<Select
|
||||
value={tempFilters.appType || "all"}
|
||||
onValueChange={(v) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
appType: v === "all" ? undefined : v,
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder={t("usage.endpoint", "端点")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">{t("common.all", "全部")}</SelectItem>
|
||||
<SelectItem value="claude">Claude</SelectItem>
|
||||
<SelectItem value="codex">Codex</SelectItem>
|
||||
<SelectItem value="gemini">Gemini</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Select
|
||||
value={tempFilters.statusCode?.toString() || "all"}
|
||||
onValueChange={(v) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
statusCode: v === "all" ? undefined : parseInt(v),
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-[130px] bg-background">
|
||||
<SelectValue placeholder={t("usage.status", "状态码")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">{t("common.all", "全部状态")}</SelectItem>
|
||||
<SelectItem value="200">200 OK</SelectItem>
|
||||
<SelectItem value="400">400 Bad Request</SelectItem>
|
||||
<SelectItem value="401">401 Unauthorized</SelectItem>
|
||||
<SelectItem value="429">429 Rate Limit</SelectItem>
|
||||
<SelectItem value="500">500 Server Error</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select
|
||||
value={tempFilters.statusCode?.toString() || "all"}
|
||||
onValueChange={(v) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
statusCode: v === "all" ? undefined : parseInt(v),
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder={t("usage.status", "状态码")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">{t("common.all", "全部")}</SelectItem>
|
||||
<SelectItem value="200">200</SelectItem>
|
||||
<SelectItem value="400">400</SelectItem>
|
||||
<SelectItem value="401">401</SelectItem>
|
||||
<SelectItem value="429">429</SelectItem>
|
||||
<SelectItem value="500">500</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<div className="flex items-center gap-2 flex-1 min-w-[300px]">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder={t("usage.provider", "搜索供应商...")}
|
||||
className="pl-9 bg-background"
|
||||
value={tempFilters.providerName || ""}
|
||||
onChange={(e) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
providerName: e.target.value || undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
placeholder={t("usage.model", "搜索模型...")}
|
||||
className="w-[180px] bg-background"
|
||||
value={tempFilters.model || ""}
|
||||
onChange={(e) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
model: e.target.value || undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<Input
|
||||
placeholder={t("usage.provider", "供应商名称")}
|
||||
className="w-[140px]"
|
||||
value={tempFilters.providerName || ""}
|
||||
onChange={(e) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
providerName: e.target.value || undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<span className="whitespace-nowrap">时间范围:</span>
|
||||
<Input
|
||||
type="datetime-local"
|
||||
className="h-8 w-[200px] bg-background"
|
||||
value={
|
||||
tempFilters.startDate
|
||||
? new Date(tempFilters.startDate * 1000)
|
||||
.toISOString()
|
||||
.slice(0, 16)
|
||||
: ""
|
||||
}
|
||||
onChange={(e) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
startDate: e.target.value
|
||||
? Math.floor(new Date(e.target.value).getTime() / 1000)
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span>-</span>
|
||||
<Input
|
||||
type="datetime-local"
|
||||
className="h-8 w-[200px] bg-background"
|
||||
value={
|
||||
tempFilters.endDate
|
||||
? new Date(tempFilters.endDate * 1000)
|
||||
.toISOString()
|
||||
.slice(0, 16)
|
||||
: ""
|
||||
}
|
||||
onChange={(e) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
endDate: e.target.value
|
||||
? Math.floor(new Date(e.target.value).getTime() / 1000)
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
placeholder={t("usage.model", "模型名称")}
|
||||
className="w-[140px]"
|
||||
value={tempFilters.model || ""}
|
||||
onChange={(e) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
model: e.target.value || undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="flex items-center gap-2 ml-auto">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="default"
|
||||
onClick={handleSearch}
|
||||
className="h-8"
|
||||
>
|
||||
<Search className="mr-2 h-3.5 w-3.5" />
|
||||
{t("common.search", "查询")}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={handleReset}
|
||||
className="h-8"
|
||||
>
|
||||
<X className="mr-2 h-3.5 w-3.5" />
|
||||
{t("common.reset", "重置")}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={handleRefresh}
|
||||
className="h-8 px-2"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<Input
|
||||
type="datetime-local"
|
||||
className="w-[180px]"
|
||||
value={
|
||||
tempFilters.startDate
|
||||
? new Date(tempFilters.startDate * 1000)
|
||||
.toISOString()
|
||||
.slice(0, 16)
|
||||
: ""
|
||||
}
|
||||
onChange={(e) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
startDate: e.target.value
|
||||
? Math.floor(new Date(e.target.value).getTime() / 1000)
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
|
||||
<Input
|
||||
type="datetime-local"
|
||||
className="w-[180px]"
|
||||
value={
|
||||
tempFilters.endDate
|
||||
? new Date(tempFilters.endDate * 1000).toISOString().slice(0, 16)
|
||||
: ""
|
||||
}
|
||||
onChange={(e) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
endDate: e.target.value
|
||||
? Math.floor(new Date(e.target.value).getTime() / 1000)
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="ml-auto flex gap-2">
|
||||
<Button size="sm" onClick={handleSearch}>
|
||||
<Search className="mr-1 h-4 w-4" />
|
||||
{t("common.search", "查询")}
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onClick={handleReset}>
|
||||
<X className="mr-1 h-4 w-4" />
|
||||
{t("common.reset", "重置")}
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onClick={handleRefresh}>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -217,40 +189,34 @@ export function RequestLogTable() {
|
||||
<div className="h-[400px] animate-pulse rounded bg-gray-100" />
|
||||
) : (
|
||||
<>
|
||||
<div className="rounded-lg border border-border/50 bg-card/40 backdrop-blur-sm overflow-x-auto">
|
||||
<div className="rounded-md bg-card/60 shadow-sm overflow-x-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="whitespace-nowrap">
|
||||
{t("usage.time", "时间")}
|
||||
</TableHead>
|
||||
<TableHead className="whitespace-nowrap">
|
||||
{t("usage.provider", "供应商")}
|
||||
</TableHead>
|
||||
<TableHead className="min-w-[280px] whitespace-nowrap">
|
||||
<TableHead>{t("usage.time", "时间")}</TableHead>
|
||||
<TableHead>{t("usage.provider", "供应商")}</TableHead>
|
||||
<TableHead className="min-w-[280px]">
|
||||
{t("usage.billingModel", "计费模型")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right whitespace-nowrap">
|
||||
<TableHead className="text-right">
|
||||
{t("usage.inputTokens", "输入")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right whitespace-nowrap">
|
||||
<TableHead className="text-right">
|
||||
{t("usage.outputTokens", "输出")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right min-w-[90px] whitespace-nowrap">
|
||||
{t("usage.cacheReadTokens", "缓存读取")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right min-w-[90px] whitespace-nowrap">
|
||||
<TableHead className="text-right min-w-[90px]">
|
||||
{t("usage.cacheCreationTokens", "缓存写入")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right whitespace-nowrap">
|
||||
<TableHead className="text-right min-w-[90px]">
|
||||
{t("usage.cacheReadTokens", "缓存读取")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right">
|
||||
{t("usage.totalCost", "成本")}
|
||||
</TableHead>
|
||||
<TableHead className="text-center min-w-[140px] whitespace-nowrap">
|
||||
<TableHead className="text-center min-w-[140px]">
|
||||
{t("usage.timingInfo", "用时/首字")}
|
||||
</TableHead>
|
||||
<TableHead className="whitespace-nowrap">
|
||||
{t("usage.status", "状态")}
|
||||
</TableHead>
|
||||
<TableHead>{t("usage.status", "状态")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
@@ -286,10 +252,10 @@ export function RequestLogTable() {
|
||||
{log.outputTokens.toLocaleString()}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
{log.cacheReadTokens.toLocaleString()}
|
||||
{log.cacheCreationTokens.toLocaleString()}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
{log.cacheCreationTokens.toLocaleString()}
|
||||
{log.cacheReadTokens.toLocaleString()}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
${parseFloat(log.totalCostUsd).toFixed(6)}
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { UsageSummaryCards } from "./UsageSummaryCards";
|
||||
import { UsageTrendChart } from "./UsageTrendChart";
|
||||
import { RequestLogTable } from "./RequestLogTable";
|
||||
import { ProviderStatsTable } from "./ProviderStatsTable";
|
||||
import { ModelStatsTable } from "./ModelStatsTable";
|
||||
import type { TimeRange } from "@/types/usage";
|
||||
import { motion } from "framer-motion";
|
||||
import { BarChart3, ListFilter, Activity } from "lucide-react";
|
||||
|
||||
export function UsageDashboard() {
|
||||
const { t } = useTranslation();
|
||||
@@ -17,90 +16,50 @@ export function UsageDashboard() {
|
||||
const days = timeRange === "1d" ? 1 : timeRange === "7d" ? 7 : 30;
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.4 }}
|
||||
className="space-y-8 pb-8"
|
||||
>
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h2 className="text-2xl font-bold">{t("usage.title", "使用统计")}</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("usage.subtitle", "查看 AI 模型的使用情况和成本统计")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Tabs
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-end">
|
||||
<select
|
||||
value={timeRange}
|
||||
onValueChange={(v) => setTimeRange(v as TimeRange)}
|
||||
className="w-full sm:w-auto"
|
||||
onChange={(e) => setTimeRange(e.target.value as TimeRange)}
|
||||
className="rounded-md border px-3 py-1.5 text-sm"
|
||||
>
|
||||
<TabsList className="flex w-full sm:w-auto bg-card/60 border border-border/50 backdrop-blur-sm shadow-sm h-10 p-1">
|
||||
<TabsTrigger
|
||||
value="1d"
|
||||
className="flex-1 sm:flex-none sm:px-6 data-[state=active]:bg-primary/10 data-[state=active]:text-primary hover:text-primary transition-colors"
|
||||
>
|
||||
{t("usage.today", "24小时")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value="7d"
|
||||
className="flex-1 sm:flex-none sm:px-6 data-[state=active]:bg-primary/10 data-[state=active]:text-primary hover:text-primary transition-colors"
|
||||
>
|
||||
{t("usage.last7days", "7天")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value="30d"
|
||||
className="flex-1 sm:flex-none sm:px-6 data-[state=active]:bg-primary/10 data-[state=active]:text-primary hover:text-primary transition-colors"
|
||||
>
|
||||
{t("usage.last30days", "30天")}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
<option value="1d">{t("usage.today", "今天")}</option>
|
||||
<option value="7d">{t("usage.last7days", "过去 7 天")}</option>
|
||||
<option value="30d">{t("usage.last30days", "过去 30 天")}</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<UsageSummaryCards days={days} />
|
||||
|
||||
<UsageTrendChart days={days} />
|
||||
<Card className="border-none bg-transparent p-0 shadow-none">
|
||||
<UsageTrendChart days={days} />
|
||||
</Card>
|
||||
|
||||
<div className="space-y-4">
|
||||
<Tabs defaultValue="logs" className="w-full">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<TabsList className="bg-muted/50">
|
||||
<TabsTrigger value="logs" className="gap-2">
|
||||
<ListFilter className="h-4 w-4" />
|
||||
{t("usage.requestLogs", "请求日志")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="providers" className="gap-2">
|
||||
<Activity className="h-4 w-4" />
|
||||
{t("usage.providerStats", "Provider 统计")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="models" className="gap-2">
|
||||
<BarChart3 className="h-4 w-4" />
|
||||
{t("usage.modelStats", "模型统计")}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
<Tabs defaultValue="logs" className="w-full">
|
||||
<TabsList>
|
||||
<TabsTrigger value="logs">
|
||||
{t("usage.requestLogs", "请求日志")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="providers">
|
||||
{t("usage.providerStats", "Provider 统计")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="models">
|
||||
{t("usage.modelStats", "模型统计")}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.2 }}
|
||||
>
|
||||
<TabsContent value="logs" className="mt-0">
|
||||
<RequestLogTable />
|
||||
</TabsContent>
|
||||
<TabsContent value="logs" className="mt-4">
|
||||
<RequestLogTable />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="providers" className="mt-0">
|
||||
<ProviderStatsTable />
|
||||
</TabsContent>
|
||||
<TabsContent value="providers" className="mt-4">
|
||||
<ProviderStatsTable />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="models" className="mt-0">
|
||||
<ModelStatsTable />
|
||||
</TabsContent>
|
||||
</motion.div>
|
||||
</Tabs>
|
||||
</div>
|
||||
</motion.div>
|
||||
<TabsContent value="models" className="mt-4">
|
||||
<ModelStatsTable />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { useUsageSummary } from "@/lib/query/usage";
|
||||
import { Activity, DollarSign, Layers, Database, Loader2 } from "lucide-react";
|
||||
import { motion } from "framer-motion";
|
||||
|
||||
interface UsageSummaryCardsProps {
|
||||
days: number;
|
||||
@@ -11,118 +8,29 @@ interface UsageSummaryCardsProps {
|
||||
|
||||
export function UsageSummaryCards({ days }: UsageSummaryCardsProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { startDate, endDate } = useMemo(() => {
|
||||
const end = Math.floor(Date.now() / 1000);
|
||||
const start = end - days * 24 * 60 * 60;
|
||||
return { startDate: start, endDate: end };
|
||||
}, [days]);
|
||||
const endDate = Math.floor(Date.now() / 1000);
|
||||
const startDate = endDate - days * 24 * 60 * 60;
|
||||
|
||||
const { data: summary, isLoading } = useUsageSummary(startDate, endDate);
|
||||
|
||||
const stats = useMemo(() => {
|
||||
const totalRequests = summary?.totalRequests ?? 0;
|
||||
const totalCost = parseFloat(summary?.totalCost || "0");
|
||||
|
||||
const inputTokens = summary?.totalInputTokens ?? 0;
|
||||
const outputTokens = summary?.totalOutputTokens ?? 0;
|
||||
const totalTokens = inputTokens + outputTokens;
|
||||
|
||||
const cacheWriteTokens = summary?.totalCacheCreationTokens ?? 0;
|
||||
const cacheReadTokens = summary?.totalCacheReadTokens ?? 0;
|
||||
const totalCacheTokens = cacheWriteTokens + cacheReadTokens;
|
||||
|
||||
return [
|
||||
{
|
||||
title: t("usage.totalRequests", "总请求数"),
|
||||
value: totalRequests.toLocaleString(),
|
||||
icon: Activity,
|
||||
color: "text-blue-500",
|
||||
bg: "bg-blue-500/10",
|
||||
subValue: null,
|
||||
},
|
||||
{
|
||||
title: t("usage.totalCost", "总成本"),
|
||||
value: `$${totalCost.toFixed(4)}`,
|
||||
icon: DollarSign,
|
||||
color: "text-green-500",
|
||||
bg: "bg-green-500/10",
|
||||
subValue: null,
|
||||
},
|
||||
{
|
||||
title: t("usage.totalTokens", "总 Token 数"),
|
||||
value: totalTokens.toLocaleString(),
|
||||
icon: Layers,
|
||||
color: "text-purple-500",
|
||||
bg: "bg-purple-500/10",
|
||||
subValue: (
|
||||
<div className="flex flex-col gap-1 text-xs text-muted-foreground mt-3 pt-3 border-t border-border/50">
|
||||
<div className="flex justify-between items-center">
|
||||
<span>Input</span>
|
||||
<span className="text-foreground/80">
|
||||
{(inputTokens / 1000).toFixed(1)}k
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span>Output</span>
|
||||
<span className="text-foreground/80">
|
||||
{(outputTokens / 1000).toFixed(1)}k
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t("usage.cacheTokens", "缓存 Token"),
|
||||
value: totalCacheTokens.toLocaleString(),
|
||||
icon: Database,
|
||||
color: "text-orange-500",
|
||||
bg: "bg-orange-500/10",
|
||||
subValue: (
|
||||
<div className="flex flex-col gap-1 text-xs text-muted-foreground mt-3 pt-3 border-t border-border/50">
|
||||
<div className="flex justify-between items-center">
|
||||
<span>Write</span>
|
||||
<span className="text-foreground/80">
|
||||
{(cacheWriteTokens / 1000).toFixed(1)}k
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span>Read</span>
|
||||
<span className="text-foreground/80">
|
||||
{(cacheReadTokens / 1000).toFixed(1)}k
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
];
|
||||
}, [summary, t]);
|
||||
|
||||
const container = {
|
||||
hidden: { opacity: 0 },
|
||||
show: {
|
||||
opacity: 1,
|
||||
transition: {
|
||||
staggerChildren: 0.1,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const item = {
|
||||
hidden: { opacity: 0, y: 20 },
|
||||
show: { opacity: 1, y: 0 },
|
||||
};
|
||||
const totalRequests = summary?.totalRequests ?? 0;
|
||||
const totalCost = parseFloat(summary?.totalCost || "0").toFixed(4);
|
||||
const totalInputTokens = summary?.totalInputTokens ?? 0;
|
||||
const totalOutputTokens = summary?.totalOutputTokens ?? 0;
|
||||
const totalTokens = totalInputTokens + totalOutputTokens;
|
||||
const cacheWriteTokens = summary?.totalCacheCreationTokens ?? 0;
|
||||
const cacheReadTokens = summary?.totalCacheReadTokens ?? 0;
|
||||
const totalCacheTokens = cacheWriteTokens + cacheReadTokens;
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="grid gap-4 md:grid-cols-4">
|
||||
{[...Array(4)].map((_, i) => (
|
||||
<Card
|
||||
key={i}
|
||||
className="border border-border/50 bg-card/40 backdrop-blur-sm shadow-sm"
|
||||
>
|
||||
<CardContent className="p-6 flex items-center justify-center min-h-[160px]">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground/50" />
|
||||
<Card key={i}>
|
||||
<CardHeader className="pb-2">
|
||||
<div className="h-4 w-24 animate-pulse rounded bg-gray-200" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="h-8 w-32 animate-pulse rounded bg-gray-200" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
@@ -131,39 +39,75 @@ export function UsageSummaryCards({ days }: UsageSummaryCardsProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
variants={container}
|
||||
initial="hidden"
|
||||
animate="show"
|
||||
className="grid gap-4 md:grid-cols-4"
|
||||
>
|
||||
{stats.map((stat, i) => (
|
||||
<motion.div key={i} variants={item}>
|
||||
<Card className="relative h-full overflow-hidden border border-border/50 bg-gradient-to-br from-card/50 to-background/50 backdrop-blur-xl hover:from-card/60 hover:to-background/60 transition-all shadow-sm">
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-start justify-between mb-2">
|
||||
<p className="text-sm font-medium text-muted-foreground">
|
||||
{stat.title}
|
||||
</p>
|
||||
<div className={`p-2 rounded-lg ${stat.bg}`}>
|
||||
<stat.icon className={`h-4 w-4 ${stat.color}`} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-4 md:grid-cols-4">
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">
|
||||
{t("usage.totalRequests", "总请求数")}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">
|
||||
{totalRequests.toLocaleString()}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-2xl font-bold truncate" title={stat.value}>
|
||||
{stat.value}
|
||||
</h3>
|
||||
</div>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">
|
||||
{t("usage.totalCost", "总成本")}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">${totalCost}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{stat.subValue || (
|
||||
/* Placeholder to properly align cards if no subvalue (first 2 cards) - effectively adding empty space or using flex-1 equivalent */
|
||||
<div className="mt-3 pt-3 border-t border-transparent h-[52px]"></div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</motion.div>
|
||||
))}
|
||||
</motion.div>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">
|
||||
{t("usage.totalTokens", "总 Token 数")}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">
|
||||
{totalTokens.toLocaleString()}
|
||||
</div>
|
||||
<div className="mt-2 space-y-1 text-sm text-muted-foreground">
|
||||
<div>
|
||||
{t("usage.inputTokens", "输入")}:{" "}
|
||||
{totalInputTokens.toLocaleString()}
|
||||
</div>
|
||||
<div>
|
||||
{t("usage.outputTokens", "输出")}:{" "}
|
||||
{totalOutputTokens.toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">
|
||||
{t("usage.cacheTokens", "缓存 Token")}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">
|
||||
{totalCacheTokens.toLocaleString()}
|
||||
</div>
|
||||
<div className="mt-2 space-y-1 text-sm text-muted-foreground">
|
||||
<div>
|
||||
{t("usage.cacheWrite", "写入")}:{" "}
|
||||
{cacheWriteTokens.toLocaleString()}
|
||||
</div>
|
||||
<div>
|
||||
{t("usage.cacheRead", "读取")}: {cacheReadTokens.toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
AreaChart,
|
||||
Area,
|
||||
LineChart,
|
||||
Line,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
Legend,
|
||||
} from "recharts";
|
||||
import { useUsageTrends } from "@/lib/query/usage";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
interface UsageTrendChartProps {
|
||||
days: number;
|
||||
@@ -21,11 +20,7 @@ export function UsageTrendChart({ days }: UsageTrendChartProps) {
|
||||
const { data: trends, isLoading } = useUsageTrends(days);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex h-[350px] items-center justify-center rounded-xl bg-card/40 border border-border/50">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground/30" />
|
||||
</div>
|
||||
);
|
||||
return <div className="h-[320px] animate-pulse rounded bg-gray-100" />;
|
||||
}
|
||||
|
||||
const isToday = days === 1;
|
||||
@@ -43,6 +38,8 @@ export function UsageTrendChart({ days }: UsageTrendChartProps) {
|
||||
hour: pointDate.getHours(),
|
||||
inputTokens: stat.totalInputTokens,
|
||||
outputTokens: stat.totalOutputTokens,
|
||||
cacheCreationTokens: stat.totalCacheCreationTokens,
|
||||
cacheReadTokens: stat.totalCacheReadTokens,
|
||||
cost: parseFloat(stat.totalCost),
|
||||
};
|
||||
}) || [];
|
||||
@@ -59,6 +56,8 @@ export function UsageTrendChart({ days }: UsageTrendChartProps) {
|
||||
label: `${hour.toString().padStart(2, "0")}:00`,
|
||||
inputTokens: bucket?.inputTokens ?? 0,
|
||||
outputTokens: bucket?.outputTokens ?? 0,
|
||||
cacheCreationTokens: bucket?.cacheCreationTokens ?? 0,
|
||||
cacheReadTokens: bucket?.cacheReadTokens ?? 0,
|
||||
cost: bucket?.cost ?? 0,
|
||||
};
|
||||
});
|
||||
@@ -66,129 +65,96 @@ export function UsageTrendChart({ days }: UsageTrendChartProps) {
|
||||
|
||||
const displayData = isToday ? hourlyData : chartData;
|
||||
|
||||
const CustomTooltip = ({ active, payload, label }: any) => {
|
||||
if (active && payload && payload.length) {
|
||||
return (
|
||||
<div className="rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-md">
|
||||
<p className="mb-2 font-medium">{label}</p>
|
||||
{payload.map((entry: any, index: number) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center gap-2 text-sm"
|
||||
style={{ color: entry.color }}
|
||||
>
|
||||
<div
|
||||
className="h-2 w-2 rounded-full"
|
||||
style={{ backgroundColor: entry.color }}
|
||||
/>
|
||||
<span className="font-medium">{entry.name}:</span>
|
||||
<span>
|
||||
{entry.name.includes(t("usage.cost", "成本"))
|
||||
? `$${typeof entry.value === "number" ? entry.value.toFixed(6) : entry.value}`
|
||||
: entry.value.toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
const rangeLabel = isToday
|
||||
? t("usage.rangeToday", "今天 (按小时)")
|
||||
: days === 7
|
||||
? t("usage.rangeLast7Days", "过去 7 天")
|
||||
: t("usage.rangeLast30Days", "过去 30 天");
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border border-border/50 bg-card/40 p-6 backdrop-blur-sm">
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold">
|
||||
{t("usage.trends", "使用趋势")}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{isToday
|
||||
? t("usage.rangeToday", "今天 (按小时)")
|
||||
: days === 7
|
||||
? t("usage.rangeLast7Days", "过去 7 天")
|
||||
: t("usage.rangeLast30Days", "过去 30 天")}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">{rangeLabel}</p>
|
||||
</div>
|
||||
|
||||
<div className="h-[350px] w-full">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart
|
||||
data={displayData}
|
||||
margin={{ top: 10, right: 10, left: 0, bottom: 0 }}
|
||||
>
|
||||
<defs>
|
||||
<linearGradient id="colorInput" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#3b82f6" stopOpacity={0.2} />
|
||||
<stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
|
||||
</linearGradient>
|
||||
<linearGradient id="colorOutput" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#22c55e" stopOpacity={0.2} />
|
||||
<stop offset="95%" stopColor="#22c55e" stopOpacity={0} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid
|
||||
strokeDasharray="3 3"
|
||||
vertical={false}
|
||||
stroke="hsl(var(--border))"
|
||||
opacity={0.4}
|
||||
/>
|
||||
<XAxis
|
||||
dataKey="label"
|
||||
axisLine={false}
|
||||
tickLine={false}
|
||||
tick={{ fill: "hsl(var(--muted-foreground))", fontSize: 12 }}
|
||||
dy={10}
|
||||
/>
|
||||
<YAxis
|
||||
yAxisId="tokens"
|
||||
axisLine={false}
|
||||
tickLine={false}
|
||||
tick={{ fill: "hsl(var(--muted-foreground))", fontSize: 12 }}
|
||||
tickFormatter={(value) => `${(value / 1000).toFixed(0)}k`}
|
||||
/>
|
||||
<YAxis
|
||||
yAxisId="cost"
|
||||
orientation="right"
|
||||
axisLine={false}
|
||||
tickLine={false}
|
||||
tick={{ fill: "hsl(var(--muted-foreground))", fontSize: 12 }}
|
||||
tickFormatter={(value) => `$${value}`}
|
||||
/>
|
||||
<Tooltip content={<CustomTooltip />} />
|
||||
<Legend />
|
||||
<Area
|
||||
yAxisId="tokens"
|
||||
type="monotone"
|
||||
dataKey="inputTokens"
|
||||
name={t("usage.inputTokens", "输入 Tokens")}
|
||||
stroke="#3b82f6"
|
||||
fillOpacity={1}
|
||||
fill="url(#colorInput)"
|
||||
strokeWidth={2}
|
||||
/>
|
||||
<Area
|
||||
yAxisId="tokens"
|
||||
type="monotone"
|
||||
dataKey="outputTokens"
|
||||
name={t("usage.outputTokens", "输出 Tokens")}
|
||||
stroke="#22c55e"
|
||||
fillOpacity={1}
|
||||
fill="url(#colorOutput)"
|
||||
strokeWidth={2}
|
||||
/>
|
||||
<Area
|
||||
yAxisId="cost"
|
||||
type="monotone"
|
||||
dataKey="cost"
|
||||
name={t("usage.cost", "成本")}
|
||||
stroke="#f43f5e"
|
||||
fill="none"
|
||||
strokeWidth={2}
|
||||
strokeDasharray="4 4"
|
||||
/>
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
<ResponsiveContainer width="100%" height={320}>
|
||||
<LineChart data={displayData}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis dataKey="label" />
|
||||
<YAxis
|
||||
yAxisId="tokens"
|
||||
label={{
|
||||
value: t("usage.tokensAxis", "Tokens"),
|
||||
angle: -90,
|
||||
position: "insideLeft",
|
||||
}}
|
||||
/>
|
||||
<YAxis
|
||||
yAxisId="cost"
|
||||
orientation="right"
|
||||
label={{
|
||||
value: t("usage.costAxis", "成本 (USD)"),
|
||||
angle: 90,
|
||||
position: "insideRight",
|
||||
}}
|
||||
/>
|
||||
<Tooltip />
|
||||
<Legend />
|
||||
<Line
|
||||
yAxisId="tokens"
|
||||
type="monotone"
|
||||
dataKey="inputTokens"
|
||||
name={t("usage.inputTokens", "输入 Tokens")}
|
||||
stroke="#2563eb"
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
isAnimationActive
|
||||
/>
|
||||
<Line
|
||||
yAxisId="tokens"
|
||||
type="monotone"
|
||||
dataKey="outputTokens"
|
||||
name={t("usage.outputTokens", "输出 Tokens")}
|
||||
stroke="#16a34a"
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
isAnimationActive
|
||||
/>
|
||||
<Line
|
||||
yAxisId="tokens"
|
||||
type="monotone"
|
||||
dataKey="cacheCreationTokens"
|
||||
name={t("usage.cacheCreationTokens", "缓存写入")}
|
||||
stroke="#f97316"
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
isAnimationActive
|
||||
/>
|
||||
<Line
|
||||
yAxisId="tokens"
|
||||
type="monotone"
|
||||
dataKey="cacheReadTokens"
|
||||
name={t("usage.cacheReadTokens", "缓存读取")}
|
||||
stroke="#a855f7"
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
isAnimationActive
|
||||
/>
|
||||
<Line
|
||||
yAxisId="cost"
|
||||
type="monotone"
|
||||
dataKey="cost"
|
||||
name={t("usage.cost", "成本")}
|
||||
stroke="#dc2626"
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
isAnimationActive
|
||||
/>
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { useState, useCallback } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { testProviderModel, type ModelTestResult } from "@/lib/api/model-test";
|
||||
import type { AppId } from "@/lib/api";
|
||||
|
||||
export function useModelTest(appId: AppId) {
|
||||
const { t } = useTranslation();
|
||||
const [testingIds, setTestingIds] = useState<Set<string>>(new Set());
|
||||
|
||||
const testProvider = useCallback(
|
||||
async (
|
||||
providerId: string,
|
||||
providerName: string,
|
||||
): Promise<ModelTestResult | null> => {
|
||||
setTestingIds((prev) => new Set(prev).add(providerId));
|
||||
|
||||
try {
|
||||
const result = await testProviderModel(appId, providerId);
|
||||
|
||||
if (result.success) {
|
||||
toast.success(
|
||||
t("modelTest.success", {
|
||||
name: providerName,
|
||||
time: result.responseTimeMs,
|
||||
defaultValue: `${providerName} 测试成功 (${result.responseTimeMs}ms)`,
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
toast.error(
|
||||
t("modelTest.failed", {
|
||||
name: providerName,
|
||||
error: result.message,
|
||||
defaultValue: `${providerName} 测试失败: ${result.message}`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (e) {
|
||||
toast.error(
|
||||
t("modelTest.error", {
|
||||
name: providerName,
|
||||
error: String(e),
|
||||
defaultValue: `${providerName} 测试出错: ${String(e)}`,
|
||||
}),
|
||||
);
|
||||
return null;
|
||||
} finally {
|
||||
setTestingIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.delete(providerId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
},
|
||||
[appId, t],
|
||||
);
|
||||
|
||||
const isTesting = useCallback(
|
||||
(providerId: string) => testingIds.has(providerId),
|
||||
[testingIds],
|
||||
);
|
||||
|
||||
return { testProvider, isTesting };
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
useUpdateProviderMutation,
|
||||
useDeleteProviderMutation,
|
||||
useSwitchProviderMutation,
|
||||
useSetProxyTargetMutation,
|
||||
} from "@/lib/query";
|
||||
import { extractErrorMessage } from "@/utils/errorUtils";
|
||||
|
||||
@@ -24,6 +25,7 @@ export function useProviderActions(activeApp: AppId) {
|
||||
const updateProviderMutation = useUpdateProviderMutation(activeApp);
|
||||
const deleteProviderMutation = useDeleteProviderMutation(activeApp);
|
||||
const switchProviderMutation = useSwitchProviderMutation(activeApp);
|
||||
const setProxyTargetMutation = useSetProxyTargetMutation(activeApp);
|
||||
|
||||
// Claude 插件同步逻辑
|
||||
const syncClaudePlugin = useCallback(
|
||||
@@ -91,6 +93,14 @@ export function useProviderActions(activeApp: AppId) {
|
||||
[switchProviderMutation, syncClaudePlugin],
|
||||
);
|
||||
|
||||
// 设置代理目标
|
||||
const setProxyTarget = useCallback(
|
||||
async (provider: Provider) => {
|
||||
await setProxyTargetMutation.mutateAsync(provider.id);
|
||||
},
|
||||
[setProxyTargetMutation],
|
||||
);
|
||||
|
||||
// 删除供应商
|
||||
const deleteProvider = useCallback(
|
||||
async (id: string) => {
|
||||
@@ -136,12 +146,14 @@ export function useProviderActions(activeApp: AppId) {
|
||||
addProvider,
|
||||
updateProvider,
|
||||
switchProvider,
|
||||
setProxyTarget,
|
||||
deleteProvider,
|
||||
saveUsageScript,
|
||||
isLoading:
|
||||
addProviderMutation.isPending ||
|
||||
updateProviderMutation.isPending ||
|
||||
deleteProviderMutation.isPending ||
|
||||
switchProviderMutation.isPending,
|
||||
switchProviderMutation.isPending ||
|
||||
setProxyTargetMutation.isPending,
|
||||
};
|
||||
}
|
||||
|
||||
+15
-83
@@ -5,16 +5,13 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ProxyStatus, ProxyServerInfo } from "@/types/proxy";
|
||||
import { extractErrorMessage } from "@/utils/errorUtils";
|
||||
|
||||
/**
|
||||
* 代理服务状态管理
|
||||
*/
|
||||
export function useProxyStatus() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
// 查询状态(自动轮询)
|
||||
const { data: status, isLoading } = useQuery({
|
||||
@@ -26,71 +23,27 @@ export function useProxyStatus() {
|
||||
placeholderData: (previousData) => previousData,
|
||||
});
|
||||
|
||||
// 查询接管状态
|
||||
const { data: isTakeoverActive } = useQuery({
|
||||
queryKey: ["proxyTakeoverActive"],
|
||||
queryFn: () => invoke<boolean>("is_live_takeover_active"),
|
||||
});
|
||||
|
||||
// 启动服务器(带 Live 配置接管)
|
||||
const startWithTakeoverMutation = useMutation({
|
||||
mutationFn: () => invoke<ProxyServerInfo>("start_proxy_with_takeover"),
|
||||
// 启动服务器
|
||||
const startMutation = useMutation({
|
||||
mutationFn: () => invoke<ProxyServerInfo>("start_proxy_server"),
|
||||
onSuccess: (info) => {
|
||||
toast.success(
|
||||
t("proxy.startedWithTakeover", {
|
||||
defaultValue: `代理模式已启用 - ${info.address}:${info.port}`,
|
||||
}),
|
||||
);
|
||||
toast.success(`代理服务已启动 - ${info.address}:${info.port}`);
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyStatus"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyTakeoverActive"] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
const detail = extractErrorMessage(error) || "未知错误";
|
||||
toast.error(
|
||||
t("proxy.startWithTakeoverFailed", {
|
||||
defaultValue: `启动失败: ${detail}`,
|
||||
}),
|
||||
);
|
||||
toast.error(`启动失败: ${error.message}`);
|
||||
},
|
||||
});
|
||||
|
||||
// 停止服务器(恢复 Live 配置)
|
||||
const stopWithRestoreMutation = useMutation({
|
||||
mutationFn: () => invoke("stop_proxy_with_restore"),
|
||||
onSuccess: () => {
|
||||
toast.success(
|
||||
t("proxy.stoppedWithRestore", {
|
||||
defaultValue: "代理模式已关闭,配置已恢复",
|
||||
}),
|
||||
);
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyStatus"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyTakeoverActive"] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
const detail = extractErrorMessage(error) || "未知错误";
|
||||
toast.error(
|
||||
t("proxy.stopWithRestoreFailed", {
|
||||
defaultValue: `停止失败: ${detail}`,
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
// 代理模式切换供应商(热切换)
|
||||
const switchProxyProviderMutation = useMutation({
|
||||
mutationFn: ({
|
||||
appType,
|
||||
providerId,
|
||||
}: {
|
||||
appType: string;
|
||||
providerId: string;
|
||||
}) => invoke("switch_proxy_provider", { appType, providerId }),
|
||||
// 停止服务器
|
||||
const stopMutation = useMutation({
|
||||
mutationFn: () => invoke("stop_proxy_server"),
|
||||
onSuccess: () => {
|
||||
toast.success("代理服务已停止");
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyStatus"] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
const detail = extractErrorMessage(error) || "未知错误";
|
||||
toast.error(`切换失败: ${detail}`);
|
||||
toast.error(`停止失败: ${error.message}`);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -103,36 +56,15 @@ export function useProxyStatus() {
|
||||
}
|
||||
};
|
||||
|
||||
// 检查接管状态
|
||||
const checkTakeoverActive = async () => {
|
||||
try {
|
||||
return await invoke<boolean>("is_live_takeover_active");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
status,
|
||||
isLoading,
|
||||
isRunning: status?.running || false,
|
||||
isTakeoverActive: isTakeoverActive || false,
|
||||
|
||||
// 启动/停止(接管模式)
|
||||
startWithTakeover: startWithTakeoverMutation.mutateAsync,
|
||||
stopWithRestore: stopWithRestoreMutation.mutateAsync,
|
||||
|
||||
// 代理模式下切换供应商
|
||||
switchProxyProvider: switchProxyProviderMutation.mutateAsync,
|
||||
|
||||
// 状态检查
|
||||
start: startMutation.mutateAsync,
|
||||
stop: stopMutation.mutateAsync,
|
||||
checkRunning,
|
||||
checkTakeoverActive,
|
||||
|
||||
// 加载状态
|
||||
isStarting: startWithTakeoverMutation.isPending,
|
||||
isStopping: stopWithRestoreMutation.isPending,
|
||||
isPending:
|
||||
startWithTakeoverMutation.isPending || stopWithRestoreMutation.isPending,
|
||||
isStarting: startMutation.isPending,
|
||||
isStopping: stopMutation.isPending,
|
||||
isPending: startMutation.isPending || stopMutation.isPending,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
import { useState, useCallback } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
streamCheckProvider,
|
||||
type StreamCheckResult,
|
||||
} from "@/lib/api/model-test";
|
||||
import type { AppId } from "@/lib/api";
|
||||
|
||||
export function useStreamCheck(appId: AppId) {
|
||||
const { t } = useTranslation();
|
||||
const [checkingIds, setCheckingIds] = useState<Set<string>>(new Set());
|
||||
|
||||
const checkProvider = useCallback(
|
||||
async (
|
||||
providerId: string,
|
||||
providerName: string,
|
||||
): Promise<StreamCheckResult | null> => {
|
||||
setCheckingIds((prev) => new Set(prev).add(providerId));
|
||||
|
||||
try {
|
||||
const result = await streamCheckProvider(appId, providerId);
|
||||
|
||||
if (result.status === "operational") {
|
||||
toast.success(
|
||||
t("streamCheck.operational", {
|
||||
name: providerName,
|
||||
time: result.responseTimeMs,
|
||||
defaultValue: `${providerName} 运行正常 (${result.responseTimeMs}ms)`,
|
||||
}),
|
||||
);
|
||||
} else if (result.status === "degraded") {
|
||||
toast.warning(
|
||||
t("streamCheck.degraded", {
|
||||
name: providerName,
|
||||
time: result.responseTimeMs,
|
||||
defaultValue: `${providerName} 响应较慢 (${result.responseTimeMs}ms)`,
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
toast.error(
|
||||
t("streamCheck.failed", {
|
||||
name: providerName,
|
||||
error: result.message,
|
||||
defaultValue: `${providerName} 检查失败: ${result.message}`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (e) {
|
||||
toast.error(
|
||||
t("streamCheck.error", {
|
||||
name: providerName,
|
||||
error: String(e),
|
||||
defaultValue: `${providerName} 检查出错: ${String(e)}`,
|
||||
}),
|
||||
);
|
||||
return null;
|
||||
} finally {
|
||||
setCheckingIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.delete(providerId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
},
|
||||
[appId, t],
|
||||
);
|
||||
|
||||
const isChecking = useCallback(
|
||||
(providerId: string) => checkingIds.has(providerId),
|
||||
[checkingIds],
|
||||
);
|
||||
|
||||
return { checkProvider, isChecking };
|
||||
}
|
||||
@@ -217,7 +217,7 @@ export const iconMetadata: Record<string, IconMetadata> = {
|
||||
displayName: "OpenAI",
|
||||
category: "ai-provider",
|
||||
keywords: ["gpt", "chatgpt"],
|
||||
defaultColor: "currentColor",
|
||||
defaultColor: "#00A67E",
|
||||
},
|
||||
packycode: {
|
||||
name: "packycode",
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import type {
|
||||
ProviderHealth,
|
||||
CircuitBreakerConfig,
|
||||
CircuitBreakerStats,
|
||||
} from "@/types/proxy";
|
||||
|
||||
export interface Provider {
|
||||
id: string;
|
||||
name: string;
|
||||
settingsConfig: unknown;
|
||||
websiteUrl?: string;
|
||||
category?: string;
|
||||
createdAt?: number;
|
||||
sortIndex?: number;
|
||||
notes?: string;
|
||||
meta?: unknown;
|
||||
icon?: string;
|
||||
iconColor?: string;
|
||||
isProxyTarget?: boolean;
|
||||
}
|
||||
|
||||
export const failoverApi = {
|
||||
// 获取代理目标列表
|
||||
async getProxyTargets(appType: string): Promise<Provider[]> {
|
||||
return invoke("get_proxy_targets", { appType });
|
||||
},
|
||||
|
||||
// 设置代理目标
|
||||
async setProxyTarget(
|
||||
providerId: string,
|
||||
appType: string,
|
||||
enabled: boolean,
|
||||
): Promise<void> {
|
||||
return invoke("set_proxy_target", { providerId, appType, enabled });
|
||||
},
|
||||
|
||||
// 获取供应商健康状态
|
||||
async getProviderHealth(
|
||||
providerId: string,
|
||||
appType: string,
|
||||
): Promise<ProviderHealth> {
|
||||
return invoke("get_provider_health", { providerId, appType });
|
||||
},
|
||||
|
||||
// 重置熔断器
|
||||
async resetCircuitBreaker(
|
||||
providerId: string,
|
||||
appType: string,
|
||||
): Promise<void> {
|
||||
return invoke("reset_circuit_breaker", { providerId, appType });
|
||||
},
|
||||
|
||||
// 获取熔断器配置
|
||||
async getCircuitBreakerConfig(): Promise<CircuitBreakerConfig> {
|
||||
return invoke("get_circuit_breaker_config");
|
||||
},
|
||||
|
||||
// 更新熔断器配置
|
||||
async updateCircuitBreakerConfig(
|
||||
config: CircuitBreakerConfig,
|
||||
): Promise<void> {
|
||||
return invoke("update_circuit_breaker_config", { config });
|
||||
},
|
||||
|
||||
// 获取熔断器统计信息
|
||||
async getCircuitBreakerStats(
|
||||
providerId: string,
|
||||
appType: string,
|
||||
): Promise<CircuitBreakerStats | null> {
|
||||
return invoke("get_circuit_breaker_stats", { providerId, appType });
|
||||
},
|
||||
};
|
||||
+52
-27
@@ -1,64 +1,89 @@
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import type { AppId } from "./types";
|
||||
|
||||
// ===== 流式健康检查类型 =====
|
||||
|
||||
export type HealthStatus = "operational" | "degraded" | "failed";
|
||||
|
||||
export interface StreamCheckConfig {
|
||||
timeoutSecs: number;
|
||||
maxRetries: number;
|
||||
degradedThresholdMs: number;
|
||||
export interface ModelTestConfig {
|
||||
claudeModel: string;
|
||||
codexModel: string;
|
||||
geminiModel: string;
|
||||
testPrompt: string;
|
||||
timeoutSecs: number;
|
||||
}
|
||||
|
||||
export interface StreamCheckResult {
|
||||
status: HealthStatus;
|
||||
export interface ModelTestResult {
|
||||
success: boolean;
|
||||
message: string;
|
||||
responseTimeMs?: number;
|
||||
httpStatus?: number;
|
||||
modelUsed: string;
|
||||
testedAt: number;
|
||||
retryCount: number;
|
||||
}
|
||||
|
||||
// ===== 流式健康检查 API =====
|
||||
export interface ModelTestLog {
|
||||
id: number;
|
||||
providerId: string;
|
||||
providerName: string;
|
||||
appType: string;
|
||||
model: string;
|
||||
prompt: string;
|
||||
success: boolean;
|
||||
message: string;
|
||||
responseTimeMs?: number;
|
||||
httpStatus?: number;
|
||||
testedAt: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 流式健康检查(单个供应商)
|
||||
* 测试单个供应商的模型可用性
|
||||
*/
|
||||
export async function streamCheckProvider(
|
||||
export async function testProviderModel(
|
||||
appType: AppId,
|
||||
providerId: string,
|
||||
): Promise<StreamCheckResult> {
|
||||
return invoke("stream_check_provider", { appType, providerId });
|
||||
): Promise<ModelTestResult> {
|
||||
return invoke("test_provider_model", { appType, providerId });
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量流式健康检查
|
||||
* 批量测试所有供应商
|
||||
*/
|
||||
export async function streamCheckAllProviders(
|
||||
export async function testAllProvidersModel(
|
||||
appType: AppId,
|
||||
proxyTargetsOnly: boolean = false,
|
||||
): Promise<Array<[string, StreamCheckResult]>> {
|
||||
return invoke("stream_check_all_providers", { appType, proxyTargetsOnly });
|
||||
): Promise<Array<[string, ModelTestResult]>> {
|
||||
return invoke("test_all_providers_model", { appType, proxyTargetsOnly });
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取流式检查配置
|
||||
* 获取模型测试配置
|
||||
*/
|
||||
export async function getStreamCheckConfig(): Promise<StreamCheckConfig> {
|
||||
return invoke("get_stream_check_config");
|
||||
export async function getModelTestConfig(): Promise<ModelTestConfig> {
|
||||
return invoke("get_model_test_config");
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存流式检查配置
|
||||
* 保存模型测试配置
|
||||
*/
|
||||
export async function saveStreamCheckConfig(
|
||||
config: StreamCheckConfig,
|
||||
export async function saveModelTestConfig(
|
||||
config: ModelTestConfig,
|
||||
): Promise<void> {
|
||||
return invoke("save_stream_check_config", { config });
|
||||
return invoke("save_model_test_config", { config });
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取模型测试日志
|
||||
*/
|
||||
export async function getModelTestLogs(
|
||||
appType?: string,
|
||||
providerId?: string,
|
||||
limit?: number,
|
||||
): Promise<ModelTestLog[]> {
|
||||
return invoke("get_model_test_logs", { appType, providerId, limit });
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理旧的测试日志
|
||||
*/
|
||||
export async function cleanupModelTestLogs(
|
||||
keepCount?: number,
|
||||
): Promise<number> {
|
||||
return invoke("cleanup_model_test_logs", { keepCount });
|
||||
}
|
||||
|
||||
@@ -115,15 +115,4 @@ export const settingsApi = {
|
||||
async getAutoLaunchStatus(): Promise<boolean> {
|
||||
return await invoke("get_auto_launch_status");
|
||||
},
|
||||
|
||||
async getToolVersions(): Promise<
|
||||
Array<{
|
||||
name: string;
|
||||
version: string | null;
|
||||
latest_version: string | null;
|
||||
error: string | null;
|
||||
}>
|
||||
> {
|
||||
return await invoke("get_tool_versions");
|
||||
},
|
||||
};
|
||||
|
||||
+6
-20
@@ -19,31 +19,17 @@ export interface SkillRepo {
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export type AppType = "claude" | "codex" | "gemini";
|
||||
|
||||
export const skillsApi = {
|
||||
async getAll(app: AppType = "claude"): Promise<Skill[]> {
|
||||
if (app === "claude") {
|
||||
return await invoke("get_skills");
|
||||
}
|
||||
return await invoke("get_skills_for_app", { app });
|
||||
async getAll(): Promise<Skill[]> {
|
||||
return await invoke("get_skills");
|
||||
},
|
||||
|
||||
async install(directory: string, app: AppType = "claude"): Promise<boolean> {
|
||||
if (app === "claude") {
|
||||
return await invoke("install_skill", { directory });
|
||||
}
|
||||
return await invoke("install_skill_for_app", { app, directory });
|
||||
async install(directory: string): Promise<boolean> {
|
||||
return await invoke("install_skill", { directory });
|
||||
},
|
||||
|
||||
async uninstall(
|
||||
directory: string,
|
||||
app: AppType = "claude",
|
||||
): Promise<boolean> {
|
||||
if (app === "claude") {
|
||||
return await invoke("uninstall_skill", { directory });
|
||||
}
|
||||
return await invoke("uninstall_skill_for_app", { app, directory });
|
||||
async uninstall(directory: string): Promise<boolean> {
|
||||
return await invoke("uninstall_skill", { directory });
|
||||
},
|
||||
|
||||
async getRepos(): Promise<SkillRepo[]> {
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { failoverApi } from "@/lib/api/failover";
|
||||
|
||||
/**
|
||||
* 获取代理目标列表
|
||||
*/
|
||||
export function useProxyTargets(appType: string) {
|
||||
return useQuery({
|
||||
queryKey: ["proxyTargets", appType],
|
||||
queryFn: () => failoverApi.getProxyTargets(appType),
|
||||
enabled: !!appType,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取供应商健康状态
|
||||
*/
|
||||
export function useProviderHealth(providerId: string, appType: string) {
|
||||
return useQuery({
|
||||
queryKey: ["providerHealth", providerId, appType],
|
||||
queryFn: () => failoverApi.getProviderHealth(providerId, appType),
|
||||
enabled: !!providerId && !!appType,
|
||||
refetchInterval: 5000, // 每 5 秒刷新一次
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置代理目标
|
||||
*/
|
||||
export function useSetProxyTarget() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({
|
||||
providerId,
|
||||
appType,
|
||||
enabled,
|
||||
}: {
|
||||
providerId: string;
|
||||
appType: string;
|
||||
enabled: boolean;
|
||||
}) => failoverApi.setProxyTarget(providerId, appType, enabled),
|
||||
onSuccess: (_, variables) => {
|
||||
// 刷新代理目标列表
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["proxyTargets", variables.appType],
|
||||
});
|
||||
// 刷新供应商列表
|
||||
queryClient.invalidateQueries({ queryKey: ["providers"] });
|
||||
// 刷新健康状态
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["providerHealth", variables.providerId, variables.appType],
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置熔断器
|
||||
*/
|
||||
export function useResetCircuitBreaker() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({
|
||||
providerId,
|
||||
appType,
|
||||
}: {
|
||||
providerId: string;
|
||||
appType: string;
|
||||
}) => failoverApi.resetCircuitBreaker(providerId, appType),
|
||||
onSuccess: (_, variables) => {
|
||||
// 刷新健康状态
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["providerHealth", variables.providerId, variables.appType],
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取熔断器配置
|
||||
*/
|
||||
export function useCircuitBreakerConfig() {
|
||||
return useQuery({
|
||||
queryKey: ["circuitBreakerConfig"],
|
||||
queryFn: () => failoverApi.getCircuitBreakerConfig(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新熔断器配置
|
||||
*/
|
||||
export function useUpdateCircuitBreakerConfig() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: failoverApi.updateCircuitBreakerConfig,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["circuitBreakerConfig"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取熔断器统计信息
|
||||
*/
|
||||
export function useCircuitBreakerStats(providerId: string, appType: string) {
|
||||
return useQuery({
|
||||
queryKey: ["circuitBreakerStats", providerId, appType],
|
||||
queryFn: () => failoverApi.getCircuitBreakerStats(providerId, appType),
|
||||
enabled: !!providerId && !!appType,
|
||||
refetchInterval: 5000, // 每 5 秒刷新一次
|
||||
});
|
||||
}
|
||||
+12
-16
@@ -36,10 +36,9 @@ export const useAddProviderMutation = (appId: AppId) => {
|
||||
toast.success(
|
||||
t("notifications.providerAdded", {
|
||||
defaultValue: "供应商已添加",
|
||||
}),
|
||||
{
|
||||
closeButton: true,
|
||||
},
|
||||
}), {
|
||||
closeButton: true
|
||||
}
|
||||
);
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
@@ -67,10 +66,9 @@ export const useUpdateProviderMutation = (appId: AppId) => {
|
||||
toast.success(
|
||||
t("notifications.updateSuccess", {
|
||||
defaultValue: "供应商更新成功",
|
||||
}),
|
||||
{
|
||||
closeButton: true,
|
||||
},
|
||||
}), {
|
||||
closeButton: true
|
||||
}
|
||||
);
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
@@ -108,10 +106,9 @@ export const useDeleteProviderMutation = (appId: AppId) => {
|
||||
toast.success(
|
||||
t("notifications.deleteSuccess", {
|
||||
defaultValue: "供应商已删除",
|
||||
}),
|
||||
{
|
||||
closeButton: true,
|
||||
},
|
||||
}), {
|
||||
closeButton: true
|
||||
}
|
||||
);
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
@@ -150,10 +147,9 @@ export const useSwitchProviderMutation = (appId: AppId) => {
|
||||
t("notifications.switchSuccess", {
|
||||
defaultValue: "切换供应商成功",
|
||||
appName: t(`apps.${appId}`, { defaultValue: appId }),
|
||||
}),
|
||||
{
|
||||
closeButton: true,
|
||||
},
|
||||
}), {
|
||||
closeButton: true
|
||||
}
|
||||
);
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
|
||||
@@ -34,22 +34,12 @@ export interface ProvidersQueryData {
|
||||
currentProviderId: string;
|
||||
}
|
||||
|
||||
export interface UseProvidersQueryOptions {
|
||||
isProxyRunning?: boolean; // 代理服务是否运行中
|
||||
}
|
||||
|
||||
export const useProvidersQuery = (
|
||||
appId: AppId,
|
||||
options?: UseProvidersQueryOptions,
|
||||
): UseQueryResult<ProvidersQueryData> => {
|
||||
const { isProxyRunning = false } = options || {};
|
||||
|
||||
return useQuery({
|
||||
queryKey: ["providers", appId],
|
||||
placeholderData: keepPreviousData,
|
||||
// 当代理服务运行时,每 10 秒刷新一次供应商列表
|
||||
// 这样可以自动反映后端熔断器自动禁用代理目标的变更
|
||||
refetchInterval: isProxyRunning ? 10000 : false,
|
||||
queryFn: async () => {
|
||||
let providers: Record<string, Provider> = {};
|
||||
let currentProviderId = "";
|
||||
|
||||
@@ -5,7 +5,6 @@ export interface ProxyConfig {
|
||||
max_retries: number;
|
||||
request_timeout: number;
|
||||
enable_logging: boolean;
|
||||
live_takeover_active?: boolean;
|
||||
}
|
||||
|
||||
export interface ProxyStatus {
|
||||
@@ -49,39 +48,6 @@ export interface ProviderHealth {
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
// 熔断器相关类型
|
||||
export interface CircuitBreakerConfig {
|
||||
failureThreshold: number;
|
||||
successThreshold: number;
|
||||
timeoutSeconds: number;
|
||||
errorRateThreshold: number;
|
||||
minRequests: number;
|
||||
}
|
||||
|
||||
export type CircuitState = "closed" | "open" | "half_open";
|
||||
|
||||
export interface CircuitBreakerStats {
|
||||
state: CircuitState;
|
||||
consecutiveFailures: number;
|
||||
consecutiveSuccesses: number;
|
||||
totalRequests: number;
|
||||
failedRequests: number;
|
||||
}
|
||||
|
||||
// 供应商健康状态枚举
|
||||
export enum ProviderHealthStatus {
|
||||
Healthy = "healthy",
|
||||
Degraded = "degraded",
|
||||
Failed = "failed",
|
||||
Unknown = "unknown",
|
||||
}
|
||||
|
||||
// 扩展 ProviderHealth 以包含前端计算的状态
|
||||
export interface ProviderHealthWithStatus extends ProviderHealth {
|
||||
status: ProviderHealthStatus;
|
||||
circuitState?: CircuitState;
|
||||
}
|
||||
|
||||
export interface ProxyUsageRecord {
|
||||
provider_id: string;
|
||||
app_type: string;
|
||||
|
||||
+112
-165
@@ -4,172 +4,119 @@ export default {
|
||||
"./src/index.html",
|
||||
"./src/**/*.{js,ts,jsx,tsx}",
|
||||
],
|
||||
darkMode: ["selector", "class"],
|
||||
darkMode: "selector",
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
background: 'hsl(var(--background))',
|
||||
foreground: 'hsl(var(--foreground))',
|
||||
card: {
|
||||
DEFAULT: 'hsl(var(--card))',
|
||||
foreground: 'hsl(var(--card-foreground))'
|
||||
},
|
||||
popover: {
|
||||
DEFAULT: 'hsl(var(--popover))',
|
||||
foreground: 'hsl(var(--popover-foreground))'
|
||||
},
|
||||
primary: {
|
||||
DEFAULT: 'hsl(var(--primary))',
|
||||
foreground: 'hsl(var(--primary-foreground))'
|
||||
},
|
||||
secondary: {
|
||||
DEFAULT: 'hsl(var(--secondary))',
|
||||
foreground: 'hsl(var(--secondary-foreground))'
|
||||
},
|
||||
muted: {
|
||||
DEFAULT: 'hsl(var(--muted))',
|
||||
foreground: 'hsl(var(--muted-foreground))'
|
||||
},
|
||||
accent: {
|
||||
DEFAULT: 'hsl(var(--accent))',
|
||||
foreground: 'hsl(var(--accent-foreground))'
|
||||
},
|
||||
destructive: {
|
||||
DEFAULT: 'hsl(var(--destructive))',
|
||||
foreground: 'hsl(var(--destructive-foreground))'
|
||||
},
|
||||
border: 'hsl(var(--border))',
|
||||
input: 'hsl(var(--input))',
|
||||
ring: 'hsl(var(--ring))',
|
||||
blue: {
|
||||
'400': '#409CFF',
|
||||
'500': '#0A84FF',
|
||||
'600': '#0060DF'
|
||||
},
|
||||
gray: {
|
||||
'50': '#fafafa',
|
||||
'100': '#f4f4f5',
|
||||
'200': '#e4e4e7',
|
||||
'300': '#d4d4d8',
|
||||
'400': '#a1a1aa',
|
||||
'500': '#71717a',
|
||||
'600': '#636366',
|
||||
'700': '#48484A',
|
||||
'800': '#3A3A3C',
|
||||
'900': '#2C2C2E',
|
||||
'950': '#1C1C1E'
|
||||
},
|
||||
green: {
|
||||
'100': '#d1fae5',
|
||||
'500': '#10b981'
|
||||
},
|
||||
red: {
|
||||
'100': '#fee2e2',
|
||||
'500': '#ef4444'
|
||||
},
|
||||
amber: {
|
||||
'100': '#fef3c7',
|
||||
'500': '#f59e0b'
|
||||
}
|
||||
},
|
||||
boxShadow: {
|
||||
sm: '0 1px 2px 0 rgb(0 0 0 / 0.05)',
|
||||
md: '0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)',
|
||||
lg: '0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)'
|
||||
},
|
||||
borderRadius: {
|
||||
sm: '0.375rem',
|
||||
md: '0.5rem',
|
||||
lg: '0.75rem',
|
||||
xl: '0.875rem'
|
||||
},
|
||||
fontFamily: {
|
||||
// 使用与之前版本保持一致的系统字体栈
|
||||
sans: [
|
||||
'-apple-system',
|
||||
'BlinkMacSystemFont',
|
||||
'"Segoe UI"',
|
||||
'Roboto',
|
||||
'"Helvetica Neue"',
|
||||
'Arial',
|
||||
'sans-serif',
|
||||
],
|
||||
mono: [
|
||||
'ui-monospace',
|
||||
'SFMono-Regular',
|
||||
'"SF Mono"',
|
||||
'Consolas',
|
||||
'"Liberation Mono"',
|
||||
'Menlo',
|
||||
'monospace',
|
||||
],
|
||||
},
|
||||
animation: {
|
||||
'fade-in': 'fadeIn 0.5s ease-out',
|
||||
'slide-up': 'slideUp 0.5s ease-out',
|
||||
'slide-down': 'slideDown 0.3s ease-out',
|
||||
'slide-in-right': 'slideInRight 0.3s ease-out',
|
||||
'pulse-slow': 'pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite',
|
||||
'accordion-down': 'accordion-down 0.2s ease-out',
|
||||
'accordion-up': 'accordion-up 0.2s ease-out'
|
||||
},
|
||||
keyframes: {
|
||||
fadeIn: {
|
||||
'0%': {
|
||||
opacity: '0'
|
||||
},
|
||||
'100%': {
|
||||
opacity: '1'
|
||||
}
|
||||
},
|
||||
slideUp: {
|
||||
'0%': {
|
||||
transform: 'translateY(20px)',
|
||||
opacity: '0'
|
||||
},
|
||||
'100%': {
|
||||
transform: 'translateY(0)',
|
||||
opacity: '1'
|
||||
}
|
||||
},
|
||||
slideDown: {
|
||||
'0%': {
|
||||
transform: 'translateY(-100%)',
|
||||
opacity: '0'
|
||||
},
|
||||
'100%': {
|
||||
transform: 'translateY(0)',
|
||||
opacity: '1'
|
||||
}
|
||||
},
|
||||
slideInRight: {
|
||||
'0%': {
|
||||
transform: 'translateX(100%)',
|
||||
opacity: '0'
|
||||
},
|
||||
'100%': {
|
||||
transform: 'translateX(0)',
|
||||
opacity: '1'
|
||||
}
|
||||
},
|
||||
'accordion-down': {
|
||||
from: {
|
||||
height: '0'
|
||||
},
|
||||
to: {
|
||||
height: 'var(--radix-accordion-content-height)'
|
||||
}
|
||||
},
|
||||
'accordion-up': {
|
||||
from: {
|
||||
height: 'var(--radix-accordion-content-height)'
|
||||
},
|
||||
to: {
|
||||
height: '0'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
extend: {
|
||||
colors: {
|
||||
// shadcn/ui CSS 变量映射
|
||||
background: "hsl(var(--background))",
|
||||
foreground: "hsl(var(--foreground))",
|
||||
card: {
|
||||
DEFAULT: "hsl(var(--card))",
|
||||
foreground: "hsl(var(--card-foreground))",
|
||||
},
|
||||
popover: {
|
||||
DEFAULT: "hsl(var(--popover))",
|
||||
foreground: "hsl(var(--popover-foreground))",
|
||||
},
|
||||
primary: {
|
||||
DEFAULT: "hsl(var(--primary))",
|
||||
foreground: "hsl(var(--primary-foreground))",
|
||||
},
|
||||
secondary: {
|
||||
DEFAULT: "hsl(var(--secondary))",
|
||||
foreground: "hsl(var(--secondary-foreground))",
|
||||
},
|
||||
muted: {
|
||||
DEFAULT: "hsl(var(--muted))",
|
||||
foreground: "hsl(var(--muted-foreground))",
|
||||
},
|
||||
accent: {
|
||||
DEFAULT: "hsl(var(--accent))",
|
||||
foreground: "hsl(var(--accent-foreground))",
|
||||
},
|
||||
destructive: {
|
||||
DEFAULT: "hsl(var(--destructive))",
|
||||
foreground: "hsl(var(--destructive-foreground))",
|
||||
},
|
||||
border: "hsl(var(--border))",
|
||||
input: "hsl(var(--input))",
|
||||
ring: "hsl(var(--ring))",
|
||||
// macOS 风格系统蓝
|
||||
blue: {
|
||||
400: '#409CFF',
|
||||
500: '#0A84FF',
|
||||
600: '#0060DF',
|
||||
},
|
||||
// 自定义灰色系列(对齐 macOS 深色 System Gray)
|
||||
gray: {
|
||||
50: '#fafafa', // bg-primary
|
||||
100: '#f4f4f5', // bg-tertiary
|
||||
200: '#e4e4e7', // border
|
||||
300: '#d4d4d8', // border-hover
|
||||
400: '#a1a1aa', // text-tertiary
|
||||
500: '#71717a', // text-secondary
|
||||
600: '#636366', // text-secondary-dark / systemGray2
|
||||
700: '#48484A', // bg-tertiary-dark / separators
|
||||
800: '#3A3A3C', // bg-secondary-dark
|
||||
900: '#2C2C2E', // header / modal bg
|
||||
950: '#1C1C1E', // app main bg
|
||||
},
|
||||
// 状态颜色
|
||||
green: {
|
||||
500: '#10b981',
|
||||
100: '#d1fae5',
|
||||
},
|
||||
red: {
|
||||
500: '#ef4444',
|
||||
100: '#fee2e2',
|
||||
},
|
||||
amber: {
|
||||
500: '#f59e0b',
|
||||
100: '#fef3c7',
|
||||
},
|
||||
},
|
||||
boxShadow: {
|
||||
'sm': '0 1px 2px 0 rgb(0 0 0 / 0.05)',
|
||||
'md': '0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)',
|
||||
'lg': '0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)',
|
||||
},
|
||||
borderRadius: {
|
||||
'sm': '0.375rem',
|
||||
'md': '0.5rem',
|
||||
'lg': '0.75rem',
|
||||
'xl': '0.875rem',
|
||||
},
|
||||
fontFamily: {
|
||||
sans: ['-apple-system', 'BlinkMacSystemFont', '"Segoe UI"', 'Roboto', '"Helvetica Neue"', 'Arial', 'sans-serif'],
|
||||
mono: ['ui-monospace', 'SFMono-Regular', '"SF Mono"', 'Consolas', '"Liberation Mono"', 'Menlo', 'monospace'],
|
||||
},
|
||||
animation: {
|
||||
'fade-in': 'fadeIn 0.5s ease-out',
|
||||
'slide-up': 'slideUp 0.5s ease-out',
|
||||
'slide-down': 'slideDown 0.3s ease-out',
|
||||
'slide-in-right': 'slideInRight 0.3s ease-out',
|
||||
'pulse-slow': 'pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite',
|
||||
},
|
||||
keyframes: {
|
||||
fadeIn: {
|
||||
'0%': { opacity: '0' },
|
||||
'100%': { opacity: '1' },
|
||||
},
|
||||
slideUp: {
|
||||
'0%': { transform: 'translateY(20px)', opacity: '0' },
|
||||
'100%': { transform: 'translateY(0)', opacity: '1' },
|
||||
},
|
||||
slideDown: {
|
||||
'0%': { transform: 'translateY(-100%)', opacity: '0' },
|
||||
'100%': { transform: 'translateY(0)', opacity: '1' },
|
||||
},
|
||||
slideInRight: {
|
||||
'0%': { transform: 'translateX(100%)', opacity: '0' },
|
||||
'100%': { transform: 'translateX(0)', opacity: '1' },
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
}
|
||||
|
||||
@@ -125,6 +125,7 @@ describe("ProviderList Component", () => {
|
||||
onDelete={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onOpenWebsite={vi.fn()}
|
||||
onSetProxyTarget={vi.fn()}
|
||||
isLoading
|
||||
/>,
|
||||
);
|
||||
@@ -153,6 +154,7 @@ describe("ProviderList Component", () => {
|
||||
onDelete={vi.fn()}
|
||||
onDuplicate={vi.fn()}
|
||||
onOpenWebsite={vi.fn()}
|
||||
onSetProxyTarget={vi.fn()}
|
||||
onCreate={handleCreate}
|
||||
/>,
|
||||
);
|
||||
@@ -193,6 +195,7 @@ describe("ProviderList Component", () => {
|
||||
onDuplicate={handleDuplicate}
|
||||
onConfigureUsage={handleUsage}
|
||||
onOpenWebsite={handleOpenWebsite}
|
||||
onSetProxyTarget={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user