mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-07-24 21:30:17 +08:00
Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0ef670325b | |||
| 07fc6b175e | |||
| 79d3ecc1b8 | |||
| 9c249d9486 | |||
| 15f60e8ce2 | |||
| 3d733a3b80 | |||
| cfb113ac8d | |||
| 62a4ab2ad3 | |||
| aa0f191420 | |||
| b8305f281b | |||
| b3af191fab | |||
| e6b6bc18a9 | |||
| b1f7ff4768 | |||
| 09d8c27972 | |||
| 9736861ace | |||
| fef750bb4c | |||
| 3677bb61f5 | |||
| 2d17bde790 | |||
| dc865fbbbf | |||
| a187380d6f | |||
| b993b1f664 | |||
| 00168877d9 | |||
| 4496110dd8 | |||
| c9e85e8cac | |||
| eab1d08527 | |||
| 30009ad5f1 | |||
| e7badb1a24 | |||
| 7bb458eecb | |||
| 76897e2b97 | |||
| fb9e7dee50 | |||
| e1d4dd7f55 | |||
| 6ce6f16a99 |
@@ -9,6 +9,78 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
---
|
||||
|
||||
## [3.10.1] - 2026-01-23
|
||||
|
||||
### Patch Release
|
||||
|
||||
This maintenance release includes important bug fixes for Windows platform, UI improvements, and code quality enhancements.
|
||||
|
||||
### Added
|
||||
|
||||
- **Provider Icons**: Updated RightCode provider icon with improved visual design
|
||||
|
||||
### Changed
|
||||
|
||||
- **Proxy Rectifier**: Changed rectifier default state to disabled for better stability
|
||||
- **Window Settings**: Reordered window settings and updated default values for improved UX
|
||||
- **UI Layout**: Increased app icon collapse threshold from 3 to 4 icons
|
||||
- **Code Quality**: Simplified `RectifierConfig` implementation using `#[derive(Default)]`
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Windows Platform**:
|
||||
- Fixed terminal window closing immediately after execution on Windows
|
||||
- Corrected OpenCode config path resolution on Windows
|
||||
- **UI Improvements**:
|
||||
- Fixed ProviderIcon color validation to prevent black icons from appearing
|
||||
- Unified layout padding across all panels for consistent spacing
|
||||
- Fixed panel content alignment with header constraints
|
||||
- **Code Quality**: Resolved Rust Clippy warnings and applied consistent formatting
|
||||
|
||||
---
|
||||
|
||||
## [3.10.0] - 2026-01-21
|
||||
|
||||
### Feature Release
|
||||
|
||||
This release introduces OpenCode support and brings improvements across proxy, usage tracking, and overall UX.
|
||||
|
||||
### Added
|
||||
|
||||
- **OpenCode Support** - Manage OpenCode providers, MCP servers, and Skills, with first-launch import and full internationalization (#695)
|
||||
- **Global Proxy** - Add global proxy settings for outbound network requests (#596)
|
||||
- **Claude Rectifier** - Add thinking signature rectifier for Claude API (#595)
|
||||
- **Health Check Enhancements** - Configurable prompt and CLI-compatible requests for stream health check (#623)
|
||||
- **Per-Provider Config** - Support provider-specific configuration and persistence (#663)
|
||||
- **App Visibility Controls** - Show/hide apps and keep tray menu in sync (Gemini hidden by default)
|
||||
- **Takeover Compact Mode** - Use a compact AppSwitcher layout when showing 3+ visible apps
|
||||
- **Keyboard Shortcut** - Press `ESC` to quickly go back/close panels (#670)
|
||||
- **Terminal Improvements** - Provider-specific terminal button, `fnm` path support, and safer cross-platform launching (#564)
|
||||
- **WSL Tool Detection** - Detect tool versions in WSL with additional security hardening (#627)
|
||||
- **Skills Presets** - Add `baoyu-skills` preset repo and auto-supplement missing default repos
|
||||
|
||||
### Changed
|
||||
|
||||
- **Proxy Logging** - Simplify proxy log output (#585)
|
||||
- **Pricing Editor UX** - Unify pricing edit modal with `FullScreenPanel`
|
||||
- **Advanced Settings Layout** - Move rectifier section below failover for better flow
|
||||
- **OpenRouter Compat Mode** - Disable OpenRouter compatibility mode by default and hide UI toggle
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Auto Failover** - Switch to P1 immediately when enabling auto failover
|
||||
- **Provider Edit Dialog** - Fix stale data when reopening provider editor after save (#654)
|
||||
- **Deeplink** - Support multiple endpoints and prioritize `GOOGLE_GEMINI_BASE_URL` over `GEMINI_BASE_URL` (#597)
|
||||
- **MCP (WSL)** - Skip `cmd /c` wrapper for WSL target paths (#592)
|
||||
- **Usage Templates** - Add variable hints and validation fixes; prevent config leaking between providers (#628)
|
||||
- **Gemini Timeout Format** - Convert timeout params to Gemini CLI format (#580)
|
||||
- **UI** - Fix Select dropdown rendering in `FullScreenPanel`; auto-apply default icon color when unset
|
||||
- **Usage UI** - Auto-adapt usage block offset based on action buttons width (#613)
|
||||
- **Provider Endpoint** - Persist endpoint auto-select state (#611)
|
||||
- **Provider Form** - Reset baseUrl and apiKey states when switching presets
|
||||
|
||||
---
|
||||
|
||||
## [3.9.1] - 2026-01-09
|
||||
|
||||
### Bug Fix Release
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
# All-in-One Assistant for Claude Code, Codex & Gemini CLI
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://tauri.app/)
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
@@ -52,7 +52,7 @@ This project is sponsored by Z.ai, supporting us with their GLM CODING PLAN.GLM
|
||||
|
||||
## Features
|
||||
|
||||
### Current Version: v3.9.1 | [Full Changelog](CHANGELOG.md) | [Release Notes](docs/release-note-v3.9.0-en.md)
|
||||
### Current Version: v3.10.0 | [Full Changelog](CHANGELOG.md) | [Release Notes](docs/release-note-v3.9.0-en.md)
|
||||
|
||||
**v3.8.0 Major Update (2025-11-28)**
|
||||
|
||||
@@ -181,7 +181,7 @@ Download `CC-Switch-v{version}-macOS.zip` from the [Releases](../../releases) pa
|
||||
|
||||
> **Note**: Since the author doesn't have an Apple Developer account, you may see an "unidentified developer" warning on first launch. Please close it first, then go to "System Settings" → "Privacy & Security" → click "Open Anyway", and you'll be able to open it normally afterwards.
|
||||
|
||||
### ArchLinux 用户
|
||||
### Arch Linux Users
|
||||
|
||||
**Install via paru (Recommended)**
|
||||
|
||||
|
||||
+2
-2
@@ -2,7 +2,7 @@
|
||||
|
||||
# Claude Code / Codex / Gemini CLI オールインワン・アシスタント
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://tauri.app/)
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
@@ -52,7 +52,7 @@
|
||||
|
||||
## 特長
|
||||
|
||||
### 現在のバージョン:v3.9.1 | [完全な更新履歴](CHANGELOG.md) | [リリースノート](docs/release-note-v3.9.0-ja.md)
|
||||
### 現在のバージョン:v3.10.0 | [完全な更新履歴](CHANGELOG.md) | [リリースノート](docs/release-note-v3.9.0-ja.md)
|
||||
|
||||
**v3.8.0 メジャーアップデート (2025-11-28)**
|
||||
|
||||
|
||||
+2
-2
@@ -2,7 +2,7 @@
|
||||
|
||||
# Claude Code / Codex / Gemini CLI 全方位辅助工具
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://tauri.app/)
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
@@ -52,7 +52,7 @@
|
||||
|
||||
## 功能特性
|
||||
|
||||
### 当前版本:v3.9.1 | [完整更新日志](CHANGELOG.md) | [发布说明](docs/release-note-v3.9.0-zh.md)
|
||||
### 当前版本:v3.10.0 | [完整更新日志](CHANGELOG.md) | [发布说明](docs/release-note-v3.9.0-zh.md)
|
||||
|
||||
**v3.8.0 重大更新(2025-11-28)**
|
||||
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
# CC Switch v3.10.0
|
||||
|
||||
> OpenCode Support, Global Proxy, Claude Rectifier & Multi-App Experience Enhancements
|
||||
|
||||
**[中文版 →](release-note-v3.10.0-zh.md) | [日本語版 →](release-note-v3.10.0-ja.md)**
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
CC Switch v3.10.0 introduces OpenCode support, becoming the fourth managed CLI application.
|
||||
This release also brings global proxy settings, Claude Rectifier (thinking signature fixer), enhanced health checks, per-provider configuration, and many other important features, along with comprehensive improvements to multi-app workflows and terminal experience.
|
||||
|
||||
**Release Date**: 2026-01-21
|
||||
|
||||
---
|
||||
|
||||
## Highlights
|
||||
|
||||
- OpenCode Support: Full management of providers, MCP servers, and Skills with auto-import on first launch
|
||||
- Global Proxy: Configure a unified proxy for all outbound network requests
|
||||
- Claude Rectifier: Thinking signature fixer for better compatibility with third-party APIs
|
||||
- Enhanced Health Checks: Configurable prompts and CLI-compatible request format
|
||||
- Per-Provider Config: Persistent provider-specific configuration support
|
||||
- App Visibility Control: Freely show/hide apps with synchronized tray menu updates
|
||||
- Terminal Improvements: Provider-specific terminal buttons, fnm path support, cross-platform safe launch
|
||||
- WSL Tool Detection: Detect tool versions in WSL environment with security hardening
|
||||
|
||||
---
|
||||
|
||||
## Main Features
|
||||
|
||||
### OpenCode Support (New Fourth App)
|
||||
|
||||
- Complete OpenCode provider management: add, edit, switch, delete
|
||||
- MCP server management: unified architecture with Claude/Codex/Gemini
|
||||
- Skills support: OpenCode can also use Skills functionality
|
||||
- Auto-import on first launch: automatically imports existing OpenCode configuration when detected
|
||||
- Full internationalization: Chinese/English/Japanese support (#695)
|
||||
|
||||
### Global Proxy
|
||||
|
||||
- Configure a unified proxy for all outbound network requests (#596, thanks @yovinchen)
|
||||
- Supports HTTP/HTTPS proxy protocols
|
||||
- Suitable for network environments requiring proxy access to external APIs
|
||||
|
||||
### Claude Rectifier (Thinking Signature Fixer)
|
||||
|
||||
- Automatically fixes Claude API thinking signatures (#595, thanks @yovinchen)
|
||||
- Resolves incompatible thinking block formats returned by some third-party API gateways
|
||||
- Can be enabled/disabled in Advanced Settings
|
||||
|
||||
### Enhanced Health Checks
|
||||
|
||||
- Configurable custom prompts for streaming health checks (#623, thanks @yovinchen)
|
||||
- Supports CLI-compatible request format for better simulation of real usage scenarios
|
||||
- Improves fault detection accuracy
|
||||
|
||||
### Per-Provider Config
|
||||
|
||||
- Support for saving configuration separately for each provider (#663, thanks @yovinchen)
|
||||
- Persistent configuration: provider-specific settings retained after restart
|
||||
- Suitable for scenarios where different providers require different configurations
|
||||
|
||||
### App Visibility Control
|
||||
|
||||
- Freely show/hide any app (Gemini hidden by default)
|
||||
- Tray menu automatically syncs visibility settings
|
||||
- Hidden apps won't appear in the main interface or tray menu
|
||||
|
||||
### Takeover Compact Mode
|
||||
|
||||
- Automatically uses compact layout when 3 or more visible apps are displayed
|
||||
- Optimizes space utilization in multi-app scenarios
|
||||
|
||||
### Terminal Improvements
|
||||
|
||||
- Provider-specific terminal button: one-click to use current provider in terminal (#564, thanks @kkkman22)
|
||||
- `fnm` path support: automatically recognizes Node.js paths managed by fnm
|
||||
- Cross-platform safe launch: improved terminal launch logic for Windows/macOS/Linux
|
||||
|
||||
### WSL Tool Detection
|
||||
|
||||
- Detect tool versions in WSL environment (#627, thanks @yovinchen)
|
||||
- Added security hardening to prevent command injection risks
|
||||
|
||||
### Skills Preset Enhancements
|
||||
|
||||
- Added `baoyu-skills` preset repository
|
||||
- Automatically supplements missing default repositories for out-of-the-box experience
|
||||
|
||||
---
|
||||
|
||||
## Experience Improvements
|
||||
|
||||
- Keyboard shortcuts: Press `ESC` to quickly return/close panels (#670, thanks @xxk8)
|
||||
- Simplified proxy logs: cleaner and more readable output (#585, thanks @yovinchen)
|
||||
- Pricing editor UX: unified `FullScreenPanel` style
|
||||
- Advanced settings layout: Rectifier section moved below Failover for better logical flow
|
||||
- OpenRouter compatibility mode: disabled by default, UI toggle hidden (reduces clutter)
|
||||
|
||||
---
|
||||
|
||||
## Bug Fixes
|
||||
|
||||
### Proxy & Failover
|
||||
|
||||
- Immediately switch to P1 when auto-failover is enabled (instead of waiting for next request)
|
||||
|
||||
### Provider Management
|
||||
|
||||
- Fixed stale data when reopening provider edit dialog after save (#654, thanks @YangYongAn)
|
||||
- Fixed baseUrl and apiKey state not resetting when switching presets
|
||||
- Fixed endpoint auto-selection state not persisting (#611, thanks @yovinchen)
|
||||
- Automatically apply default color when icon color is not set
|
||||
|
||||
### Deep Links
|
||||
|
||||
- Support multi-endpoint import (#597, thanks @yovinchen)
|
||||
- Prefer `GOOGLE_GEMINI_BASE_URL` over `GEMINI_BASE_URL`
|
||||
|
||||
### MCP
|
||||
|
||||
- Skip `cmd /c` wrapper for WSL target paths (#592, thanks @cxyfer)
|
||||
|
||||
### Usage Templates
|
||||
|
||||
- Added variable hints, fixed validation issues (#628, thanks @YangYongAn)
|
||||
- Prevent configuration leakage between providers
|
||||
- Usage block offset automatically adapts to action button width (#613, thanks @yovinchen)
|
||||
|
||||
### Gemini
|
||||
|
||||
- Convert timeout parameters to Gemini CLI format (#580, thanks @cxyfer)
|
||||
|
||||
### UI
|
||||
|
||||
- Fixed Select dropdown rendering issues in `FullScreenPanel`
|
||||
|
||||
---
|
||||
|
||||
## Notes & Considerations
|
||||
|
||||
- **OpenCode is a newly supported app**: OpenCode CLI must be installed first to use related features.
|
||||
- **Global proxy affects all outbound requests**: including usage queries, health checks, and other network operations.
|
||||
- **Rectifier is experimental**: can be disabled in Advanced Settings if issues occur.
|
||||
|
||||
---
|
||||
|
||||
## Special Thanks
|
||||
|
||||
Thanks to @yovinchen @YangYongAn @cxyfer @xxk8 @kkkman22 @Shuimo03 for their contributions to this release!
|
||||
Thanks to @libukai for designing the elegant failover-related UI!
|
||||
|
||||
---
|
||||
|
||||
## Download & Installation
|
||||
|
||||
Visit [Releases](https://github.com/farion1231/cc-switch/releases/latest) to download the appropriate version.
|
||||
|
||||
### System Requirements
|
||||
|
||||
| System | Minimum Version | Architecture |
|
||||
| ------- | ------------------------------ | ----------------------------------- |
|
||||
| Windows | Windows 10 or later | x64 |
|
||||
| macOS | macOS 10.15 (Catalina) or later | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | See table below | x64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| File | Description |
|
||||
| ---------------------------------------- | ---------------------------------------------------- |
|
||||
| `CC-Switch-v3.10.0-Windows.msi` | **Recommended** - MSI installer with auto-update |
|
||||
| `CC-Switch-v3.10.0-Windows-Portable.zip` | Portable version, extract and run, no registry write |
|
||||
|
||||
### macOS
|
||||
|
||||
| File | Description |
|
||||
| -------------------------------- | ------------------------------------------------------------------ |
|
||||
| `CC-Switch-v3.10.0-macOS.zip` | **Recommended** - Extract and drag to Applications, Universal Binary |
|
||||
| `CC-Switch-v3.10.0-macOS.tar.gz` | For Homebrew installation and auto-update |
|
||||
|
||||
> **Note**: Since the author doesn't have an Apple Developer account, you may see an "unidentified developer" warning on first launch. Please close it, then go to "System Settings" → "Privacy & Security" → click "Open Anyway", and it will open normally afterwards.
|
||||
|
||||
### Homebrew (macOS)
|
||||
|
||||
```bash
|
||||
brew tap farion1231/ccswitch
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
Update:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
| Distribution | Recommended Format | Installation Method |
|
||||
| --------------------------------------- | ------------------ | ---------------------------------------------------------------------- |
|
||||
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` or `sudo apt install ./CC-Switch-*.deb` |
|
||||
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` or `sudo dnf install ./CC-Switch-*.rpm` |
|
||||
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
|
||||
| Arch Linux / Manjaro | `.AppImage` | Add execute permission and run directly, or use AUR |
|
||||
| Other distributions / Unsure | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
|
||||
@@ -0,0 +1,206 @@
|
||||
# CC Switch v3.10.0
|
||||
|
||||
> OpenCode サポート、グローバルプロキシ、Claude Rectifier とマルチアプリ体験の強化
|
||||
|
||||
**[中文版 →](release-note-v3.10.0-zh.md) | [English →](release-note-v3.10.0-en.md)**
|
||||
|
||||
---
|
||||
|
||||
## 概要
|
||||
|
||||
CC Switch v3.10.0 では OpenCode サポートが追加され、4番目の管理対象 CLI アプリケーションとなりました。
|
||||
また、グローバルプロキシ設定、Claude Rectifier(thinking 署名修正機能)、ヘルスチェックの強化、プロバイダー別設定など、多くの重要な機能が追加され、マルチアプリワークフローとターミナル体験が全面的に改善されました。
|
||||
|
||||
**リリース日**: 2026-01-21
|
||||
|
||||
---
|
||||
|
||||
## ハイライト
|
||||
|
||||
- OpenCode サポート:プロバイダー、MCP サーバー、Skills の完全管理、初回起動時の自動インポート
|
||||
- グローバルプロキシ:すべての送信ネットワークリクエストに統一プロキシを設定
|
||||
- Claude Rectifier:thinking 署名修正機能、サードパーティ API との互換性向上
|
||||
- ヘルスチェック強化:カスタムプロンプト設定、CLI 互換リクエスト形式
|
||||
- プロバイダー別設定:プロバイダー固有の設定の永続化をサポート
|
||||
- アプリ表示制御:アプリの表示/非表示を自由に設定、トレイメニューと同期
|
||||
- ターミナル改善:プロバイダー専用ターミナルボタン、fnm パスサポート、クロスプラットフォーム安全起動
|
||||
- WSL ツール検出:WSL 環境でのツールバージョン検出とセキュリティ強化
|
||||
|
||||
---
|
||||
|
||||
## 主な機能
|
||||
|
||||
### OpenCode サポート(新しい4番目のアプリ)
|
||||
|
||||
- 完全な OpenCode プロバイダー管理:追加、編集、切り替え、削除
|
||||
- MCP サーバー管理:Claude/Codex/Gemini と統一されたアーキテクチャ
|
||||
- Skills サポート:OpenCode でも Skills 機能を使用可能
|
||||
- 初回起動時の自動インポート:既存の OpenCode 設定を検出すると自動的にインポート
|
||||
- 完全な国際化:中国語/英語/日本語サポート (#695)
|
||||
|
||||
### グローバルプロキシ
|
||||
|
||||
- すべての送信ネットワークリクエストに統一プロキシを設定 (#596、@yovinchen に感謝)
|
||||
- HTTP/HTTPS プロキシプロトコルをサポート
|
||||
- 外部 API へのプロキシアクセスが必要なネットワーク環境に適用
|
||||
|
||||
### Claude Rectifier(Thinking 署名修正機能)
|
||||
|
||||
- Claude API の thinking 署名を自動修正 (#595、@yovinchen に感謝)
|
||||
- 一部のサードパーティ API ゲートウェイが返す互換性のない thinking ブロック形式を解決
|
||||
- 詳細設定で有効/無効を切り替え可能
|
||||
|
||||
### ヘルスチェック強化
|
||||
|
||||
- ストリーミングヘルスチェック用のカスタムプロンプトを設定可能 (#623、@yovinchen に感謝)
|
||||
- CLI 互換リクエスト形式をサポートし、実際の使用シナリオをより良くシミュレート
|
||||
- 障害検出の精度を向上
|
||||
|
||||
### プロバイダー別設定
|
||||
|
||||
- 各プロバイダーごとに設定を個別に保存可能 (#663、@yovinchen に感謝)
|
||||
- 設定の永続化:再起動後もプロバイダー固有の設定を保持
|
||||
- 異なるプロバイダーに異なる設定が必要なシナリオに適用
|
||||
|
||||
### アプリ表示制御
|
||||
|
||||
- 任意のアプリを自由に表示/非表示(Gemini はデフォルトで非表示)
|
||||
- トレイメニューは表示設定と自動的に同期
|
||||
- 非表示のアプリはメインインターフェースとトレイメニューに表示されない
|
||||
|
||||
### Takeover コンパクトモード
|
||||
|
||||
- 3つ以上の表示アプリがある場合、自動的にコンパクトレイアウトを使用
|
||||
- マルチアプリシナリオでのスペース利用を最適化
|
||||
|
||||
### ターミナル改善
|
||||
|
||||
- プロバイダー専用ターミナルボタン:ワンクリックでターミナルで現在のプロバイダーを使用 (#564、@kkkman22 に感謝)
|
||||
- `fnm` パスサポート:fnm で管理された Node.js パスを自動認識
|
||||
- クロスプラットフォーム安全起動:Windows/macOS/Linux のターミナル起動ロジックを改善
|
||||
|
||||
### WSL ツール検出
|
||||
|
||||
- WSL 環境でツールバージョンを検出 (#627、@yovinchen に感謝)
|
||||
- コマンドインジェクションリスクを防ぐためのセキュリティ強化を追加
|
||||
|
||||
### Skills プリセット強化
|
||||
|
||||
- `baoyu-skills` プリセットリポジトリを追加
|
||||
- 不足しているデフォルトリポジトリを自動補完し、すぐに使える状態を確保
|
||||
|
||||
---
|
||||
|
||||
## 体験の改善
|
||||
|
||||
- キーボードショートカット:`ESC` を押してパネルをすばやく戻る/閉じる (#670、@xxk8 に感謝)
|
||||
- プロキシログの簡素化:より明確で読みやすい出力 (#585、@yovinchen に感謝)
|
||||
- 価格エディター UX:統一された `FullScreenPanel` スタイル
|
||||
- 詳細設定レイアウト:Rectifier セクションを Failover の下に移動し、論理的な流れを改善
|
||||
- OpenRouter 互換モード:デフォルトで無効、UI トグルを非表示(煩雑さを軽減)
|
||||
|
||||
---
|
||||
|
||||
## バグ修正
|
||||
|
||||
### プロキシとフェイルオーバー
|
||||
|
||||
- 自動フェイルオーバーが有効な場合、すぐに P1 に切り替え(次のリクエストを待たずに)
|
||||
|
||||
### プロバイダー管理
|
||||
|
||||
- 保存後にプロバイダー編集ダイアログを再度開いたときにデータが古い問題を修正 (#654、@YangYongAn に感謝)
|
||||
- プリセット切り替え時に baseUrl と apiKey の状態がリセットされない問題を修正
|
||||
- エンドポイント自動選択状態が永続化されない問題を修正 (#611、@yovinchen に感謝)
|
||||
- アイコンカラーが設定されていない場合、デフォルトカラーを自動適用
|
||||
|
||||
### ディープリンク
|
||||
|
||||
- マルチエンドポイントインポートをサポート (#597、@yovinchen に感謝)
|
||||
- `GEMINI_BASE_URL` より `GOOGLE_GEMINI_BASE_URL` を優先
|
||||
|
||||
### MCP
|
||||
|
||||
- WSL ターゲットパスの `cmd /c` ラッパーをスキップ (#592、@cxyfer に感謝)
|
||||
|
||||
### 使用量テンプレート
|
||||
|
||||
- 変数ヒントを追加、検証の問題を修正 (#628、@YangYongAn に感謝)
|
||||
- プロバイダー間での設定漏洩を防止
|
||||
- 使用量ブロックのオフセットがアクションボタンの幅に自動適応 (#613、@yovinchen に感謝)
|
||||
|
||||
### Gemini
|
||||
|
||||
- タイムアウトパラメータを Gemini CLI 形式に変換 (#580、@cxyfer に感謝)
|
||||
|
||||
### UI
|
||||
|
||||
- `FullScreenPanel` での Select ドロップダウンのレンダリング問題を修正
|
||||
|
||||
---
|
||||
|
||||
## 注意事項
|
||||
|
||||
- **OpenCode は新しくサポートされたアプリです**:関連機能を使用するには、まず OpenCode CLI をインストールする必要があります。
|
||||
- **グローバルプロキシはすべての送信リクエストに影響します**:使用量クエリ、ヘルスチェックなどのネットワーク操作を含みます。
|
||||
- **Rectifier は実験的機能です**:問題が発生した場合は、詳細設定で無効にできます。
|
||||
|
||||
---
|
||||
|
||||
## 特別な感謝
|
||||
|
||||
@yovinchen @YangYongAn @cxyfer @xxk8 @kkkman22 @Shuimo03 の皆様、このリリースへの貢献に感謝します!
|
||||
@libukai 様、エレガントなフェイルオーバー関連 UI のデザインに感謝します!
|
||||
|
||||
---
|
||||
|
||||
## ダウンロードとインストール
|
||||
|
||||
[Releases](https://github.com/farion1231/cc-switch/releases/latest) から適切なバージョンをダウンロードしてください。
|
||||
|
||||
### システム要件
|
||||
|
||||
| システム | 最小バージョン | アーキテクチャ |
|
||||
| -------- | -------------------------------- | ----------------------------------- |
|
||||
| Windows | Windows 10 以降 | x64 |
|
||||
| macOS | macOS 10.15 (Catalina) 以降 | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | 下表参照 | x64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| ファイル | 説明 |
|
||||
| ---------------------------------------- | ---------------------------------------------------- |
|
||||
| `CC-Switch-v3.10.0-Windows.msi` | **推奨** - MSI インストーラー、自動更新対応 |
|
||||
| `CC-Switch-v3.10.0-Windows-Portable.zip` | ポータブル版、解凍して実行、レジストリ書き込みなし |
|
||||
|
||||
### macOS
|
||||
|
||||
| ファイル | 説明 |
|
||||
| -------------------------------- | ----------------------------------------------------------------- |
|
||||
| `CC-Switch-v3.10.0-macOS.zip` | **推奨** - 解凍して Applications にドラッグ、Universal Binary |
|
||||
| `CC-Switch-v3.10.0-macOS.tar.gz` | Homebrew インストールと自動更新用 |
|
||||
|
||||
> **注意**:作者が Apple Developer アカウントを持っていないため、初回起動時に「開発元を確認できません」という警告が表示される場合があります。一度閉じてから、「システム設定」→「プライバシーとセキュリティ」→「このまま開く」をクリックすると、その後は正常に開けます。
|
||||
|
||||
### Homebrew (macOS)
|
||||
|
||||
```bash
|
||||
brew tap farion1231/ccswitch
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
更新:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
| ディストリビューション | 推奨形式 | インストール方法 |
|
||||
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
|
||||
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` または `sudo apt install ./CC-Switch-*.deb` |
|
||||
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` または `sudo dnf install ./CC-Switch-*.rpm` |
|
||||
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
|
||||
| Arch Linux / Manjaro | `.AppImage` | 実行権限を追加して直接実行、または AUR を使用 |
|
||||
| その他のディストリビューション / 不明 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
|
||||
@@ -0,0 +1,206 @@
|
||||
# CC Switch v3.10.0
|
||||
|
||||
> OpenCode 支持、全局代理、Claude Rectifier 与多应用体验增强
|
||||
|
||||
**[English →](release-note-v3.10.0-en.md) | [日本語版 →](release-note-v3.10.0-ja.md)**
|
||||
|
||||
---
|
||||
|
||||
## 概览
|
||||
|
||||
CC Switch v3.10.0 新增 OpenCode 支持,成为第四个受管理的 CLI 应用。
|
||||
同时带来全局代理设置、Claude Rectifier(thinking 签名修正器)、健康检查增强、按供应商配置等多项重要功能,并对多应用工作流与终端体验做了全面改进。
|
||||
|
||||
**发布日期**:2026-01-21
|
||||
|
||||
---
|
||||
|
||||
## 重点内容
|
||||
|
||||
- OpenCode 支持:供应商、MCP 服务器、Skills 全面管理,首次启动自动导入
|
||||
- 全局代理:为出站网络请求统一配置代理
|
||||
- Claude Rectifier:thinking 签名修正器,兼容更多第三方 API
|
||||
- 健康检查增强:可配置提示词、CLI 兼容请求
|
||||
- 按供应商配置:支持供应商特定配置的持久化
|
||||
- 应用可见性控制:自由显示/隐藏应用,托盘菜单同步更新
|
||||
- 终端改进:供应商专属终端按钮、fnm 路径支持、跨平台安全启动
|
||||
- WSL 工具检测:在 WSL 环境检测工具版本,并增加安全加固
|
||||
|
||||
---
|
||||
|
||||
## 主要功能
|
||||
|
||||
### OpenCode 支持(新增第四应用)
|
||||
|
||||
- 完整的 OpenCode 供应商管理:新增、编辑、切换、删除
|
||||
- MCP 服务器管理:与 Claude/Codex/Gemini 统一架构
|
||||
- Skills 支持:OpenCode 也可使用 Skills 功能
|
||||
- 首次启动自动导入:检测到已有 OpenCode 配置时自动导入
|
||||
- 完整国际化:中/英/日三语支持(#695)
|
||||
|
||||
### 全局代理(Global Proxy)
|
||||
|
||||
- 为所有出站网络请求配置统一代理(#596,感谢 @yovinchen)
|
||||
- 支持 HTTP/HTTPS 代理协议
|
||||
- 适用于需要代理访问外部 API 的网络环境
|
||||
|
||||
### Claude Rectifier(Thinking 签名修正器)
|
||||
|
||||
- 自动修正 Claude API 的 thinking 签名(#595,感谢 @yovinchen)
|
||||
- 解决部分第三方 API 网关返回的 thinking 块格式不兼容问题
|
||||
- 在高级设置中可开启/关闭
|
||||
|
||||
### 健康检查增强
|
||||
|
||||
- 可配置自定义提示词(prompt)用于流式健康检查(#623,感谢 @yovinchen)
|
||||
- 支持 CLI 兼容请求格式,更好地模拟真实使用场景
|
||||
- 提升故障检测的准确性
|
||||
|
||||
### 按供应商配置(Per-Provider Config)
|
||||
|
||||
- 支持为每个供应商单独保存配置(#663,感谢 @yovinchen)
|
||||
- 配置持久化:重启后保留供应商专属设置
|
||||
- 适用于不同供应商需要不同配置的场景
|
||||
|
||||
### 应用可见性控制
|
||||
|
||||
- 自由显示/隐藏任意应用(Gemini 默认隐藏)
|
||||
- 托盘菜单自动同步可见性设置
|
||||
- 隐藏的应用不会出现在主界面和托盘菜单中
|
||||
|
||||
### Takeover Compact Mode
|
||||
|
||||
- 当显示 3 个及以上可见应用时,自动使用紧凑布局
|
||||
- 优化多应用场景下的空间利用
|
||||
|
||||
### 终端改进
|
||||
|
||||
- 供应商专属终端按钮:一键在终端中使用当前供应商(#564,感谢 @kkkman22)
|
||||
- `fnm` 路径支持:自动识别 fnm 管理的 Node.js 路径
|
||||
- 跨平台安全启动:改进 Windows/macOS/Linux 的终端启动逻辑
|
||||
|
||||
### WSL 工具检测
|
||||
|
||||
- 在 WSL 环境中检测工具版本(#627,感谢 @yovinchen)
|
||||
- 增加安全加固,防止命令注入风险
|
||||
|
||||
### Skills 预设增强
|
||||
|
||||
- 新增 `baoyu-skills` 预设仓库
|
||||
- 自动补充缺失的默认仓库,确保开箱即用
|
||||
|
||||
---
|
||||
|
||||
## 体验优化
|
||||
|
||||
- 键盘快捷键:按 `ESC` 快速返回/关闭面板(#670,感谢 @xxk8)
|
||||
- 代理日志简化:输出更清晰易读(#585,感谢 @yovinchen)
|
||||
- 定价编辑器 UX:统一使用 `FullScreenPanel` 风格
|
||||
- 高级设置布局:Rectifier 区块移至 Failover 下方,逻辑更顺畅
|
||||
- OpenRouter 兼容模式:默认禁用,UI 开关隐藏(减少干扰)
|
||||
|
||||
---
|
||||
|
||||
## Bug 修复
|
||||
|
||||
### 代理与故障切换
|
||||
|
||||
- 启用自动故障切换时立即切换到 P1(而非等待下次请求)
|
||||
|
||||
### 供应商管理
|
||||
|
||||
- 修复供应商编辑对话框保存后重新打开时数据过时的问题(#654,感谢 @YangYongAn)
|
||||
- 修复切换预设时 baseUrl 和 apiKey 状态未重置的问题
|
||||
- 修复端点自动选择状态未持久化的问题(#611,感谢 @yovinchen)
|
||||
- 未设置图标颜色时自动应用默认颜色
|
||||
|
||||
### 深链接
|
||||
|
||||
- 支持多端点导入(#597,感谢 @yovinchen)
|
||||
- 优先使用 `GOOGLE_GEMINI_BASE_URL` 而非 `GEMINI_BASE_URL`
|
||||
|
||||
### MCP
|
||||
|
||||
- WSL 目标路径跳过 `cmd /c` 包裹(#592,感谢 @cxyfer)
|
||||
|
||||
### 用量模板
|
||||
|
||||
- 新增变量提示,修复验证问题(#628,感谢 @YangYongAn)
|
||||
- 防止配置在供应商之间泄漏
|
||||
- 用量区块偏移量根据操作按钮宽度自动适应(#613,感谢 @yovinchen)
|
||||
|
||||
### Gemini
|
||||
|
||||
- 超时参数转换为 Gemini CLI 格式(#580,感谢 @cxyfer)
|
||||
|
||||
### UI
|
||||
|
||||
- 修复 `FullScreenPanel` 中 Select 下拉框渲染问题
|
||||
|
||||
---
|
||||
|
||||
## 说明与注意事项
|
||||
|
||||
- **OpenCode 为新支持的应用**:需要先安装 OpenCode CLI 才能使用相关功能。
|
||||
- **全局代理会影响所有出站请求**:包括用量查询、健康检查等网络操作。
|
||||
- **Rectifier 功能为实验性**:如遇问题可在高级设置中关闭。
|
||||
|
||||
---
|
||||
|
||||
## 特别感谢
|
||||
|
||||
感谢 @yovinchen @YangYongAn @cxyfer @xxk8 @kkkman22 @Shuimo03 为本版本做出的贡献!
|
||||
感谢 @libukai 设计的故障转移相关 UI,非常优雅!
|
||||
|
||||
---
|
||||
|
||||
## 下载与安装
|
||||
|
||||
访问 [Releases](https://github.com/farion1231/cc-switch/releases/latest) 下载对应版本。
|
||||
|
||||
### 系统要求
|
||||
|
||||
| 系统 | 最低版本 | 架构 |
|
||||
| ------- | ----------------------------- | ----------------------------------- |
|
||||
| Windows | Windows 10 及以上 | x64 |
|
||||
| macOS | macOS 10.15 (Catalina) 及以上 | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | 见下表 | x64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| 文件 | 说明 |
|
||||
| ---------------------------------------- | ----------------------------------- |
|
||||
| `CC-Switch-v3.10.0-Windows.msi` | **推荐** - MSI 安装包,支持自动更新 |
|
||||
| `CC-Switch-v3.10.0-Windows-Portable.zip` | 便携版,解压即用,不写入注册表 |
|
||||
|
||||
### macOS
|
||||
|
||||
| 文件 | 说明 |
|
||||
| -------------------------------- | --------------------------------------------------------- |
|
||||
| `CC-Switch-v3.10.0-macOS.zip` | **推荐** - 解压后拖入 Applications 即可,Universal Binary |
|
||||
| `CC-Switch-v3.10.0-macOS.tar.gz` | 用于 Homebrew 安装和自动更新 |
|
||||
|
||||
> **注意**:由于作者没有苹果开发者账号,首次打开可能出现"未知开发者"警告,请先关闭,然后前往"系统设置" → "隐私与安全性" → 点击"仍要打开",之后便可以正常打开
|
||||
|
||||
### Homebrew(macOS)
|
||||
|
||||
```bash
|
||||
brew tap farion1231/ccswitch
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
更新:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
| 发行版 | 推荐格式 | 安装方式 |
|
||||
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
|
||||
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` 或 `sudo apt install ./CC-Switch-*.deb` |
|
||||
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` 或 `sudo dnf install ./CC-Switch-*.rpm` |
|
||||
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
|
||||
| Arch Linux / Manjaro | `.AppImage` | 添加执行权限后直接运行,或使用 AUR |
|
||||
| 其他发行版 / 不确定 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cc-switch",
|
||||
"version": "3.9.1",
|
||||
"version": "3.10.1",
|
||||
"description": "All-in-One Assistant for Claude Code, Codex & Gemini CLI",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
Generated
+1
-1
@@ -701,7 +701,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cc-switch"
|
||||
version = "3.9.1"
|
||||
version = "3.10.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-stream",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "cc-switch"
|
||||
version = "3.9.1"
|
||||
version = "3.10.1"
|
||||
description = "All-in-One Assistant for Claude Code, Codex & Gemini CLI"
|
||||
authors = ["Jason Young"]
|
||||
license = "MIT"
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
use crate::database::FailoverQueueItem;
|
||||
use crate::provider::Provider;
|
||||
use crate::store::AppState;
|
||||
use std::str::FromStr;
|
||||
use tauri::Emitter;
|
||||
|
||||
/// 获取故障转移队列
|
||||
#[tauri::command]
|
||||
@@ -75,6 +77,7 @@ pub async fn get_auto_failover_enabled(
|
||||
/// 注意:关闭故障转移时不会清除队列,队列内容会保留供下次开启时使用
|
||||
#[tauri::command]
|
||||
pub async fn set_auto_failover_enabled(
|
||||
app: tauri::AppHandle,
|
||||
state: tauri::State<'_, AppState>,
|
||||
app_type: String,
|
||||
enabled: bool,
|
||||
@@ -83,6 +86,47 @@ pub async fn set_auto_failover_enabled(
|
||||
"[Failover] Setting auto_failover_enabled: app_type='{app_type}', enabled={enabled}"
|
||||
);
|
||||
|
||||
// 强一致语义:开启故障转移后立即切到队列 P1(并确保队列非空)
|
||||
//
|
||||
// 说明:
|
||||
// - 仅在 enabled=true 时执行“切到 P1”
|
||||
// - 若队列为空,则尝试把“当前供应商”自动加入队列作为 P1,避免用户在 UI 上陷入死锁(无法先加队列再开启)
|
||||
let p1_provider_id = if enabled {
|
||||
let mut queue = state
|
||||
.db
|
||||
.get_failover_queue(&app_type)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
if queue.is_empty() {
|
||||
let app_enum = crate::app_config::AppType::from_str(&app_type)
|
||||
.map_err(|_| format!("无效的应用类型: {app_type}"))?;
|
||||
|
||||
let current_id = crate::settings::get_effective_current_provider(&state.db, &app_enum)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let Some(current_id) = current_id else {
|
||||
return Err("故障转移队列为空,且未设置当前供应商,无法开启故障转移".to_string());
|
||||
};
|
||||
|
||||
state
|
||||
.db
|
||||
.add_to_failover_queue(&app_type, ¤t_id)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
queue = state
|
||||
.db
|
||||
.get_failover_queue(&app_type)
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
|
||||
queue
|
||||
.first()
|
||||
.map(|item| item.provider_id.clone())
|
||||
.ok_or_else(|| "故障转移队列为空,无法开启故障转移".to_string())?
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
// 读取当前配置
|
||||
let mut config = state
|
||||
.db
|
||||
@@ -98,5 +142,30 @@ pub async fn set_auto_failover_enabled(
|
||||
.db
|
||||
.update_proxy_config_for_app(config)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
// 开启后立即切到 P1:更新 is_current + 本地 settings + Live 备份(接管模式下)
|
||||
if enabled {
|
||||
state
|
||||
.proxy_service
|
||||
.switch_proxy_target(&app_type, &p1_provider_id)
|
||||
.await?;
|
||||
|
||||
// 发射 provider-switched 事件(让前端刷新当前供应商)
|
||||
let event_data = serde_json::json!({
|
||||
"appType": app_type,
|
||||
"providerId": p1_provider_id,
|
||||
"source": "failoverEnabled"
|
||||
});
|
||||
let _ = app.emit("provider-switched", event_data);
|
||||
}
|
||||
|
||||
// 刷新托盘菜单,确保状态同步
|
||||
if let Ok(new_menu) = crate::tray::create_tray_menu(&app, &state) {
|
||||
if let Some(tray) = app.tray_by_id("main") {
|
||||
let _ = tray.set_menu(Some(new_menu));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+126
-78
@@ -322,6 +322,19 @@ fn scan_cli_version(tool: &str) -> (Option<String>, Option<String>) {
|
||||
search_paths.push(std::path::PathBuf::from("C:\\Program Files\\nodejs"));
|
||||
}
|
||||
|
||||
// 添加 fnm 路径支持
|
||||
let fnm_base = home.join(".local/state/fnm_multishells");
|
||||
if fnm_base.exists() {
|
||||
if let Ok(entries) = std::fs::read_dir(&fnm_base) {
|
||||
for entry in entries.flatten() {
|
||||
let bin_path = entry.path().join("bin");
|
||||
if bin_path.exists() {
|
||||
search_paths.push(bin_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 扫描 nvm 目录下的所有 node 版本
|
||||
let nvm_base = home.join(".nvm/versions/node");
|
||||
if nvm_base.exists() {
|
||||
@@ -526,18 +539,15 @@ fn launch_terminal_with_env(
|
||||
// 创建并写入配置文件
|
||||
write_claude_config(&config_file, &env_vars)?;
|
||||
|
||||
// 转义配置文件路径用于 shell
|
||||
let config_path_escaped = escape_shell_path(&config_file);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
launch_macos_terminal(&config_file, &config_path_escaped)?;
|
||||
launch_macos_terminal(&config_file)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
launch_linux_terminal(&config_file, &config_path_escaped)?;
|
||||
launch_linux_terminal(&config_file)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -571,104 +581,132 @@ fn write_claude_config(
|
||||
std::fs::write(config_file, config_json).map_err(|e| format!("写入配置文件失败: {e}"))
|
||||
}
|
||||
|
||||
/// 转义 shell 路径
|
||||
fn escape_shell_path(path: &std::path::Path) -> String {
|
||||
path.to_string_lossy()
|
||||
.replace('\\', "\\\\")
|
||||
.replace('"', "\\\"")
|
||||
.replace('$', "\\$")
|
||||
.replace(' ', "\\ ")
|
||||
}
|
||||
|
||||
/// 生成 bash 包装脚本,用于清理临时文件
|
||||
fn generate_wrapper_script(config_path: &str, escaped_path: &str) -> String {
|
||||
format!(
|
||||
"bash -c 'trap \"rm -f \\\"{config_path}\\\"\" EXIT; echo \"Using provider-specific claude config:\"; echo \"{escaped_path}\"; claude --settings \"{escaped_path}\"; exec bash --norc --noprofile'"
|
||||
)
|
||||
}
|
||||
|
||||
/// macOS: 使用 Terminal.app 启动
|
||||
#[cfg(target_os = "macos")]
|
||||
fn launch_macos_terminal(
|
||||
config_file: &std::path::Path,
|
||||
config_path_escaped: &str,
|
||||
) -> Result<(), String> {
|
||||
fn launch_macos_terminal(config_file: &std::path::Path) -> Result<(), String> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::process::Command;
|
||||
|
||||
let config_path_for_script = config_file.to_string_lossy().replace('\"', "\\\"");
|
||||
let temp_dir = std::env::temp_dir();
|
||||
let script_file = temp_dir.join(format!("cc_switch_launcher_{}.sh", std::process::id()));
|
||||
|
||||
let shell_script = generate_wrapper_script(&config_path_for_script, config_path_escaped);
|
||||
let config_path = config_file.to_string_lossy();
|
||||
|
||||
let script = format!(
|
||||
r#"tell application "Terminal"
|
||||
activate
|
||||
do script "{}"
|
||||
end tell"#,
|
||||
shell_script.replace('\"', "\\\"")
|
||||
// Write the shell script to a temp file (no escaping needed!)
|
||||
let script_content = format!(
|
||||
r#"#!/bin/bash
|
||||
trap 'rm -f "{config_path}" "{script_file}"' EXIT
|
||||
echo "Using provider-specific claude config:"
|
||||
echo "{config_path}"
|
||||
claude --settings "{config_path}"
|
||||
exec bash --norc --noprofile
|
||||
"#,
|
||||
config_path = config_path,
|
||||
script_file = script_file.display()
|
||||
);
|
||||
|
||||
Command::new("osascript")
|
||||
std::fs::write(&script_file, &script_content).map_err(|e| format!("写入启动脚本失败: {e}"))?;
|
||||
|
||||
// Make script executable
|
||||
std::fs::set_permissions(&script_file, std::fs::Permissions::from_mode(0o755))
|
||||
.map_err(|e| format!("设置脚本权限失败: {e}"))?;
|
||||
|
||||
// Simple AppleScript - just execute the script file
|
||||
let applescript = format!(
|
||||
r#"tell application "Terminal"
|
||||
activate
|
||||
do script "bash '{}'"
|
||||
end tell"#,
|
||||
script_file.display()
|
||||
);
|
||||
|
||||
let output = Command::new("osascript")
|
||||
.arg("-e")
|
||||
.arg(&script)
|
||||
.spawn()
|
||||
.map_err(|e| format!("启动 macOS 终端失败: {e}"))?;
|
||||
.arg(&applescript)
|
||||
.output()
|
||||
.map_err(|e| format!("执行 osascript 失败: {e}"))?;
|
||||
|
||||
if !output.status.success() {
|
||||
// Clean up on failure
|
||||
let _ = std::fs::remove_file(&script_file);
|
||||
let _ = std::fs::remove_file(config_file);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
return Err(format!(
|
||||
"AppleScript 执行失败 (exit code: {:?}): {}",
|
||||
output.status.code(),
|
||||
stderr
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Linux: 尝试使用常见终端启动
|
||||
#[cfg(target_os = "linux")]
|
||||
fn launch_linux_terminal(
|
||||
config_file: &std::path::Path,
|
||||
config_path_escaped: &str,
|
||||
) -> Result<(), String> {
|
||||
fn launch_linux_terminal(config_file: &std::path::Path) -> Result<(), String> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::process::Command;
|
||||
|
||||
let terminals = [
|
||||
"gnome-terminal",
|
||||
"konsole",
|
||||
"xfce4-terminal",
|
||||
"mate-terminal",
|
||||
"lxterminal",
|
||||
"alacritty",
|
||||
"kitty",
|
||||
("gnome-terminal", vec!["--"]),
|
||||
("konsole", vec!["-e"]),
|
||||
("xfce4-terminal", vec!["-e"]),
|
||||
("mate-terminal", vec!["--"]),
|
||||
("lxterminal", vec!["-e"]),
|
||||
("alacritty", vec!["-e"]),
|
||||
("kitty", vec!["-e"]),
|
||||
];
|
||||
|
||||
let config_path_for_bash = config_file.to_string_lossy();
|
||||
let shell_cmd = generate_wrapper_script(&config_path_for_bash, config_path_escaped);
|
||||
// Create temp script file (same approach as macOS)
|
||||
let temp_dir = std::env::temp_dir();
|
||||
let script_file = temp_dir.join(format!("cc_switch_launcher_{}.sh", std::process::id()));
|
||||
let config_path = config_file.to_string_lossy();
|
||||
|
||||
let script_content = format!(
|
||||
r#"#!/bin/bash
|
||||
trap 'rm -f "{config_path}" "{script_file}"' EXIT
|
||||
echo "Using provider-specific claude config:"
|
||||
echo "{config_path}"
|
||||
claude --settings "{config_path}"
|
||||
exec bash --norc --noprofile
|
||||
"#,
|
||||
config_path = config_path,
|
||||
script_file = script_file.display()
|
||||
);
|
||||
|
||||
std::fs::write(&script_file, &script_content).map_err(|e| format!("写入启动脚本失败: {e}"))?;
|
||||
|
||||
std::fs::set_permissions(&script_file, std::fs::Permissions::from_mode(0o755))
|
||||
.map_err(|e| format!("设置脚本权限失败: {e}"))?;
|
||||
|
||||
let mut last_error = String::from("未找到可用的终端");
|
||||
|
||||
for terminal in terminals {
|
||||
// 检查终端是否存在
|
||||
for (terminal, args) in terminals {
|
||||
// Check if terminal exists
|
||||
if std::path::Path::new(&format!("/usr/bin/{}", terminal)).exists()
|
||||
|| std::path::Path::new(&format!("/bin/{}", terminal)).exists()
|
||||
{
|
||||
let result = match terminal {
|
||||
"gnome-terminal" | "mate-terminal" => Command::new(terminal)
|
||||
.arg("--")
|
||||
.arg("bash")
|
||||
.arg("-c")
|
||||
.arg(&shell_cmd)
|
||||
.spawn(),
|
||||
_ => Command::new(terminal)
|
||||
.arg("-e")
|
||||
.arg("bash")
|
||||
.arg("-c")
|
||||
.arg(&shell_cmd)
|
||||
.spawn(),
|
||||
};
|
||||
let result = Command::new(terminal)
|
||||
.args(&args)
|
||||
.arg("bash")
|
||||
.arg(script_file.to_string_lossy().as_ref())
|
||||
.output();
|
||||
|
||||
match result {
|
||||
Ok(_) => return Ok(()),
|
||||
Ok(output) if output.status.success() => return Ok(()),
|
||||
Ok(output) => {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
last_error = format!("启动 {} 失败: {}", terminal, stderr);
|
||||
}
|
||||
Err(e) => {
|
||||
last_error = format!("启动 {} 失败: {}", terminal, e);
|
||||
last_error = format!("执行 {} 失败: {}", terminal, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 清理配置文件
|
||||
// Clean up on failure
|
||||
let _ = std::fs::remove_file(&script_file);
|
||||
let _ = std::fs::remove_file(config_file);
|
||||
Err(last_error)
|
||||
}
|
||||
@@ -691,21 +729,31 @@ echo {}
|
||||
claude --settings \"{}\"
|
||||
del \"{}\" >nul 2>&1
|
||||
del \"%~f0\" >nul 2>&1
|
||||
if errorlevel 1 (
|
||||
echo.
|
||||
echo Press any key to close...
|
||||
pause >nul
|
||||
)",
|
||||
",
|
||||
config_path_for_batch, config_path_for_batch, config_path_for_batch
|
||||
);
|
||||
|
||||
std::fs::write(&bat_file, content).map_err(|e| format!("写入批处理文件失败: {e}"))?;
|
||||
|
||||
Command::new("cmd")
|
||||
.args(["/C", "start", "cmd", "/C", &bat_file.to_string_lossy()])
|
||||
// Use output() to capture errors from the start command
|
||||
// Use /K instead of /C to keep the window open after execution
|
||||
let output = Command::new("cmd")
|
||||
.args(["/C", "start", "cmd", "/K", &bat_file.to_string_lossy()])
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.spawn()
|
||||
.map_err(|e| format!("启动 Windows 终端失败: {e}"))?;
|
||||
.output()
|
||||
.map_err(|e| format!("执行 cmd 失败: {e}"))?;
|
||||
|
||||
if !output.status.success() {
|
||||
// Clean up on failure
|
||||
let _ = std::fs::remove_file(&bat_file);
|
||||
let _ = std::fs::remove_file(config_file);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
return Err(format!(
|
||||
"启动 Windows 终端失败 (exit code: {:?}): {}",
|
||||
output.status.code(),
|
||||
stderr
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -80,3 +80,30 @@ pub async fn set_rectifier_config(
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// 获取日志配置
|
||||
#[tauri::command]
|
||||
pub async fn get_log_config(
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
) -> Result<crate::proxy::types::LogConfig, String> {
|
||||
state.db.get_log_config().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 设置日志配置
|
||||
#[tauri::command]
|
||||
pub async fn set_log_config(
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
config: crate::proxy::types::LogConfig,
|
||||
) -> Result<bool, String> {
|
||||
state
|
||||
.db
|
||||
.set_log_config(&config)
|
||||
.map_err(|e| e.to_string())?;
|
||||
log::set_max_level(config.to_level_filter());
|
||||
log::info!(
|
||||
"日志配置已更新: enabled={}, level={}",
|
||||
config.enabled,
|
||||
config.level
|
||||
);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
@@ -614,4 +614,51 @@ impl Database {
|
||||
log::info!("已删除所有 Live 配置备份");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ==================== Sync Methods for Tray Menu ====================
|
||||
|
||||
/// 同步获取应用的 proxy 启用状态和自动故障转移状态
|
||||
///
|
||||
/// 用于托盘菜单构建等同步场景
|
||||
/// 返回 (enabled, auto_failover_enabled)
|
||||
pub fn get_proxy_flags_sync(&self, app_type: &str) -> (bool, bool) {
|
||||
let conn = match self.conn.lock() {
|
||||
Ok(c) => c,
|
||||
Err(_) => return (false, false),
|
||||
};
|
||||
|
||||
conn.query_row(
|
||||
"SELECT enabled, auto_failover_enabled FROM proxy_config WHERE app_type = ?1",
|
||||
[app_type],
|
||||
|row| Ok((row.get::<_, i32>(0)? != 0, row.get::<_, i32>(1)? != 0)),
|
||||
)
|
||||
.unwrap_or((false, false))
|
||||
}
|
||||
|
||||
/// 同步设置应用的 proxy 启用状态和自动故障转移状态
|
||||
///
|
||||
/// 用于托盘菜单点击等同步场景
|
||||
pub fn set_proxy_flags_sync(
|
||||
&self,
|
||||
app_type: &str,
|
||||
enabled: bool,
|
||||
auto_failover_enabled: bool,
|
||||
) -> Result<(), AppError> {
|
||||
let conn = self
|
||||
.conn
|
||||
.lock()
|
||||
.map_err(|e| AppError::Database(format!("Mutex lock failed: {e}")))?;
|
||||
|
||||
conn.execute(
|
||||
"UPDATE proxy_config SET enabled = ?2, auto_failover_enabled = ?3, updated_at = datetime('now') WHERE app_type = ?1",
|
||||
rusqlite::params![
|
||||
app_type,
|
||||
if enabled { 1 } else { 0 },
|
||||
if auto_failover_enabled { 1 } else { 0 },
|
||||
],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,4 +186,22 @@ impl Database {
|
||||
.map_err(|e| AppError::Database(format!("序列化整流器配置失败: {e}")))?;
|
||||
self.set_setting("rectifier_config", &json)
|
||||
}
|
||||
|
||||
// --- 日志配置 ---
|
||||
|
||||
/// 获取日志配置
|
||||
pub fn get_log_config(&self) -> Result<crate::proxy::types::LogConfig, AppError> {
|
||||
match self.get_setting("log_config")? {
|
||||
Some(json) => serde_json::from_str(&json)
|
||||
.map_err(|e| AppError::Database(format!("解析日志配置失败: {e}"))),
|
||||
None => Ok(crate::proxy::types::LogConfig::default()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 更新日志配置
|
||||
pub fn set_log_config(&self, config: &crate::proxy::types::LogConfig) -> Result<(), AppError> {
|
||||
let json = serde_json::to_string(config)
|
||||
.map_err(|e| AppError::Database(format!("序列化日志配置失败: {e}")))?;
|
||||
self.set_setting("log_config", &json)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,24 +203,32 @@ impl Database {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 初始化默认的 Skill 仓库(首次启动时调用)
|
||||
/// 初始化默认的 Skill 仓库(启动时调用,补充缺失的默认仓库)
|
||||
pub fn init_default_skill_repos(&self) -> Result<usize, AppError> {
|
||||
// 检查是否已有仓库
|
||||
// 获取已有仓库列表
|
||||
let existing = self.get_skill_repos()?;
|
||||
if !existing.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
let existing_keys: std::collections::HashSet<(String, String)> = existing
|
||||
.iter()
|
||||
.map(|r| (r.owner.clone(), r.name.clone()))
|
||||
.collect();
|
||||
|
||||
// 获取默认仓库列表
|
||||
let default_store = crate::services::skill::SkillStore::default();
|
||||
let mut count = 0;
|
||||
|
||||
// 仅插入缺失的默认仓库
|
||||
for repo in &default_store.repos {
|
||||
self.save_skill_repo(repo)?;
|
||||
count += 1;
|
||||
let key = (repo.owner.clone(), repo.name.clone());
|
||||
if !existing_keys.contains(&key) {
|
||||
self.save_skill_repo(repo)?;
|
||||
count += 1;
|
||||
log::info!("补充默认 Skill 仓库: {}/{}", repo.owner, repo.name);
|
||||
}
|
||||
}
|
||||
|
||||
log::info!("初始化默认 Skill 仓库完成,共 {count} 个");
|
||||
if count > 0 {
|
||||
log::info!("补充默认 Skill 仓库完成,新增 {count} 个");
|
||||
}
|
||||
Ok(count)
|
||||
}
|
||||
}
|
||||
|
||||
+33
-10
@@ -266,33 +266,41 @@ pub fn run() {
|
||||
log::warn!("初始化 Updater 插件失败,已跳过:{e}");
|
||||
}
|
||||
}
|
||||
// 初始化日志(Debug 和 Release 模式都启用 Info 级别)
|
||||
// 日志同时输出到控制台和文件(<app_config_dir>/logs/;若设置了覆盖则使用覆盖目录)
|
||||
// 初始化日志(单文件输出到 <app_config_dir>/logs/cc-switch.log)
|
||||
{
|
||||
use tauri_plugin_log::{RotationStrategy, Target, TargetKind, TimezoneStrategy};
|
||||
|
||||
let log_dir = panic_hook::get_log_dir();
|
||||
|
||||
// 确保日志目录存在
|
||||
if let Err(e) = std::fs::create_dir_all(&log_dir) {
|
||||
eprintln!("创建日志目录失败: {e}");
|
||||
}
|
||||
|
||||
// 启动时删除旧日志文件,实现单文件覆盖效果
|
||||
let log_file_path = log_dir.join("cc-switch.log");
|
||||
let _ = std::fs::remove_file(&log_file_path);
|
||||
|
||||
app.handle().plugin(
|
||||
tauri_plugin_log::Builder::default()
|
||||
.level(log::LevelFilter::Info)
|
||||
// 初始化为 Trace,允许后续通过 log::set_max_level() 动态调整级别
|
||||
.level(log::LevelFilter::Trace)
|
||||
.targets([
|
||||
// 输出到控制台
|
||||
Target::new(TargetKind::Stdout),
|
||||
// 输出到日志文件
|
||||
Target::new(TargetKind::Folder {
|
||||
path: log_dir,
|
||||
file_name: Some("cc-switch".into()),
|
||||
}),
|
||||
])
|
||||
.rotation_strategy(RotationStrategy::KeepAll)
|
||||
.max_file_size(5_000_000) // 5MB 单文件上限
|
||||
// 单文件模式:启动时删除旧文件,达到大小时轮转
|
||||
// 注意:KeepSome(n) 内部会做 n-2 运算,n=1 会导致 usize 下溢
|
||||
// KeepSome(2) 是最小安全值,表示不保留轮转文件
|
||||
.rotation_strategy(RotationStrategy::KeepSome(2))
|
||||
// 单文件大小限制 1GB
|
||||
.max_file_size(1024 * 1024 * 1024)
|
||||
.timezone_strategy(TimezoneStrategy::UseLocal)
|
||||
.build(),
|
||||
)?;
|
||||
|
||||
// 清理旧日志文件,只保留最近 2 个
|
||||
panic_hook::cleanup_old_logs();
|
||||
}
|
||||
|
||||
// 初始化数据库
|
||||
@@ -660,6 +668,19 @@ pub fn run() {
|
||||
// 将同一个实例注入到全局状态,避免重复创建导致的不一致
|
||||
app.manage(app_state);
|
||||
|
||||
// 从数据库加载日志配置并应用
|
||||
{
|
||||
let db = &app.state::<AppState>().db;
|
||||
if let Ok(log_config) = db.get_log_config() {
|
||||
log::set_max_level(log_config.to_level_filter());
|
||||
log::info!(
|
||||
"已加载日志配置: enabled={}, level={}",
|
||||
log_config.enabled,
|
||||
log_config.level
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化 SkillService
|
||||
let skill_service = SkillService::new();
|
||||
app.manage(commands::skill::SkillServiceState(Arc::new(skill_service)));
|
||||
@@ -757,6 +778,8 @@ pub fn run() {
|
||||
commands::save_settings,
|
||||
commands::get_rectifier_config,
|
||||
commands::set_rectifier_config,
|
||||
commands::get_log_config,
|
||||
commands::set_log_config,
|
||||
commands::restart_app,
|
||||
commands::check_for_updates,
|
||||
commands::is_portable_mode,
|
||||
|
||||
@@ -96,10 +96,7 @@ pub fn convert_to_opencode_format(spec: &Value) -> Result<Value, AppError> {
|
||||
result.insert("enabled".into(), json!(true));
|
||||
}
|
||||
_ => {
|
||||
return Err(AppError::McpValidation(format!(
|
||||
"Unknown MCP type: {}",
|
||||
typ
|
||||
)));
|
||||
return Err(AppError::McpValidation(format!("Unknown MCP type: {typ}")));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,8 +168,7 @@ pub fn convert_from_opencode_format(spec: &Value) -> Result<Value, AppError> {
|
||||
}
|
||||
_ => {
|
||||
return Err(AppError::McpValidation(format!(
|
||||
"Unknown OpenCode MCP type: {}",
|
||||
typ
|
||||
"Unknown OpenCode MCP type: {typ}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
@@ -230,16 +226,16 @@ pub fn import_from_opencode(config: &mut MultiAppConfig) -> Result<usize, AppErr
|
||||
let unified_spec = match convert_from_opencode_format(&spec) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
log::warn!("Skip invalid OpenCode MCP server '{}': {}", id, e);
|
||||
errors.push(format!("{}: {}", id, e));
|
||||
log::warn!("Skip invalid OpenCode MCP server '{id}': {e}");
|
||||
errors.push(format!("{id}: {e}"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
// Validate the converted spec
|
||||
if let Err(e) = validate_server_spec(&unified_spec) {
|
||||
log::warn!("Skip invalid MCP server '{}' after conversion: {}", id, e);
|
||||
errors.push(format!("{}: {}", id, e));
|
||||
log::warn!("Skip invalid MCP server '{id}' after conversion: {e}");
|
||||
errors.push(format!("{id}: {e}"));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -248,7 +244,7 @@ pub fn import_from_opencode(config: &mut MultiAppConfig) -> Result<usize, AppErr
|
||||
if !existing.apps.opencode {
|
||||
existing.apps.opencode = true;
|
||||
changed += 1;
|
||||
log::info!("MCP server '{}' enabled for OpenCode", id);
|
||||
log::info!("MCP server '{id}' enabled for OpenCode");
|
||||
}
|
||||
} else {
|
||||
// New server: default to only OpenCode enabled
|
||||
@@ -271,7 +267,7 @@ pub fn import_from_opencode(config: &mut MultiAppConfig) -> Result<usize, AppErr
|
||||
},
|
||||
);
|
||||
changed += 1;
|
||||
log::info!("Imported new MCP server '{}' from OpenCode", id);
|
||||
log::info!("Imported new MCP server '{id}' from OpenCode");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -42,21 +42,10 @@ pub fn get_opencode_dir() -> PathBuf {
|
||||
return override_dir;
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
// Windows: %APPDATA%\opencode
|
||||
dirs::data_dir()
|
||||
.map(|d| d.join("opencode"))
|
||||
.unwrap_or_else(|| PathBuf::from(".config").join("opencode"))
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
// Unix: ~/.config/opencode
|
||||
dirs::home_dir()
|
||||
.map(|h| h.join(".config").join("opencode"))
|
||||
.unwrap_or_else(|| PathBuf::from(".config").join("opencode"))
|
||||
}
|
||||
// 所有平台统一使用 ~/.config/opencode
|
||||
dirs::home_dir()
|
||||
.map(|h| h.join(".config").join("opencode"))
|
||||
.unwrap_or_else(|| PathBuf::from(".config").join("opencode"))
|
||||
}
|
||||
|
||||
/// 获取 OpenCode 配置文件路径
|
||||
@@ -103,7 +92,7 @@ pub fn write_opencode_config(config: &Value) -> Result<(), AppError> {
|
||||
// 复用统一的原子写入逻辑(兼容 Windows 上目标文件已存在的情况)
|
||||
write_json_file(&path, config)?;
|
||||
|
||||
log::debug!("OpenCode config written to {:?}", path);
|
||||
log::debug!("OpenCode config written to {path:?}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -165,7 +154,7 @@ pub fn get_typed_providers() -> Result<IndexMap<String, OpenCodeProviderConfig>,
|
||||
result.insert(id, config);
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("Failed to parse provider '{}': {}", id, e);
|
||||
log::warn!("Failed to parse provider '{id}': {e}");
|
||||
// Skip invalid providers but continue
|
||||
}
|
||||
}
|
||||
@@ -219,4 +208,3 @@ pub fn remove_mcp_server(id: &str) -> Result<(), AppError> {
|
||||
|
||||
write_opencode_config(&config)
|
||||
}
|
||||
|
||||
|
||||
@@ -12,9 +12,6 @@ use std::sync::OnceLock;
|
||||
/// 应用版本号(从 Cargo.toml 读取)
|
||||
const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
/// 日志文件保留数量
|
||||
const LOG_FILES_TO_KEEP: usize = 2;
|
||||
|
||||
static APP_CONFIG_DIR: OnceLock<PathBuf> = OnceLock::new();
|
||||
|
||||
pub fn init_app_config_dir(dir: PathBuf) {
|
||||
@@ -46,48 +43,6 @@ pub fn get_log_dir() -> PathBuf {
|
||||
get_app_config_dir().join("logs")
|
||||
}
|
||||
|
||||
/// 清理旧日志文件,只保留最近 N 个
|
||||
///
|
||||
/// 在应用启动时调用,确保日志文件不会无限增长。
|
||||
pub fn cleanup_old_logs() {
|
||||
let log_dir = get_log_dir();
|
||||
|
||||
if !log_dir.exists() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 读取目录中的所有 .log 文件
|
||||
let mut log_files: Vec<_> = match std::fs::read_dir(&log_dir) {
|
||||
Ok(entries) => entries
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().map(|ext| ext == "log").unwrap_or(false))
|
||||
.collect(),
|
||||
Err(_) => return,
|
||||
};
|
||||
|
||||
// 如果文件数量不超过保留数量,无需清理
|
||||
if log_files.len() <= LOG_FILES_TO_KEEP {
|
||||
return;
|
||||
}
|
||||
|
||||
// 按修改时间排序(最新的在前)
|
||||
log_files.sort_by(|a, b| {
|
||||
let time_a = a.metadata().and_then(|m| m.modified()).ok();
|
||||
let time_b = b.metadata().and_then(|m| m.modified()).ok();
|
||||
time_b.cmp(&time_a) // 降序
|
||||
});
|
||||
|
||||
// 删除多余的旧文件
|
||||
for old_file in log_files.into_iter().skip(LOG_FILES_TO_KEEP) {
|
||||
if let Err(e) = std::fs::remove_file(&old_file) {
|
||||
log::warn!("清理旧日志文件失败 {}: {e}", old_file.display());
|
||||
} else {
|
||||
log::info!("已清理旧日志文件: {}", old_file.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 安全获取环境信息(不会 panic)
|
||||
fn get_system_info() -> String {
|
||||
let os = std::env::consts::OS;
|
||||
|
||||
@@ -142,6 +142,55 @@ pub struct UsageResult {
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// 供应商单独的模型测试配置
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct ProviderTestConfig {
|
||||
/// 是否启用单独配置(false 时使用全局配置)
|
||||
#[serde(default)]
|
||||
pub enabled: bool,
|
||||
/// 测试用的模型名称(覆盖全局配置)
|
||||
#[serde(rename = "testModel", skip_serializing_if = "Option::is_none")]
|
||||
pub test_model: Option<String>,
|
||||
/// 超时时间(秒)
|
||||
#[serde(rename = "timeoutSecs", skip_serializing_if = "Option::is_none")]
|
||||
pub timeout_secs: Option<u64>,
|
||||
/// 测试提示词
|
||||
#[serde(rename = "testPrompt", skip_serializing_if = "Option::is_none")]
|
||||
pub test_prompt: Option<String>,
|
||||
/// 降级阈值(毫秒)
|
||||
#[serde(
|
||||
rename = "degradedThresholdMs",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub degraded_threshold_ms: Option<u64>,
|
||||
/// 最大重试次数
|
||||
#[serde(rename = "maxRetries", skip_serializing_if = "Option::is_none")]
|
||||
pub max_retries: Option<u32>,
|
||||
}
|
||||
|
||||
/// 供应商单独的代理配置
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct ProviderProxyConfig {
|
||||
/// 是否启用单独配置(false 时使用全局/系统代理)
|
||||
#[serde(default)]
|
||||
pub enabled: bool,
|
||||
/// 代理类型:http, https, socks5
|
||||
#[serde(rename = "proxyType", skip_serializing_if = "Option::is_none")]
|
||||
pub proxy_type: Option<String>,
|
||||
/// 代理主机
|
||||
#[serde(rename = "proxyHost", skip_serializing_if = "Option::is_none")]
|
||||
pub proxy_host: Option<String>,
|
||||
/// 代理端口
|
||||
#[serde(rename = "proxyPort", skip_serializing_if = "Option::is_none")]
|
||||
pub proxy_port: Option<u16>,
|
||||
/// 代理用户名(可选)
|
||||
#[serde(rename = "proxyUsername", skip_serializing_if = "Option::is_none")]
|
||||
pub proxy_username: Option<String>,
|
||||
/// 代理密码(可选)
|
||||
#[serde(rename = "proxyPassword", skip_serializing_if = "Option::is_none")]
|
||||
pub proxy_password: Option<String>,
|
||||
}
|
||||
|
||||
/// 供应商元数据
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct ProviderMeta {
|
||||
@@ -172,6 +221,12 @@ pub struct ProviderMeta {
|
||||
/// 每月消费限额(USD)
|
||||
#[serde(rename = "limitMonthlyUsd", skip_serializing_if = "Option::is_none")]
|
||||
pub limit_monthly_usd: Option<String>,
|
||||
/// 供应商单独的模型测试配置
|
||||
#[serde(rename = "testConfig", skip_serializing_if = "Option::is_none")]
|
||||
pub test_config: Option<ProviderTestConfig>,
|
||||
/// 供应商单独的代理配置
|
||||
#[serde(rename = "proxyConfig", skip_serializing_if = "Option::is_none")]
|
||||
pub proxy_config: Option<ProviderProxyConfig>,
|
||||
}
|
||||
|
||||
impl ProviderManager {
|
||||
|
||||
@@ -28,6 +28,7 @@ const HEADER_BLACKLIST: &[&str] = &[
|
||||
// 认证类(会被覆盖)
|
||||
"authorization",
|
||||
"x-api-key",
|
||||
"x-goog-api-key",
|
||||
// 连接类(由 HTTP 客户端管理)
|
||||
"host",
|
||||
"content-length",
|
||||
@@ -585,8 +586,9 @@ impl RequestForwarder {
|
||||
// 默认使用空白名单,过滤所有 _ 前缀字段
|
||||
let filtered_body = filter_private_params_with_whitelist(request_body, &[]);
|
||||
|
||||
// 每次请求时获取最新的全局 HTTP 客户端(支持热更新代理配置)
|
||||
let client = super::http_client::get();
|
||||
// 获取 HTTP 客户端:优先使用供应商单独代理配置,否则使用全局客户端
|
||||
let proxy_config = provider.meta.as_ref().and_then(|m| m.proxy_config.as_ref());
|
||||
let client = super::http_client::get_for_provider(proxy_config);
|
||||
let mut request = client.post(&url);
|
||||
|
||||
// 只有当 timeout > 0 时才设置请求超时
|
||||
@@ -662,6 +664,17 @@ impl RequestForwarder {
|
||||
request = request.header("anthropic-version", version_str);
|
||||
}
|
||||
|
||||
// 输出请求信息日志
|
||||
let tag = adapter.name();
|
||||
log::debug!("[{tag}] >>> 请求 URL: {url}");
|
||||
if let Ok(body_str) = serde_json::to_string(&filtered_body) {
|
||||
log::debug!(
|
||||
"[{tag}] >>> 请求体内容 ({}字节): {}",
|
||||
body_str.len(),
|
||||
body_str
|
||||
);
|
||||
}
|
||||
|
||||
// 发送请求
|
||||
let response = request.json(&filtered_body).send().await.map_err(|e| {
|
||||
if e.is_timeout() {
|
||||
|
||||
@@ -3,8 +3,11 @@
|
||||
//! 提供支持全局代理配置的 HTTP 客户端。
|
||||
//! 所有需要发送 HTTP 请求的模块都应使用此模块提供的客户端。
|
||||
|
||||
use crate::provider::ProviderProxyConfig;
|
||||
use once_cell::sync::OnceCell;
|
||||
use reqwest::Client;
|
||||
use std::env;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::RwLock;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -155,23 +158,15 @@ pub fn update_proxy(proxy_url: Option<&str>) -> Result<(), String> {
|
||||
|
||||
/// 获取全局 HTTP 客户端
|
||||
///
|
||||
/// 返回配置了代理的客户端(如果已配置代理),否则返回直连客户端。
|
||||
/// 返回配置了代理的客户端(如果已配置代理),否则返回跟随系统代理的客户端。
|
||||
pub fn get() -> Client {
|
||||
GLOBAL_CLIENT
|
||||
.get()
|
||||
.and_then(|lock| lock.read().ok())
|
||||
.map(|c| c.clone())
|
||||
.unwrap_or_else(|| {
|
||||
// 如果还没初始化,创建一个默认客户端(配置与 build_client 一致)
|
||||
log::warn!("[GlobalProxy] [GP-004] Client not initialized, using fallback");
|
||||
Client::builder()
|
||||
.timeout(Duration::from_secs(600))
|
||||
.connect_timeout(Duration::from_secs(30))
|
||||
.pool_max_idle_per_host(10)
|
||||
.tcp_keepalive(Duration::from_secs(60))
|
||||
.no_proxy()
|
||||
.build()
|
||||
.unwrap_or_default()
|
||||
build_client(None).unwrap_or_default()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -199,7 +194,7 @@ fn build_client(proxy_url: Option<&str>) -> Result<Client, String> {
|
||||
.pool_max_idle_per_host(10)
|
||||
.tcp_keepalive(Duration::from_secs(60));
|
||||
|
||||
// 有代理地址则使用代理,否则直连
|
||||
// 有代理地址则使用代理,否则跟随系统代理
|
||||
if let Some(url) = proxy_url {
|
||||
// 先验证 URL 格式和 scheme
|
||||
let parsed = url::Url::parse(url)
|
||||
@@ -219,8 +214,16 @@ fn build_client(proxy_url: Option<&str>) -> Result<Client, String> {
|
||||
builder = builder.proxy(proxy);
|
||||
log::debug!("[GlobalProxy] Proxy configured: {}", mask_url(url));
|
||||
} else {
|
||||
builder = builder.no_proxy();
|
||||
log::debug!("[GlobalProxy] Direct connection (no proxy)");
|
||||
// 未设置全局代理时,让 reqwest 自动检测系统代理(环境变量)
|
||||
// 若系统代理指向本机,禁用系统代理避免自环
|
||||
if system_proxy_points_to_loopback() {
|
||||
builder = builder.no_proxy();
|
||||
log::warn!(
|
||||
"[GlobalProxy] System proxy points to localhost, bypassing to avoid recursion"
|
||||
);
|
||||
} else {
|
||||
log::debug!("[GlobalProxy] Following system proxy (no explicit proxy configured)");
|
||||
}
|
||||
}
|
||||
|
||||
builder
|
||||
@@ -228,6 +231,50 @@ fn build_client(proxy_url: Option<&str>) -> Result<Client, String> {
|
||||
.map_err(|e| format!("Failed to build HTTP client: {e}"))
|
||||
}
|
||||
|
||||
fn system_proxy_points_to_loopback() -> bool {
|
||||
const KEYS: [&str; 6] = [
|
||||
"HTTP_PROXY",
|
||||
"http_proxy",
|
||||
"HTTPS_PROXY",
|
||||
"https_proxy",
|
||||
"ALL_PROXY",
|
||||
"all_proxy",
|
||||
];
|
||||
|
||||
KEYS.iter()
|
||||
.filter_map(|key| env::var(key).ok())
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
.any(|value| proxy_points_to_loopback(&value))
|
||||
}
|
||||
|
||||
fn proxy_points_to_loopback(value: &str) -> bool {
|
||||
fn host_is_loopback(host: &str) -> bool {
|
||||
if host.eq_ignore_ascii_case("localhost") {
|
||||
return true;
|
||||
}
|
||||
host.parse::<IpAddr>()
|
||||
.map(|ip| ip.is_loopback())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
if let Ok(parsed) = url::Url::parse(value) {
|
||||
if let Some(host) = parsed.host_str() {
|
||||
return host_is_loopback(host);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
let with_scheme = format!("http://{value}");
|
||||
if let Ok(parsed) = url::Url::parse(&with_scheme) {
|
||||
if let Some(host) = parsed.host_str() {
|
||||
return host_is_loopback(host);
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
/// 隐藏 URL 中的敏感信息(用于日志)
|
||||
pub fn mask_url(url: &str) -> String {
|
||||
if let Ok(parsed) = url::Url::parse(url) {
|
||||
@@ -247,9 +294,109 @@ pub fn mask_url(url: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// 根据供应商单独代理配置构建代理 URL
|
||||
///
|
||||
/// 将 ProviderProxyConfig 转换为代理 URL 字符串
|
||||
fn build_proxy_url_from_config(config: &ProviderProxyConfig) -> Option<String> {
|
||||
let proxy_type = config.proxy_type.as_deref().unwrap_or("http");
|
||||
let host = config.proxy_host.as_deref()?;
|
||||
let port = config.proxy_port?;
|
||||
|
||||
// 构建带认证的代理 URL
|
||||
if let (Some(username), Some(password)) = (&config.proxy_username, &config.proxy_password) {
|
||||
if !username.is_empty() && !password.is_empty() {
|
||||
return Some(format!(
|
||||
"{proxy_type}://{username}:{password}@{host}:{port}"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Some(format!("{proxy_type}://{host}:{port}"))
|
||||
}
|
||||
|
||||
/// 根据供应商单独代理配置构建 HTTP 客户端
|
||||
///
|
||||
/// 如果供应商配置了单独代理(enabled = true),则使用该代理构建客户端;
|
||||
/// 否则返回 None,调用方应使用全局客户端。
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `proxy_config` - 供应商的代理配置
|
||||
///
|
||||
/// # Returns
|
||||
/// 如果配置有效则返回 Some(Client),否则返回 None
|
||||
pub fn build_client_for_provider(proxy_config: Option<&ProviderProxyConfig>) -> Option<Client> {
|
||||
let config = proxy_config.filter(|c| c.enabled)?;
|
||||
|
||||
let proxy_url = build_proxy_url_from_config(config)?;
|
||||
|
||||
log::debug!(
|
||||
"[ProviderProxy] Building client with proxy: {}",
|
||||
mask_url(&proxy_url)
|
||||
);
|
||||
|
||||
// 构建带代理的客户端
|
||||
let proxy = match reqwest::Proxy::all(&proxy_url) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
log::error!(
|
||||
"[ProviderProxy] Failed to create proxy from '{}': {}",
|
||||
mask_url(&proxy_url),
|
||||
e
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
match Client::builder()
|
||||
.timeout(Duration::from_secs(600))
|
||||
.connect_timeout(Duration::from_secs(30))
|
||||
.pool_max_idle_per_host(10)
|
||||
.tcp_keepalive(Duration::from_secs(60))
|
||||
.proxy(proxy)
|
||||
.build()
|
||||
{
|
||||
Ok(client) => {
|
||||
log::info!(
|
||||
"[ProviderProxy] Client built with proxy: {}",
|
||||
mask_url(&proxy_url)
|
||||
);
|
||||
Some(client)
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("[ProviderProxy] Failed to build client: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取供应商专用的 HTTP 客户端
|
||||
///
|
||||
/// 优先使用供应商单独代理配置,如果未启用则返回全局客户端。
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `proxy_config` - 供应商的代理配置
|
||||
///
|
||||
/// # Returns
|
||||
/// 返回适合该供应商的 HTTP 客户端
|
||||
pub fn get_for_provider(proxy_config: Option<&ProviderProxyConfig>) -> Client {
|
||||
// 优先使用供应商单独代理
|
||||
if let Some(client) = build_client_for_provider(proxy_config) {
|
||||
return client;
|
||||
}
|
||||
|
||||
// 回退到全局客户端
|
||||
get()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
fn env_lock() -> &'static Mutex<()> {
|
||||
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
|
||||
LOCK.get_or_init(|| Mutex::new(()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mask_url() {
|
||||
@@ -298,4 +445,40 @@ mod tests {
|
||||
let result = build_client(Some("invalid-scheme://127.0.0.1:7890"));
|
||||
assert!(result.is_err(), "Should reject invalid proxy scheme");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_proxy_points_to_loopback() {
|
||||
assert!(proxy_points_to_loopback("http://127.0.0.1:7890"));
|
||||
assert!(proxy_points_to_loopback("socks5://localhost:1080"));
|
||||
assert!(proxy_points_to_loopback("127.0.0.1:7890"));
|
||||
assert!(!proxy_points_to_loopback("http://192.168.1.10:7890"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_system_proxy_points_to_loopback() {
|
||||
let _guard = env_lock().lock().unwrap();
|
||||
|
||||
let keys = [
|
||||
"HTTP_PROXY",
|
||||
"http_proxy",
|
||||
"HTTPS_PROXY",
|
||||
"https_proxy",
|
||||
"ALL_PROXY",
|
||||
"all_proxy",
|
||||
];
|
||||
|
||||
for key in &keys {
|
||||
std::env::remove_var(key);
|
||||
}
|
||||
|
||||
std::env::set_var("HTTP_PROXY", "http://127.0.0.1:7890");
|
||||
assert!(system_proxy_points_to_loopback());
|
||||
|
||||
std::env::set_var("HTTP_PROXY", "http://10.0.0.2:7890");
|
||||
assert!(!system_proxy_points_to_loopback());
|
||||
|
||||
for key in &keys {
|
||||
std::env::remove_var(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,11 +2,13 @@
|
||||
//!
|
||||
//! 负责选择和管理代理目标供应商,实现智能故障转移
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::database::Database;
|
||||
use crate::error::AppError;
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::circuit_breaker::{AllowResult, CircuitBreaker, CircuitBreakerConfig};
|
||||
use std::collections::HashMap;
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
@@ -31,7 +33,7 @@ impl ProviderRouter {
|
||||
///
|
||||
/// 返回按优先级排序的可用供应商列表:
|
||||
/// - 故障转移关闭时:仅返回当前供应商
|
||||
/// - 故障转移开启时:完全按照故障转移队列顺序返回,忽略当前供应商设置
|
||||
/// - 故障转移开启时:仅使用故障转移队列,按队列顺序依次尝试(P1 → P2 → ...)
|
||||
pub async fn select_providers(&self, app_type: &str) -> Result<Vec<Provider>, AppError> {
|
||||
let mut result = Vec::new();
|
||||
let mut total_providers = 0usize;
|
||||
@@ -47,12 +49,25 @@ impl ProviderRouter {
|
||||
};
|
||||
|
||||
if auto_failover_enabled {
|
||||
// 故障转移开启:使用 in_failover_queue 标记的供应商,按 sort_index 排序
|
||||
let failover_providers = self.db.get_failover_providers(app_type)?;
|
||||
total_providers = failover_providers.len();
|
||||
// 故障转移开启:仅按队列顺序依次尝试(P1 → P2 → ...)
|
||||
let all_providers = self.db.get_all_providers(app_type)?;
|
||||
|
||||
for provider in failover_providers {
|
||||
let circuit_key = format!("{}:{}", app_type, provider.id);
|
||||
// 使用 DAO 返回的排序结果,确保和前端展示一致
|
||||
let ordered_ids: Vec<String> = self
|
||||
.db
|
||||
.get_failover_queue(app_type)?
|
||||
.into_iter()
|
||||
.map(|item| item.provider_id)
|
||||
.collect();
|
||||
|
||||
total_providers = ordered_ids.len();
|
||||
|
||||
for provider_id in ordered_ids {
|
||||
let Some(provider) = all_providers.get(&provider_id).cloned() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let circuit_key = format!("{app_type}:{}", provider.id);
|
||||
let breaker = self.get_or_create_circuit_breaker(&circuit_key).await;
|
||||
|
||||
if breaker.is_available().await {
|
||||
@@ -63,7 +78,16 @@ impl ProviderRouter {
|
||||
}
|
||||
} else {
|
||||
// 故障转移关闭:仅使用当前供应商,跳过熔断器检查
|
||||
if let Some(current_id) = self.db.get_current_provider(app_type)? {
|
||||
let current_id = AppType::from_str(app_type)
|
||||
.ok()
|
||||
.and_then(|app_enum| {
|
||||
crate::settings::get_effective_current_provider(&self.db, &app_enum)
|
||||
.ok()
|
||||
.flatten()
|
||||
})
|
||||
.or_else(|| self.db.get_current_provider(app_type).ok().flatten());
|
||||
|
||||
if let Some(current_id) = current_id {
|
||||
if let Some(current) = self.db.get_provider_by_id(¤t_id, app_type)? {
|
||||
total_providers = 1;
|
||||
result.push(current);
|
||||
@@ -239,9 +263,53 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::database::Database;
|
||||
use serde_json::json;
|
||||
use serial_test::serial;
|
||||
use std::env;
|
||||
use tempfile::TempDir;
|
||||
|
||||
struct TempHome {
|
||||
#[allow(dead_code)]
|
||||
dir: TempDir,
|
||||
original_home: Option<String>,
|
||||
original_userprofile: Option<String>,
|
||||
}
|
||||
|
||||
impl TempHome {
|
||||
fn new() -> Self {
|
||||
let dir = TempDir::new().expect("failed to create temp home");
|
||||
let original_home = env::var("HOME").ok();
|
||||
let original_userprofile = env::var("USERPROFILE").ok();
|
||||
|
||||
env::set_var("HOME", dir.path());
|
||||
env::set_var("USERPROFILE", dir.path());
|
||||
crate::settings::reload_settings().expect("reload settings");
|
||||
|
||||
Self {
|
||||
dir,
|
||||
original_home,
|
||||
original_userprofile,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempHome {
|
||||
fn drop(&mut self) {
|
||||
match &self.original_home {
|
||||
Some(value) => env::set_var("HOME", value),
|
||||
None => env::remove_var("HOME"),
|
||||
}
|
||||
|
||||
match &self.original_userprofile {
|
||||
Some(value) => env::set_var("USERPROFILE", value),
|
||||
None => env::remove_var("USERPROFILE"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn test_provider_router_creation() {
|
||||
let _home = TempHome::new();
|
||||
let db = Arc::new(Database::memory().unwrap());
|
||||
let router = ProviderRouter::new(db);
|
||||
|
||||
@@ -250,7 +318,9 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn test_failover_disabled_uses_current_provider() {
|
||||
let _home = TempHome::new();
|
||||
let db = Arc::new(Database::memory().unwrap());
|
||||
|
||||
let provider_a =
|
||||
@@ -271,7 +341,9 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_failover_enabled_uses_queue_order() {
|
||||
#[serial]
|
||||
async fn test_failover_enabled_uses_queue_order_ignoring_current() {
|
||||
let _home = TempHome::new();
|
||||
let db = Arc::new(Database::memory().unwrap());
|
||||
|
||||
// 设置 sort_index 来控制顺序:b=1, a=2
|
||||
@@ -298,13 +370,45 @@ mod tests {
|
||||
let providers = router.select_providers("claude").await.unwrap();
|
||||
|
||||
assert_eq!(providers.len(), 2);
|
||||
// 按 sort_index 排序:b(1) 在前,a(2) 在后
|
||||
// 故障转移开启时:仅按队列顺序选择(忽略当前供应商)
|
||||
assert_eq!(providers[0].id, "b");
|
||||
assert_eq!(providers[1].id, "a");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn test_failover_enabled_uses_queue_only_even_if_current_not_in_queue() {
|
||||
let _home = TempHome::new();
|
||||
let db = Arc::new(Database::memory().unwrap());
|
||||
|
||||
let provider_a =
|
||||
Provider::with_id("a".to_string(), "Provider A".to_string(), json!({}), None);
|
||||
let mut provider_b =
|
||||
Provider::with_id("b".to_string(), "Provider B".to_string(), json!({}), None);
|
||||
provider_b.sort_index = Some(1);
|
||||
|
||||
db.save_provider("claude", &provider_a).unwrap();
|
||||
db.save_provider("claude", &provider_b).unwrap();
|
||||
db.set_current_provider("claude", "a").unwrap();
|
||||
|
||||
// 只把 b 加入故障转移队列(模拟“当前供应商不在队列里”的常见配置)
|
||||
db.add_to_failover_queue("claude", "b").unwrap();
|
||||
|
||||
let mut config = db.get_proxy_config_for_app("claude").await.unwrap();
|
||||
config.auto_failover_enabled = true;
|
||||
db.update_proxy_config_for_app(config).await.unwrap();
|
||||
|
||||
let router = ProviderRouter::new(db.clone());
|
||||
let providers = router.select_providers("claude").await.unwrap();
|
||||
|
||||
assert_eq!(providers.len(), 1);
|
||||
assert_eq!(providers[0].id, "b");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn test_select_providers_does_not_consume_half_open_permit() {
|
||||
let _home = TempHome::new();
|
||||
let db = Arc::new(Database::memory().unwrap());
|
||||
|
||||
db.update_circuit_breaker_config(&CircuitBreakerConfig {
|
||||
@@ -345,7 +449,9 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn test_release_permit_neutral_frees_half_open_slot() {
|
||||
let _home = TempHome::new();
|
||||
let db = Arc::new(Database::memory().unwrap());
|
||||
|
||||
// 配置熔断器:1 次失败即熔断,0 秒超时立即进入 HalfOpen
|
||||
|
||||
@@ -104,7 +104,6 @@ pub fn create_anthropic_sse_stream(
|
||||
}
|
||||
|
||||
if let Ok(chunk) = serde_json::from_str::<OpenAIStreamChunk>(data) {
|
||||
// 仅在 DEBUG 级别简短记录 SSE 事件
|
||||
log::debug!("[Claude/OpenRouter] <<< SSE chunk received");
|
||||
|
||||
if message_id.is_none() {
|
||||
|
||||
@@ -12,6 +12,7 @@ use super::{
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use bytes::Bytes;
|
||||
use futures::stream::{Stream, StreamExt};
|
||||
use reqwest::header::HeaderMap;
|
||||
use rust_decimal::Decimal;
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
@@ -47,6 +48,12 @@ pub async fn handle_streaming(
|
||||
parser_config: &UsageParserConfig,
|
||||
) -> Response {
|
||||
let status = response.status();
|
||||
log::debug!(
|
||||
"[{}] 已接收上游流式响应: status={}, headers={}",
|
||||
ctx.tag,
|
||||
status.as_u16(),
|
||||
format_headers(response.headers())
|
||||
);
|
||||
let mut builder = axum::response::Response::builder().status(status);
|
||||
|
||||
// 复制响应头
|
||||
@@ -94,6 +101,19 @@ pub async fn handle_non_streaming(
|
||||
log::error!("[{}] 读取响应失败: {e}", ctx.tag);
|
||||
ProxyError::ForwardFailed(format!("Failed to read response body: {e}"))
|
||||
})?;
|
||||
log::debug!(
|
||||
"[{}] 已接收上游响应体: status={}, bytes={}, headers={}",
|
||||
ctx.tag,
|
||||
status.as_u16(),
|
||||
body_bytes.len(),
|
||||
format_headers(&response_headers)
|
||||
);
|
||||
|
||||
log::debug!(
|
||||
"[{}] 上游响应体内容: {}",
|
||||
ctx.tag,
|
||||
String::from_utf8_lossy(&body_bytes)
|
||||
);
|
||||
|
||||
// 解析并记录使用量
|
||||
if let Ok(json_value) = serde_json::from_slice::<Value>(&body_bytes) {
|
||||
@@ -470,6 +490,12 @@ pub fn create_logged_passthrough_stream(
|
||||
|
||||
match chunk_result {
|
||||
Some(Ok(bytes)) => {
|
||||
if is_first_chunk {
|
||||
log::debug!(
|
||||
"[{tag}] 已接收上游流式首包: bytes={}",
|
||||
bytes.len()
|
||||
);
|
||||
}
|
||||
is_first_chunk = false;
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
buffer.push_str(&text);
|
||||
@@ -488,13 +514,9 @@ pub fn create_logged_passthrough_stream(
|
||||
if let Some(c) = &collector {
|
||||
c.push(json_value.clone()).await;
|
||||
}
|
||||
log::debug!(
|
||||
"[{}] <<< SSE 事件: {}",
|
||||
tag,
|
||||
data.chars().take(100).collect::<String>()
|
||||
);
|
||||
log::debug!("[{tag}] <<< SSE 事件: {data}");
|
||||
} else {
|
||||
log::debug!("[{tag}] <<< SSE 数据: {}", data.chars().take(100).collect::<String>());
|
||||
log::debug!("[{tag}] <<< SSE 数据: {data}");
|
||||
}
|
||||
} else {
|
||||
log::debug!("[{tag}] <<< SSE: [DONE]");
|
||||
@@ -523,3 +545,14 @@ pub fn create_logged_passthrough_stream(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn format_headers(headers: &HeaderMap) -> String {
|
||||
headers
|
||||
.iter()
|
||||
.map(|(key, value)| {
|
||||
let value_str = value.to_str().unwrap_or("<non-utf8>");
|
||||
format!("{key}={value_str}")
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ use super::{
|
||||
};
|
||||
use crate::database::Database;
|
||||
use axum::{
|
||||
extract::DefaultBodyLimit,
|
||||
routing::{get, post},
|
||||
Router,
|
||||
};
|
||||
@@ -189,6 +190,18 @@ impl ProxyServer {
|
||||
status
|
||||
}
|
||||
|
||||
/// 更新某个应用类型当前“目标供应商”(用于 UI 展示 active_targets)
|
||||
///
|
||||
/// 注意:这不代表该供应商一定已经处理过请求,而是用于“热切换/启用故障转移立即切 P1”
|
||||
/// 等场景下,让 UI 能立刻反映最新目标。
|
||||
pub async fn set_active_target(&self, app_type: &str, provider_id: &str, provider_name: &str) {
|
||||
let mut current_providers = self.state.current_providers.write().await;
|
||||
current_providers.insert(
|
||||
app_type.to_string(),
|
||||
(provider_id.to_string(), provider_name.to_string()),
|
||||
);
|
||||
}
|
||||
|
||||
fn build_router(&self) -> Router {
|
||||
let cors = CorsLayer::new()
|
||||
.allow_origin(Any)
|
||||
@@ -224,6 +237,8 @@ impl ProxyServer {
|
||||
// Gemini API (支持带前缀和不带前缀)
|
||||
.route("/v1beta/*path", post(handlers::handle_gemini))
|
||||
.route("/gemini/v1beta/*path", post(handlers::handle_gemini))
|
||||
// 提高默认请求体大小限制(避免 413 Payload Too Large)
|
||||
.layer(DefaultBodyLimit::max(200 * 1024 * 1024))
|
||||
.layer(cors)
|
||||
.with_state(self.state.clone())
|
||||
}
|
||||
|
||||
+136
-28
@@ -16,13 +16,13 @@ pub struct ProxyConfig {
|
||||
/// 是否正在接管 Live 配置
|
||||
#[serde(default)]
|
||||
pub live_takeover_active: bool,
|
||||
/// 流式首字超时(秒)- 等待首个数据块的最大时间
|
||||
/// 流式首字超时(秒)- 等待首个数据块的最大时间,范围 1-120 秒,默认 60 秒
|
||||
#[serde(default = "default_streaming_first_byte_timeout")]
|
||||
pub streaming_first_byte_timeout: u64,
|
||||
/// 流式静默超时(秒)- 两个数据块之间的最大间隔
|
||||
/// 流式静默超时(秒)- 两个数据块之间的最大间隔,范围 60-600 秒,填 0 禁用(防止中途卡住)
|
||||
#[serde(default = "default_streaming_idle_timeout")]
|
||||
pub streaming_idle_timeout: u64,
|
||||
/// 非流式总超时(秒)- 非流式请求的总超时时间
|
||||
/// 非流式总超时(秒)- 非流式请求的总超时时间,范围 60-1200 秒,默认 600 秒(10 分钟)
|
||||
#[serde(default = "default_non_streaming_timeout")]
|
||||
pub non_streaming_timeout: u64,
|
||||
}
|
||||
@@ -195,63 +195,171 @@ pub struct AppProxyConfig {
|
||||
/// 整流器配置
|
||||
///
|
||||
/// 存储在 settings 表中
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RectifierConfig {
|
||||
/// 总开关:是否启用整流器
|
||||
#[serde(default = "default_true")]
|
||||
#[serde(default)]
|
||||
pub enabled: bool,
|
||||
/// 请求整流:启用 thinking 签名整流器
|
||||
///
|
||||
/// 处理错误:Invalid 'signature' in 'thinking' block
|
||||
#[serde(default = "default_true")]
|
||||
#[serde(default)]
|
||||
pub request_thinking_signature: bool,
|
||||
}
|
||||
|
||||
impl Default for RectifierConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
request_thinking_signature: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn default_log_level() -> String {
|
||||
"info".to_string()
|
||||
}
|
||||
|
||||
/// 日志配置
|
||||
///
|
||||
/// 存储在 settings 表的 log_config 字段中(JSON 格式)
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LogConfig {
|
||||
/// 总开关:是否启用日志
|
||||
#[serde(default = "default_true")]
|
||||
pub enabled: bool,
|
||||
/// 日志级别: error, warn, info, debug, trace
|
||||
#[serde(default = "default_log_level")]
|
||||
pub level: String,
|
||||
}
|
||||
|
||||
impl Default for LogConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
level: "info".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LogConfig {
|
||||
/// 将配置转换为 log::LevelFilter
|
||||
pub fn to_level_filter(&self) -> log::LevelFilter {
|
||||
if !self.enabled {
|
||||
return log::LevelFilter::Off;
|
||||
}
|
||||
match self.level.to_lowercase().as_str() {
|
||||
"error" => log::LevelFilter::Error,
|
||||
"warn" => log::LevelFilter::Warn,
|
||||
"info" => log::LevelFilter::Info,
|
||||
"debug" => log::LevelFilter::Debug,
|
||||
"trace" => log::LevelFilter::Trace,
|
||||
_ => log::LevelFilter::Info,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_rectifier_config_default_enabled() {
|
||||
// 验证 RectifierConfig::default() 返回全启用状态
|
||||
// 防止回归:#[derive(Default)] 会使 bool 默认为 false
|
||||
fn test_rectifier_config_default_disabled() {
|
||||
// 验证 RectifierConfig::default() 返回全禁用状态
|
||||
let config = RectifierConfig::default();
|
||||
assert!(config.enabled, "整流器总开关默认应为 true");
|
||||
assert!(!config.enabled, "整流器总开关默认应为 false");
|
||||
assert!(
|
||||
config.request_thinking_signature,
|
||||
"thinking 签名整流器默认应为 true"
|
||||
!config.request_thinking_signature,
|
||||
"thinking 签名整流器默认应为 false"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rectifier_config_serde_default() {
|
||||
// 验证反序列化缺字段时使用 default_true
|
||||
// 验证反序列化缺字段时使用默认值 false
|
||||
let json = "{}";
|
||||
let config: RectifierConfig = serde_json::from_str(json).unwrap();
|
||||
assert!(!config.enabled);
|
||||
assert!(!config.request_thinking_signature);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rectifier_config_serde_explicit_true() {
|
||||
// 验证显式设置 true 时正确反序列化
|
||||
let json = r#"{"enabled": true, "requestThinkingSignature": true}"#;
|
||||
let config: RectifierConfig = serde_json::from_str(json).unwrap();
|
||||
assert!(config.enabled);
|
||||
assert!(config.request_thinking_signature);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rectifier_config_serde_explicit_false() {
|
||||
// 验证显式设置 false 时正确反序列化
|
||||
let json = r#"{"enabled": false, "requestThinkingSignature": false}"#;
|
||||
let config: RectifierConfig = serde_json::from_str(json).unwrap();
|
||||
assert!(!config.enabled);
|
||||
assert!(!config.request_thinking_signature);
|
||||
fn test_log_config_default() {
|
||||
let config = LogConfig::default();
|
||||
assert!(config.enabled);
|
||||
assert_eq!(config.level, "info");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_log_config_serde_default() {
|
||||
let json = "{}";
|
||||
let config: LogConfig = serde_json::from_str(json).unwrap();
|
||||
assert!(config.enabled);
|
||||
assert_eq!(config.level, "info");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_log_config_to_level_filter() {
|
||||
let config = LogConfig {
|
||||
level: "error".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(config.to_level_filter(), log::LevelFilter::Error);
|
||||
|
||||
let config = LogConfig {
|
||||
level: "warn".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(config.to_level_filter(), log::LevelFilter::Warn);
|
||||
|
||||
let config = LogConfig {
|
||||
level: "info".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(config.to_level_filter(), log::LevelFilter::Info);
|
||||
|
||||
let config = LogConfig {
|
||||
level: "debug".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(config.to_level_filter(), log::LevelFilter::Debug);
|
||||
|
||||
let config = LogConfig {
|
||||
level: "trace".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(config.to_level_filter(), log::LevelFilter::Trace);
|
||||
|
||||
// 无效级别回退到 info
|
||||
let config = LogConfig {
|
||||
level: "invalid".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(config.to_level_filter(), log::LevelFilter::Info);
|
||||
|
||||
// 禁用时返回 Off
|
||||
let config = LogConfig {
|
||||
enabled: false,
|
||||
level: "debug".to_string(),
|
||||
};
|
||||
assert_eq!(config.to_level_filter(), log::LevelFilter::Off);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_log_config_serde_roundtrip() {
|
||||
let config = LogConfig {
|
||||
enabled: true,
|
||||
level: "debug".to_string(),
|
||||
};
|
||||
let json = serde_json::to_string(&config).unwrap();
|
||||
let parsed: LogConfig = serde_json::from_str(&json).unwrap();
|
||||
assert!(parsed.enabled);
|
||||
assert_eq!(parsed.level, "debug");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -500,18 +500,12 @@ pub(crate) fn remove_opencode_provider_from_live(provider_id: &str) -> Result<()
|
||||
|
||||
// Check if OpenCode config directory exists
|
||||
if !opencode_config::get_opencode_dir().exists() {
|
||||
log::debug!(
|
||||
"OpenCode config directory doesn't exist, skipping removal of '{}'",
|
||||
provider_id
|
||||
);
|
||||
log::debug!("OpenCode config directory doesn't exist, skipping removal of '{provider_id}'");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
opencode_config::remove_provider(provider_id)?;
|
||||
log::info!(
|
||||
"OpenCode provider '{}' removed from live config",
|
||||
provider_id
|
||||
);
|
||||
log::info!("OpenCode provider '{provider_id}' removed from live config");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -535,10 +529,7 @@ pub fn import_opencode_providers_from_live(state: &AppState) -> Result<usize, Ap
|
||||
for (id, config) in providers {
|
||||
// Skip if already exists in database
|
||||
if existing.contains_key(&id) {
|
||||
log::debug!(
|
||||
"OpenCode provider '{}' already exists in database, skipping",
|
||||
id
|
||||
);
|
||||
log::debug!("OpenCode provider '{id}' already exists in database, skipping");
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -546,7 +537,7 @@ pub fn import_opencode_providers_from_live(state: &AppState) -> Result<usize, Ap
|
||||
let settings_config = match serde_json::to_value(&config) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
log::warn!("Failed to serialize OpenCode provider '{}': {}", id, e);
|
||||
log::warn!("Failed to serialize OpenCode provider '{id}': {e}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
@@ -561,12 +552,12 @@ pub fn import_opencode_providers_from_live(state: &AppState) -> Result<usize, Ap
|
||||
|
||||
// Save to database
|
||||
if let Err(e) = state.db.save_provider("opencode", &provider) {
|
||||
log::warn!("Failed to import OpenCode provider '{}': {}", id, e);
|
||||
log::warn!("Failed to import OpenCode provider '{id}': {e}");
|
||||
continue;
|
||||
}
|
||||
|
||||
imported += 1;
|
||||
log::info!("Imported OpenCode provider '{}' from live config", id);
|
||||
log::info!("Imported OpenCode provider '{id}' from live config");
|
||||
}
|
||||
|
||||
Ok(imported)
|
||||
|
||||
@@ -1530,7 +1530,10 @@ impl ProxyService {
|
||||
app_type: &str,
|
||||
provider_id: &str,
|
||||
) -> Result<(), String> {
|
||||
// 更新数据库中的 is_current 标记
|
||||
// 代理模式切换供应商(热切换):
|
||||
// - 更新 SSOT(数据库 is_current)
|
||||
// - 同步本地 settings(设备级 current_provider_*)
|
||||
// - 若该应用正处于接管模式,则同步更新 Live 备份(用于停止代理时恢复)
|
||||
let app_type_enum =
|
||||
AppType::from_str(app_type).map_err(|_| format!("无效的应用类型: {app_type}"))?;
|
||||
|
||||
@@ -1538,6 +1541,35 @@ impl ProxyService {
|
||||
.set_current_provider(app_type_enum.as_str(), provider_id)
|
||||
.map_err(|e| format!("更新当前供应商失败: {e}"))?;
|
||||
|
||||
// 同步本地 settings(设备级优先)
|
||||
crate::settings::set_current_provider(&app_type_enum, Some(provider_id))
|
||||
.map_err(|e| format!("更新本地当前供应商失败: {e}"))?;
|
||||
|
||||
// 仅在确实处于接管状态时才更新 Live 备份,避免无接管时误写覆盖 Live
|
||||
let has_backup = self
|
||||
.db
|
||||
.get_live_backup(app_type_enum.as_str())
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some();
|
||||
let live_taken_over = self.detect_takeover_in_live_config_for_app(&app_type_enum);
|
||||
|
||||
if let Ok(Some(provider)) = self.db.get_provider_by_id(provider_id, app_type) {
|
||||
// 同步更新 Live 备份(用于 stop_with_restore 恢复)
|
||||
if has_backup || live_taken_over {
|
||||
self.update_live_backup_from_provider(app_type, &provider)
|
||||
.await?;
|
||||
}
|
||||
|
||||
// 同步更新 ProxyStatus.active_targets(用于 UI 立即反映切换目标)
|
||||
if let Some(server) = self.server.read().await.as_ref() {
|
||||
server
|
||||
.set_active_target(app_type_enum.as_str(), &provider.id, &provider.name)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
log::info!("代理模式:已切换 {app_type} 的目标供应商为 {provider_id}");
|
||||
Ok(())
|
||||
}
|
||||
@@ -2058,4 +2090,66 @@ model = "gpt-5.1-codex"
|
||||
"should not add ANTHROPIC_AUTH_TOKEN when absent"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn switch_proxy_target_updates_live_backup_when_taken_over() {
|
||||
let _home = TempHome::new();
|
||||
crate::settings::reload_settings().expect("reload settings");
|
||||
|
||||
let db = Arc::new(Database::memory().expect("init db"));
|
||||
let service = ProxyService::new(db.clone());
|
||||
|
||||
let provider_a = Provider::with_id(
|
||||
"a".to_string(),
|
||||
"A".to_string(),
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_API_KEY": "a-key"
|
||||
}
|
||||
}),
|
||||
None,
|
||||
);
|
||||
let provider_b = Provider::with_id(
|
||||
"b".to_string(),
|
||||
"B".to_string(),
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_API_KEY": "b-key"
|
||||
}
|
||||
}),
|
||||
None,
|
||||
);
|
||||
db.save_provider("claude", &provider_a)
|
||||
.expect("save provider a");
|
||||
db.save_provider("claude", &provider_b)
|
||||
.expect("save provider b");
|
||||
db.set_current_provider("claude", "a")
|
||||
.expect("set current provider");
|
||||
|
||||
// 模拟“已接管”状态:存在 Live 备份(内容不重要,会被热切换更新)
|
||||
db.save_live_backup("claude", "{\"env\":{}}")
|
||||
.await
|
||||
.expect("seed live backup");
|
||||
|
||||
service
|
||||
.switch_proxy_target("claude", "b")
|
||||
.await
|
||||
.expect("switch proxy target");
|
||||
|
||||
// 断言:本地 settings 的 current provider 已同步
|
||||
assert_eq!(
|
||||
crate::settings::get_current_provider(&AppType::Claude).as_deref(),
|
||||
Some("b")
|
||||
);
|
||||
|
||||
// 断言:Live 备份已更新为目标供应商配置(用于 stop_with_restore 恢复)
|
||||
let backup = db
|
||||
.get_live_backup("claude")
|
||||
.await
|
||||
.expect("get live backup")
|
||||
.expect("backup exists");
|
||||
let expected = serde_json::to_string(&provider_b.settings_config).expect("serialize");
|
||||
assert_eq!(backup.original_config, expected);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,6 +128,12 @@ impl Default for SkillStore {
|
||||
branch: "master".to_string(),
|
||||
enabled: true,
|
||||
},
|
||||
SkillRepo {
|
||||
owner: "JimLiu".to_string(),
|
||||
name: "baoyu-skills".to_string(),
|
||||
branch: "main".to_string(),
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
@@ -323,7 +329,12 @@ impl SkillService {
|
||||
.ok_or_else(|| anyhow!("Skill not found: {id}"))?;
|
||||
|
||||
// 从所有应用目录删除
|
||||
for app in [AppType::Claude, AppType::Codex, AppType::Gemini, AppType::OpenCode] {
|
||||
for app in [
|
||||
AppType::Claude,
|
||||
AppType::Codex,
|
||||
AppType::Gemini,
|
||||
AppType::OpenCode,
|
||||
] {
|
||||
let _ = Self::remove_from_app(&skill.directory, &app);
|
||||
}
|
||||
|
||||
@@ -382,7 +393,12 @@ impl SkillService {
|
||||
|
||||
let mut unmanaged: HashMap<String, UnmanagedSkill> = HashMap::new();
|
||||
|
||||
for app in [AppType::Claude, AppType::Codex, AppType::Gemini, AppType::OpenCode] {
|
||||
for app in [
|
||||
AppType::Claude,
|
||||
AppType::Codex,
|
||||
AppType::Gemini,
|
||||
AppType::OpenCode,
|
||||
] {
|
||||
let app_dir = match Self::get_app_skills_dir(&app) {
|
||||
Ok(d) => d,
|
||||
Err(_) => continue,
|
||||
@@ -464,7 +480,12 @@ impl SkillService {
|
||||
let mut source_path: Option<PathBuf> = None;
|
||||
let mut found_in: Vec<String> = Vec::new();
|
||||
|
||||
for app in [AppType::Claude, AppType::Codex, AppType::Gemini, AppType::OpenCode] {
|
||||
for app in [
|
||||
AppType::Claude,
|
||||
AppType::Codex,
|
||||
AppType::Gemini,
|
||||
AppType::OpenCode,
|
||||
] {
|
||||
if let Ok(app_dir) = Self::get_app_skills_dir(&app) {
|
||||
let skill_path = app_dir.join(&dir_name);
|
||||
if skill_path.exists() {
|
||||
@@ -985,7 +1006,12 @@ pub fn migrate_skills_to_ssot(db: &Arc<Database>) -> Result<usize> {
|
||||
let mut discovered: HashMap<String, SkillApps> = HashMap::new();
|
||||
|
||||
// 扫描各应用目录
|
||||
for app in [AppType::Claude, AppType::Codex, AppType::Gemini, AppType::OpenCode] {
|
||||
for app in [
|
||||
AppType::Claude,
|
||||
AppType::Codex,
|
||||
AppType::Gemini,
|
||||
AppType::OpenCode,
|
||||
] {
|
||||
let app_dir = match SkillService::get_app_skills_dir(&app) {
|
||||
Ok(d) => d,
|
||||
Err(_) => continue,
|
||||
|
||||
@@ -78,15 +78,19 @@ pub struct StreamCheckService;
|
||||
|
||||
impl StreamCheckService {
|
||||
/// 执行流式健康检查(带重试)
|
||||
///
|
||||
/// 如果 Provider 配置了单独的测试配置(meta.testConfig),则使用该配置覆盖全局配置
|
||||
pub async fn check_with_retry(
|
||||
app_type: &AppType,
|
||||
provider: &Provider,
|
||||
config: &StreamCheckConfig,
|
||||
) -> Result<StreamCheckResult, AppError> {
|
||||
// 合并供应商单独配置和全局配置
|
||||
let effective_config = Self::merge_provider_config(provider, config);
|
||||
let mut last_result = None;
|
||||
|
||||
for attempt in 0..=config.max_retries {
|
||||
let result = Self::check_once(app_type, provider, config).await;
|
||||
for attempt in 0..=effective_config.max_retries {
|
||||
let result = Self::check_once(app_type, provider, &effective_config).await;
|
||||
|
||||
match &result {
|
||||
Ok(r) if r.success => {
|
||||
@@ -97,7 +101,7 @@ impl StreamCheckService {
|
||||
}
|
||||
Ok(r) => {
|
||||
// 失败但非异常,判断是否重试
|
||||
if Self::should_retry(&r.message) && attempt < config.max_retries {
|
||||
if Self::should_retry(&r.message) && attempt < effective_config.max_retries {
|
||||
last_result = Some(r.clone());
|
||||
continue;
|
||||
}
|
||||
@@ -107,7 +111,8 @@ impl StreamCheckService {
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
if Self::should_retry(&e.to_string()) && attempt < config.max_retries {
|
||||
if Self::should_retry(&e.to_string()) && attempt < effective_config.max_retries
|
||||
{
|
||||
continue;
|
||||
}
|
||||
return Err(AppError::Message(e.to_string()));
|
||||
@@ -123,10 +128,51 @@ impl StreamCheckService {
|
||||
http_status: None,
|
||||
model_used: String::new(),
|
||||
tested_at: chrono::Utc::now().timestamp(),
|
||||
retry_count: config.max_retries,
|
||||
retry_count: effective_config.max_retries,
|
||||
}))
|
||||
}
|
||||
|
||||
/// 合并供应商单独配置和全局配置
|
||||
///
|
||||
/// 如果供应商配置了 meta.testConfig 且 enabled 为 true,则使用供应商配置覆盖全局配置
|
||||
fn merge_provider_config(
|
||||
provider: &Provider,
|
||||
global_config: &StreamCheckConfig,
|
||||
) -> StreamCheckConfig {
|
||||
let test_config = provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|m| m.test_config.as_ref())
|
||||
.filter(|tc| tc.enabled);
|
||||
|
||||
match test_config {
|
||||
Some(tc) => StreamCheckConfig {
|
||||
timeout_secs: tc.timeout_secs.unwrap_or(global_config.timeout_secs),
|
||||
max_retries: tc.max_retries.unwrap_or(global_config.max_retries),
|
||||
degraded_threshold_ms: tc
|
||||
.degraded_threshold_ms
|
||||
.unwrap_or(global_config.degraded_threshold_ms),
|
||||
claude_model: tc
|
||||
.test_model
|
||||
.clone()
|
||||
.unwrap_or_else(|| global_config.claude_model.clone()),
|
||||
codex_model: tc
|
||||
.test_model
|
||||
.clone()
|
||||
.unwrap_or_else(|| global_config.codex_model.clone()),
|
||||
gemini_model: tc
|
||||
.test_model
|
||||
.clone()
|
||||
.unwrap_or_else(|| global_config.gemini_model.clone()),
|
||||
test_prompt: tc
|
||||
.test_prompt
|
||||
.clone()
|
||||
.unwrap_or_else(|| global_config.test_prompt.clone()),
|
||||
},
|
||||
None => global_config.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 单次流式检查
|
||||
async fn check_once(
|
||||
app_type: &AppType,
|
||||
@@ -144,8 +190,9 @@ impl StreamCheckService {
|
||||
.extract_auth(provider)
|
||||
.ok_or_else(|| AppError::Message("API Key not found".to_string()))?;
|
||||
|
||||
// 使用全局 HTTP 客户端(已包含代理配置)
|
||||
let client = crate::proxy::http_client::get();
|
||||
// 获取 HTTP 客户端:优先使用供应商单独代理配置,否则使用全局客户端
|
||||
let proxy_config = provider.meta.as_ref().and_then(|m| m.proxy_config.as_ref());
|
||||
let client = crate::proxy::http_client::get_for_provider(proxy_config);
|
||||
let request_timeout = std::time::Duration::from_secs(config.timeout_secs);
|
||||
|
||||
let model_to_test = Self::resolve_test_model(app_type, provider, config);
|
||||
@@ -389,6 +436,8 @@ impl StreamCheckService {
|
||||
}
|
||||
|
||||
/// Gemini 流式检查
|
||||
///
|
||||
/// 使用 Gemini 原生 API 格式 (streamGenerateContent)
|
||||
async fn check_gemini_stream(
|
||||
client: &Client,
|
||||
base_url: &str,
|
||||
@@ -398,20 +447,28 @@ impl StreamCheckService {
|
||||
timeout: std::time::Duration,
|
||||
) -> Result<(u16, String), AppError> {
|
||||
let base = base_url.trim_end_matches('/');
|
||||
let url = format!("{base}/v1/chat/completions");
|
||||
// Gemini 原生 API: /v1beta/models/{model}:streamGenerateContent?alt=sse
|
||||
// 智能处理 /v1beta 路径:如果 base_url 不包含版本路径,则添加 /v1beta
|
||||
// alt=sse 参数使 API 返回 SSE 格式(text/event-stream)而非 JSON 数组
|
||||
let url = if base.contains("/v1beta") || base.contains("/v1/") {
|
||||
format!("{base}/models/{model}:streamGenerateContent?alt=sse")
|
||||
} else {
|
||||
format!("{base}/v1beta/models/{model}:streamGenerateContent?alt=sse")
|
||||
};
|
||||
|
||||
// Gemini 原生请求体格式
|
||||
let body = json!({
|
||||
"model": model,
|
||||
"messages": [{ "role": "user", "content": test_prompt }],
|
||||
"max_tokens": 1,
|
||||
"temperature": 0,
|
||||
"stream": true
|
||||
"contents": [{
|
||||
"role": "user",
|
||||
"parts": [{ "text": test_prompt }]
|
||||
}]
|
||||
});
|
||||
|
||||
let response = client
|
||||
.post(&url)
|
||||
.header("Authorization", format!("Bearer {}", auth.api_key))
|
||||
.header("x-goog-api-key", &auth.api_key)
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Accept", "text/event-stream")
|
||||
.timeout(timeout)
|
||||
.json(&body)
|
||||
.send()
|
||||
|
||||
@@ -16,6 +16,47 @@ pub struct CustomEndpoint {
|
||||
pub last_used: Option<i64>,
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// 主页面显示的应用配置
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct VisibleApps {
|
||||
#[serde(default = "default_true")]
|
||||
pub claude: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub codex: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub gemini: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub opencode: bool,
|
||||
}
|
||||
|
||||
impl Default for VisibleApps {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
claude: true,
|
||||
codex: true,
|
||||
gemini: true,
|
||||
opencode: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl VisibleApps {
|
||||
/// Check if the specified app is visible
|
||||
pub fn is_visible(&self, app: &AppType) -> bool {
|
||||
match app {
|
||||
AppType::Claude => self.claude,
|
||||
AppType::Codex => self.codex,
|
||||
AppType::Gemini => self.gemini,
|
||||
AppType::OpenCode => self.opencode,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 应用设置结构
|
||||
///
|
||||
/// 存储设备级别设置,保存在本地 `~/.cc-switch/settings.json`,不随数据库同步。
|
||||
@@ -32,7 +73,7 @@ pub struct AppSettings {
|
||||
#[serde(default)]
|
||||
pub enable_claude_plugin_integration: bool,
|
||||
/// 是否跳过 Claude Code 初次安装确认
|
||||
#[serde(default = "default_true")]
|
||||
#[serde(default)]
|
||||
pub skip_claude_onboarding: bool,
|
||||
/// 是否开机自启
|
||||
#[serde(default)]
|
||||
@@ -40,6 +81,10 @@ pub struct AppSettings {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub language: Option<String>,
|
||||
|
||||
// ===== 主页面显示的应用 =====
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub visible_apps: Option<VisibleApps>,
|
||||
|
||||
// ===== 设备级目录覆盖 =====
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub claude_config_dir: Option<String>,
|
||||
@@ -73,19 +118,16 @@ fn default_minimize_to_tray_on_close() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
impl Default for AppSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
show_in_tray: true,
|
||||
minimize_to_tray_on_close: true,
|
||||
enable_claude_plugin_integration: false,
|
||||
skip_claude_onboarding: true,
|
||||
skip_claude_onboarding: false,
|
||||
launch_on_startup: false,
|
||||
language: None,
|
||||
visible_apps: None,
|
||||
claude_config_dir: None,
|
||||
codex_config_dir: None,
|
||||
gemini_config_dir: None,
|
||||
|
||||
+199
-42
@@ -15,6 +15,7 @@ pub struct TrayTexts {
|
||||
pub show_main: &'static str,
|
||||
pub no_provider_hint: &'static str,
|
||||
pub quit: &'static str,
|
||||
pub auto_label: &'static str,
|
||||
}
|
||||
|
||||
impl TrayTexts {
|
||||
@@ -24,17 +25,20 @@ impl TrayTexts {
|
||||
show_main: "Open main window",
|
||||
no_provider_hint: " (No providers yet, please add them from the main window)",
|
||||
quit: "Quit",
|
||||
auto_label: "Auto (Failover)",
|
||||
},
|
||||
"ja" => Self {
|
||||
show_main: "メインウィンドウを開く",
|
||||
no_provider_hint:
|
||||
" (プロバイダーがまだありません。メイン画面から追加してください)",
|
||||
quit: "終了",
|
||||
auto_label: "自動 (フェイルオーバー)",
|
||||
},
|
||||
_ => Self {
|
||||
show_main: "打开主界面",
|
||||
no_provider_hint: " (无供应商,请在主界面添加)",
|
||||
quit: "退出",
|
||||
auto_label: "自动 (故障转移)",
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -50,6 +54,9 @@ pub struct TrayAppSection {
|
||||
pub log_name: &'static str,
|
||||
}
|
||||
|
||||
/// Auto 菜单项后缀
|
||||
pub const AUTO_SUFFIX: &str = "auto";
|
||||
|
||||
pub const TRAY_SECTIONS: [TrayAppSection; 3] = [
|
||||
TrayAppSection {
|
||||
app_type: AppType::Claude,
|
||||
@@ -84,6 +91,7 @@ fn append_provider_section<'a>(
|
||||
manager: Option<&crate::provider::ProviderManager>,
|
||||
section: &TrayAppSection,
|
||||
tray_texts: &TrayTexts,
|
||||
app_state: &AppState,
|
||||
) -> Result<MenuBuilder<'a, tauri::Wry, tauri::AppHandle<tauri::Wry>>, AppError> {
|
||||
let Some(manager) = manager else {
|
||||
return Ok(menu_builder);
|
||||
@@ -111,6 +119,23 @@ fn append_provider_section<'a>(
|
||||
return Ok(menu_builder.item(&empty_hint));
|
||||
}
|
||||
|
||||
// 获取 proxy 状态,决定 Auto 是否选中
|
||||
let (proxy_enabled, auto_failover) =
|
||||
app_state.db.get_proxy_flags_sync(section.app_type.as_str());
|
||||
let auto_mode = proxy_enabled && auto_failover;
|
||||
|
||||
// 添加 Auto 菜单项(始终显示在供应商列表前)
|
||||
let auto_item = CheckMenuItem::with_id(
|
||||
app,
|
||||
format!("{}{}", section.prefix, AUTO_SUFFIX),
|
||||
tray_texts.auto_label,
|
||||
true,
|
||||
auto_mode,
|
||||
None::<&str>,
|
||||
)
|
||||
.map_err(|e| AppError::Message(format!("创建{}Auto菜单项失败: {e}", section.log_name)))?;
|
||||
menu_builder = menu_builder.item(&auto_item);
|
||||
|
||||
let mut sorted_providers: Vec<_> = manager.providers.iter().collect();
|
||||
sorted_providers.sort_by(|(_, a), (_, b)| {
|
||||
match (a.sort_index, b.sort_index) {
|
||||
@@ -131,7 +156,8 @@ fn append_provider_section<'a>(
|
||||
});
|
||||
|
||||
for (id, provider) in sorted_providers {
|
||||
let is_current = manager.current == *id;
|
||||
// Auto 模式下所有供应商都不选中
|
||||
let is_current = !auto_mode && manager.current == *id;
|
||||
let item = CheckMenuItem::with_id(
|
||||
app,
|
||||
format!("{}{}", section.prefix, id),
|
||||
@@ -150,13 +176,27 @@ fn append_provider_section<'a>(
|
||||
/// 处理供应商托盘事件
|
||||
pub fn handle_provider_tray_event(app: &tauri::AppHandle, event_id: &str) -> bool {
|
||||
for section in TRAY_SECTIONS.iter() {
|
||||
if let Some(provider_id) = event_id.strip_prefix(section.prefix) {
|
||||
log::info!("切换到{}供应商: {provider_id}", section.log_name);
|
||||
if let Some(suffix) = event_id.strip_prefix(section.prefix) {
|
||||
// 处理 Auto 点击
|
||||
if suffix == AUTO_SUFFIX {
|
||||
log::info!("切换到{} Auto模式", section.log_name);
|
||||
let app_handle = app.clone();
|
||||
let app_type = section.app_type.clone();
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
if let Err(e) = handle_auto_click(&app_handle, &app_type) {
|
||||
log::error!("切换{}Auto模式失败: {e}", section.log_name);
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
// 处理供应商点击
|
||||
log::info!("切换到{}供应商: {suffix}", section.log_name);
|
||||
let app_handle = app.clone();
|
||||
let provider_id = provider_id.to_string();
|
||||
let provider_id = suffix.to_string();
|
||||
let app_type = section.app_type.clone();
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
if let Err(e) = switch_provider_internal(&app_handle, app_type, provider_id) {
|
||||
if let Err(e) = handle_provider_click(&app_handle, &app_type, &provider_id) {
|
||||
log::error!("切换{}供应商失败: {e}", section.log_name);
|
||||
}
|
||||
});
|
||||
@@ -166,6 +206,143 @@ pub fn handle_provider_tray_event(app: &tauri::AppHandle, event_id: &str) -> boo
|
||||
false
|
||||
}
|
||||
|
||||
/// 处理 Auto 点击:启用 proxy 和 auto_failover
|
||||
fn handle_auto_click(app: &tauri::AppHandle, app_type: &AppType) -> Result<(), AppError> {
|
||||
if let Some(app_state) = app.try_state::<AppState>() {
|
||||
let app_type_str = app_type.as_str();
|
||||
|
||||
// 强一致语义:Auto 模式开启后立即切到队列 P1(P1→P2→...)
|
||||
// 若队列为空,则尝试把“当前供应商”自动加入队列作为 P1,避免用户陷入无法开启的死锁。
|
||||
let mut queue = app_state.db.get_failover_queue(app_type_str)?;
|
||||
if queue.is_empty() {
|
||||
let current_id =
|
||||
crate::settings::get_effective_current_provider(&app_state.db, app_type)?;
|
||||
let Some(current_id) = current_id else {
|
||||
return Err(AppError::Message(
|
||||
"故障转移队列为空,且未设置当前供应商,无法启用 Auto 模式".to_string(),
|
||||
));
|
||||
};
|
||||
app_state
|
||||
.db
|
||||
.add_to_failover_queue(app_type_str, ¤t_id)?;
|
||||
queue = app_state.db.get_failover_queue(app_type_str)?;
|
||||
}
|
||||
|
||||
let p1_provider_id = queue
|
||||
.first()
|
||||
.map(|item| item.provider_id.clone())
|
||||
.ok_or_else(|| AppError::Message("故障转移队列为空,无法启用 Auto 模式".to_string()))?;
|
||||
|
||||
// 真正启用 failover:启动代理服务 + 执行接管 + 开启 auto_failover
|
||||
let proxy_service = &app_state.proxy_service;
|
||||
|
||||
// 1) 确保代理服务运行(会自动设置 proxy_enabled = true)
|
||||
let is_running = futures::executor::block_on(proxy_service.is_running());
|
||||
if !is_running {
|
||||
log::info!("[Tray] Auto 模式:启动代理服务");
|
||||
if let Err(e) = futures::executor::block_on(proxy_service.start()) {
|
||||
log::error!("[Tray] 启动代理服务失败: {e}");
|
||||
return Err(AppError::Message(format!("启动代理服务失败: {e}")));
|
||||
}
|
||||
}
|
||||
|
||||
// 2) 执行 Live 配置接管(确保该 app 被代理接管)
|
||||
log::info!("[Tray] Auto 模式:对 {app_type_str} 执行接管");
|
||||
if let Err(e) =
|
||||
futures::executor::block_on(proxy_service.set_takeover_for_app(app_type_str, true))
|
||||
{
|
||||
log::error!("[Tray] 执行接管失败: {e}");
|
||||
return Err(AppError::Message(format!("执行接管失败: {e}")));
|
||||
}
|
||||
|
||||
// 3) 设置 auto_failover_enabled = true
|
||||
app_state
|
||||
.db
|
||||
.set_proxy_flags_sync(app_type_str, true, true)?;
|
||||
|
||||
// 3.1) 立即切到队列 P1(热切换:不写 Live,仅更新 DB/settings/备份)
|
||||
if let Err(e) = futures::executor::block_on(
|
||||
proxy_service.switch_proxy_target(app_type_str, &p1_provider_id),
|
||||
) {
|
||||
log::error!("[Tray] Auto 模式切换到队列 P1 失败: {e}");
|
||||
return Err(AppError::Message(format!(
|
||||
"Auto 模式切换到队列 P1 失败: {e}"
|
||||
)));
|
||||
}
|
||||
|
||||
// 4) 更新托盘菜单
|
||||
if let Ok(new_menu) = create_tray_menu(app, app_state.inner()) {
|
||||
if let Some(tray) = app.tray_by_id("main") {
|
||||
let _ = tray.set_menu(Some(new_menu));
|
||||
}
|
||||
}
|
||||
|
||||
// 5) 发射事件到前端
|
||||
let event_data = serde_json::json!({
|
||||
"appType": app_type_str,
|
||||
"proxyEnabled": true,
|
||||
"autoFailoverEnabled": true,
|
||||
"providerId": p1_provider_id
|
||||
});
|
||||
if let Err(e) = app.emit("proxy-flags-changed", event_data.clone()) {
|
||||
log::error!("发射 proxy-flags-changed 事件失败: {e}");
|
||||
}
|
||||
// 发射 provider-switched 事件(保持向后兼容,Auto 切换也算一种切换)
|
||||
if let Err(e) = app.emit("provider-switched", event_data) {
|
||||
log::error!("发射 provider-switched 事件失败: {e}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 处理供应商点击:关闭 auto_failover + 切换供应商
|
||||
fn handle_provider_click(
|
||||
app: &tauri::AppHandle,
|
||||
app_type: &AppType,
|
||||
provider_id: &str,
|
||||
) -> Result<(), AppError> {
|
||||
if let Some(app_state) = app.try_state::<AppState>() {
|
||||
let app_type_str = app_type.as_str();
|
||||
|
||||
// 获取当前 proxy 状态,保持 enabled 不变,只关闭 auto_failover
|
||||
let (proxy_enabled, _) = app_state.db.get_proxy_flags_sync(app_type_str);
|
||||
app_state
|
||||
.db
|
||||
.set_proxy_flags_sync(app_type_str, proxy_enabled, false)?;
|
||||
|
||||
// 切换供应商
|
||||
crate::commands::switch_provider(
|
||||
app_state.clone(),
|
||||
app_type_str.to_string(),
|
||||
provider_id.to_string(),
|
||||
)
|
||||
.map_err(AppError::Message)?;
|
||||
|
||||
// 更新托盘菜单
|
||||
if let Ok(new_menu) = create_tray_menu(app, app_state.inner()) {
|
||||
if let Some(tray) = app.tray_by_id("main") {
|
||||
let _ = tray.set_menu(Some(new_menu));
|
||||
}
|
||||
}
|
||||
|
||||
// 发射事件到前端
|
||||
let event_data = serde_json::json!({
|
||||
"appType": app_type_str,
|
||||
"proxyEnabled": proxy_enabled,
|
||||
"autoFailoverEnabled": false,
|
||||
"providerId": provider_id
|
||||
});
|
||||
if let Err(e) = app.emit("proxy-flags-changed", event_data.clone()) {
|
||||
log::error!("发射 proxy-flags-changed 事件失败: {e}");
|
||||
}
|
||||
// 发射 provider-switched 事件(保持向后兼容)
|
||||
if let Err(e) = app.emit("provider-switched", event_data) {
|
||||
log::error!("发射 provider-switched 事件失败: {e}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 创建动态托盘菜单
|
||||
pub fn create_tray_menu(
|
||||
app: &tauri::AppHandle,
|
||||
@@ -174,6 +351,9 @@ pub fn create_tray_menu(
|
||||
let app_settings = crate::settings::get_settings();
|
||||
let tray_texts = TrayTexts::from_language(app_settings.language.as_deref().unwrap_or("zh"));
|
||||
|
||||
// Get visible apps setting, default to all visible
|
||||
let visible_apps = app_settings.visible_apps.unwrap_or_default();
|
||||
|
||||
let mut menu_builder = MenuBuilder::new(app);
|
||||
|
||||
// 顶部:打开主界面
|
||||
@@ -183,7 +363,13 @@ pub fn create_tray_menu(
|
||||
menu_builder = menu_builder.item(&show_main_item).separator();
|
||||
|
||||
// 直接添加所有供应商到主菜单(扁平化结构,更简单可靠)
|
||||
// Only add visible app sections
|
||||
for section in TRAY_SECTIONS.iter() {
|
||||
// Skip hidden apps
|
||||
if !visible_apps.is_visible(§ion.app_type) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let app_type_str = section.app_type.as_str();
|
||||
let providers = app_state.db.get_all_providers(app_type_str)?;
|
||||
|
||||
@@ -197,8 +383,14 @@ pub fn create_tray_menu(
|
||||
current: current_id,
|
||||
};
|
||||
|
||||
menu_builder =
|
||||
append_provider_section(app, menu_builder, Some(&manager), section, &tray_texts)?;
|
||||
menu_builder = append_provider_section(
|
||||
app,
|
||||
menu_builder,
|
||||
Some(&manager),
|
||||
section,
|
||||
&tray_texts,
|
||||
app_state,
|
||||
)?;
|
||||
}
|
||||
|
||||
// 分隔符和退出菜单
|
||||
@@ -263,38 +455,3 @@ pub fn handle_tray_menu_event(app: &tauri::AppHandle, event_id: &str) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 内部切换供应商函数
|
||||
pub fn switch_provider_internal(
|
||||
app: &tauri::AppHandle,
|
||||
app_type: AppType,
|
||||
provider_id: String,
|
||||
) -> Result<(), AppError> {
|
||||
if let Some(app_state) = app.try_state::<AppState>() {
|
||||
// 在使用前先保存需要的值
|
||||
let app_type_str = app_type.as_str().to_string();
|
||||
let provider_id_clone = provider_id.clone();
|
||||
|
||||
crate::commands::switch_provider(app_state.clone(), app_type_str.clone(), provider_id)
|
||||
.map_err(AppError::Message)?;
|
||||
|
||||
// 切换成功后重新创建托盘菜单
|
||||
if let Ok(new_menu) = create_tray_menu(app, app_state.inner()) {
|
||||
if let Some(tray) = app.tray_by_id("main") {
|
||||
if let Err(e) = tray.set_menu(Some(new_menu)) {
|
||||
log::error!("更新托盘菜单失败: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 发射事件到前端,通知供应商已切换
|
||||
let event_data = serde_json::json!({
|
||||
"appType": app_type_str,
|
||||
"providerId": provider_id_clone
|
||||
});
|
||||
if let Err(e) = app.emit("provider-switched", event_data) {
|
||||
log::error!("发射供应商切换事件失败: {e}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "CC Switch",
|
||||
"version": "3.9.1",
|
||||
"version": "3.10.1",
|
||||
"identifier": "com.ccswitch.desktop",
|
||||
"build": {
|
||||
"frontendDist": "../dist",
|
||||
|
||||
+129
-29
@@ -11,14 +11,14 @@ import {
|
||||
// Bot, // TODO: Agents 功能开发中,暂时不需要
|
||||
Book,
|
||||
Wrench,
|
||||
Server,
|
||||
RefreshCw,
|
||||
Search,
|
||||
Download,
|
||||
BarChart2,
|
||||
} from "lucide-react";
|
||||
import type { Provider } from "@/types";
|
||||
import type { Provider, VisibleApps } from "@/types";
|
||||
import type { EnvConflict } from "@/types/env";
|
||||
import { useProvidersQuery } from "@/lib/query";
|
||||
import { useProvidersQuery, useSettingsQuery } from "@/lib/query";
|
||||
import {
|
||||
providersApi,
|
||||
settingsApi,
|
||||
@@ -30,6 +30,7 @@ import { useProviderActions } from "@/hooks/useProviderActions";
|
||||
import { useProxyStatus } from "@/hooks/useProxyStatus";
|
||||
import { useLastValidValue } from "@/hooks/useLastValidValue";
|
||||
import { extractErrorMessage } from "@/utils/errorUtils";
|
||||
import { isTextEditableTarget } from "@/utils/domUtils";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { isWindows, isLinux } from "@/lib/platform";
|
||||
import { AppSwitcher } from "@/components/AppSwitcher";
|
||||
@@ -41,6 +42,7 @@ import { SettingsPage } from "@/components/settings/SettingsPage";
|
||||
import { UpdateBadge } from "@/components/UpdateBadge";
|
||||
import { EnvWarningBanner } from "@/components/env/EnvWarningBanner";
|
||||
import { ProxyToggle } from "@/components/proxy/ProxyToggle";
|
||||
import { FailoverToggle } from "@/components/proxy/FailoverToggle";
|
||||
import UsageScriptModal from "@/components/UsageScriptModal";
|
||||
import UnifiedMcpPanel from "@/components/mcp/UnifiedMcpPanel";
|
||||
import PromptPanel from "@/components/prompts/PromptPanel";
|
||||
@@ -49,6 +51,7 @@ import UnifiedSkillsPanel from "@/components/skills/UnifiedSkillsPanel";
|
||||
import { DeepLinkImportDialog } from "@/components/DeepLinkImportDialog";
|
||||
import { AgentsPanel } from "@/components/agents/AgentsPanel";
|
||||
import { UniversalProviderPanel } from "@/components/universal";
|
||||
import { McpIcon } from "@/components/BrandIcons";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
type View =
|
||||
@@ -75,6 +78,31 @@ function App() {
|
||||
const [settingsDefaultTab, setSettingsDefaultTab] = useState("general");
|
||||
const [isAddOpen, setIsAddOpen] = useState(false);
|
||||
|
||||
// Get settings for visibleApps
|
||||
const { data: settingsData } = useSettingsQuery();
|
||||
const visibleApps: VisibleApps = settingsData?.visibleApps ?? {
|
||||
claude: true,
|
||||
codex: true,
|
||||
gemini: true,
|
||||
opencode: true,
|
||||
};
|
||||
|
||||
// Get first visible app for fallback
|
||||
const getFirstVisibleApp = (): AppId => {
|
||||
if (visibleApps.claude) return "claude";
|
||||
if (visibleApps.codex) return "codex";
|
||||
if (visibleApps.gemini) return "gemini";
|
||||
if (visibleApps.opencode) return "opencode";
|
||||
return "claude"; // fallback
|
||||
};
|
||||
|
||||
// If current active app is hidden, switch to first visible app
|
||||
useEffect(() => {
|
||||
if (!visibleApps[activeApp]) {
|
||||
setActiveApp(getFirstVisibleApp());
|
||||
}
|
||||
}, [visibleApps, activeApp]);
|
||||
|
||||
const [editingProvider, setEditingProvider] = useState<Provider | null>(null);
|
||||
const [usageProvider, setUsageProvider] = useState<Provider | null>(null);
|
||||
// Confirm action state: 'remove' = remove from live config, 'delete' = delete from database
|
||||
@@ -291,18 +319,40 @@ function App() {
|
||||
checkEnvOnSwitch();
|
||||
}, [activeApp]);
|
||||
|
||||
// 全局键盘快捷键
|
||||
const currentViewRef = useRef(currentView);
|
||||
|
||||
useEffect(() => {
|
||||
const handleGlobalShortcut = (event: KeyboardEvent) => {
|
||||
if (event.key !== "," || !(event.metaKey || event.ctrlKey)) {
|
||||
currentViewRef.current = currentView;
|
||||
}, [currentView]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
// Cmd/Ctrl + , 打开设置
|
||||
if (event.key === "," && (event.metaKey || event.ctrlKey)) {
|
||||
event.preventDefault();
|
||||
setCurrentView("settings");
|
||||
return;
|
||||
}
|
||||
|
||||
// ESC 键返回
|
||||
if (event.key !== "Escape" || event.defaultPrevented) return;
|
||||
|
||||
// 如果有模态框打开(通过 overflow hidden 判断),则不处理全局 ESC,交给模态框处理
|
||||
if (document.body.style.overflow === "hidden") return;
|
||||
|
||||
const view = currentViewRef.current;
|
||||
if (view === "providers") return;
|
||||
|
||||
if (isTextEditableTarget(event.target)) return;
|
||||
|
||||
event.preventDefault();
|
||||
setCurrentView("settings");
|
||||
setCurrentView(view === "skillsDiscovery" ? "skills" : "providers");
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", handleGlobalShortcut);
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", handleGlobalShortcut);
|
||||
window.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -353,7 +403,10 @@ function App() {
|
||||
};
|
||||
|
||||
// Generate a unique provider key for OpenCode duplication
|
||||
const generateUniqueOpencodeKey = (originalKey: string, existingKeys: string[]): string => {
|
||||
const generateUniqueOpencodeKey = (
|
||||
originalKey: string,
|
||||
existingKeys: string[],
|
||||
): string => {
|
||||
const baseKey = `${originalKey}-copy`;
|
||||
|
||||
if (!existingKeys.includes(baseKey)) {
|
||||
@@ -374,7 +427,9 @@ function App() {
|
||||
const newSortIndex =
|
||||
provider.sortIndex !== undefined ? provider.sortIndex + 1 : undefined;
|
||||
|
||||
const duplicatedProvider: Omit<Provider, "id" | "createdAt"> & { providerKey?: string } = {
|
||||
const duplicatedProvider: Omit<Provider, "id" | "createdAt"> & {
|
||||
providerKey?: string;
|
||||
} = {
|
||||
name: `${provider.name} copy`,
|
||||
settingsConfig: JSON.parse(JSON.stringify(provider.settingsConfig)), // 深拷贝
|
||||
websiteUrl: provider.websiteUrl,
|
||||
@@ -390,7 +445,10 @@ function App() {
|
||||
// OpenCode: generate unique provider key (used as ID)
|
||||
if (activeApp === "opencode") {
|
||||
const existingKeys = Object.keys(providers);
|
||||
duplicatedProvider.providerKey = generateUniqueOpencodeKey(provider.id, existingKeys);
|
||||
duplicatedProvider.providerKey = generateUniqueOpencodeKey(
|
||||
provider.id,
|
||||
existingKeys,
|
||||
);
|
||||
}
|
||||
|
||||
// 2️⃣ 如果原供应商有 sortIndex,需要将后续所有供应商的 sortIndex +1
|
||||
@@ -499,7 +557,12 @@ function App() {
|
||||
/>
|
||||
);
|
||||
case "skillsDiscovery":
|
||||
return <SkillsPage ref={skillsPageRef} initialApp={activeApp === "opencode" ? "claude" : activeApp} />;
|
||||
return (
|
||||
<SkillsPage
|
||||
ref={skillsPageRef}
|
||||
initialApp={activeApp === "opencode" ? "claude" : activeApp}
|
||||
/>
|
||||
);
|
||||
case "mcp":
|
||||
return (
|
||||
<UnifiedMcpPanel
|
||||
@@ -672,8 +735,8 @@ function App() {
|
||||
</h1>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative inline-flex items-center">
|
||||
<a
|
||||
href="https://github.com/farion1231/cc-switch"
|
||||
target="_blank"
|
||||
@@ -687,31 +750,48 @@ function App() {
|
||||
>
|
||||
CC Switch
|
||||
</a>
|
||||
<UpdateBadge
|
||||
onClick={() => {
|
||||
setSettingsDefaultTab("about");
|
||||
setCurrentView("settings");
|
||||
}}
|
||||
className="absolute -top-4 -right-4"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => {
|
||||
setSettingsDefaultTab("general");
|
||||
setCurrentView("settings");
|
||||
}}
|
||||
title={t("common.settings")}
|
||||
className="hover:bg-black/5 dark:hover:bg-white/5"
|
||||
>
|
||||
<Settings className="w-4 h-4" />
|
||||
</Button>
|
||||
{isCurrentAppTakeoverActive && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => {
|
||||
setSettingsDefaultTab("general");
|
||||
setSettingsDefaultTab("usage");
|
||||
setCurrentView("settings");
|
||||
}}
|
||||
title={t("common.settings")}
|
||||
title={t("settings.usage.title", {
|
||||
defaultValue: "使用统计",
|
||||
})}
|
||||
className="hover:bg-black/5 dark:hover:bg-white/5"
|
||||
>
|
||||
<Settings className="w-4 h-4" />
|
||||
<BarChart2 className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<UpdateBadge
|
||||
onClick={() => {
|
||||
setSettingsDefaultTab("about");
|
||||
setCurrentView("settings");
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="flex items-center gap-2 h-[32px]"
|
||||
className="flex items-center gap-1.5 h-[32px]"
|
||||
style={{ WebkitAppRegion: "no-drag" } as any}
|
||||
>
|
||||
{currentView === "prompts" && (
|
||||
@@ -794,10 +874,30 @@ function App() {
|
||||
{currentView === "providers" && (
|
||||
<>
|
||||
{activeApp !== "opencode" && (
|
||||
<ProxyToggle activeApp={activeApp} />
|
||||
<>
|
||||
<ProxyToggle activeApp={activeApp} />
|
||||
<div
|
||||
className={cn(
|
||||
"transition-all duration-300 ease-in-out overflow-hidden",
|
||||
isCurrentAppTakeoverActive
|
||||
? "opacity-100 max-w-[100px] scale-100"
|
||||
: "opacity-0 max-w-0 scale-75 pointer-events-none",
|
||||
)}
|
||||
>
|
||||
<FailoverToggle activeApp={activeApp} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<AppSwitcher activeApp={activeApp} onSwitch={setActiveApp} />
|
||||
<AppSwitcher
|
||||
activeApp={activeApp}
|
||||
onSwitch={setActiveApp}
|
||||
visibleApps={visibleApps}
|
||||
compact={
|
||||
isCurrentAppTakeoverActive &&
|
||||
Object.values(visibleApps).filter(Boolean).length >= 4
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="flex items-center gap-1 p-1 bg-muted rounded-xl">
|
||||
<Button
|
||||
@@ -843,7 +943,7 @@ function App() {
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
|
||||
title={t("mcp.title")}
|
||||
>
|
||||
<Server className="w-4 h-4" />
|
||||
<McpIcon size={16} />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.2 KiB |
@@ -1,12 +1,22 @@
|
||||
import type { AppId } from "@/lib/api";
|
||||
import type { VisibleApps } from "@/types";
|
||||
import { ProviderIcon } from "@/components/ProviderIcon";
|
||||
|
||||
interface AppSwitcherProps {
|
||||
activeApp: AppId;
|
||||
onSwitch: (app: AppId) => void;
|
||||
visibleApps?: VisibleApps;
|
||||
compact?: boolean;
|
||||
}
|
||||
|
||||
export function AppSwitcher({ activeApp, onSwitch }: AppSwitcherProps) {
|
||||
const ALL_APPS: AppId[] = ["claude", "codex", "gemini", "opencode"];
|
||||
|
||||
export function AppSwitcher({
|
||||
activeApp,
|
||||
onSwitch,
|
||||
visibleApps,
|
||||
compact,
|
||||
}: AppSwitcherProps) {
|
||||
const handleSwitch = (app: AppId) => {
|
||||
if (app === activeApp) return;
|
||||
onSwitch(app);
|
||||
@@ -25,95 +35,33 @@ export function AppSwitcher({ activeApp, onSwitch }: AppSwitcherProps) {
|
||||
opencode: "OpenCode",
|
||||
};
|
||||
|
||||
// Filter apps based on visibility settings (default all visible)
|
||||
const appsToShow = ALL_APPS.filter((app) => {
|
||||
if (!visibleApps) return true;
|
||||
return visibleApps[app];
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="inline-flex bg-muted rounded-xl p-1 gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleSwitch("claude")}
|
||||
className={`group inline-flex items-center gap-2 px-3 h-8 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"
|
||||
}`}
|
||||
>
|
||||
<ProviderIcon
|
||||
icon={appIconName.claude}
|
||||
name={appDisplayName.claude}
|
||||
size={iconSize}
|
||||
className={
|
||||
activeApp === "claude"
|
||||
? "text-foreground"
|
||||
: "text-muted-foreground group-hover:text-foreground transition-colors"
|
||||
}
|
||||
/>
|
||||
<span>{appDisplayName.claude}</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleSwitch("codex")}
|
||||
className={`group inline-flex items-center gap-2 px-3 h-8 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"
|
||||
}`}
|
||||
>
|
||||
<ProviderIcon
|
||||
icon={appIconName.codex}
|
||||
name={appDisplayName.codex}
|
||||
size={iconSize}
|
||||
className={
|
||||
activeApp === "codex"
|
||||
? "text-foreground"
|
||||
: "text-muted-foreground group-hover:text-foreground transition-colors"
|
||||
}
|
||||
/>
|
||||
<span>{appDisplayName.codex}</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleSwitch("gemini")}
|
||||
className={`group inline-flex items-center gap-2 px-3 h-8 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"
|
||||
}`}
|
||||
>
|
||||
<ProviderIcon
|
||||
icon={appIconName.gemini}
|
||||
name={appDisplayName.gemini}
|
||||
size={iconSize}
|
||||
className={
|
||||
activeApp === "gemini"
|
||||
? "text-foreground"
|
||||
: "text-muted-foreground group-hover:text-foreground transition-colors"
|
||||
}
|
||||
/>
|
||||
<span>{appDisplayName.gemini}</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleSwitch("opencode")}
|
||||
className={`group inline-flex items-center gap-2 px-3 h-8 rounded-md text-sm font-medium transition-all duration-200 ${
|
||||
activeApp === "opencode"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-background/50"
|
||||
}`}
|
||||
>
|
||||
<ProviderIcon
|
||||
icon={appIconName.opencode}
|
||||
name={appDisplayName.opencode}
|
||||
size={iconSize}
|
||||
className={
|
||||
activeApp === "opencode"
|
||||
? "text-foreground"
|
||||
: "text-muted-foreground group-hover:text-foreground transition-colors"
|
||||
}
|
||||
/>
|
||||
<span>{appDisplayName.opencode}</span>
|
||||
</button>
|
||||
{appsToShow.map((app) => (
|
||||
<button
|
||||
key={app}
|
||||
type="button"
|
||||
onClick={() => handleSwitch(app)}
|
||||
className={`group inline-flex items-center gap-2 px-3 h-8 rounded-md text-sm font-medium transition-all duration-200 ${
|
||||
activeApp === app
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-background/50"
|
||||
}`}
|
||||
>
|
||||
<ProviderIcon
|
||||
icon={appIconName[app]}
|
||||
name={appDisplayName[app]}
|
||||
size={iconSize}
|
||||
/>
|
||||
{!compact && <span>{appDisplayName[app]}</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -46,3 +46,21 @@ export function GeminiIcon({ size = 16, className = "" }: IconProps) {
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// MCP icon uses inline SVG to support currentColor for hover effects
|
||||
export function McpIcon({ size = 16, className = "" }: IconProps) {
|
||||
return (
|
||||
<svg
|
||||
fill="currentColor"
|
||||
fillRule="evenodd"
|
||||
height={size}
|
||||
width={size}
|
||||
className={className}
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path d="M15.688 2.343a2.588 2.588 0 00-3.61 0l-9.626 9.44a.863.863 0 01-1.203 0 .823.823 0 010-1.18l9.626-9.44a4.313 4.313 0 016.016 0 4.116 4.116 0 011.204 3.54 4.3 4.3 0 013.609 1.18l.05.05a4.115 4.115 0 010 5.9l-8.706 8.537a.274.274 0 000 .393l1.788 1.754a.823.823 0 010 1.18.863.863 0 01-1.203 0l-1.788-1.753a1.92 1.92 0 010-2.754l8.706-8.538a2.47 2.47 0 000-3.54l-.05-.049a2.588 2.588 0 00-3.607-.003l-7.172 7.034-.002.002-.098.097a.863.863 0 01-1.204 0 .823.823 0 010-1.18l7.273-7.133a2.47 2.47 0 00-.003-3.537z" />
|
||||
<path d="M14.485 4.703a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a4.115 4.115 0 000 5.9 4.314 4.314 0 006.016 0l7.12-6.982a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a2.588 2.588 0 01-3.61 0 2.47 2.47 0 010-3.54l7.12-6.982z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useMemo } from "react";
|
||||
import { getIcon, hasIcon } from "@/icons/extracted";
|
||||
import { getIcon, hasIcon, getIconMetadata } from "@/icons/extracted";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface ProviderIconProps {
|
||||
@@ -39,6 +39,23 @@ export const ProviderIcon: React.FC<ProviderIconProps> = ({
|
||||
};
|
||||
}, [size]);
|
||||
|
||||
// 获取有效颜色:优先使用传入的有效 color,否则从元数据获取 defaultColor
|
||||
const effectiveColor = useMemo(() => {
|
||||
// 只有当 color 是有效的非空字符串时才使用
|
||||
if (color && typeof color === "string" && color.trim() !== "") {
|
||||
return color;
|
||||
}
|
||||
// 否则从元数据获取 defaultColor
|
||||
if (icon) {
|
||||
const metadata = getIconMetadata(icon);
|
||||
// 只有当 defaultColor 不是 currentColor 时才使用
|
||||
if (metadata?.defaultColor && metadata.defaultColor !== "currentColor") {
|
||||
return metadata.defaultColor;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}, [color, icon]);
|
||||
|
||||
// 如果有图标,显示图标
|
||||
if (iconSvg) {
|
||||
return (
|
||||
@@ -47,7 +64,7 @@ export const ProviderIcon: React.FC<ProviderIconProps> = ({
|
||||
"inline-flex items-center justify-center flex-shrink-0",
|
||||
className,
|
||||
)}
|
||||
style={{ ...sizeStyle, color }}
|
||||
style={{ ...sizeStyle, color: effectiveColor }}
|
||||
dangerouslySetInnerHTML={{ __html: iconSvg }}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { X, Download } from "lucide-react";
|
||||
import { useUpdate } from "@/contexts/UpdateContext";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
interface UpdateBadgeProps {
|
||||
className?: string;
|
||||
@@ -8,56 +8,39 @@ interface UpdateBadgeProps {
|
||||
}
|
||||
|
||||
export function UpdateBadge({ className = "", onClick }: UpdateBadgeProps) {
|
||||
const { hasUpdate, updateInfo, isDismissed, dismissUpdate } = useUpdate();
|
||||
const { hasUpdate, updateInfo } = useUpdate();
|
||||
const { t } = useTranslation();
|
||||
const isActive = hasUpdate && updateInfo;
|
||||
const title = isActive
|
||||
? t("settings.updateAvailable", {
|
||||
version: updateInfo?.availableVersion ?? "",
|
||||
})
|
||||
: t("settings.checkForUpdates");
|
||||
|
||||
// 如果没有更新或已关闭,不显示
|
||||
if (!hasUpdate || isDismissed || !updateInfo) {
|
||||
if (!isActive) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
title={title}
|
||||
aria-label={title}
|
||||
onClick={onClick}
|
||||
className={`
|
||||
flex items-center gap-1.5 px-2.5 py-1
|
||||
bg-white dark:bg-gray-800
|
||||
border border-border-default
|
||||
rounded-lg text-xs
|
||||
shadow-sm
|
||||
transition-all duration-200
|
||||
${onClick ? "cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-750" : ""}
|
||||
relative h-6 w-6 rounded-full
|
||||
${isActive ? "text-blue-600 dark:text-blue-300 hover:bg-blue-50 dark:hover:bg-blue-500/10" : "text-muted-foreground hover:bg-muted/60"}
|
||||
${className}
|
||||
`}
|
||||
role={onClick ? "button" : undefined}
|
||||
tabIndex={onClick ? 0 : -1}
|
||||
onClick={onClick}
|
||||
onKeyDown={(e) => {
|
||||
if (!onClick) return;
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
onClick();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Download className="w-3 h-3 text-blue-500 dark:text-blue-400" />
|
||||
<span className="text-gray-700 dark:text-gray-300 font-medium">
|
||||
{t("settings.updateBadge")}
|
||||
</span>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
dismissUpdate();
|
||||
}}
|
||||
className="
|
||||
ml-1 -mr-0.5 p-0.5 rounded
|
||||
hover:bg-gray-100 dark:hover:bg-gray-700
|
||||
transition-colors
|
||||
focus:outline-none focus:ring-2 focus:ring-blue-500/20
|
||||
"
|
||||
aria-label={t("common.close")}
|
||||
>
|
||||
<X className="w-3 h-3 text-muted-foreground" />
|
||||
</button>
|
||||
</div>
|
||||
<span
|
||||
className={`
|
||||
absolute inset-0 m-auto h-2 w-2 rounded-full ring-1 ring-background
|
||||
${isActive ? "bg-blue-500 dark:bg-blue-400" : "bg-blue-300/70 dark:bg-blue-300/60"}
|
||||
`}
|
||||
/>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ interface AgentsPanelProps {
|
||||
|
||||
export function AgentsPanel({}: AgentsPanelProps) {
|
||||
return (
|
||||
<div className="mx-auto max-w-5xl flex flex-col h-[calc(100vh-8rem)]">
|
||||
<div className="px-6 flex flex-col h-[calc(100vh-8rem)]">
|
||||
<div className="flex-1 glass-card rounded-xl p-8 flex flex-col items-center justify-center text-center space-y-4">
|
||||
<div className="w-20 h-20 rounded-full bg-white/5 flex items-center justify-center mb-4 animate-pulse-slow">
|
||||
<Bot className="w-10 h-10 text-muted-foreground" />
|
||||
|
||||
@@ -4,6 +4,7 @@ import { motion, AnimatePresence } from "framer-motion";
|
||||
import { ArrowLeft } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { isWindows, isLinux } from "@/lib/platform";
|
||||
import { isTextEditableTarget } from "@/utils/domUtils";
|
||||
|
||||
interface FullScreenPanelProps {
|
||||
isOpen: boolean;
|
||||
@@ -37,6 +38,39 @@ export const FullScreenPanel: React.FC<FullScreenPanelProps> = ({
|
||||
};
|
||||
}, [isOpen]);
|
||||
|
||||
// ESC 键关闭面板
|
||||
const onCloseRef = React.useRef(onClose);
|
||||
|
||||
React.useEffect(() => {
|
||||
onCloseRef.current = onClose;
|
||||
}, [onClose]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") {
|
||||
// 子组件(例如 Radix 的 Select/Dialog/Dropdown)如果已经消费了 ESC,就不要再关闭整个面板
|
||||
if (event.defaultPrevented) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isTextEditableTarget(event.target)) {
|
||||
return; // 让输入框自己处理 ESC(比如清空、失焦等)
|
||||
}
|
||||
|
||||
event.stopPropagation(); // 阻止事件继续冒泡到 window,避免触发 App.tsx 的全局监听
|
||||
onCloseRef.current();
|
||||
}
|
||||
};
|
||||
|
||||
// 使用冒泡阶段监听,让子组件(如 Radix UI)优先处理 ESC
|
||||
window.addEventListener("keydown", handleKeyDown, false);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", handleKeyDown, false);
|
||||
};
|
||||
}, [isOpen]);
|
||||
|
||||
return createPortal(
|
||||
<AnimatePresence>
|
||||
{isOpen && (
|
||||
@@ -94,9 +128,7 @@ export const FullScreenPanel: React.FC<FullScreenPanelProps> = ({
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 overflow-y-auto scroll-overlay">
|
||||
<div className="px-6 py-6 space-y-6 w-full">
|
||||
{children}
|
||||
</div>
|
||||
<div className="px-6 py-6 space-y-6 w-full">{children}</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
|
||||
@@ -24,7 +24,9 @@ interface AddProviderDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
appId: AppId;
|
||||
onSubmit: (provider: Omit<Provider, "id"> & { providerKey?: string }) => Promise<void> | void;
|
||||
onSubmit: (
|
||||
provider: Omit<Provider, "id"> & { providerKey?: string },
|
||||
) => Promise<void> | void;
|
||||
}
|
||||
|
||||
export function AddProviderDialog({
|
||||
@@ -186,7 +188,9 @@ export function AddProviderDialog({
|
||||
}
|
||||
} else if (appId === "opencode") {
|
||||
// OpenCode uses options.baseURL
|
||||
const options = parsedConfig.options as Record<string, any> | undefined;
|
||||
const options = parsedConfig.options as
|
||||
| Record<string, any>
|
||||
| undefined;
|
||||
if (options?.baseURL) {
|
||||
addUrl(options.baseURL);
|
||||
}
|
||||
|
||||
@@ -128,9 +128,10 @@ export function EditProviderDialog({
|
||||
iconColor: provider.iconColor,
|
||||
};
|
||||
}, [
|
||||
open, // 修复:编辑保存后再次打开显示旧数据,依赖 open 确保每次打开时重新读取最新 provider 数据
|
||||
provider?.id, // 只依赖 ID,provider 对象更新不会触发重新计算
|
||||
provider?.meta, // 需要依赖 meta 以便正确初始化 testConfig 和 proxyConfig
|
||||
initialSettingsConfig,
|
||||
// 注意:不依赖 provider 的其他字段,防止表单重置
|
||||
]);
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
|
||||
@@ -64,7 +64,8 @@ export function ProviderActions({
|
||||
const isOpenCodeMode = appId === "opencode";
|
||||
|
||||
// 故障转移模式下的按钮逻辑(OpenCode 不支持故障转移)
|
||||
const isFailoverMode = !isOpenCodeMode && isAutoFailoverEnabled && onToggleFailover;
|
||||
const isFailoverMode =
|
||||
!isOpenCodeMode && isAutoFailoverEnabled && onToggleFailover;
|
||||
|
||||
// 处理主按钮点击
|
||||
const handleMainButtonClick = () => {
|
||||
|
||||
@@ -29,7 +29,10 @@ interface BasicFormFieldsProps {
|
||||
beforeNameSlot?: ReactNode;
|
||||
}
|
||||
|
||||
export function BasicFormFields({ form, beforeNameSlot }: BasicFormFieldsProps) {
|
||||
export function BasicFormFields({
|
||||
form,
|
||||
beforeNameSlot,
|
||||
}: BasicFormFieldsProps) {
|
||||
const { t } = useTranslation();
|
||||
const [iconDialogOpen, setIconDialogOpen] = useState(false);
|
||||
|
||||
|
||||
@@ -525,7 +525,7 @@ const EndpointSpeedTest: React.FC<EndpointSpeedTestProps> = ({
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
type="url"
|
||||
type="text"
|
||||
value={customUrl}
|
||||
placeholder={t("endpointTest.addEndpointPlaceholder")}
|
||||
onChange={(event) => setCustomUrl(event.target.value)}
|
||||
|
||||
@@ -265,7 +265,7 @@ export function OpenCodeFormFields({
|
||||
const handleModelOptionKeyChange = (
|
||||
modelKey: string,
|
||||
oldKey: string,
|
||||
newKey: string
|
||||
newKey: string,
|
||||
) => {
|
||||
if (!newKey.trim() || oldKey === newKey) return;
|
||||
const model = models[modelKey];
|
||||
@@ -283,7 +283,7 @@ export function OpenCodeFormFields({
|
||||
const handleModelOptionValueChange = (
|
||||
modelKey: string,
|
||||
optionKey: string,
|
||||
value: string
|
||||
value: string,
|
||||
) => {
|
||||
const model = models[modelKey];
|
||||
let parsedValue: unknown;
|
||||
@@ -443,7 +443,9 @@ export function OpenCodeFormFields({
|
||||
/>
|
||||
<Input
|
||||
value={value}
|
||||
onChange={(e) => handleExtraOptionValueChange(key, e.target.value)}
|
||||
onChange={(e) =>
|
||||
handleExtraOptionValueChange(key, e.target.value)
|
||||
}
|
||||
placeholder={t("opencode.extraOptionValuePlaceholder", {
|
||||
defaultValue: "600000",
|
||||
})}
|
||||
@@ -521,7 +523,7 @@ export function OpenCodeFormFields({
|
||||
<ChevronRight
|
||||
className={cn(
|
||||
"h-4 w-4 transition-transform",
|
||||
expandedModels.has(key) && "rotate-90"
|
||||
expandedModels.has(key) && "rotate-90",
|
||||
)}
|
||||
/>
|
||||
</Button>
|
||||
@@ -575,17 +577,24 @@ export function OpenCodeFormFields({
|
||||
<>
|
||||
{Object.entries(model.options || {}).map(
|
||||
([optKey, optValue]) => (
|
||||
<div key={optKey} className="flex items-center gap-2">
|
||||
<div
|
||||
key={optKey}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<ModelOptionKeyInput
|
||||
optionKey={optKey}
|
||||
onChange={(newKey) =>
|
||||
handleModelOptionKeyChange(key, optKey, newKey)
|
||||
handleModelOptionKeyChange(
|
||||
key,
|
||||
optKey,
|
||||
newKey,
|
||||
)
|
||||
}
|
||||
placeholder={t(
|
||||
"opencode.modelOptionKeyPlaceholder",
|
||||
{
|
||||
defaultValue: "provider",
|
||||
}
|
||||
},
|
||||
)}
|
||||
/>
|
||||
<Input
|
||||
@@ -598,14 +607,14 @@ export function OpenCodeFormFields({
|
||||
handleModelOptionValueChange(
|
||||
key,
|
||||
optKey,
|
||||
e.target.value
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
placeholder={t(
|
||||
"opencode.modelOptionValuePlaceholder",
|
||||
{
|
||||
defaultValue: '{"order": ["baseten"]}',
|
||||
}
|
||||
},
|
||||
)}
|
||||
className="flex-1"
|
||||
/>
|
||||
@@ -621,7 +630,7 @@ export function OpenCodeFormFields({
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
),
|
||||
)}
|
||||
<div className="flex items-center justify-end">
|
||||
<Button
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useState, useEffect } from "react";
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
FlaskConical,
|
||||
Globe,
|
||||
Eye,
|
||||
EyeOff,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ProviderTestConfig, ProviderProxyConfig } from "@/types";
|
||||
|
||||
interface ProviderAdvancedConfigProps {
|
||||
testConfig: ProviderTestConfig;
|
||||
proxyConfig: ProviderProxyConfig;
|
||||
onTestConfigChange: (config: ProviderTestConfig) => void;
|
||||
onProxyConfigChange: (config: ProviderProxyConfig) => void;
|
||||
}
|
||||
|
||||
/** 从 ProviderProxyConfig 构建完整 URL */
|
||||
function buildProxyUrl(config: ProviderProxyConfig): string {
|
||||
if (!config.proxyHost) return "";
|
||||
|
||||
const protocol = config.proxyType || "http";
|
||||
const host = config.proxyHost;
|
||||
const port = config.proxyPort || (protocol === "socks5" ? 1080 : 7890);
|
||||
|
||||
return `${protocol}://${host}:${port}`;
|
||||
}
|
||||
|
||||
/** 从完整 URL 解析为 ProviderProxyConfig */
|
||||
function parseProxyUrl(url: string): Partial<ProviderProxyConfig> {
|
||||
if (!url.trim()) {
|
||||
return { proxyHost: undefined, proxyPort: undefined, proxyType: undefined };
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
const protocol = parsed.protocol.replace(":", "") as
|
||||
| "http"
|
||||
| "https"
|
||||
| "socks5";
|
||||
const host = parsed.hostname;
|
||||
const port = parsed.port ? parseInt(parsed.port, 10) : undefined;
|
||||
|
||||
return {
|
||||
proxyType: protocol,
|
||||
proxyHost: host || undefined,
|
||||
proxyPort: port,
|
||||
};
|
||||
} catch {
|
||||
// 尝试简单解析(不是标准 URL 格式)
|
||||
const match = url.match(/^(?:(\w+):\/\/)?([^:]+)(?::(\d+))?$/);
|
||||
if (match) {
|
||||
return {
|
||||
proxyType: (match[1] as "http" | "https" | "socks5") || "http",
|
||||
proxyHost: match[2] || undefined,
|
||||
proxyPort: match[3] ? parseInt(match[3], 10) : undefined,
|
||||
};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function ProviderAdvancedConfig({
|
||||
testConfig,
|
||||
proxyConfig,
|
||||
onTestConfigChange,
|
||||
onProxyConfigChange,
|
||||
}: ProviderAdvancedConfigProps) {
|
||||
const { t } = useTranslation();
|
||||
const [isTestConfigOpen, setIsTestConfigOpen] = useState(testConfig.enabled);
|
||||
const [isProxyConfigOpen, setIsProxyConfigOpen] = useState(
|
||||
proxyConfig.enabled,
|
||||
);
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
|
||||
// 代理 URL 输入状态(仅在初始化时从 proxyConfig 构建)
|
||||
const [proxyUrl, setProxyUrl] = useState(() => buildProxyUrl(proxyConfig));
|
||||
|
||||
// 标记是否为用户主动输入(用于区分外部更新和用户输入)
|
||||
const [isUserTyping, setIsUserTyping] = useState(false);
|
||||
|
||||
// 同步外部 testConfig.enabled 变化到展开状态
|
||||
useEffect(() => {
|
||||
setIsTestConfigOpen(testConfig.enabled);
|
||||
}, [testConfig.enabled]);
|
||||
|
||||
// 同步外部 proxyConfig.enabled 变化到展开状态
|
||||
useEffect(() => {
|
||||
setIsProxyConfigOpen(proxyConfig.enabled);
|
||||
}, [proxyConfig.enabled]);
|
||||
|
||||
// 仅在外部 proxyConfig 变化且非用户输入时同步(如:重置表单、加载数据)
|
||||
useEffect(() => {
|
||||
if (!isUserTyping) {
|
||||
const newUrl = buildProxyUrl(proxyConfig);
|
||||
if (newUrl !== proxyUrl) {
|
||||
setProxyUrl(newUrl);
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [proxyConfig.proxyType, proxyConfig.proxyHost, proxyConfig.proxyPort]);
|
||||
|
||||
// 处理代理 URL 变化(用户输入时不触发 URL 重建)
|
||||
const handleProxyUrlChange = (value: string) => {
|
||||
setIsUserTyping(true);
|
||||
setProxyUrl(value);
|
||||
const parsed = parseProxyUrl(value);
|
||||
onProxyConfigChange({
|
||||
...proxyConfig,
|
||||
...parsed,
|
||||
});
|
||||
};
|
||||
|
||||
// 输入框失焦时结束用户输入状态
|
||||
const handleProxyUrlBlur = () => {
|
||||
setIsUserTyping(false);
|
||||
};
|
||||
|
||||
// 清除代理配置
|
||||
const handleClearProxy = () => {
|
||||
setProxyUrl("");
|
||||
onProxyConfigChange({
|
||||
...proxyConfig,
|
||||
proxyType: undefined,
|
||||
proxyHost: undefined,
|
||||
proxyPort: undefined,
|
||||
proxyUsername: undefined,
|
||||
proxyPassword: undefined,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* 模型测试配置 */}
|
||||
<div className="rounded-lg border border-border/50 bg-muted/20">
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-center justify-between p-4 hover:bg-muted/30 transition-colors"
|
||||
onClick={() => setIsTestConfigOpen(!isTestConfigOpen)}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<FlaskConical className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium">
|
||||
{t("providerAdvanced.testConfig", {
|
||||
defaultValue: "模型测试配置",
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div
|
||||
className="flex items-center gap-2"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Label
|
||||
htmlFor="test-config-enabled"
|
||||
className="text-sm text-muted-foreground"
|
||||
>
|
||||
{t("providerAdvanced.useCustomConfig", {
|
||||
defaultValue: "使用单独配置",
|
||||
})}
|
||||
</Label>
|
||||
<Switch
|
||||
id="test-config-enabled"
|
||||
checked={testConfig.enabled}
|
||||
onCheckedChange={(checked) => {
|
||||
onTestConfigChange({ ...testConfig, enabled: checked });
|
||||
if (checked) setIsTestConfigOpen(true);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{isTestConfigOpen ? (
|
||||
<ChevronDown className="h-4 w-4 text-muted-foreground" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
<div
|
||||
className={cn(
|
||||
"overflow-hidden transition-all duration-200",
|
||||
isTestConfigOpen
|
||||
? "max-h-[500px] opacity-100"
|
||||
: "max-h-0 opacity-0",
|
||||
)}
|
||||
>
|
||||
<div className="border-t border-border/50 p-4 space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("providerAdvanced.testConfigDesc", {
|
||||
defaultValue:
|
||||
"为此供应商配置单独的模型测试参数,不启用时使用全局配置。",
|
||||
})}
|
||||
</p>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="test-model">
|
||||
{t("providerAdvanced.testModel", {
|
||||
defaultValue: "测试模型",
|
||||
})}
|
||||
</Label>
|
||||
<Input
|
||||
id="test-model"
|
||||
value={testConfig.testModel || ""}
|
||||
onChange={(e) =>
|
||||
onTestConfigChange({
|
||||
...testConfig,
|
||||
testModel: e.target.value || undefined,
|
||||
})
|
||||
}
|
||||
placeholder={t("providerAdvanced.testModelPlaceholder", {
|
||||
defaultValue: "留空使用全局配置",
|
||||
})}
|
||||
disabled={!testConfig.enabled}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="test-timeout">
|
||||
{t("providerAdvanced.timeoutSecs", {
|
||||
defaultValue: "超时时间(秒)",
|
||||
})}
|
||||
</Label>
|
||||
<Input
|
||||
id="test-timeout"
|
||||
type="number"
|
||||
min={1}
|
||||
max={300}
|
||||
value={testConfig.timeoutSecs || ""}
|
||||
onChange={(e) =>
|
||||
onTestConfigChange({
|
||||
...testConfig,
|
||||
timeoutSecs: e.target.value
|
||||
? parseInt(e.target.value, 10)
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
placeholder="45"
|
||||
disabled={!testConfig.enabled}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="test-prompt">
|
||||
{t("providerAdvanced.testPrompt", {
|
||||
defaultValue: "测试提示词",
|
||||
})}
|
||||
</Label>
|
||||
<Input
|
||||
id="test-prompt"
|
||||
value={testConfig.testPrompt || ""}
|
||||
onChange={(e) =>
|
||||
onTestConfigChange({
|
||||
...testConfig,
|
||||
testPrompt: e.target.value || undefined,
|
||||
})
|
||||
}
|
||||
placeholder="Who are you?"
|
||||
disabled={!testConfig.enabled}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="degraded-threshold">
|
||||
{t("providerAdvanced.degradedThreshold", {
|
||||
defaultValue: "降级阈值(毫秒)",
|
||||
})}
|
||||
</Label>
|
||||
<Input
|
||||
id="degraded-threshold"
|
||||
type="number"
|
||||
min={100}
|
||||
max={60000}
|
||||
value={testConfig.degradedThresholdMs || ""}
|
||||
onChange={(e) =>
|
||||
onTestConfigChange({
|
||||
...testConfig,
|
||||
degradedThresholdMs: e.target.value
|
||||
? parseInt(e.target.value, 10)
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
placeholder="6000"
|
||||
disabled={!testConfig.enabled}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="max-retries">
|
||||
{t("providerAdvanced.maxRetries", {
|
||||
defaultValue: "最大重试次数",
|
||||
})}
|
||||
</Label>
|
||||
<Input
|
||||
id="max-retries"
|
||||
type="number"
|
||||
min={0}
|
||||
max={10}
|
||||
value={testConfig.maxRetries ?? ""}
|
||||
onChange={(e) =>
|
||||
onTestConfigChange({
|
||||
...testConfig,
|
||||
maxRetries: e.target.value
|
||||
? parseInt(e.target.value, 10)
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
placeholder="2"
|
||||
disabled={!testConfig.enabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 代理配置 */}
|
||||
<div className="rounded-lg border border-border/50 bg-muted/20">
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-center justify-between p-4 hover:bg-muted/30 transition-colors"
|
||||
onClick={() => setIsProxyConfigOpen(!isProxyConfigOpen)}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<Globe className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium">
|
||||
{t("providerAdvanced.proxyConfig", {
|
||||
defaultValue: "代理配置",
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div
|
||||
className="flex items-center gap-2"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Label
|
||||
htmlFor="proxy-config-enabled"
|
||||
className="text-sm text-muted-foreground"
|
||||
>
|
||||
{t("providerAdvanced.useCustomProxy", {
|
||||
defaultValue: "使用单独代理",
|
||||
})}
|
||||
</Label>
|
||||
<Switch
|
||||
id="proxy-config-enabled"
|
||||
checked={proxyConfig.enabled}
|
||||
onCheckedChange={(checked) => {
|
||||
onProxyConfigChange({ ...proxyConfig, enabled: checked });
|
||||
if (checked) setIsProxyConfigOpen(true);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{isProxyConfigOpen ? (
|
||||
<ChevronDown className="h-4 w-4 text-muted-foreground" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
<div
|
||||
className={cn(
|
||||
"overflow-hidden transition-all duration-200",
|
||||
isProxyConfigOpen
|
||||
? "max-h-[500px] opacity-100"
|
||||
: "max-h-0 opacity-0",
|
||||
)}
|
||||
>
|
||||
<div className="border-t border-border/50 p-4 space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("providerAdvanced.proxyConfigDesc", {
|
||||
defaultValue:
|
||||
"为此供应商配置单独的网络代理,不启用时使用系统代理或全局设置。",
|
||||
})}
|
||||
</p>
|
||||
|
||||
{/* 代理地址输入框(仿照全局代理样式) */}
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="http://127.0.0.1:7890 / socks5://127.0.0.1:1080"
|
||||
value={proxyUrl}
|
||||
onChange={(e) => handleProxyUrlChange(e.target.value)}
|
||||
onBlur={handleProxyUrlBlur}
|
||||
className="font-mono text-sm flex-1"
|
||||
disabled={!proxyConfig.enabled}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
disabled={!proxyConfig.enabled || !proxyUrl}
|
||||
onClick={handleClearProxy}
|
||||
title={t("common.clear", { defaultValue: "清除" })}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 认证信息:用户名 + 密码(可选) */}
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder={t("providerAdvanced.proxyUsername", {
|
||||
defaultValue: "用户名(可选)",
|
||||
})}
|
||||
value={proxyConfig.proxyUsername || ""}
|
||||
onChange={(e) =>
|
||||
onProxyConfigChange({
|
||||
...proxyConfig,
|
||||
proxyUsername: e.target.value || undefined,
|
||||
})
|
||||
}
|
||||
className="font-mono text-sm flex-1"
|
||||
disabled={!proxyConfig.enabled}
|
||||
/>
|
||||
<div className="relative flex-1">
|
||||
<Input
|
||||
type={showPassword ? "text" : "password"}
|
||||
placeholder={t("providerAdvanced.proxyPassword", {
|
||||
defaultValue: "密码(可选)",
|
||||
})}
|
||||
value={proxyConfig.proxyPassword || ""}
|
||||
onChange={(e) =>
|
||||
onProxyConfigChange({
|
||||
...proxyConfig,
|
||||
proxyPassword: e.target.value || undefined,
|
||||
})
|
||||
}
|
||||
className="font-mono text-sm pr-10"
|
||||
disabled={!proxyConfig.enabled}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
tabIndex={-1}
|
||||
disabled={!proxyConfig.enabled}
|
||||
>
|
||||
{showPassword ? (
|
||||
<EyeOff className="h-4 w-4 text-muted-foreground" />
|
||||
) : (
|
||||
<Eye className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -8,7 +8,12 @@ import { Form, FormField, FormItem, FormMessage } from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { providerSchema, type ProviderFormData } from "@/lib/schemas/provider";
|
||||
import type { AppId } from "@/lib/api";
|
||||
import type { ProviderCategory, ProviderMeta } from "@/types";
|
||||
import type {
|
||||
ProviderCategory,
|
||||
ProviderMeta,
|
||||
ProviderTestConfig,
|
||||
ProviderProxyConfig,
|
||||
} from "@/types";
|
||||
import {
|
||||
providerPresets,
|
||||
type ProviderPreset,
|
||||
@@ -41,6 +46,7 @@ import { BasicFormFields } from "./BasicFormFields";
|
||||
import { ClaudeFormFields } from "./ClaudeFormFields";
|
||||
import { CodexFormFields } from "./CodexFormFields";
|
||||
import { GeminiFormFields } from "./GeminiFormFields";
|
||||
import { ProviderAdvancedConfig } from "./ProviderAdvancedConfig";
|
||||
import {
|
||||
useProviderCategory,
|
||||
useApiKeyState,
|
||||
@@ -87,7 +93,11 @@ const OPENCODE_DEFAULT_CONFIG = JSON.stringify(
|
||||
|
||||
type PresetEntry = {
|
||||
id: string;
|
||||
preset: ProviderPreset | CodexProviderPreset | GeminiProviderPreset | OpenCodeProviderPreset;
|
||||
preset:
|
||||
| ProviderPreset
|
||||
| CodexProviderPreset
|
||||
| GeminiProviderPreset
|
||||
| OpenCodeProviderPreset;
|
||||
};
|
||||
|
||||
interface ProviderFormProps {
|
||||
@@ -151,6 +161,14 @@ export function ProviderForm({
|
||||
() => initialData?.meta?.endpointAutoSelect ?? true,
|
||||
);
|
||||
|
||||
// 高级配置:模型测试和代理配置
|
||||
const [testConfig, setTestConfig] = useState<ProviderTestConfig>(
|
||||
() => initialData?.meta?.testConfig ?? { enabled: false },
|
||||
);
|
||||
const [proxyConfig, setProxyConfig] = useState<ProviderProxyConfig>(
|
||||
() => initialData?.meta?.proxyConfig ?? { enabled: false },
|
||||
);
|
||||
|
||||
// 使用 category hook
|
||||
const { category } = useProviderCategory({
|
||||
appId,
|
||||
@@ -168,6 +186,8 @@ export function ProviderForm({
|
||||
setDraftCustomEndpoints([]);
|
||||
}
|
||||
setEndpointAutoSelect(initialData?.meta?.endpointAutoSelect ?? true);
|
||||
setTestConfig(initialData?.meta?.testConfig ?? { enabled: false });
|
||||
setProxyConfig(initialData?.meta?.proxyConfig ?? { enabled: false });
|
||||
}, [appId, initialData]);
|
||||
|
||||
const defaultValues: ProviderFormData = useMemo(
|
||||
@@ -506,7 +526,7 @@ export function ProviderForm({
|
||||
if (!opencodeProvidersData?.providers) return [];
|
||||
// Exclude current provider ID when in edit mode
|
||||
return Object.keys(opencodeProvidersData.providers).filter(
|
||||
(k) => k !== providerId
|
||||
(k) => k !== providerId,
|
||||
);
|
||||
}, [opencodeProvidersData?.providers, providerId]);
|
||||
|
||||
@@ -521,7 +541,11 @@ export function ProviderForm({
|
||||
const [opencodeNpm, setOpencodeNpm] = useState<string>(() => {
|
||||
if (appId !== "opencode") return "@ai-sdk/openai-compatible";
|
||||
try {
|
||||
const config = JSON.parse(initialData?.settingsConfig ? JSON.stringify(initialData.settingsConfig) : OPENCODE_DEFAULT_CONFIG);
|
||||
const config = JSON.parse(
|
||||
initialData?.settingsConfig
|
||||
? JSON.stringify(initialData.settingsConfig)
|
||||
: OPENCODE_DEFAULT_CONFIG,
|
||||
);
|
||||
return config.npm || "@ai-sdk/openai-compatible";
|
||||
} catch {
|
||||
return "@ai-sdk/openai-compatible";
|
||||
@@ -531,7 +555,11 @@ export function ProviderForm({
|
||||
const [opencodeApiKey, setOpencodeApiKey] = useState<string>(() => {
|
||||
if (appId !== "opencode") return "";
|
||||
try {
|
||||
const config = JSON.parse(initialData?.settingsConfig ? JSON.stringify(initialData.settingsConfig) : OPENCODE_DEFAULT_CONFIG);
|
||||
const config = JSON.parse(
|
||||
initialData?.settingsConfig
|
||||
? JSON.stringify(initialData.settingsConfig)
|
||||
: OPENCODE_DEFAULT_CONFIG,
|
||||
);
|
||||
return config.options?.apiKey || "";
|
||||
} catch {
|
||||
return "";
|
||||
@@ -541,17 +569,27 @@ export function ProviderForm({
|
||||
const [opencodeBaseUrl, setOpencodeBaseUrl] = useState<string>(() => {
|
||||
if (appId !== "opencode") return "";
|
||||
try {
|
||||
const config = JSON.parse(initialData?.settingsConfig ? JSON.stringify(initialData.settingsConfig) : OPENCODE_DEFAULT_CONFIG);
|
||||
const config = JSON.parse(
|
||||
initialData?.settingsConfig
|
||||
? JSON.stringify(initialData.settingsConfig)
|
||||
: OPENCODE_DEFAULT_CONFIG,
|
||||
);
|
||||
return config.options?.baseURL || "";
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
});
|
||||
|
||||
const [opencodeModels, setOpencodeModels] = useState<Record<string, OpenCodeModel>>(() => {
|
||||
const [opencodeModels, setOpencodeModels] = useState<
|
||||
Record<string, OpenCodeModel>
|
||||
>(() => {
|
||||
if (appId !== "opencode") return {};
|
||||
try {
|
||||
const config = JSON.parse(initialData?.settingsConfig ? JSON.stringify(initialData.settingsConfig) : OPENCODE_DEFAULT_CONFIG);
|
||||
const config = JSON.parse(
|
||||
initialData?.settingsConfig
|
||||
? JSON.stringify(initialData.settingsConfig)
|
||||
: OPENCODE_DEFAULT_CONFIG,
|
||||
);
|
||||
return config.models || {};
|
||||
} catch {
|
||||
return {};
|
||||
@@ -559,10 +597,16 @@ export function ProviderForm({
|
||||
});
|
||||
|
||||
// OpenCode extra options state (e.g., timeout, setCacheKey)
|
||||
const [opencodeExtraOptions, setOpencodeExtraOptions] = useState<Record<string, string>>(() => {
|
||||
const [opencodeExtraOptions, setOpencodeExtraOptions] = useState<
|
||||
Record<string, string>
|
||||
>(() => {
|
||||
if (appId !== "opencode") return {};
|
||||
try {
|
||||
const config = JSON.parse(initialData?.settingsConfig ? JSON.stringify(initialData.settingsConfig) : OPENCODE_DEFAULT_CONFIG);
|
||||
const config = JSON.parse(
|
||||
initialData?.settingsConfig
|
||||
? JSON.stringify(initialData.settingsConfig)
|
||||
: OPENCODE_DEFAULT_CONFIG,
|
||||
);
|
||||
const options = config.options || {};
|
||||
const extra: Record<string, string> = {};
|
||||
const knownKeys = ["baseURL", "apiKey", "headers"];
|
||||
@@ -583,7 +627,9 @@ export function ProviderForm({
|
||||
(npm: string) => {
|
||||
setOpencodeNpm(npm);
|
||||
try {
|
||||
const config = JSON.parse(form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG);
|
||||
const config = JSON.parse(
|
||||
form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG,
|
||||
);
|
||||
config.npm = npm;
|
||||
form.setValue("settingsConfig", JSON.stringify(config, null, 2));
|
||||
} catch {
|
||||
@@ -597,7 +643,9 @@ export function ProviderForm({
|
||||
(apiKey: string) => {
|
||||
setOpencodeApiKey(apiKey);
|
||||
try {
|
||||
const config = JSON.parse(form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG);
|
||||
const config = JSON.parse(
|
||||
form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG,
|
||||
);
|
||||
if (!config.options) config.options = {};
|
||||
config.options.apiKey = apiKey;
|
||||
form.setValue("settingsConfig", JSON.stringify(config, null, 2));
|
||||
@@ -612,7 +660,9 @@ export function ProviderForm({
|
||||
(baseUrl: string) => {
|
||||
setOpencodeBaseUrl(baseUrl);
|
||||
try {
|
||||
const config = JSON.parse(form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG);
|
||||
const config = JSON.parse(
|
||||
form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG,
|
||||
);
|
||||
if (!config.options) config.options = {};
|
||||
config.options.baseURL = baseUrl.trim().replace(/\/+$/, "");
|
||||
form.setValue("settingsConfig", JSON.stringify(config, null, 2));
|
||||
@@ -627,7 +677,9 @@ export function ProviderForm({
|
||||
(models: Record<string, OpenCodeModel>) => {
|
||||
setOpencodeModels(models);
|
||||
try {
|
||||
const config = JSON.parse(form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG);
|
||||
const config = JSON.parse(
|
||||
form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG,
|
||||
);
|
||||
config.models = models;
|
||||
form.setValue("settingsConfig", JSON.stringify(config, null, 2));
|
||||
} catch {
|
||||
@@ -641,7 +693,9 @@ export function ProviderForm({
|
||||
(options: Record<string, string>) => {
|
||||
setOpencodeExtraOptions(options);
|
||||
try {
|
||||
const config = JSON.parse(form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG);
|
||||
const config = JSON.parse(
|
||||
form.getValues("settingsConfig") || OPENCODE_DEFAULT_CONFIG,
|
||||
);
|
||||
if (!config.options) config.options = {};
|
||||
|
||||
// Remove old extra options (keep only known keys)
|
||||
@@ -883,6 +937,9 @@ export function ProviderForm({
|
||||
payload.meta = {
|
||||
...(baseMeta ?? {}),
|
||||
endpointAutoSelect,
|
||||
// 添加高级配置
|
||||
testConfig: testConfig.enabled ? testConfig : undefined,
|
||||
proxyConfig: proxyConfig.enabled ? proxyConfig : undefined,
|
||||
};
|
||||
|
||||
onSubmit(payload);
|
||||
@@ -1122,32 +1179,44 @@ export function ProviderForm({
|
||||
<Input
|
||||
id="opencode-key"
|
||||
value={opencodeProviderKey}
|
||||
onChange={(e) => setOpencodeProviderKey(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ""))}
|
||||
onChange={(e) =>
|
||||
setOpencodeProviderKey(
|
||||
e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ""),
|
||||
)
|
||||
}
|
||||
placeholder={t("opencode.providerKeyPlaceholder")}
|
||||
disabled={isEditMode}
|
||||
className={
|
||||
(existingOpencodeKeys.includes(opencodeProviderKey) && !isEditMode) ||
|
||||
(opencodeProviderKey.trim() !== "" && !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(opencodeProviderKey))
|
||||
(existingOpencodeKeys.includes(opencodeProviderKey) &&
|
||||
!isEditMode) ||
|
||||
(opencodeProviderKey.trim() !== "" &&
|
||||
!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(opencodeProviderKey))
|
||||
? "border-destructive"
|
||||
: ""
|
||||
}
|
||||
/>
|
||||
{existingOpencodeKeys.includes(opencodeProviderKey) && !isEditMode && (
|
||||
<p className="text-xs text-destructive">
|
||||
{t("opencode.providerKeyDuplicate")}
|
||||
</p>
|
||||
)}
|
||||
{opencodeProviderKey.trim() !== "" && !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(opencodeProviderKey) && (
|
||||
<p className="text-xs text-destructive">
|
||||
{t("opencode.providerKeyInvalid")}
|
||||
</p>
|
||||
)}
|
||||
{!(existingOpencodeKeys.includes(opencodeProviderKey) && !isEditMode) &&
|
||||
(opencodeProviderKey.trim() === "" || /^[a-z0-9]+(-[a-z0-9]+)*$/.test(opencodeProviderKey)) && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("opencode.providerKeyHint")}
|
||||
</p>
|
||||
)}
|
||||
{existingOpencodeKeys.includes(opencodeProviderKey) &&
|
||||
!isEditMode && (
|
||||
<p className="text-xs text-destructive">
|
||||
{t("opencode.providerKeyDuplicate")}
|
||||
</p>
|
||||
)}
|
||||
{opencodeProviderKey.trim() !== "" &&
|
||||
!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(opencodeProviderKey) && (
|
||||
<p className="text-xs text-destructive">
|
||||
{t("opencode.providerKeyInvalid")}
|
||||
</p>
|
||||
)}
|
||||
{!(
|
||||
existingOpencodeKeys.includes(opencodeProviderKey) &&
|
||||
!isEditMode
|
||||
) &&
|
||||
(opencodeProviderKey.trim() === "" ||
|
||||
/^[a-z0-9]+(-[a-z0-9]+)*$/.test(opencodeProviderKey)) && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("opencode.providerKeyHint")}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : undefined
|
||||
}
|
||||
@@ -1391,6 +1460,14 @@ export function ProviderForm({
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* 高级配置:模型测试和代理配置 */}
|
||||
<ProviderAdvancedConfig
|
||||
testConfig={testConfig}
|
||||
proxyConfig={proxyConfig}
|
||||
onTestConfigChange={setTestConfig}
|
||||
onProxyConfigChange={setProxyConfig}
|
||||
/>
|
||||
|
||||
{showButtons && (
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" type="button" onClick={onCancel}>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useCallback, useEffect } from "react";
|
||||
import { useState, useCallback, useEffect, useRef } from "react";
|
||||
|
||||
interface UseModelStateProps {
|
||||
settingsConfig: string;
|
||||
@@ -19,12 +19,27 @@ export function useModelState({
|
||||
const [defaultSonnetModel, setDefaultSonnetModel] = useState("");
|
||||
const [defaultOpusModel, setDefaultOpusModel] = useState("");
|
||||
|
||||
const isUserEditingRef = useRef(false);
|
||||
const lastConfigRef = useRef(settingsConfig);
|
||||
|
||||
// 初始化读取:读新键;若缺失,按兼容优先级回退
|
||||
// Haiku: DEFAULT_HAIKU || SMALL_FAST || MODEL
|
||||
// Sonnet: DEFAULT_SONNET || MODEL || SMALL_FAST
|
||||
// Opus: DEFAULT_OPUS || MODEL || SMALL_FAST
|
||||
// 仅在 settingsConfig 变化时同步一次(表单加载/切换预设时)
|
||||
useEffect(() => {
|
||||
if (lastConfigRef.current === settingsConfig) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isUserEditingRef.current) {
|
||||
isUserEditingRef.current = false;
|
||||
lastConfigRef.current = settingsConfig;
|
||||
return;
|
||||
}
|
||||
|
||||
lastConfigRef.current = settingsConfig;
|
||||
|
||||
try {
|
||||
const cfg = settingsConfig ? JSON.parse(settingsConfig) : {};
|
||||
const env = cfg?.env || {};
|
||||
@@ -71,6 +86,8 @@ export function useModelState({
|
||||
| "ANTHROPIC_DEFAULT_OPUS_MODEL",
|
||||
value: string,
|
||||
) => {
|
||||
isUserEditingRef.current = true;
|
||||
|
||||
if (field === "ANTHROPIC_MODEL") setClaudeModel(value);
|
||||
if (field === "ANTHROPIC_REASONING_MODEL") setReasoningModel(value);
|
||||
if (field === "ANTHROPIC_DEFAULT_HAIKU_MODEL")
|
||||
|
||||
@@ -49,7 +49,7 @@ export function EndpointField({
|
||||
</div>
|
||||
<Input
|
||||
id={id}
|
||||
type="url"
|
||||
type="text"
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder={placeholder}
|
||||
|
||||
@@ -25,9 +25,9 @@ export function AutoFailoverConfigPanel({
|
||||
const [formData, setFormData] = useState({
|
||||
autoFailoverEnabled: false,
|
||||
maxRetries: "3",
|
||||
streamingFirstByteTimeout: "30",
|
||||
streamingIdleTimeout: "60",
|
||||
nonStreamingTimeout: "300",
|
||||
streamingFirstByteTimeout: "60",
|
||||
streamingIdleTimeout: "120",
|
||||
nonStreamingTimeout: "600",
|
||||
circuitFailureThreshold: "5",
|
||||
circuitSuccessThreshold: "2",
|
||||
circuitTimeoutSeconds: "60",
|
||||
@@ -67,9 +67,9 @@ export function AutoFailoverConfigPanel({
|
||||
// 定义各字段的有效范围
|
||||
const ranges = {
|
||||
maxRetries: { min: 0, max: 10 },
|
||||
streamingFirstByteTimeout: { min: 0, max: 180 },
|
||||
streamingFirstByteTimeout: { min: 1, max: 120 },
|
||||
streamingIdleTimeout: { min: 0, max: 600 },
|
||||
nonStreamingTimeout: { min: 0, max: 1800 },
|
||||
nonStreamingTimeout: { min: 60, max: 1200 },
|
||||
circuitFailureThreshold: { min: 1, max: 20 },
|
||||
circuitSuccessThreshold: { min: 1, max: 10 },
|
||||
circuitTimeoutSeconds: { min: 0, max: 300 },
|
||||
@@ -307,8 +307,8 @@ export function AutoFailoverConfigPanel({
|
||||
<Input
|
||||
id={`streamingFirstByte-${appType}`}
|
||||
type="number"
|
||||
min="0"
|
||||
max="180"
|
||||
min="1"
|
||||
max="120"
|
||||
value={formData.streamingFirstByteTimeout}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
@@ -321,7 +321,7 @@ export function AutoFailoverConfigPanel({
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
"proxy.autoFailover.streamingFirstByteHint",
|
||||
"等待首个数据块的最大时间",
|
||||
"等待首个数据块的最大时间,范围 1-120 秒,默认 60 秒",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
@@ -347,7 +347,7 @@ export function AutoFailoverConfigPanel({
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
"proxy.autoFailover.streamingIdleHint",
|
||||
"数据块之间的最大间隔",
|
||||
"数据块之间的最大间隔,范围 60-600 秒,填 0 禁用(防止中途卡住)",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
@@ -359,8 +359,8 @@ export function AutoFailoverConfigPanel({
|
||||
<Input
|
||||
id={`nonStreaming-${appType}`}
|
||||
type="number"
|
||||
min="0"
|
||||
max="1800"
|
||||
min="60"
|
||||
max="1200"
|
||||
value={formData.nonStreamingTimeout}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
@@ -373,7 +373,7 @@ export function AutoFailoverConfigPanel({
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
"proxy.autoFailover.nonStreamingHint",
|
||||
"非流式请求的总超时时间",
|
||||
"非流式请求的总超时时间,范围 60-1200 秒,默认 600 秒(10 分钟)",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -140,7 +140,8 @@ export function FailoverQueueManager({
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("proxy.failover.autoSwitchDescription", {
|
||||
defaultValue: "开启后,请求失败时自动切换到队列中的下一个供应商",
|
||||
defaultValue:
|
||||
"开启后将立即切换到队列 P1,并在请求失败时自动切换到队列中的下一个供应商",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* 故障转移切换开关组件
|
||||
*
|
||||
* 放置在主界面头部,用于一键启用/关闭自动故障转移
|
||||
*/
|
||||
|
||||
import { Shuffle, Loader2 } from "lucide-react";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import {
|
||||
useAutoFailoverEnabled,
|
||||
useSetAutoFailoverEnabled,
|
||||
} from "@/lib/query/failover";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { AppId } from "@/lib/api";
|
||||
|
||||
interface FailoverToggleProps {
|
||||
className?: string;
|
||||
activeApp: AppId;
|
||||
}
|
||||
|
||||
export function FailoverToggle({ className, activeApp }: FailoverToggleProps) {
|
||||
const { t } = useTranslation();
|
||||
const { data: isEnabled = false, isLoading } =
|
||||
useAutoFailoverEnabled(activeApp);
|
||||
const setEnabled = useSetAutoFailoverEnabled();
|
||||
|
||||
const handleToggle = (checked: boolean) => {
|
||||
setEnabled.mutate({ appType: activeApp, enabled: checked });
|
||||
};
|
||||
|
||||
const appLabel =
|
||||
activeApp === "claude"
|
||||
? "Claude"
|
||||
: activeApp === "codex"
|
||||
? "Codex"
|
||||
: "Gemini";
|
||||
|
||||
const tooltipText = isEnabled
|
||||
? t("failover.tooltip.enabled", {
|
||||
app: appLabel,
|
||||
defaultValue: `${appLabel} 故障转移已启用\n按队列优先级(P1→P2→...)选择供应商`,
|
||||
})
|
||||
: t("failover.tooltip.disabled", {
|
||||
app: appLabel,
|
||||
defaultValue: `启用 ${appLabel} 故障转移\n将立即切换到队列 P1,并在失败时自动切换到下一个`,
|
||||
});
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-1 px-1.5 h-8 rounded-lg bg-muted/50 transition-all",
|
||||
className,
|
||||
)}
|
||||
title={tooltipText}
|
||||
>
|
||||
{setEnabled.isPending || isLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : (
|
||||
<Shuffle
|
||||
className={cn(
|
||||
"h-4 w-4 transition-colors",
|
||||
isEnabled
|
||||
? "text-emerald-500 animate-pulse"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<Switch
|
||||
checked={isEnabled}
|
||||
onCheckedChange={handleToggle}
|
||||
disabled={setEnabled.isPending || isLoading}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -50,8 +50,8 @@ export function ProxyPanel() {
|
||||
}
|
||||
}, [globalConfig]);
|
||||
|
||||
// 获取所有三个应用类型的故障转移队列(不包含当前供应商)
|
||||
// 当前供应商始终优先,队列仅用于失败后的备用顺序
|
||||
// 获取所有三个应用类型的故障转移队列
|
||||
// 启用自动故障转移后,将按队列优先级(P1→P2→...)选择供应商
|
||||
const { data: claudeQueue = [] } = useFailoverQueue("claude");
|
||||
const { data: codexQueue = [] } = useFailoverQueue("codex");
|
||||
const { data: geminiQueue = [] } = useFailoverQueue("gemini");
|
||||
|
||||
@@ -55,39 +55,29 @@ export function ProxyToggle({ className, activeApp }: ProxyToggleProps) {
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn("p-1 rounded-xl transition-all", className)}
|
||||
className={cn(
|
||||
"flex items-center gap-1 px-1.5 h-8 rounded-lg bg-muted/50 transition-all",
|
||||
className,
|
||||
)}
|
||||
title={tooltipText}
|
||||
>
|
||||
<div className="flex items-center gap-2 px-2 h-8 rounded-md cursor-default">
|
||||
{isPending ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : (
|
||||
<Radio
|
||||
className={cn(
|
||||
"h-4 w-4 transition-colors",
|
||||
takeoverEnabled
|
||||
? "text-emerald-500 animate-pulse"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<span
|
||||
{isPending ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : (
|
||||
<Radio
|
||||
className={cn(
|
||||
"text-sm font-medium transition-colors select-none",
|
||||
"h-4 w-4 transition-colors",
|
||||
takeoverEnabled
|
||||
? "text-emerald-600 dark:text-emerald-400"
|
||||
? "text-emerald-500 animate-pulse"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
Proxy
|
||||
</span>
|
||||
<Switch
|
||||
checked={takeoverEnabled}
|
||||
onCheckedChange={handleToggle}
|
||||
disabled={isPending}
|
||||
className="ml-1"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<Switch
|
||||
checked={takeoverEnabled}
|
||||
onCheckedChange={handleToggle}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
Terminal,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
Sparkles,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -20,6 +19,7 @@ import { useUpdate } from "@/contexts/UpdateContext";
|
||||
import { relaunchApp } from "@/lib/updater";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { motion } from "framer-motion";
|
||||
import appIcon from "@/assets/icons/app-icon.png";
|
||||
|
||||
interface AboutSectionProps {
|
||||
isPortable: boolean;
|
||||
@@ -204,7 +204,7 @@ export function AboutSection({ isPortable }: AboutSectionProps) {
|
||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Sparkles className="h-5 w-5 text-primary" />
|
||||
<img src={appIcon} alt="CC Switch" className="h-5 w-5" />
|
||||
<h4 className="text-lg font-semibold text-foreground">
|
||||
CC Switch
|
||||
</h4>
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { ProviderIcon } from "@/components/ProviderIcon";
|
||||
import type { SettingsFormState } from "@/hooks/useSettings";
|
||||
import type { VisibleApps } from "@/types";
|
||||
import type { AppId } from "@/lib/api";
|
||||
|
||||
interface AppVisibilitySettingsProps {
|
||||
settings: SettingsFormState;
|
||||
onChange: (updates: Partial<SettingsFormState>) => void;
|
||||
}
|
||||
|
||||
const APP_CONFIG: Array<{
|
||||
id: AppId;
|
||||
icon: string;
|
||||
nameKey: string;
|
||||
}> = [
|
||||
{ id: "claude", icon: "claude", nameKey: "apps.claude" },
|
||||
{ id: "codex", icon: "openai", nameKey: "apps.codex" },
|
||||
{ id: "gemini", icon: "gemini", nameKey: "apps.gemini" },
|
||||
{ id: "opencode", icon: "opencode", nameKey: "apps.opencode" },
|
||||
];
|
||||
|
||||
export function AppVisibilitySettings({
|
||||
settings,
|
||||
onChange,
|
||||
}: AppVisibilitySettingsProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const visibleApps: VisibleApps = settings.visibleApps ?? {
|
||||
claude: true,
|
||||
codex: true,
|
||||
gemini: false,
|
||||
opencode: true,
|
||||
};
|
||||
|
||||
// Count how many apps are currently visible
|
||||
const visibleCount = Object.values(visibleApps).filter(Boolean).length;
|
||||
|
||||
const handleToggle = (appId: AppId) => {
|
||||
const isCurrentlyVisible = visibleApps[appId];
|
||||
// Prevent disabling the last visible app
|
||||
if (isCurrentlyVisible && visibleCount <= 1) return;
|
||||
|
||||
onChange({
|
||||
visibleApps: {
|
||||
...visibleApps,
|
||||
[appId]: !isCurrentlyVisible,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="space-y-2">
|
||||
<header className="space-y-1">
|
||||
<h3 className="text-sm font-medium">
|
||||
{t("settings.appVisibility.title")}
|
||||
</h3>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("settings.appVisibility.description")}
|
||||
</p>
|
||||
</header>
|
||||
<div className="inline-flex gap-1 rounded-md border border-border-default bg-background p-1">
|
||||
{APP_CONFIG.map((app) => {
|
||||
const isVisible = visibleApps[app.id];
|
||||
// Disable button if this is the last visible app
|
||||
const isDisabled = isVisible && visibleCount <= 1;
|
||||
|
||||
return (
|
||||
<AppButton
|
||||
key={app.id}
|
||||
active={isVisible}
|
||||
disabled={isDisabled}
|
||||
onClick={() => handleToggle(app.id)}
|
||||
icon={app.icon}
|
||||
name={t(app.nameKey)}
|
||||
>
|
||||
{t(app.nameKey)}
|
||||
</AppButton>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
interface AppButtonProps {
|
||||
active: boolean;
|
||||
disabled?: boolean;
|
||||
onClick: () => void;
|
||||
icon: string;
|
||||
name: string;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
function AppButton({
|
||||
active,
|
||||
disabled,
|
||||
onClick,
|
||||
icon,
|
||||
name,
|
||||
children,
|
||||
}: AppButtonProps) {
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
size="sm"
|
||||
variant={active ? "default" : "ghost"}
|
||||
className={cn(
|
||||
"w-[90px] gap-1.5",
|
||||
active
|
||||
? "shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-muted",
|
||||
)}
|
||||
>
|
||||
<ProviderIcon icon={icon} name={name} size={14} />
|
||||
{children}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { settingsApi, type LogConfig } from "@/lib/api/settings";
|
||||
|
||||
const LOG_LEVELS = ["error", "warn", "info", "debug", "trace"] as const;
|
||||
|
||||
export function LogConfigPanel() {
|
||||
const { t } = useTranslation();
|
||||
const [config, setConfig] = useState<LogConfig>({
|
||||
enabled: true,
|
||||
level: "info",
|
||||
});
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
settingsApi
|
||||
.getLogConfig()
|
||||
.then(setConfig)
|
||||
.catch((e) => console.error("Failed to load log config:", e))
|
||||
.finally(() => setIsLoading(false));
|
||||
}, []);
|
||||
|
||||
const handleChange = async (updates: Partial<LogConfig>) => {
|
||||
const newConfig = { ...config, ...updates };
|
||||
setConfig(newConfig);
|
||||
try {
|
||||
await settingsApi.setLogConfig(newConfig);
|
||||
} catch (e) {
|
||||
console.error("Failed to save log config:", e);
|
||||
toast.error(String(e));
|
||||
setConfig(config);
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) return null;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label>{t("settings.advanced.logConfig.enabled")}</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("settings.advanced.logConfig.enabledDescription")}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={config.enabled}
|
||||
onCheckedChange={(checked) => handleChange({ enabled: checked })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label>{t("settings.advanced.logConfig.level")}</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("settings.advanced.logConfig.levelDescription")}
|
||||
</p>
|
||||
</div>
|
||||
<Select
|
||||
value={config.level}
|
||||
disabled={!config.enabled}
|
||||
onValueChange={(value) =>
|
||||
handleChange({ level: value as LogConfig["level"] })
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{LOG_LEVELS.map((level) => (
|
||||
<SelectItem key={level} value={level}>
|
||||
{t(`settings.advanced.logConfig.levels.${level}`)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* 日志级别说明 */}
|
||||
<div className="rounded-lg bg-muted/50 p-4 text-xs space-y-1.5">
|
||||
<p className="font-medium text-muted-foreground mb-2">
|
||||
{t("settings.advanced.logConfig.levelHint")}
|
||||
</p>
|
||||
<div className="grid gap-1 text-muted-foreground">
|
||||
<p>
|
||||
<span className="font-mono text-red-500">error</span> -{" "}
|
||||
{t("settings.advanced.logConfig.levelDesc.error")}
|
||||
</p>
|
||||
<p>
|
||||
<span className="font-mono text-orange-500">warn</span> -{" "}
|
||||
{t("settings.advanced.logConfig.levelDesc.warn")}
|
||||
</p>
|
||||
<p>
|
||||
<span className="font-mono text-blue-500">info</span> -{" "}
|
||||
{t("settings.advanced.logConfig.levelDesc.info")}
|
||||
</p>
|
||||
<p>
|
||||
<span className="font-mono text-green-500">debug</span> -{" "}
|
||||
{t("settings.advanced.logConfig.levelDesc.debug")}
|
||||
</p>
|
||||
<p>
|
||||
<span className="font-mono text-gray-500">trace</span> -{" "}
|
||||
{t("settings.advanced.logConfig.levelDesc.trace")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
ChevronDown,
|
||||
Zap,
|
||||
Globe,
|
||||
ScrollText,
|
||||
} from "lucide-react";
|
||||
import * as AccordionPrimitive from "@radix-ui/react-accordion";
|
||||
import { toast } from "sonner";
|
||||
@@ -33,6 +34,7 @@ import { settingsApi } from "@/lib/api";
|
||||
import { LanguageSettings } from "@/components/settings/LanguageSettings";
|
||||
import { ThemeSettings } from "@/components/settings/ThemeSettings";
|
||||
import { WindowSettings } from "@/components/settings/WindowSettings";
|
||||
import { AppVisibilitySettings } from "@/components/settings/AppVisibilitySettings";
|
||||
import { DirectorySettings } from "@/components/settings/DirectorySettings";
|
||||
import { ImportExportSection } from "@/components/settings/ImportExportSection";
|
||||
import { AboutSection } from "@/components/settings/AboutSection";
|
||||
@@ -44,6 +46,7 @@ import { AutoFailoverConfigPanel } from "@/components/proxy/AutoFailoverConfigPa
|
||||
import { FailoverQueueManager } from "@/components/proxy/FailoverQueueManager";
|
||||
import { UsageDashboard } from "@/components/usage/UsageDashboard";
|
||||
import { RectifierConfigPanel } from "@/components/settings/RectifierConfigPanel";
|
||||
import { LogConfigPanel } from "@/components/settings/LogConfigPanel";
|
||||
import { useSettings } from "@/hooks/useSettings";
|
||||
import { useImportExport } from "@/hooks/useImportExport";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -238,6 +241,10 @@ export function SettingsPage({
|
||||
onChange={(lang) => handleAutoSave({ language: lang })}
|
||||
/>
|
||||
<ThemeSettings />
|
||||
<AppVisibilitySettings
|
||||
settings={settings}
|
||||
onChange={handleAutoSave}
|
||||
/>
|
||||
<WindowSettings
|
||||
settings={settings}
|
||||
onChange={handleAutoSave}
|
||||
@@ -455,6 +462,28 @@ export function SettingsPage({
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
|
||||
<AccordionItem
|
||||
value="rectifier"
|
||||
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">
|
||||
<Zap className="h-5 w-5 text-purple-500" />
|
||||
<div className="text-left">
|
||||
<h3 className="text-base font-semibold">
|
||||
{t("settings.advanced.rectifier.title")}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground font-normal">
|
||||
{t("settings.advanced.rectifier.description")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-6 pb-6 pt-4 border-t border-border/50">
|
||||
<RectifierConfigPanel />
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
|
||||
<AccordionItem
|
||||
value="test"
|
||||
className="rounded-xl glass-card overflow-hidden"
|
||||
@@ -554,24 +583,24 @@ export function SettingsPage({
|
||||
</AccordionItem>
|
||||
|
||||
<AccordionItem
|
||||
value="rectifier"
|
||||
value="logConfig"
|
||||
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">
|
||||
<Zap className="h-5 w-5 text-purple-500" />
|
||||
<ScrollText className="h-5 w-5 text-cyan-500" />
|
||||
<div className="text-left">
|
||||
<h3 className="text-base font-semibold">
|
||||
{t("settings.advanced.rectifier.title")}
|
||||
{t("settings.advanced.logConfig.title")}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground font-normal">
|
||||
{t("settings.advanced.rectifier.description")}
|
||||
{t("settings.advanced.logConfig.description")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-6 pb-6 pt-4 border-t border-border/50">
|
||||
<RectifierConfigPanel />
|
||||
<LogConfigPanel />
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { SettingsFormState } from "@/hooks/useSettings";
|
||||
import { AppWindow, MonitorUp, Power } from "lucide-react";
|
||||
import { ToggleRow } from "@/components/ui/toggle-row";
|
||||
|
||||
interface WindowSettingsProps {
|
||||
settings: SettingsFormState;
|
||||
@@ -27,16 +27,6 @@ export function WindowSettings({ settings, onChange }: WindowSettingsProps) {
|
||||
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
|
||||
icon={<MonitorUp className="h-4 w-4 text-purple-500" />}
|
||||
title={t("settings.enableClaudePluginIntegration")}
|
||||
@@ -54,44 +44,17 @@ export function WindowSettings({ settings, onChange }: WindowSettingsProps) {
|
||||
checked={!!settings.skipClaudeOnboarding}
|
||||
onCheckedChange={(value) => onChange({ skipClaudeOnboarding: 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 })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
interface ToggleRowProps {
|
||||
icon: React.ReactNode;
|
||||
title: string;
|
||||
description?: string;
|
||||
checked: boolean;
|
||||
onCheckedChange: (value: boolean) => void;
|
||||
}
|
||||
|
||||
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>
|
||||
<Switch
|
||||
checked={checked}
|
||||
onCheckedChange={onCheckedChange}
|
||||
aria-label={title}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
import { Toaster as SonnerToaster } from "sonner";
|
||||
import { useTheme } from "@/components/theme-provider";
|
||||
|
||||
export function Toaster() {
|
||||
const { theme } = useTheme();
|
||||
|
||||
// 将应用主题映射到 Sonner 的主题
|
||||
// 如果是 "system",Sonner 会自己处理
|
||||
const sonnerTheme = theme === "system" ? "system" : theme;
|
||||
|
||||
return (
|
||||
<SonnerToaster
|
||||
position="top-center"
|
||||
richColors
|
||||
theme="system"
|
||||
theme={sonnerTheme}
|
||||
toastOptions={{
|
||||
duration: 2000,
|
||||
classNames: {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
|
||||
export interface ToggleRowProps {
|
||||
icon: React.ReactNode;
|
||||
title: string;
|
||||
description?: string;
|
||||
checked: boolean;
|
||||
onCheckedChange: (value: boolean) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function ToggleRow({
|
||||
icon,
|
||||
title,
|
||||
description,
|
||||
checked,
|
||||
onCheckedChange,
|
||||
disabled,
|
||||
}: 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>
|
||||
<Switch
|
||||
checked={checked}
|
||||
onCheckedChange={onCheckedChange}
|
||||
disabled={disabled}
|
||||
aria-label={title}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -100,7 +100,7 @@ export const providerPresets: ProviderPreset[] = [
|
||||
iconColor: "#0F62FE",
|
||||
},
|
||||
{
|
||||
name: "Z.ai GLM",
|
||||
name: "Zhipu GLM en",
|
||||
websiteUrl: "https://z.ai",
|
||||
apiKeyUrl: "https://z.ai/subscribe?ic=8JVLJQFSKB",
|
||||
settingsConfig: {
|
||||
@@ -211,6 +211,7 @@ export const providerPresets: ProviderPreset[] = [
|
||||
editorValue: "",
|
||||
},
|
||||
},
|
||||
icon: "catcoder",
|
||||
},
|
||||
{
|
||||
name: "Longcat",
|
||||
@@ -336,6 +337,42 @@ export const providerPresets: ProviderPreset[] = [
|
||||
icon: "aihubmix",
|
||||
iconColor: "#006FFB",
|
||||
},
|
||||
{
|
||||
name: "SiliconFlow",
|
||||
websiteUrl: "https://siliconflow.cn",
|
||||
apiKeyUrl: "https://cloud.siliconflow.cn/me/account/ak",
|
||||
settingsConfig: {
|
||||
env: {
|
||||
ANTHROPIC_BASE_URL: "https://api.siliconflow.cn",
|
||||
ANTHROPIC_AUTH_TOKEN: "",
|
||||
ANTHROPIC_MODEL: "Pro/MiniMaxAI/MiniMax-M2.1",
|
||||
ANTHROPIC_DEFAULT_HAIKU_MODEL: "Pro/MiniMaxAI/MiniMax-M2.1",
|
||||
ANTHROPIC_DEFAULT_SONNET_MODEL: "Pro/MiniMaxAI/MiniMax-M2.1",
|
||||
ANTHROPIC_DEFAULT_OPUS_MODEL: "Pro/MiniMaxAI/MiniMax-M2.1",
|
||||
},
|
||||
},
|
||||
category: "aggregator",
|
||||
icon: "siliconflow",
|
||||
iconColor: "#6E29F6",
|
||||
},
|
||||
{
|
||||
name: "SiliconFlow en",
|
||||
websiteUrl: "https://siliconflow.com",
|
||||
apiKeyUrl: "https://cloud.siliconflow.com/account/ak",
|
||||
settingsConfig: {
|
||||
env: {
|
||||
ANTHROPIC_BASE_URL: "https://api.siliconflow.com",
|
||||
ANTHROPIC_AUTH_TOKEN: "",
|
||||
ANTHROPIC_MODEL: "MiniMaxAI/MiniMax-M2.1",
|
||||
ANTHROPIC_DEFAULT_HAIKU_MODEL: "MiniMaxAI/MiniMax-M2.1",
|
||||
ANTHROPIC_DEFAULT_SONNET_MODEL: "MiniMaxAI/MiniMax-M2.1",
|
||||
ANTHROPIC_DEFAULT_OPUS_MODEL: "MiniMaxAI/MiniMax-M2.1",
|
||||
},
|
||||
},
|
||||
category: "aggregator",
|
||||
icon: "siliconflow",
|
||||
iconColor: "#000000",
|
||||
},
|
||||
{
|
||||
name: "DMXAPI",
|
||||
websiteUrl: "https://www.dmxapi.cn",
|
||||
@@ -412,6 +449,20 @@ export const providerPresets: ProviderPreset[] = [
|
||||
icon: "aigocode",
|
||||
iconColor: "#5B7FFF",
|
||||
},
|
||||
{
|
||||
name: "RightCode",
|
||||
websiteUrl: "https://www.right.codes",
|
||||
apiKeyUrl: "https://www.right.codes/register?aff=0bdf9bfa",
|
||||
settingsConfig: {
|
||||
env: {
|
||||
ANTHROPIC_BASE_URL: "https://www.right.codes/claude",
|
||||
ANTHROPIC_AUTH_TOKEN: "",
|
||||
},
|
||||
},
|
||||
category: "third_party",
|
||||
icon: "rc",
|
||||
iconColor: "#E96B2C",
|
||||
},
|
||||
{
|
||||
name: "OpenRouter",
|
||||
websiteUrl: "https://openrouter.ai",
|
||||
|
||||
@@ -192,6 +192,20 @@ requires_openai_auth = true`,
|
||||
icon: "aigocode",
|
||||
iconColor: "#5B7FFF",
|
||||
},
|
||||
{
|
||||
name: "RightCode",
|
||||
websiteUrl: "https://www.right.codes",
|
||||
apiKeyUrl: "https://www.right.codes/register?aff=0bdf9bfa",
|
||||
auth: generateThirdPartyAuth(""),
|
||||
config: generateThirdPartyConfig(
|
||||
"rightcode",
|
||||
"https://right.codes/codex/v1",
|
||||
"gpt-5.2",
|
||||
),
|
||||
category: "third_party",
|
||||
icon: "rc",
|
||||
iconColor: "#E96B2C",
|
||||
},
|
||||
{
|
||||
name: "OpenRouter",
|
||||
websiteUrl: "https://openrouter.ai",
|
||||
|
||||
@@ -103,12 +103,12 @@ export const opencodeProviderPresets: OpenCodeProviderPreset[] = [
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Z.ai GLM",
|
||||
name: "Zhipu GLM en",
|
||||
websiteUrl: "https://z.ai",
|
||||
apiKeyUrl: "https://z.ai/subscribe?ic=8JVLJQFSKB",
|
||||
settingsConfig: {
|
||||
npm: "@ai-sdk/openai-compatible",
|
||||
name: "Z.ai GLM",
|
||||
name: "Zhipu GLM en",
|
||||
options: {
|
||||
baseURL: "https://api.z.ai/v1",
|
||||
apiKey: "",
|
||||
@@ -302,6 +302,7 @@ export const opencodeProviderPresets: OpenCodeProviderPreset[] = [
|
||||
editorValue: "",
|
||||
},
|
||||
},
|
||||
icon: "catcoder",
|
||||
},
|
||||
{
|
||||
name: "Longcat",
|
||||
@@ -645,6 +646,33 @@ export const opencodeProviderPresets: OpenCodeProviderPreset[] = [
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "RightCode",
|
||||
websiteUrl: "https://www.right.codes",
|
||||
apiKeyUrl: "https://www.right.codes/register?aff=0bdf9bfa",
|
||||
settingsConfig: {
|
||||
npm: "@ai-sdk/openai",
|
||||
name: "RightCode",
|
||||
options: {
|
||||
baseURL: "https://right.codes/codex/v1",
|
||||
apiKey: "",
|
||||
},
|
||||
models: {
|
||||
"gpt-5.2": { name: "GPT-5.2" },
|
||||
"gpt-5.2-codex": { name: "GPT-5.2 Codex" },
|
||||
},
|
||||
},
|
||||
category: "third_party",
|
||||
icon: "rc",
|
||||
iconColor: "#E96B2C",
|
||||
templateValues: {
|
||||
apiKey: {
|
||||
label: "API Key",
|
||||
placeholder: "",
|
||||
editorValue: "",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// ========== 自定义模板 ==========
|
||||
{
|
||||
|
||||
@@ -83,7 +83,7 @@ export function useSettingsForm(): UseSettingsFormResult {
|
||||
minimizeToTrayOnClose: data.minimizeToTrayOnClose ?? true,
|
||||
enableClaudePluginIntegration:
|
||||
data.enableClaudePluginIntegration ?? false,
|
||||
skipClaudeOnboarding: data.skipClaudeOnboarding ?? true,
|
||||
skipClaudeOnboarding: data.skipClaudeOnboarding ?? false,
|
||||
claudeConfigDir: sanitizeDir(data.claudeConfigDir),
|
||||
codexConfigDir: sanitizeDir(data.codexConfigDir),
|
||||
language: normalizedLanguage,
|
||||
@@ -103,7 +103,7 @@ export function useSettingsForm(): UseSettingsFormResult {
|
||||
showInTray: true,
|
||||
minimizeToTrayOnClose: true,
|
||||
enableClaudePluginIntegration: false,
|
||||
skipClaudeOnboarding: true,
|
||||
skipClaudeOnboarding: false,
|
||||
language: readPersistedLanguage(),
|
||||
} as SettingsFormState);
|
||||
|
||||
@@ -138,7 +138,7 @@ export function useSettingsForm(): UseSettingsFormResult {
|
||||
minimizeToTrayOnClose: serverData.minimizeToTrayOnClose ?? true,
|
||||
enableClaudePluginIntegration:
|
||||
serverData.enableClaudePluginIntegration ?? false,
|
||||
skipClaudeOnboarding: serverData.skipClaudeOnboarding ?? true,
|
||||
skipClaudeOnboarding: serverData.skipClaudeOnboarding ?? false,
|
||||
claudeConfigDir: sanitizeDir(serverData.claudeConfigDir),
|
||||
codexConfigDir: sanitizeDir(serverData.codexConfigDir),
|
||||
language: normalizedLanguage,
|
||||
|
||||
@@ -208,6 +208,29 @@
|
||||
"responseGroup": "Response Rectification",
|
||||
"thinkingSignature": "Thinking Signature Rectification",
|
||||
"thinkingSignatureDescription": "Automatically fix Claude API errors caused by thinking signature validation failures"
|
||||
},
|
||||
"logConfig": {
|
||||
"title": "Log Management",
|
||||
"description": "Control log output level",
|
||||
"enabled": "Enable Logging",
|
||||
"enabledDescription": "Master switch, all logging will be disabled when turned off",
|
||||
"level": "Log Level",
|
||||
"levelDescription": "Set the minimum log level to output",
|
||||
"levels": {
|
||||
"error": "Error",
|
||||
"warn": "Warning",
|
||||
"info": "Info",
|
||||
"debug": "Debug",
|
||||
"trace": "Trace"
|
||||
},
|
||||
"levelHint": "Log level descriptions:",
|
||||
"levelDesc": {
|
||||
"error": "Critical errors only",
|
||||
"warn": "Errors + warnings",
|
||||
"info": "General operation info (default)",
|
||||
"debug": "Detailed info including SSE stream and request/response",
|
||||
"trace": "All logs, most verbose"
|
||||
}
|
||||
}
|
||||
},
|
||||
"language": "Language",
|
||||
@@ -249,6 +272,14 @@
|
||||
"enableClaudePluginIntegrationDescription": "When enabled, the VS Code Claude Code extension provider will switch with this app",
|
||||
"skipClaudeOnboarding": "Skip Claude Code first-run confirmation",
|
||||
"skipClaudeOnboardingDescription": "When enabled, Claude Code will skip the first-run confirmation",
|
||||
"appVisibility": {
|
||||
"title": "Homepage Display",
|
||||
"description": "Choose which apps to show on the homepage",
|
||||
"claudeDesc": "Anthropic Claude Code CLI",
|
||||
"codexDesc": "OpenAI Codex CLI",
|
||||
"geminiDesc": "Google Gemini CLI",
|
||||
"opencodeDesc": "OpenCode CLI"
|
||||
},
|
||||
"configDirectoryOverride": "Configuration Directory Override (Advanced)",
|
||||
"configDirectoryDescription": "When using Claude Code or Codex in environments like WSL, you can manually specify the configuration directory to the one in WSL to keep provider data consistent with the main environment.",
|
||||
"appConfigDir": "CC Switch Configuration Directory",
|
||||
@@ -310,7 +341,7 @@
|
||||
}
|
||||
},
|
||||
"apps": {
|
||||
"claude": "Claude Code",
|
||||
"claude": "Claude",
|
||||
"codex": "Codex",
|
||||
"gemini": "Gemini",
|
||||
"opencode": "OpenCode"
|
||||
@@ -427,6 +458,22 @@
|
||||
"testFailed": "Speed test failed: {{error}}",
|
||||
"status": "Status: {{code}}"
|
||||
},
|
||||
"providerAdvanced": {
|
||||
"testConfig": "Model Test Config",
|
||||
"useCustomConfig": "Use separate config",
|
||||
"testConfigDesc": "Configure separate model testing parameters for this provider. Uses global settings when disabled.",
|
||||
"testModel": "Test Model",
|
||||
"testModelPlaceholder": "Leave empty to use global config",
|
||||
"timeoutSecs": "Timeout (seconds)",
|
||||
"testPrompt": "Test Prompt",
|
||||
"degradedThreshold": "Degraded Threshold (ms)",
|
||||
"maxRetries": "Max Retries",
|
||||
"proxyConfig": "Proxy Config",
|
||||
"useCustomProxy": "Use separate proxy",
|
||||
"proxyConfigDesc": "Configure separate network proxy for this provider. Uses system proxy or global settings when disabled.",
|
||||
"proxyUsername": "Username (optional)",
|
||||
"proxyPassword": "Password (optional)"
|
||||
},
|
||||
"codexConfig": {
|
||||
"authJson": "auth.json (JSON) *",
|
||||
"authJsonPlaceholder": "{\n \"OPENAI_API_KEY\": \"sk-your-api-key-here\"\n}",
|
||||
@@ -1088,6 +1135,20 @@
|
||||
"circuitOpen": "Circuit Open",
|
||||
"consecutiveFailures": "{{count}} consecutive failures"
|
||||
},
|
||||
"failover": {
|
||||
"enabled": "{{app}} failover enabled",
|
||||
"disabled": "{{app}} failover disabled",
|
||||
"toggleFailed": "Operation failed: {{detail}}",
|
||||
"inQueue": "In queue",
|
||||
"addQueue": "Add",
|
||||
"priority": {
|
||||
"tooltip": "Failover priority {{priority}}"
|
||||
},
|
||||
"tooltip": {
|
||||
"enabled": "{{app}} failover enabled\nRequests follow queue priority (P1→P2→...)",
|
||||
"disabled": "Enable {{app}} failover\nSwitches to queue P1 immediately, then falls back on failures"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"panel": {
|
||||
"serviceAddress": "Service Address",
|
||||
@@ -1187,15 +1248,18 @@
|
||||
},
|
||||
"switchFailed": "Switch failed: {{error}}",
|
||||
"failover": {
|
||||
"proxyRequired": "Proxy service must be started to configure failover"
|
||||
"proxyRequired": "Proxy service must be started to configure failover",
|
||||
"autoSwitch": "Auto Failover",
|
||||
"autoSwitchDescription": "When enabled, switches to queue P1 immediately and automatically tries the next provider in the queue on failures"
|
||||
},
|
||||
"failoverQueue": {
|
||||
"title": "Failover Queue",
|
||||
"description": "Manage failover order for each app's providers",
|
||||
"info": "The current active provider always takes priority. When requests fail, the system will try other providers in queue order.",
|
||||
"info": "When auto failover is enabled, requests follow the queue priority order (P1 first). On failures, the system will try the next provider in the queue.",
|
||||
"selectProvider": "Select a provider to add to queue",
|
||||
"noAvailableProviders": "No providers available to add",
|
||||
"empty": "Failover queue is empty. Add providers to enable automatic failover.",
|
||||
"orderHint": "Queue order matches the provider list order on the Home page. Reorder providers on the Home page to change priority.",
|
||||
"dragHint": "Drag providers to adjust failover order. Lower numbers have higher priority.",
|
||||
"toggleEnabled": "Enable/Disable",
|
||||
"addSuccess": "Added to failover queue",
|
||||
|
||||
@@ -208,6 +208,29 @@
|
||||
"responseGroup": "レスポンス整流",
|
||||
"thinkingSignature": "Thinking 署名整流",
|
||||
"thinkingSignatureDescription": "Claude API の thinking 署名検証エラーを自動修正"
|
||||
},
|
||||
"logConfig": {
|
||||
"title": "ログ管理",
|
||||
"description": "ログ出力レベルを制御",
|
||||
"enabled": "ログを有効化",
|
||||
"enabledDescription": "マスタースイッチ、オフにするとすべてのログが無効になります",
|
||||
"level": "ログレベル",
|
||||
"levelDescription": "出力する最小ログレベルを設定",
|
||||
"levels": {
|
||||
"error": "エラー",
|
||||
"warn": "警告",
|
||||
"info": "情報",
|
||||
"debug": "デバッグ",
|
||||
"trace": "トレース"
|
||||
},
|
||||
"levelHint": "ログレベルの説明:",
|
||||
"levelDesc": {
|
||||
"error": "重大なエラーのみ",
|
||||
"warn": "エラー + 警告",
|
||||
"info": "一般的な操作情報(デフォルト)",
|
||||
"debug": "SSE ストリームとリクエスト/レスポンスを含む詳細情報",
|
||||
"trace": "すべてのログ、最も詳細"
|
||||
}
|
||||
}
|
||||
},
|
||||
"language": "言語",
|
||||
@@ -249,6 +272,14 @@
|
||||
"enableClaudePluginIntegrationDescription": "オンにすると VS Code の Claude Code 拡張のプロバイダーも同期します",
|
||||
"skipClaudeOnboarding": "Claude Code の初回確認をスキップ",
|
||||
"skipClaudeOnboardingDescription": "オンにすると Claude Code の初回インストール確認をスキップします",
|
||||
"appVisibility": {
|
||||
"title": "ホームページ表示",
|
||||
"description": "ホームページに表示するアプリを選択",
|
||||
"claudeDesc": "Anthropic Claude Code CLI",
|
||||
"codexDesc": "OpenAI Codex CLI",
|
||||
"geminiDesc": "Google Gemini CLI",
|
||||
"opencodeDesc": "OpenCode CLI"
|
||||
},
|
||||
"configDirectoryOverride": "設定ディレクトリの上書き(詳細)",
|
||||
"configDirectoryDescription": "WSL などで Claude Code や Codex を使う場合、ここで設定ディレクトリを WSL 側に合わせるとデータを揃えられます。",
|
||||
"appConfigDir": "CC Switch 設定ディレクトリ",
|
||||
@@ -310,7 +341,7 @@
|
||||
}
|
||||
},
|
||||
"apps": {
|
||||
"claude": "Claude Code",
|
||||
"claude": "Claude",
|
||||
"codex": "Codex",
|
||||
"gemini": "Gemini",
|
||||
"opencode": "OpenCode"
|
||||
@@ -427,6 +458,22 @@
|
||||
"testFailed": "速度テストに失敗しました: {{error}}",
|
||||
"status": "ステータス: {{code}}"
|
||||
},
|
||||
"providerAdvanced": {
|
||||
"testConfig": "モデルテスト設定",
|
||||
"useCustomConfig": "個別設定を使用",
|
||||
"testConfigDesc": "このプロバイダーに個別のモデルテストパラメータを設定します。無効の場合はグローバル設定を使用します。",
|
||||
"testModel": "テストモデル",
|
||||
"testModelPlaceholder": "空白の場合はグローバル設定を使用",
|
||||
"timeoutSecs": "タイムアウト(秒)",
|
||||
"testPrompt": "テストプロンプト",
|
||||
"degradedThreshold": "低下閾値(ミリ秒)",
|
||||
"maxRetries": "最大リトライ回数",
|
||||
"proxyConfig": "プロキシ設定",
|
||||
"useCustomProxy": "個別プロキシを使用",
|
||||
"proxyConfigDesc": "このプロバイダーに個別のネットワークプロキシを設定します。無効の場合はシステムプロキシまたはグローバル設定を使用します。",
|
||||
"proxyUsername": "ユーザー名(任意)",
|
||||
"proxyPassword": "パスワード(任意)"
|
||||
},
|
||||
"codexConfig": {
|
||||
"authJson": "auth.json (JSON) *",
|
||||
"authJsonPlaceholder": "{\n \"OPENAI_API_KEY\": \"sk-your-api-key-here\"\n}",
|
||||
@@ -1088,6 +1135,20 @@
|
||||
"circuitOpen": "サーキットオープン",
|
||||
"consecutiveFailures": "{{count}} 回連続失敗"
|
||||
},
|
||||
"failover": {
|
||||
"enabled": "{{app}} フェイルオーバーが有効になりました",
|
||||
"disabled": "{{app}} フェイルオーバーが無効になりました",
|
||||
"toggleFailed": "操作に失敗しました: {{detail}}",
|
||||
"inQueue": "キュー内",
|
||||
"addQueue": "追加",
|
||||
"priority": {
|
||||
"tooltip": "フェイルオーバー優先度 {{priority}}"
|
||||
},
|
||||
"tooltip": {
|
||||
"enabled": "{{app}} フェイルオーバーが有効\nキューの優先度(P1→P2→...)で使用します",
|
||||
"disabled": "{{app}} フェイルオーバーを有効にする\nキューの P1 に即時切替し、失敗時は次を順に試行します"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"panel": {
|
||||
"serviceAddress": "サービスアドレス",
|
||||
@@ -1182,15 +1243,18 @@
|
||||
},
|
||||
"switchFailed": "切り替えに失敗しました: {{error}}",
|
||||
"failover": {
|
||||
"proxyRequired": "フェイルオーバーを設定するには、プロキシサービスを先に起動する必要があります"
|
||||
"proxyRequired": "フェイルオーバーを設定するには、プロキシサービスを先に起動する必要があります",
|
||||
"autoSwitch": "自動フェイルオーバー",
|
||||
"autoSwitchDescription": "有効にするとキューの P1 に即時切り替え、リクエスト失敗時はキュー内の次のプロバイダーを自動で試行します"
|
||||
},
|
||||
"failoverQueue": {
|
||||
"title": "フェイルオーバーキュー",
|
||||
"description": "各アプリのプロバイダーのフェイルオーバー順序を管理します",
|
||||
"info": "現在アクティブなプロバイダーが常に優先されます。リクエストが失敗すると、システムはキュー順に他のプロバイダーを試行します。",
|
||||
"info": "自動フェイルオーバーを有効にすると、キューの優先度順(P1 優先)でプロバイダーを使用します。失敗時はキュー内の次のプロバイダーを順に試行します。",
|
||||
"selectProvider": "キューに追加するプロバイダーを選択",
|
||||
"noAvailableProviders": "追加できるプロバイダーがありません",
|
||||
"empty": "フェイルオーバーキューが空です。自動フェイルオーバーを有効にするにはプロバイダーを追加してください。",
|
||||
"orderHint": "キューの順序はホームのプロバイダー一覧の順序と一致します。ホームでドラッグして順序を変更できます。",
|
||||
"dragHint": "ドラッグでフェイルオーバー順序を調整します。番号が小さいほど優先度が高くなります。",
|
||||
"toggleEnabled": "有効/無効",
|
||||
"addSuccess": "フェイルオーバーキューに追加しました",
|
||||
|
||||
@@ -208,6 +208,29 @@
|
||||
"responseGroup": "响应整流",
|
||||
"thinkingSignature": "Thinking 签名整流",
|
||||
"thinkingSignatureDescription": "自动修复 Claude API 中因 thinking 签名校验失败导致的请求错误"
|
||||
},
|
||||
"logConfig": {
|
||||
"title": "日志管理",
|
||||
"description": "控制日志输出级别",
|
||||
"enabled": "启用日志",
|
||||
"enabledDescription": "总开关,关闭后所有日志将被禁用",
|
||||
"level": "日志级别",
|
||||
"levelDescription": "设置输出的最低日志级别",
|
||||
"levels": {
|
||||
"error": "错误",
|
||||
"warn": "警告",
|
||||
"info": "信息",
|
||||
"debug": "调试",
|
||||
"trace": "跟踪"
|
||||
},
|
||||
"levelHint": "日志级别说明:",
|
||||
"levelDesc": {
|
||||
"error": "仅严重错误",
|
||||
"warn": "错误 + 警告信息",
|
||||
"info": "一般操作信息(默认)",
|
||||
"debug": "详细信息,包含 SSE 流和请求/响应详情",
|
||||
"trace": "全部日志,最详细"
|
||||
}
|
||||
}
|
||||
},
|
||||
"language": "界面语言",
|
||||
@@ -249,6 +272,14 @@
|
||||
"enableClaudePluginIntegrationDescription": "开启后 Vscode Claude Code 插件的供应商将随本软件切换",
|
||||
"skipClaudeOnboarding": "跳过 Claude Code 初次安装确认",
|
||||
"skipClaudeOnboardingDescription": "开启后跳过 Claude Code 初次安装确认",
|
||||
"appVisibility": {
|
||||
"title": "主页面显示",
|
||||
"description": "选择在主页面显示的应用",
|
||||
"claudeDesc": "Anthropic Claude Code CLI",
|
||||
"codexDesc": "OpenAI Codex CLI",
|
||||
"geminiDesc": "Google Gemini CLI",
|
||||
"opencodeDesc": "OpenCode CLI"
|
||||
},
|
||||
"configDirectoryOverride": "配置目录覆盖(高级)",
|
||||
"configDirectoryDescription": "在 WSL 等环境使用 Claude Code 或 Codex 的时候,可手动指定为 WSL 里的配置目录,供应商数据与主环境保持一致。",
|
||||
"appConfigDir": "CC Switch 配置目录",
|
||||
@@ -310,7 +341,7 @@
|
||||
}
|
||||
},
|
||||
"apps": {
|
||||
"claude": "Claude Code",
|
||||
"claude": "Claude",
|
||||
"codex": "Codex",
|
||||
"gemini": "Gemini",
|
||||
"opencode": "OpenCode"
|
||||
@@ -427,6 +458,22 @@
|
||||
"testFailed": "测速失败: {{error}}",
|
||||
"status": "状态码:{{code}}"
|
||||
},
|
||||
"providerAdvanced": {
|
||||
"testConfig": "模型测试配置",
|
||||
"useCustomConfig": "使用单独配置",
|
||||
"testConfigDesc": "为此供应商配置单独的模型测试参数,不启用时使用全局配置。",
|
||||
"testModel": "测试模型",
|
||||
"testModelPlaceholder": "留空使用全局配置",
|
||||
"timeoutSecs": "超时时间(秒)",
|
||||
"testPrompt": "测试提示词",
|
||||
"degradedThreshold": "降级阈值(毫秒)",
|
||||
"maxRetries": "最大重试次数",
|
||||
"proxyConfig": "代理配置",
|
||||
"useCustomProxy": "使用单独代理",
|
||||
"proxyConfigDesc": "为此供应商配置单独的网络代理,不启用时使用系统代理或全局设置。",
|
||||
"proxyUsername": "用户名(可选)",
|
||||
"proxyPassword": "密码(可选)"
|
||||
},
|
||||
"codexConfig": {
|
||||
"authJson": "auth.json (JSON) *",
|
||||
"authJsonPlaceholder": "{\n \"OPENAI_API_KEY\": \"sk-your-api-key-here\"\n}",
|
||||
@@ -1088,6 +1135,20 @@
|
||||
"circuitOpen": "熔断",
|
||||
"consecutiveFailures": "连续失败 {{count}} 次"
|
||||
},
|
||||
"failover": {
|
||||
"enabled": "{{app}} 故障转移已启用",
|
||||
"disabled": "{{app}} 故障转移已关闭",
|
||||
"toggleFailed": "操作失败: {{detail}}",
|
||||
"inQueue": "已加入",
|
||||
"addQueue": "加入",
|
||||
"priority": {
|
||||
"tooltip": "故障转移优先级 {{priority}}"
|
||||
},
|
||||
"tooltip": {
|
||||
"enabled": "{{app}} 故障转移已启用\n按队列优先级(P1→P2→...)选择供应商",
|
||||
"disabled": "启用 {{app}} 故障转移\n将立即切换到队列 P1,并在失败时自动切换到下一个"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"panel": {
|
||||
"serviceAddress": "服务地址",
|
||||
@@ -1187,15 +1248,18 @@
|
||||
},
|
||||
"switchFailed": "切换失败: {{error}}",
|
||||
"failover": {
|
||||
"proxyRequired": "需要先启动代理服务才能配置故障转移"
|
||||
"proxyRequired": "需要先启动代理服务才能配置故障转移",
|
||||
"autoSwitch": "自动故障转移",
|
||||
"autoSwitchDescription": "开启后将立即切换到队列 P1,并在请求失败时自动切换到队列中的下一个供应商"
|
||||
},
|
||||
"failoverQueue": {
|
||||
"title": "故障转移队列",
|
||||
"description": "管理各应用的供应商故障转移顺序",
|
||||
"info": "当前激活的供应商始终优先。当请求失败时,系统会按队列顺序依次尝试其他供应商。",
|
||||
"info": "启用自动故障转移后,将按队列优先级选择供应商(P1 优先)。当请求失败时,系统会按队列顺序依次尝试下一个供应商。",
|
||||
"selectProvider": "选择供应商添加到队列",
|
||||
"noAvailableProviders": "没有可添加的供应商",
|
||||
"empty": "故障转移队列为空。添加供应商以启用自动故障转移。",
|
||||
"orderHint": "队列顺序与首页供应商列表顺序一致,可在首页拖拽调整顺序。",
|
||||
"dragHint": "拖拽供应商可调整故障转移顺序,序号越小优先级越高。",
|
||||
"toggleEnabled": "启用/禁用",
|
||||
"addSuccess": "已添加到故障转移队列",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>KwaiKAT</title><path d="M20.42 19.311h3.418V1l-6.781 4.177-6.778-4.111.026 7.868h3.418l-.026-2.222 3.42 2.035 3.303-2.035v12.6z"></path><path d="M3.064 10.734c2.784-2.07 6.942-2.394 9.941.907l.01.01.01.013 9.16 12.24h-3.84l-7.69-10.217c-1.63-1.737-3.891-1.689-5.515-.638-1.624 1.05-2.563 3.073-1.548 5.28 1.494 3.246 6.152 3.275 7.725.108l.032-.064 2.02 2.629c-2.98 3.968-9.329 3.926-12.165-.552-2.395-3.78-.926-7.645 1.86-9.716z"></path></svg>
|
||||
|
After Width: | Height: | Size: 608 B |
@@ -50,10 +50,14 @@ export const icons: Record<string, string> = {
|
||||
zeroone: `<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>01.AI</title><path d="M5.246 12c0 .837-.086 1.554-.257 2.151-.172.598-.45 1.055-.837 1.373-.386.317-.898.476-1.534.476-.901 0-1.563-.353-1.985-1.059C.211 14.235 0 13.255 0 12c0-.837.086-1.554.257-2.151.172-.598.45-1.055.832-1.373C1.472 8.16 1.981 8 2.618 8c.894 0 1.555.351 1.985 1.053.429.702.643 1.685.643 2.947zm-3.883 0c0 .956.09 1.668.273 2.134.183.467.51.7.982.7.465 0 .792-.23.981-.694.19-.463.285-1.176.285-2.14 0-.956-.095-1.668-.285-2.134-.19-.467-.516-.7-.981-.7-.472 0-.8.233-.982.7-.182.466-.273 1.178-.273 2.134zm8.52 3.771H8.517l.011-6.295-1.823.324V8.571l2.04-.457h1.136v7.657zm2.497-1.6h.543c.3 0 .543.256.543.572v.571a.558.558 0 01-.543.572h-.543a.558.558 0 01-.543-.572v-.571c0-.316.243-.572.543-.572zm10.317-6.057H24v7.772h-1.303V8.114zm-3.692 0l2.606 7.772h-1.303l-.69-2.058h-3.073l-.69 2.058h-1.303l2.606-7.772h1.847zm.191 4.457l-1.115-3.323-1.114 3.323h2.23z"></path></svg>`,
|
||||
zhipu: `<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Zhipu</title><path d="M11.991 23.503a.24.24 0 00-.244.248.24.24 0 00.244.249.24.24 0 00.245-.249.24.24 0 00-.22-.247l-.025-.001zM9.671 5.365a1.697 1.697 0 011.099 2.132l-.071.172-.016.04-.018.054c-.07.16-.104.32-.104.498-.035.71.47 1.279 1.186 1.314h.366c1.309.053 2.338 1.173 2.286 2.523-.052 1.332-1.152 2.38-2.478 2.327h-.174c-.715.018-1.274.64-1.239 1.368 0 .124.018.23.053.337.209.373.54.658.96.8.75.23 1.517-.125 1.9-.782l.018-.035c.402-.64 1.17-.96 1.92-.711.854.284 1.378 1.226 1.099 2.167a1.661 1.661 0 01-2.077 1.102 1.711 1.711 0 01-.907-.711l-.017-.035c-.2-.323-.463-.58-.851-.711l-.056-.018a1.646 1.646 0 00-1.954.746 1.66 1.66 0 01-1.065.764 1.677 1.677 0 01-1.989-1.279c-.209-.906.332-1.83 1.257-2.043a1.51 1.51 0 01.296-.035h.018c.68-.071 1.151-.622 1.116-1.333a1.307 1.307 0 00-.227-.693 2.515 2.515 0 01-.366-1.403 2.39 2.39 0 01.366-1.208c.14-.195.21-.444.227-.693.018-.71-.506-1.261-1.186-1.332l-.07-.018a1.43 1.43 0 01-.299-.07l-.05-.019a1.7 1.7 0 01-1.047-2.114 1.68 1.68 0 012.094-1.101zm-5.575 10.11c.26-.264.639-.367.994-.27.355.096.633.379.728.74.095.362-.007.748-.267 1.013-.402.41-1.053.41-1.455 0a1.062 1.062 0 010-1.482zm14.845-.294c.359-.09.738.024.992.297.254.274.344.665.237 1.025-.107.36-.396.634-.756.718-.551.128-1.1-.22-1.23-.781a1.05 1.05 0 01.757-1.26zm-.064-4.39c.314.32.49.753.49 1.206 0 .452-.176.886-.49 1.206-.315.32-.74.5-1.185.5-.444 0-.87-.18-1.184-.5a1.727 1.727 0 010-2.412 1.654 1.654 0 012.369 0zm-11.243.163c.364.484.447 1.128.218 1.691a1.665 1.665 0 01-2.188.923c-.855-.36-1.26-1.358-.907-2.228a1.68 1.68 0 011.33-1.038c.593-.08 1.183.169 1.547.652zm11.545-4.221c.368 0 .708.2.892.524.184.324.184.724 0 1.048a1.026 1.026 0 01-.892.524c-.568 0-1.03-.47-1.03-1.048 0-.579.462-1.048 1.03-1.048zm-14.358 0c.368 0 .707.2.891.524.184.324.184.724 0 1.048a1.026 1.026 0 01-.891.524c-.569 0-1.03-.47-1.03-1.048 0-.579.461-1.048 1.03-1.048zm10.031-1.475c.925 0 1.675.764 1.675 1.706s-.75 1.705-1.675 1.705-1.674-.763-1.674-1.705c0-.942.75-1.706 1.674-1.706zm-2.626-.684c.362-.082.653-.356.761-.718a1.062 1.062 0 00-.238-1.028 1.017 1.017 0 00-.996-.294c-.547.14-.881.7-.752 1.257.13.558.675.907 1.225.783zm0 16.876c.359-.087.644-.36.75-.72a1.062 1.062 0 00-.237-1.019 1.018 1.018 0 00-.985-.301 1.037 1.037 0 00-.762.717c-.108.361-.017.754.239 1.028.245.263.606.377.953.305l.043-.01zM17.19 3.5a.631.631 0 00.628-.64c0-.355-.279-.64-.628-.64a.631.631 0 00-.628.64c0 .355.28.64.628.64zm-10.38 0a.631.631 0 00.628-.64c0-.355-.28-.64-.628-.64a.631.631 0 00-.628.64c0 .355.279.64.628.64zm-5.182 7.852a.631.631 0 00-.628.64c0 .354.28.639.628.639a.63.63 0 00.627-.606l.001-.034a.62.62 0 00-.628-.64zm5.182 9.13a.631.631 0 00-.628.64c0 .355.279.64.628.64a.631.631 0 00.628-.64c0-.355-.28-.64-.628-.64zm10.38.018a.631.631 0 00-.628.64c0 .355.28.64.628.64a.631.631 0 00.628-.64c0-.355-.279-.64-.628-.64zm5.182-9.148a.631.631 0 00-.628.64c0 .354.279.639.628.639a.631.631 0 00.628-.64c0-.355-.28-.64-.628-.64zm-.384-4.992a.24.24 0 00.244-.249.24.24 0 00-.244-.249.24.24 0 00-.244.249c0 .142.122.249.244.249zM11.991.497a.24.24 0 00.245-.248A.24.24 0 0011.99 0a.24.24 0 00-.244.249c0 .133.108.236.223.247l.021.001zM2.011 6.36a.24.24 0 00.245-.249.24.24 0 00-.244-.249.24.24 0 00-.244.249.24.24 0 00.244.249zm0 11.263a.24.24 0 00-.243.248.24.24 0 00.244.249.24.24 0 00.244-.249.252.252 0 00-.244-.248zm19.995-.018a.24.24 0 00-.245.248.24.24 0 00.245.25.24.24 0 00.244-.25.252.252 0 00-.244-.248z" fill="#3859FF" fill-rule="nonzero"></path></svg>`,
|
||||
openrouter: `<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>OpenRouter</title><path d="M16.804 1.957l7.22 4.105v.087L16.73 10.21l.017-2.117-.821-.03c-1.059-.028-1.611.002-2.268.11-1.064.175-2.038.577-3.147 1.352L8.345 11.03c-.284.195-.495.336-.68.455l-.515.322-.397.234.385.23.53.338c.476.314 1.17.796 2.701 1.866 1.11.775 2.083 1.177 3.147 1.352l.3.045c.694.091 1.375.094 2.825.033l.022-2.159 7.22 4.105v.087L16.589 22l.014-1.862-.635.022c-1.386.042-2.137.002-3.138-.162-1.694-.28-3.26-.926-4.881-2.059l-2.158-1.5a21.997 21.997 0 00-.755-.498l-.467-.28a55.927 55.927 0 00-.76-.43C2.908 14.73.563 14.116 0 14.116V9.888l.14.004c.564-.007 2.91-.622 3.809-1.124l1.016-.58.438-.274c.428-.28 1.072-.726 2.686-1.853 1.621-1.133 3.186-1.78 4.881-2.059 1.152-.19 1.974-.213 3.814-.138l.02-1.907z"></path></svg>`,
|
||||
rc: `<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" style="flex:none;line-height:1" viewBox="0 0 128 128"><title>RightCode</title><path fill="#EA6C2C" fill-rule="evenodd" d="M 67.00 124.35 L 65.00 124.65 L 63.00 124.31 L 60.87 122.00 L 60.51 120.00 L 60.62 119.00 L 61.63 117.00 L 63.64 115.00 L 63.65 23.00 L 63.40 22.00 L 60.71 20.00 L 59.73 18.00 L 59.66 16.00 L 61.18 13.00 L 63.00 11.70 L 65.00 11.36 L 67.00 11.68 L 69.00 13.07 L 70.24 15.00 L 70.43 17.00 L 69.35 20.00 L 66.75 22.00 L 66.53 23.00 L 66.56 115.00 L 69.38 118.00 L 69.69 120.00 L 69.38 122.00 L 67.00 124.35 Z M 65.38 19.00 L 66.99 18.00 L 67.30 16.00 L 66.00 14.66 L 64.00 14.69 L 62.79 16.00 L 62.66 17.00 L 64.00 18.73 L 65.38 19.00 Z M 72.00 53.03 L 71.70 52.00 L 71.56 35.00 L 70.00 33.71 L 68.79 32.00 L 68.52 30.00 L 69.00 28.15 L 70.00 26.71 L 72.00 25.59 L 74.00 25.45 L 75.00 25.70 L 76.75 27.00 L 77.50 28.00 L 78.15 30.00 L 77.18 33.00 L 74.81 35.00 L 74.60 50.00 L 72.00 53.03 Z M 74.12 32.00 L 75.11 31.00 L 75.31 30.00 L 74.77 29.00 L 74.00 28.40 L 72.00 28.65 L 71.35 30.00 L 71.45 31.00 L 73.00 32.26 L 74.12 32.00 Z M 58.00 52.97 L 55.68 50.00 L 55.65 40.00 L 52.89 37.00 L 52.36 35.00 L 52.62 33.00 L 54.00 31.03 L 57.00 29.77 L 60.00 30.84 L 61.03 32.00 L 61.64 34.00 L 61.21 37.00 L 58.49 40.00 L 58.47 52.00 L 58.00 52.97 Z M 58.43 36.00 L 59.06 35.00 L 58.91 34.00 L 58.00 32.96 L 57.00 32.66 L 56.00 33.10 L 55.29 34.00 L 55.19 35.00 L 55.64 36.00 L 57.00 36.59 L 58.43 36.00 Z M 57.00 89.45 L 46.00 89.35 L 37.24 77.00 L 36.00 75.99 L 35.00 75.93 L 28.00 75.93 L 27.12 77.00 L 27.14 88.00 L 26.80 89.00 L 26.00 89.36 L 18.00 89.36 L 16.89 89.00 L 16.66 48.00 L 17.00 46.90 L 44.00 46.73 L 48.00 47.67 L 50.00 48.57 L 53.23 51.00 L 55.44 54.00 L 56.34 56.00 L 57.07 59.00 L 56.95 64.00 L 56.15 67.00 L 54.34 70.00 L 52.00 72.26 L 48.83 74.00 L 48.06 75.00 L 57.06 88.00 L 57.53 89.00 L 57.00 89.45 Z M 110.00 89.13 L 109.00 89.65 L 90.00 89.61 L 85.00 89.18 L 80.00 87.40 L 77.00 85.39 L 74.64 83.00 L 72.64 80.00 L 70.76 75.00 L 70.20 70.00 L 70.36 65.00 L 70.81 62.00 L 72.61 57.00 L 74.49 54.00 L 77.36 51.00 L 81.00 48.62 L 84.00 47.54 L 88.00 46.77 L 109.00 46.64 L 109.79 47.00 L 110.13 48.00 L 110.00 55.15 L 109.00 55.68 L 91.00 55.74 L 87.00 56.77 L 84.11 59.00 L 82.59 61.00 L 81.36 64.00 L 80.64 69.00 L 81.62 74.00 L 82.58 76.00 L 85.00 78.66 L 88.00 80.22 L 92.00 80.64 L 109.00 80.64 L 109.80 81.00 L 110.13 82.00 L 110.00 89.13 Z M 43.29 67.00 L 44.89 66.00 L 46.00 64.70 L 46.86 62.00 L 46.50 59.00 L 45.00 56.77 L 43.00 55.56 L 40.00 55.18 L 28.00 55.17 L 27.12 56.00 L 27.16 67.00 L 28.00 67.65 L 40.00 67.63 L 43.29 67.00 Z M 74.00 105.20 L 72.00 105.09 L 70.13 104.00 L 68.71 102.00 L 68.54 101.00 L 68.69 99.00 L 70.00 97.06 L 71.42 96.00 L 71.71 95.00 L 71.70 86.00 L 72.00 84.36 L 74.56 87.00 L 74.64 95.00 L 75.00 95.97 L 77.39 98.00 L 78.12 100.00 L 77.32 103.00 L 76.00 104.37 L 74.00 105.20 Z M 59.00 111.05 L 57.00 111.40 L 55.00 111.01 L 52.89 109.00 L 52.36 107.00 L 53.00 104.45 L 55.51 102.00 L 55.65 93.00 L 55.88 92.00 L 57.00 91.64 L 58.28 92.00 L 58.49 93.00 L 58.63 102.00 L 61.00 104.14 L 61.65 106.00 L 61.26 109.00 L 59.00 111.05 Z M 74.39 102.00 L 75.23 101.00 L 75.00 99.65 L 74.00 98.65 L 73.00 98.54 L 72.06 99.00 L 71.39 100.00 L 71.39 101.00 L 72.00 101.96 L 73.00 102.38 L 74.39 102.00 Z M 58.51 108.00 L 59.09 107.00 L 58.83 106.00 L 58.00 105.18 L 57.00 104.85 L 55.33 106.00 L 55.18 107.00 L 56.00 108.39 L 57.00 108.65 L 58.51 108.00 Z M 65.09 122.00 L 66.75 121.00 L 67.14 120.00 L 66.00 118.36 L 65.00 118.16 L 63.54 119.00 L 63.28 120.00 L 63.47 121.00 L 65.09 122.00 Z"/></svg>`,
|
||||
longcat: `<svg fill="currentColor" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>LongCat</title><path clip-rule="evenodd" d="M.507 19.883a.507.507 0 01-.489-.642L4.29 3.745a1.013 1.013 0 011.533-.578l5.622 3.687a1.013 1.013 0 001.11 0L18.2 3.165a1.013 1.013 0 011.532.58l4.25 15.497a.506.506 0 01-.49.64H18.07a6.297 6.297 0 001.53-4.115v-.177a6.09 6.09 0 00-1.513-4.017l-.697-3.495a.438.438 0 00-.694-.266L14.07 9.781a.748.748 0 01-.654.121 5.156 5.156 0 00-2.833 0 .746.746 0 01-.653-.121L7.302 7.81a.435.435 0 00-.688.269l-.675 3.652a5.36 5.36 0 00-1.539 3.76v.333c0 1.474.527 2.9 1.488 4.02l.032.038H.507z" fill="#29E154" fill-rule="evenodd"></path><path d="M9.213 16.843h1.52v-3.546h-1.29l-.23 3.546zm5.573 0h-1.52v-3.546h1.29l.23 3.546z"></path></svg>`,
|
||||
modelscope: `<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>ModelScope</title><path d="M0 7.967h2.667v2.667H0zM8 10.633h2.667V13.3H8z" fill="#36CED0"></path><path d="M0 10.633h2.667V13.3H0zM2.667 13.3h2.666v2.667H8v2.666H2.667V13.3zM2.667 5.3H8v2.667H5.333v2.666H2.667V5.3zM10.667 13.3h2.667v2.667h-2.667z" fill="#624AFF"></path><path d="M24 7.967h-2.667v2.667H24zM16 10.633h-2.667V13.3H16z" fill="#36CED0"></path><path d="M24 10.633h-2.667V13.3H24zM21.333 13.3h-2.666v2.667H16v2.666h5.333V13.3zM21.333 5.3H16v2.667h2.667v2.666h2.666V5.3z" fill="#624AFF"></path></svg>`,
|
||||
aihubmix: `<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>AiHubMix</title><path d="M12 24c6.627 0 12-5.373 12-12S18.627 0 12 0 0 5.373 0 12s5.373 12 12 12z" fill="#006FFB"></path><path clip-rule="evenodd" d="M11.24 8.393c.095-.644.302-1.47.624-2.48L12 5.496l.136.417c.322 1.01.53 1.836.624 2.48.071.472.071 1.072 0 1.8-.072.731-.072 1.336 0 1.814.106.7.426 1.281.96 1.744a2.795 2.795 0 001.89.708 2.78 2.78 0 002.034-.84c.56-.559.842-1.234.848-2.024.003-.7.075-1.472.216-2.316.069-.422.14-.775.21-1.06l.095-.384.168.356a7.862 7.862 0 01.76 3.244v.16a7.84 7.84 0 01-.624 3.089 7.952 7.952 0 01-4.228 4.228 7.841 7.841 0 01-3.089.623 7.84 7.84 0 01-3.089-.623 7.952 7.952 0 01-4.228-4.228 7.84 7.84 0 01-.623-3.09v-.159a7.862 7.862 0 01.759-3.244l.169-.356.093.385c.072.284.143.637.211 1.059.141.844.213 1.616.216 2.316.006.79.29 1.465.848 2.024.563.56 1.241.84 2.035.84.715 0 1.345-.236 1.889-.708a2.79 2.79 0 00.96-1.744c.073-.478.073-1.083 0-1.814-.071-.728-.071-1.328 0-1.8zm.76 9.694c1.097 0 2.125-.26 3.085-.778a6.379 6.379 0 001.77-1.399c.063-.07-.01-.178-.101-.153-.37.1-.75.15-1.144.15a4.236 4.236 0 01-2.18-.59 4.253 4.253 0 01-1.35-1.233.099.099 0 00-.16 0 4.253 4.253 0 01-1.35 1.232 4.236 4.236 0 01-2.18.591c-.393 0-.774-.05-1.143-.15-.091-.025-.165.083-.102.153a6.38 6.38 0 001.77 1.399c.96.518 1.988.778 3.085.778z" fill="#fff" fill-rule="evenodd"></path></svg>`,
|
||||
opencode: `<svg height="1em" width="1em" style="flex:none;line-height:1" viewBox="0 0 240 300" xmlns="http://www.w3.org/2000/svg"><title>OpenCode</title><g clip-path="url(#clip0_1401_86274)"><mask id="mask0_1401_86274" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="0" y="0" width="240" height="300"><path d="M240 0H0V300H240V0Z" fill="white"/></mask><g mask="url(#mask0_1401_86274)"><path d="M180 240H60V120H180V240Z" fill="#CFCECD"/><path d="M180 60H60V240H180V60ZM240 300H0V0H240V300Z" fill="#211E1E"/></g></g><defs><clipPath id="clip0_1401_86274"><rect width="240" height="300" fill="white"/></clipPath></defs></svg>`,
|
||||
siliconflow: `<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>SiliconCloud</title><path clip-rule="evenodd" d="M22.956 6.521H12.522c-.577 0-1.044.468-1.044 1.044v3.13c0 .577-.466 1.044-1.043 1.044H1.044c-.577 0-1.044.467-1.044 1.044v4.174C0 17.533.467 18 1.044 18h10.434c.577 0 1.044-.467 1.044-1.043v-3.13c0-.578.466-1.044 1.043-1.044h9.391c.577 0 1.044-.467 1.044-1.044V7.565c0-.576-.467-1.044-1.044-1.044z" fill="#6E29F6" fill-rule="evenodd"></path></svg>`,
|
||||
catcoder: `<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>KwaiKAT</title><path d="M20.42 19.311h3.418V1l-6.781 4.177-6.778-4.111.026 7.868h3.418l-.026-2.222 3.42 2.035 3.303-2.035v12.6z"></path><path d="M3.064 10.734c2.784-2.07 6.942-2.394 9.941.907l.01.01.01.013 9.16 12.24h-3.84l-7.69-10.217c-1.63-1.737-3.891-1.689-5.515-.638-1.624 1.05-2.563 3.073-1.548 5.28 1.494 3.246 6.152 3.275 7.725.108l.032-.064 2.02 2.629c-2.98 3.968-9.329 3.926-12.165-.552-2.395-3.78-.926-7.645 1.86-9.716z"></path></svg>`,
|
||||
mcp: `<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>ModelContextProtocol</title><path d="M15.688 2.343a2.588 2.588 0 00-3.61 0l-9.626 9.44a.863.863 0 01-1.203 0 .823.823 0 010-1.18l9.626-9.44a4.313 4.313 0 016.016 0 4.116 4.116 0 011.204 3.54 4.3 4.3 0 013.609 1.18l.05.05a4.115 4.115 0 010 5.9l-8.706 8.537a.274.274 0 000 .393l1.788 1.754a.823.823 0 010 1.18.863.863 0 01-1.203 0l-1.788-1.753a1.92 1.92 0 010-2.754l8.706-8.538a2.47 2.47 0 000-3.54l-.05-.049a2.588 2.588 0 00-3.607-.003l-7.172 7.034-.002.002-.098.097a.863.863 0 01-1.204 0 .823.823 0 010-1.18l7.273-7.133a2.47 2.47 0 00-.003-3.537z"></path><path d="M14.485 4.703a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a4.115 4.115 0 000 5.9 4.314 4.314 0 006.016 0l7.12-6.982a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a2.588 2.588 0 01-3.61 0 2.47 2.47 0 010-3.54l7.12-6.982z"></path></svg>`,
|
||||
};
|
||||
|
||||
export const iconList = Object.keys(icons);
|
||||
@@ -65,3 +69,5 @@ export function getIcon(name: string): string {
|
||||
export function hasIcon(name: string): boolean {
|
||||
return name.toLowerCase() in icons;
|
||||
}
|
||||
|
||||
export { getIconMetadata } from "./metadata";
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>ModelContextProtocol</title><path d="M15.688 2.343a2.588 2.588 0 00-3.61 0l-9.626 9.44a.863.863 0 01-1.203 0 .823.823 0 010-1.18l9.626-9.44a4.313 4.313 0 016.016 0 4.116 4.116 0 011.204 3.54 4.3 4.3 0 013.609 1.18l.05.05a4.115 4.115 0 010 5.9l-8.706 8.537a.274.274 0 000 .393l1.788 1.754a.823.823 0 010 1.18.863.863 0 01-1.203 0l-1.788-1.753a1.92 1.92 0 010-2.754l8.706-8.538a2.47 2.47 0 000-3.54l-.05-.049a2.588 2.588 0 00-3.607-.003l-7.172 7.034-.002.002-.098.097a.863.863 0 01-1.204 0 .823.823 0 010-1.18l7.273-7.133a2.47 2.47 0 00-.003-3.537z"></path><path d="M14.485 4.703a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a4.115 4.115 0 000 5.9 4.314 4.314 0 006.016 0l7.12-6.982a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a2.588 2.588 0 01-3.61 0 2.47 2.47 0 010-3.54l7.12-6.982z"></path></svg>
|
||||
|
After Width: | Height: | Size: 978 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128"><path fill="#EA6C2C" fill-rule="evenodd" d="M 67.00 124.35 L 65.00 124.65 L 63.00 124.31 L 60.87 122.00 L 60.51 120.00 L 60.62 119.00 L 61.63 117.00 L 63.64 115.00 L 63.65 23.00 L 63.40 22.00 L 60.71 20.00 L 59.73 18.00 L 59.66 16.00 L 61.18 13.00 L 63.00 11.70 L 65.00 11.36 L 67.00 11.68 L 69.00 13.07 L 70.24 15.00 L 70.43 17.00 L 69.35 20.00 L 66.75 22.00 L 66.53 23.00 L 66.56 115.00 L 69.38 118.00 L 69.69 120.00 L 69.38 122.00 L 67.00 124.35 Z M 65.38 19.00 L 66.99 18.00 L 67.30 16.00 L 66.00 14.66 L 64.00 14.69 L 62.79 16.00 L 62.66 17.00 L 64.00 18.73 L 65.38 19.00 Z M 72.00 53.03 L 71.70 52.00 L 71.56 35.00 L 70.00 33.71 L 68.79 32.00 L 68.52 30.00 L 69.00 28.15 L 70.00 26.71 L 72.00 25.59 L 74.00 25.45 L 75.00 25.70 L 76.75 27.00 L 77.50 28.00 L 78.15 30.00 L 77.18 33.00 L 74.81 35.00 L 74.60 50.00 L 72.00 53.03 Z M 74.12 32.00 L 75.11 31.00 L 75.31 30.00 L 74.77 29.00 L 74.00 28.40 L 72.00 28.65 L 71.35 30.00 L 71.45 31.00 L 73.00 32.26 L 74.12 32.00 Z M 58.00 52.97 L 55.68 50.00 L 55.65 40.00 L 52.89 37.00 L 52.36 35.00 L 52.62 33.00 L 54.00 31.03 L 57.00 29.77 L 60.00 30.84 L 61.03 32.00 L 61.64 34.00 L 61.21 37.00 L 58.49 40.00 L 58.47 52.00 L 58.00 52.97 Z M 58.43 36.00 L 59.06 35.00 L 58.91 34.00 L 58.00 32.96 L 57.00 32.66 L 56.00 33.10 L 55.29 34.00 L 55.19 35.00 L 55.64 36.00 L 57.00 36.59 L 58.43 36.00 Z M 57.00 89.45 L 46.00 89.35 L 37.24 77.00 L 36.00 75.99 L 35.00 75.93 L 28.00 75.93 L 27.12 77.00 L 27.14 88.00 L 26.80 89.00 L 26.00 89.36 L 18.00 89.36 L 16.89 89.00 L 16.66 48.00 L 17.00 46.90 L 44.00 46.73 L 48.00 47.67 L 50.00 48.57 L 53.23 51.00 L 55.44 54.00 L 56.34 56.00 L 57.07 59.00 L 56.95 64.00 L 56.15 67.00 L 54.34 70.00 L 52.00 72.26 L 48.83 74.00 L 48.06 75.00 L 57.06 88.00 L 57.53 89.00 L 57.00 89.45 Z M 110.00 89.13 L 109.00 89.65 L 90.00 89.61 L 85.00 89.18 L 80.00 87.40 L 77.00 85.39 L 74.64 83.00 L 72.64 80.00 L 70.76 75.00 L 70.20 70.00 L 70.36 65.00 L 70.81 62.00 L 72.61 57.00 L 74.49 54.00 L 77.36 51.00 L 81.00 48.62 L 84.00 47.54 L 88.00 46.77 L 109.00 46.64 L 109.79 47.00 L 110.13 48.00 L 110.00 55.15 L 109.00 55.68 L 91.00 55.74 L 87.00 56.77 L 84.11 59.00 L 82.59 61.00 L 81.36 64.00 L 80.64 69.00 L 81.62 74.00 L 82.58 76.00 L 85.00 78.66 L 88.00 80.22 L 92.00 80.64 L 109.00 80.64 L 109.80 81.00 L 110.13 82.00 L 110.00 89.13 Z M 43.29 67.00 L 44.89 66.00 L 46.00 64.70 L 46.86 62.00 L 46.50 59.00 L 45.00 56.77 L 43.00 55.56 L 40.00 55.18 L 28.00 55.17 L 27.12 56.00 L 27.16 67.00 L 28.00 67.65 L 40.00 67.63 L 43.29 67.00 Z M 74.00 105.20 L 72.00 105.09 L 70.13 104.00 L 68.71 102.00 L 68.54 101.00 L 68.69 99.00 L 70.00 97.06 L 71.42 96.00 L 71.71 95.00 L 71.70 86.00 L 72.00 84.36 L 74.56 87.00 L 74.64 95.00 L 75.00 95.97 L 77.39 98.00 L 78.12 100.00 L 77.32 103.00 L 76.00 104.37 L 74.00 105.20 Z M 59.00 111.05 L 57.00 111.40 L 55.00 111.01 L 52.89 109.00 L 52.36 107.00 L 53.00 104.45 L 55.51 102.00 L 55.65 93.00 L 55.88 92.00 L 57.00 91.64 L 58.28 92.00 L 58.49 93.00 L 58.63 102.00 L 61.00 104.14 L 61.65 106.00 L 61.26 109.00 L 59.00 111.05 Z M 74.39 102.00 L 75.23 101.00 L 75.00 99.65 L 74.00 98.65 L 73.00 98.54 L 72.06 99.00 L 71.39 100.00 L 71.39 101.00 L 72.00 101.96 L 73.00 102.38 L 74.39 102.00 Z M 58.51 108.00 L 59.09 107.00 L 58.83 106.00 L 58.00 105.18 L 57.00 104.85 L 55.33 106.00 L 55.18 107.00 L 56.00 108.39 L 57.00 108.65 L 58.51 108.00 Z M 65.09 122.00 L 66.75 121.00 L 67.14 120.00 L 66.00 118.36 L 65.00 118.16 L 63.54 119.00 L 63.28 120.00 L 63.47 121.00 L 65.09 122.00 Z"/></svg>
|
||||
|
After Width: | Height: | Size: 3.5 KiB |
@@ -0,0 +1 @@
|
||||
<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>SiliconCloud</title><path clip-rule="evenodd" d="M22.956 6.521H12.522c-.577 0-1.044.468-1.044 1.044v3.13c0 .577-.466 1.044-1.043 1.044H1.044c-.577 0-1.044.467-1.044 1.044v4.174C0 17.533.467 18 1.044 18h10.434c.577 0 1.044-.467 1.044-1.043v-3.13c0-.578.466-1.044 1.043-1.044h9.391c.577 0 1.044-.467 1.044-1.044V7.565c0-.576-.467-1.044-1.044-1.044z" fill="#6E29F6" fill-rule="evenodd"></path></svg>
|
||||
|
After Width: | Height: | Size: 520 B |
@@ -142,9 +142,22 @@ export const settingsApi = {
|
||||
async setRectifierConfig(config: RectifierConfig): Promise<boolean> {
|
||||
return await invoke("set_rectifier_config", { config });
|
||||
},
|
||||
|
||||
async getLogConfig(): Promise<LogConfig> {
|
||||
return await invoke("get_log_config");
|
||||
},
|
||||
|
||||
async setLogConfig(config: LogConfig): Promise<boolean> {
|
||||
return await invoke("set_log_config", { config });
|
||||
},
|
||||
};
|
||||
|
||||
export interface RectifierConfig {
|
||||
enabled: boolean;
|
||||
requestThinkingSignature: boolean;
|
||||
}
|
||||
|
||||
export interface LogConfig {
|
||||
enabled: boolean;
|
||||
level: "error" | "warn" | "info" | "debug" | "trace";
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { failoverApi } from "@/lib/api/failover";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { extractErrorMessage } from "@/utils/errorUtils";
|
||||
|
||||
// ========== 熔断器 Hooks ==========
|
||||
|
||||
@@ -197,6 +200,7 @@ export function useAutoFailoverEnabled(appType: string) {
|
||||
*/
|
||||
export function useSetAutoFailoverEnabled() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ appType, enabled }: { appType: string; enabled: boolean }) =>
|
||||
@@ -217,14 +221,46 @@ export function useSetAutoFailoverEnabled() {
|
||||
return { previousValue, appType };
|
||||
},
|
||||
|
||||
onSuccess: (_data, variables) => {
|
||||
const appLabel =
|
||||
variables.appType === "claude"
|
||||
? "Claude"
|
||||
: variables.appType === "codex"
|
||||
? "Codex"
|
||||
: "Gemini";
|
||||
|
||||
toast.success(
|
||||
variables.enabled
|
||||
? t("failover.enabled", {
|
||||
app: appLabel,
|
||||
defaultValue: `${appLabel} 故障转移已启用`,
|
||||
})
|
||||
: t("failover.disabled", {
|
||||
app: appLabel,
|
||||
defaultValue: `${appLabel} 故障转移已关闭`,
|
||||
}),
|
||||
{ closeButton: true },
|
||||
);
|
||||
},
|
||||
|
||||
// 错误时回滚
|
||||
onError: (_error, _variables, context) => {
|
||||
onError: (error: Error, _variables, context) => {
|
||||
if (context?.previousValue !== undefined) {
|
||||
queryClient.setQueryData(
|
||||
["autoFailoverEnabled", context.appType],
|
||||
context.previousValue,
|
||||
);
|
||||
}
|
||||
|
||||
const detail =
|
||||
extractErrorMessage(error) ||
|
||||
t("common.unknown", { defaultValue: "未知错误" });
|
||||
toast.error(
|
||||
t("failover.toggleFailed", {
|
||||
detail,
|
||||
defaultValue: `操作失败: ${detail}`,
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
// 无论成功失败,都重新获取
|
||||
@@ -232,6 +268,21 @@ export function useSetAutoFailoverEnabled() {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["autoFailoverEnabled", variables.appType],
|
||||
});
|
||||
// 启用/关闭故障转移可能触发:
|
||||
// - 立即切到队列 P1(当前供应商变化)
|
||||
// - 队列为空时自动把当前供应商加入队列(队列内容变化)
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["failoverQueue", variables.appType],
|
||||
});
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["availableProvidersForFailover", variables.appType],
|
||||
});
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["providers", variables.appType],
|
||||
});
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["proxyStatus"],
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ export const useAddProviderMutation = (appId: AppId) => {
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (
|
||||
providerInput: Omit<Provider, "id"> & { providerKey?: string }
|
||||
providerInput: Omit<Provider, "id"> & { providerKey?: string },
|
||||
) => {
|
||||
let id: string;
|
||||
|
||||
|
||||
+47
-1
@@ -87,6 +87,38 @@ export interface UsageResult {
|
||||
error?: string;
|
||||
}
|
||||
|
||||
// 供应商单独的模型测试配置
|
||||
export interface ProviderTestConfig {
|
||||
// 是否启用单独配置(false 时使用全局配置)
|
||||
enabled: boolean;
|
||||
// 测试用的模型名称(覆盖全局配置)
|
||||
testModel?: string;
|
||||
// 超时时间(秒)
|
||||
timeoutSecs?: number;
|
||||
// 测试提示词
|
||||
testPrompt?: string;
|
||||
// 降级阈值(毫秒)
|
||||
degradedThresholdMs?: number;
|
||||
// 最大重试次数
|
||||
maxRetries?: number;
|
||||
}
|
||||
|
||||
// 供应商单独的代理配置
|
||||
export interface ProviderProxyConfig {
|
||||
// 是否启用单独配置(false 时使用全局/系统代理)
|
||||
enabled: boolean;
|
||||
// 代理类型:http, https, socks5
|
||||
proxyType?: "http" | "https" | "socks5";
|
||||
// 代理主机
|
||||
proxyHost?: string;
|
||||
// 代理端口
|
||||
proxyPort?: number;
|
||||
// 代理用户名(可选)
|
||||
proxyUsername?: string;
|
||||
// 代理密码(可选)
|
||||
proxyPassword?: string;
|
||||
}
|
||||
|
||||
// 供应商元数据(字段名与后端一致,保持 snake_case)
|
||||
export interface ProviderMeta {
|
||||
// 自定义端点:以 URL 为键,值为端点信息
|
||||
@@ -99,6 +131,18 @@ export interface ProviderMeta {
|
||||
isPartner?: boolean;
|
||||
// 合作伙伴促销 key(用于后端识别 PackyCode 等)
|
||||
partnerPromotionKey?: string;
|
||||
// 供应商单独的模型测试配置
|
||||
testConfig?: ProviderTestConfig;
|
||||
// 供应商单独的代理配置
|
||||
proxyConfig?: ProviderProxyConfig;
|
||||
}
|
||||
|
||||
// 主页面显示的应用配置
|
||||
export interface VisibleApps {
|
||||
claude: boolean;
|
||||
codex: boolean;
|
||||
gemini: boolean;
|
||||
opencode: boolean;
|
||||
}
|
||||
|
||||
// 应用设置类型(用于设置对话框与 Tauri API)
|
||||
@@ -118,6 +162,9 @@ export interface Settings {
|
||||
// 首选语言(可选,默认中文)
|
||||
language?: "en" | "zh" | "ja";
|
||||
|
||||
// 主页面显示的应用(默认全部显示)
|
||||
visibleApps?: VisibleApps;
|
||||
|
||||
// ===== 设备级目录覆盖 =====
|
||||
// 覆盖 Claude Code 配置目录(可选)
|
||||
claudeConfigDir?: string;
|
||||
@@ -294,4 +341,3 @@ export interface OpenCodeMcpServerSpec {
|
||||
// 通用字段
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
export function isTextEditableTarget(target: EventTarget | null): boolean {
|
||||
if (!(target instanceof HTMLElement)) return false;
|
||||
|
||||
const tagName = target.tagName;
|
||||
return (
|
||||
tagName === "INPUT" ||
|
||||
tagName === "TEXTAREA" ||
|
||||
tagName === "SELECT" ||
|
||||
target.isContentEditable
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import type { ReactElement } from "react";
|
||||
import type { Provider } from "@/types";
|
||||
import { ProviderList } from "@/components/providers/ProviderList";
|
||||
|
||||
@@ -108,6 +110,16 @@ function createProvider(overrides: Partial<Provider> = {}): Provider {
|
||||
};
|
||||
}
|
||||
|
||||
function renderWithQueryClient(ui: ReactElement) {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>{ui}</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
useDragSortMock.mockReset();
|
||||
useSortableMock.mockReset();
|
||||
@@ -131,7 +143,7 @@ beforeEach(() => {
|
||||
|
||||
describe("ProviderList Component", () => {
|
||||
it("should render skeleton placeholders when loading", () => {
|
||||
const { container } = render(
|
||||
const { container } = renderWithQueryClient(
|
||||
<ProviderList
|
||||
providers={{}}
|
||||
currentProviderId=""
|
||||
@@ -159,7 +171,7 @@ describe("ProviderList Component", () => {
|
||||
handleDragEnd: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
renderWithQueryClient(
|
||||
<ProviderList
|
||||
providers={{}}
|
||||
currentProviderId=""
|
||||
@@ -198,7 +210,7 @@ describe("ProviderList Component", () => {
|
||||
handleDragEnd: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
renderWithQueryClient(
|
||||
<ProviderList
|
||||
providers={{ a: providerA, b: providerB }}
|
||||
currentProviderId="b"
|
||||
@@ -262,7 +274,7 @@ describe("ProviderList Component", () => {
|
||||
handleDragEnd: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
renderWithQueryClient(
|
||||
<ProviderList
|
||||
providers={{ alpha: providerAlpha, beta: providerBeta }}
|
||||
currentProviderId=""
|
||||
|
||||
Reference in New Issue
Block a user