feat(sponsor): add PackyCode as official partner

- Add PackyCode to sponsor section in README (both EN/ZH)
- Add PackyCode logo to assets/partners/logos/
- Mark PackyCode as partner in provider presets (Claude & Codex)
- Add promotion message to i18n files with 10% discount info
This commit is contained in:
Jason
2025-11-10 18:44:19 +08:00
parent be155c857e
commit b1abdf95aa
7 changed files with 262 additions and 621 deletions

435
README.md
View File

@@ -12,7 +12,7 @@ A desktop application for managing and switching between different provider conf
</div> </div>
## ❤️ Sponsor ## ❤Sponsor
![Zhipu GLM](assets/partners/banners/glm-en.jpg) ![Zhipu GLM](assets/partners/banners/glm-en.jpg)
@@ -22,95 +22,49 @@ GLM CODING PLAN is a subscription service designed for AI coding, starting at ju
Get 10% OFF the GLM CODING PLAN with [this link](https://z.ai/subscribe?ic=8JVLJQFSKB)! Get 10% OFF the GLM CODING PLAN with [this link](https://z.ai/subscribe?ic=8JVLJQFSKB)!
## Release Notes ---
> **v3.6.0**: Added edit mode (provider duplication, manual sorting), custom endpoint management, usage query features. Optimized config directory switching experience (perfect WSL environment support). Added multiple provider presets (DMXAPI, Azure Codex, AnyRouter, AiHubMix, MiniMax). Completed full-stack architecture refactoring and testing infrastructure. <table>
<tr>
> v3.5.0: Added MCP management, config import/export, endpoint speed testing. Complete i18n coverage. Added Longcat and kat-coder presets. Standardized release file naming conventions. <td width="120"><img src="assets/partners/logos/packycode.png" alt="PackyCode" width="100"></td>
<td>Thanks to PackyCode for sponsoring this project! PackyCode is a reliable and efficient API relay service provider, offering relay services for Claude Code, Codex, Gemini, and more. PackyCode provides special discounts for our software users: register using <a href="https://www.packyapi.com/register?aff=cc-switch">this link</a> and enter the "cc-switch" promo code during recharge to get 10% off.</td>
> v3.4.0: Added i18next internationalization, support for new models (qwen-3-max, GLM-4.6, DeepSeek-V3.2-Exp), Claude plugin, single-instance daemon, tray minimize, and installer optimizations. </tr>
</table>
> v3.3.0: One-click VS Code Codex plugin configuration/removal (auto-sync by default), Codex common config snippets, enhanced custom wizard, WSL environment support, cross-platform tray and UI optimizations. (VS Code write feature deprecated in v3.4.x)
> v3.2.0: Brand new UI, macOS system tray, built-in updater, atomic write with rollback, improved dark mode, Single Source of Truth (SSOT) with one-time migration/archival.
> v3.1.0: Added Codex provider management with one-click switching. Import current Codex config as default provider. Auto-backup before internal config v1 → v2 migration (see "Migration & Archival" below).
> v3.0.0 Major Update: Complete migration from Electron to Tauri 2.0. Significantly reduced app size and greatly improved startup performance.
## Features (v3.6.0)
### Core Features
- **MCP (Model Context Protocol) Management**: Complete MCP server configuration management system
- Support for stdio and http server types with command validation
- Built-in templates for popular MCP servers (e.g., mcp-fetch)
- Real-time enable/disable MCP servers with atomic file writes to prevent configuration corruption
- **Config Import/Export**: Backup and restore your provider configurations
- One-click export all configurations to JSON file
- Import configs with automatic validation and backup, auto-rotate backups (keep 10 most recent)
- Auto-sync to live config files after import to ensure immediate effect
- **Endpoint Speed Testing**: Test API endpoint response times
- Measure latency to different provider endpoints with visual connection quality indicators
- Help users choose the fastest provider
- **Internationalization & Language Switching**: Complete i18next i18n coverage (including error messages, tray menu, all UI components)
- **Claude Plugin Sync**: Built-in button to apply or restore Claude plugin configurations with one click. Takes effect immediately after switching providers.
### v3.6 New Features
- **Provider Duplication**: Quickly duplicate existing provider configs to easily create variants
- **Manual Sorting**: Drag and drop to manually reorder providers
- **Custom Endpoint Management**: Support multi-endpoint configuration for aggregator providers
- **Custom Configuration Directory (Cloud Sync Support)**:
- Customize CC Switch's configuration storage location
- Point to cloud sync folders (Dropbox, OneDrive, iCloud, etc.) to enable automatic config synchronization across devices
- Supports independent management via Tauri Store
- **Claude Configuration Data Structure Enhancements**
- **Granular Model Configuration**: Migrated from dual-key to quad-key system for better model tier differentiation
- New fields: `ANTHROPIC_DEFAULT_HAIKU_MODEL`, `ANTHROPIC_DEFAULT_SONNET_MODEL`, `ANTHROPIC_DEFAULT_OPUS_MODEL`, `ANTHROPIC_MODEL`
- Replaces legacy `ANTHROPIC_SMALL_FAST_MODEL` with automatic migration
- Backend normalizes old configs on first read/write with smart fallback chain
- UI expanded from 2 to 4 model input fields with intelligent defaults
- Support for `ANTHROPIC_API_KEY` field (in addition to `ANTHROPIC_AUTH_TOKEN`)
- Template variable system for dynamic configuration replacement (e.g., KAT-Coder's ENDPOINT_ID)
- Endpoint candidates list for speed testing and endpoint management
- Visual theme configuration (custom icons and colors for provider cards)
- Partner promotion mechanism with i18n support
- **Updated Provider Models**
- Kimi: Updated to latest `kimi-k2-thinking` model
- **Usage Query Features**
- Auto-refresh interval: Supports periodic automatic usage queries
- Test Script API: Validate JavaScript scripts before execution
- Template system expansion: Custom blank templates, support for access token and user ID parameters
- **Config Editor Improvements**
- Added JSON format button
- Real-time TOML syntax validation (for Codex configs)
- **Auto-sync on Directory Change**: When switching Claude/Codex config directories (e.g., switching to WSL environment), automatically sync current provider to new directory to avoid config file conflicts
- **Load Live Config When Editing Active Provider**: When editing the currently active provider, prioritize displaying the actual effective configuration to protect user manual modifications
- **New Provider Presets**: DMXAPI, Azure Codex, AnyRouter, AiHubMix, MiniMax
- **Partner Promotion Mechanism**: Support ecosystem partner promotion (e.g., Zhipu GLM Z.ai)
### v3.6 Architecture Improvements
- **Backend Refactoring**: Completed 5-phase refactoring (unified error handling → command layer split → integration tests → Service layer extraction → concurrency optimization)
- **Frontend Refactoring**: Completed 4-stage refactoring (test infrastructure → Hooks extraction → component splitting → code cleanup)
- **Testing System**: 100% Hooks unit test coverage, integration tests covering critical flows (vitest + MSW + @testing-library/react)
### System Features
- **System Tray & Window Behavior**: Window can minimize to tray, macOS supports hide/show Dock in tray mode, tray switching syncs Claude/Codex/plugin status.
- **Single Instance**: Ensures only one instance runs at a time to avoid multi-instance conflicts.
- **Standardized Release Naming**: All platform release files use consistent version-tagged naming (macOS: `.tar.gz` / `.zip`, Windows: `.msi` / `-Portable.zip`, Linux: `.AppImage` / `.deb`).
## Screenshots ## Screenshots
### Main Interface | Main Interface | Add Provider |
| :-----------------------------------------------: | :--------------------------------------------: |
| ![Main Interface](assets/screenshots/main-en.png) | ![Add Provider](assets/screenshots/add-en.png) |
![Main Interface](assets/screenshots/main-en.png) ## Features
### Add Provider ### Current Version: v3.6.0 | [Full Changelog](CHANGELOG.md)
![Add Provider](assets/screenshots/add-en.png) **Core Capabilities**
- **Provider Management**: One-click switching between Claude Code & Codex API configurations
- **MCP Integration**: Centralized MCP server management with stdio/http support and real-time sync
- **Speed Testing**: Measure API endpoint latency with visual quality indicators
- **Import/Export**: Backup and restore configs with auto-rotation (keep 10 most recent)
- **i18n Support**: Complete Chinese/English localization (UI, errors, tray)
- **Claude Plugin Sync**: One-click apply/restore Claude plugin configurations
**v3.6 Highlights**
- Provider duplication & drag-and-drop sorting
- Multi-endpoint management & custom config directory (cloud sync ready)
- Granular model configuration (4-tier: Haiku/Sonnet/Opus/Custom)
- WSL environment support with auto-sync on directory change
- 100% hooks test coverage & complete architecture refactoring
- New presets: DMXAPI, Azure Codex, AnyRouter, AiHubMix, MiniMax
**System Features**
- System tray with quick switching
- Single instance daemon
- Built-in auto-updater
- Atomic writes with rollback protection
## Download & Installation ## Download & Installation
@@ -149,148 +103,95 @@ Download `CC-Switch-v{version}-macOS.zip` from the [Releases](../../releases) pa
Download the latest `CC-Switch-v{version}-Linux.deb` package or `CC-Switch-v{version}-Linux.AppImage` from the [Releases](../../releases) page. Download the latest `CC-Switch-v{version}-Linux.deb` package or `CC-Switch-v{version}-Linux.AppImage` from the [Releases](../../releases) page.
## Usage Guide ## Quick Start
1. Click "Add Provider" to add your API configuration ### Basic Usage
2. Switching methods:
- Select a provider on the main interface and click switch
- Or directly select target provider from "System Tray (Menu Bar)" for immediate effect
3. Switching will write to the corresponding app's "live config file" (Claude: `settings.json`; Codex: `auth.json` + `config.toml`)
4. Restart or open new terminal to ensure it takes effect
5. To switch back to official login, select "Official Login" from presets and switch; after restarting terminal, follow the official login process
### MCP Configuration Guide (v3.5.x) 1. **Add Provider**: Click "Add Provider" → Choose preset or create custom configuration
2. **Switch Provider**:
- Main UI: Select provider → Click "Enable"
- System Tray: Click provider name directly (instant effect)
3. **Takes Effect**: Restart terminal or Claude Code/Codex to apply changes
4. **Back to Official**: Select "Official Login" preset, restart terminal, then use `/login` (Claude) or official login flow (Codex)
- Management Location: All MCP server definitions are centrally saved in `~/.cc-switch/config.json` (categorized by client `claude` / `codex`) ### MCP Management
- Sync Mechanism:
- Enabled Claude MCP servers are projected to `~/.claude.json` (path may vary with override directory)
- Enabled Codex MCP servers are projected to `~/.codex/config.toml`
- Validation & Normalization: Auto-validate field legality (stdio/http) when adding/importing, and auto-fix/populate keys like `id`
- Import Sources: Support importing from `~/.claude.json` and `~/.codex/config.toml`; existing entries only force `enabled=true`, don't override other fields
### Check for Updates - **Location**: Click "MCP" button in top-right corner
- **Add Server**: Use built-in templates (mcp-fetch, mcp-filesystem) or custom config
- **Enable/Disable**: Toggle switches to control which servers sync to live config
- **Sync**: Enabled servers auto-sync to `~/.claude.json` (Claude) or `~/.codex/config.toml` (Codex)
- Click "Check for Updates" in Settings. If built-in Updater config is available, it will detect and download directly; otherwise, it will fall back to opening the Releases page ### Configuration Files
### Codex Guide (SSOT) **Claude Code**
- Config Directory: `~/.codex/` - Live config: `~/.claude/settings.json` (or `claude.json`)
- Live main config: `auth.json` (required), `config.toml` (can be empty) - API key field: `env.ANTHROPIC_AUTH_TOKEN` or `env.ANTHROPIC_API_KEY`
- API Key Field: Uses `OPENAI_API_KEY` in `auth.json` - MCP servers: `~/.claude.json` `mcpServers`
- Switching Behavior (no longer writes "copy files"):
- Provider configs are uniformly saved in `~/.cc-switch/config.json`
- When switching, writes target provider back to live files (`auth.json` + `config.toml`)
- Uses "atomic write + rollback on failure" to avoid half-written state; `config.toml` can be empty
- Import Default: When the app has no providers, creates a default entry from existing live main config and sets it as current
- Official Login: Can switch to preset "Codex Official Login", restart terminal and follow official login process
### Claude Code Guide (SSOT) **Codex**
- Config Directory: `~/.claude/` - Live config: `~/.codex/auth.json` (required) + `config.toml` (optional)
- Live main config: `settings.json` (preferred) or legacy-compatible `claude.json` - API key field: `OPENAI_API_KEY` in `auth.json`
- API Key Field: `env.ANTHROPIC_AUTH_TOKEN` - MCP servers: `~/.codex/config.toml``[mcp.servers]`
- Switching Behavior (no longer writes "copy files"):
- Provider configs are uniformly saved in `~/.cc-switch/config.json`
- When switching, writes target provider JSON directly to live file (preferring `settings.json`)
- When editing current provider, writes live first successfully, then updates app main config to ensure consistency
- Import Default: When the app has no providers, creates a default entry from existing live main config and sets it as current
- Official Login: Can switch to preset "Claude Official Login", restart terminal and use `/login` to complete login
### Migration & Archival **CC Switch Storage**
#### v3.6 Technical Improvements - Main config (SSOT): `~/.cc-switch/config.json`
- Settings: `~/.cc-switch/settings.json`
- Backups: `~/.cc-switch/backups/` (auto-rotate, keep 10)
**Internal Optimizations (User Transparent)**: ### Cloud Sync Setup
- **Removed Legacy Migration Logic**: v3.6 removed v1 config auto-migration and copy file scanning logic 1. Go to Settings → "Custom Configuration Directory"
- **Impact**: Improved startup performance, cleaner code 2. Choose your cloud sync folder (Dropbox, OneDrive, iCloud, etc.)
- **Compatibility**: v2 format configs are fully compatible, no action required 3. Restart app to apply
- ⚠️ **Note**: Users upgrading from v3.1.0 or earlier should first upgrade to v3.2.x or v3.5.x for one-time migration, then upgrade to v3.6 4. Repeat on other devices to enable cross-device sync
- **Command Parameter Standardization**: Backend unified to use `app` parameter (values: `claude` or `codex`) > **Note**: First launch auto-imports existing Claude/Codex configs as default provider.
- **Impact**: More standardized code, friendlier error messages
- **Compatibility**: Frontend fully adapted, users don't need to care about this change
#### Startup Failure & Recovery ## Architecture Overview
- Trigger Conditions: Triggered when `~/.cc-switch/config.json` doesn't exist, is corrupted, or fails to parse. ### Design Principles
- User Action: Check JSON syntax according to popup prompt, or restore from backup files.
- Backup Location & Rotation: `~/.cc-switch/backups/backup_YYYYMMDD_HHMMSS.json` (keep up to 10, see `src-tauri/src/services/config.rs`).
- Exit Strategy: To protect data safety, the app will show a popup and force exit when the above errors occur; restart after fixing.
#### Migration Mechanism (v3.2.0+) ```
┌─────────────────────────────────────────────────────────────┐
│ Frontend (React + TS) │
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────────┐ │
│ │ Components │ │ Hooks │ │ TanStack Query │ │
│ │ (UI) │──│ (Bus. Logic) │──│ (Cache/Sync) │ │
│ └─────────────┘ └──────────────┘ └──────────────────┘ │
└────────────────────────┬────────────────────────────────────┘
│ Tauri IPC
┌────────────────────────▼────────────────────────────────────┐
│ Backend (Tauri + Rust) │
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────────┐ │
│ │ Commands │ │ Services │ │ Models/Config │ │
│ │ (API Layer) │──│ (Bus. Layer) │──│ (Data) │ │
│ └─────────────┘ └──────────────┘ └──────────────────┘ │
└─────────────────────────────────────────────────────────────┘
```
- One-time Migration: First launch of v3.2.0+ will scan old "copy files" and merge into `~/.cc-switch/config.json` **Core Design Patterns**
- Claude: `~/.claude/settings-*.json` (excluding `settings.json` / legacy `claude.json`)
- Codex: `~/.codex/auth-*.json` and `config-*.toml` (merged in pairs by name)
- Deduplication & Current Item: Deduplicate by "name (case-insensitive) + API Key"; if current is empty, set live merged item as current
- Archival & Cleanup:
- Archive directory: `~/.cc-switch/archive/<timestamp>/<category>/...`
- Delete original copies after successful archival; keep original files on failure (conservative strategy)
- v1 → v2 Structure Upgrade: Additionally generates `~/.cc-switch/config.v1.backup.<timestamp>.json` for rollback
- Note: After migration, daily switch/edit operations are no longer archived; prepare your own backup solution if long-term auditing is needed
## Architecture Overview (v3.6) - **SSOT** (Single Source of Truth): All provider configs stored in `~/.cc-switch/config.json`
- **Dual-way Sync**: Write to live files on switch, backfill from live when editing active provider
- **Atomic Writes**: Temp file + rename pattern prevents config corruption
- **Concurrency Safe**: RwLock with scoped guards avoids deadlocks
- **Layered Architecture**: Clear separation (Commands → Services → Models)
### Architecture Refactoring Highlights (v3.6) **Key Components**
**Backend Refactoring (Rust)**: Completed 5-phase refactoring - **ProviderService**: Provider CRUD, switching, backfill, sorting
- **McpService**: MCP server management, import/export, live file sync
- **ConfigService**: Config import/export, backup rotation
- **SpeedtestService**: API endpoint latency measurement
- **Phase 1**: Unified error handling (`AppError` + i18n error messages) **v3.6 Refactoring**
- **Phase 2**: Command layer split by domain (`commands/{provider,mcp,config,settings,plugin,misc}.rs`)
- **Phase 3**: Introduced integration tests and transaction mechanism (config snapshot + failure rollback)
- **Phase 4**: Extracted Service layer (`services/{provider,mcp,config,speedtest}.rs`)
- **Phase 5**: Concurrency optimization (`RwLock` instead of `Mutex`, scoped guard to avoid deadlock)
**Frontend Refactoring (React + TypeScript)**: Completed 4-stage refactoring - Backend: 5-phase refactoring (error handling → command split → tests → services → concurrency)
- Frontend: 4-stage refactoring (test infra → hooks → components → cleanup)
- **Stage 1**: Established test infrastructure (vitest + MSW + @testing-library/react) - Testing: 100% hooks coverage + integration tests (vitest + MSW)
- **Stage 2**: Extracted custom hooks (`useProviderActions`, `useMcpActions`, `useSettings`, `useImportExport`, etc.)
- **Stage 3**: Component splitting and business logic extraction
- **Stage 4**: Code cleanup and formatting unification
**Test Coverage**:
- 100% Hooks unit test coverage
- Integration tests covering critical flows (App, SettingsDialog, MCP Panel)
- MSW mocking backend API to ensure test independence
### Layered Architecture
- **Frontend (Renderer)**
- Tech Stack: TypeScript + React 18 + Vite + TailwindCSS 4
- Data Layer: TanStack React Query unified queries and mutations (`@/lib/query`), Tauri API unified wrapper (`@/lib/api`)
- Business Logic Layer: Custom Hooks (`@/hooks`) carry domain logic, components stay simple
- Event Flow: Listen to backend `provider-switched` events, drive UI refresh and tray state consistency
- Organization: Components split by domain (`providers/settings/mcp/ui`)
- **Backend (Tauri + Rust)**
- **Commands Layer** (Interface Layer): `src-tauri/src/commands/*` split by domain, only responsible for parameter parsing and permission validation
- **Services Layer** (Business Layer): `src-tauri/src/services/*` carry core logic, reusable and testable
- `ProviderService`: Provider CRUD, switch, backfill, sorting
- `McpService`: MCP server management, import/export, sync
- `ConfigService`: Config file import/export, backup/restore
- `SpeedtestService`: API endpoint latency testing
- **Models & State**:
- `provider.rs`: Domain models (`Provider`, `ProviderManager`, `ProviderMeta`)
- `app_config.rs`: Multi-app config (`MultiAppConfig`, `AppId`, `McpRoot`)
- `store.rs`: Global state (`AppState` + `RwLock<MultiAppConfig>`)
- **Reliability**:
- Unified error type `AppError` (with localized messages)
- Transactional changes (config snapshot + failure rollback)
- Atomic writes (temp file + rename, avoid half-writes)
- Tray menu & events: Rebuild menu after switch and emit `provider-switched` event to frontend
- **Design Points (SSOT + Dual-way Sync)**
- **Single Source of Truth**: Provider configs centrally stored in `~/.cc-switch/config.json`
- **Write on Switch**: Write target provider config to live files (Claude: `settings.json`; Codex: `auth.json` + `config.toml`)
- **Backfill Mechanism**: Immediately read back live files after switch, update SSOT to protect user manual modifications
- **Directory Switch Sync**: Auto-sync current provider to new directory when changing config directories (perfect WSL environment support)
- **Prioritize Live When Editing**: When editing current provider, prioritize loading live config to ensure display of actually effective configuration
- **Compatibility & Changes**
- Command Parameters Unified: Tauri commands only accept `app` (values: `claude` / `codex`)
- Frontend Types Unified: Use `AppId` to express app identifiers (replacing legacy `AppType` export)
## Development ## Development
@@ -363,12 +264,12 @@ cargo test --features test-hooks
**Test Coverage**: **Test Coverage**:
- Hooks unit tests (100% coverage) - Hooks unit tests (100% coverage)
- `useProviderActions` - Provider operations - `useProviderActions` - Provider operations
- `useMcpActions` - MCP management - `useMcpActions` - MCP management
- `useSettings` series - Settings management - `useSettings` series - Settings management
- `useImportExport` - Import/export - `useImportExport` - Import/export
- Integration tests - Integration tests
- App main application flow - App main application flow
- SettingsDialog complete interaction - SettingsDialog complete interaction
- MCP panel functionality - MCP panel functionality
@@ -388,120 +289,36 @@ pnpm test:unit --coverage
## Tech Stack ## Tech Stack
### Frontend **Frontend**: React 18 · TypeScript · Vite · TailwindCSS 4 · TanStack Query v5 · react-i18next · react-hook-form · zod · shadcn/ui · @dnd-kit
- **[React 18](https://react.dev/)** - User interface library **Backend**: Tauri 2.8 · Rust · serde · tokio · thiserror · tauri-plugin-updater/process/dialog/store/log
- **[TypeScript](https://www.typescriptlang.org/)** - Type-safe JavaScript
- **[Vite](https://vitejs.dev/)** - Lightning fast frontend build tool
- **[TailwindCSS 4](https://tailwindcss.com/)** - Utility-first CSS framework
- **[TanStack Query v5](https://tanstack.com/query/latest)** - Powerful data fetching and caching
- **[react-i18next](https://react.i18next.com/)** - React internationalization framework
- **[react-hook-form](https://react-hook-form.com/)** - High-performance forms library
- **[zod](https://zod.dev/)** - TypeScript-first schema validation
- **[shadcn/ui](https://ui.shadcn.com/)** - Reusable React components
- **[@dnd-kit](https://dndkit.com/)** - Modern drag and drop toolkit
### Backend **Testing**: vitest · MSW · @testing-library/react
- **[Tauri 2.8](https://tauri.app/)** - Cross-platform desktop app framework
- tauri-plugin-updater - Auto update
- tauri-plugin-process - Process management
- tauri-plugin-dialog - File dialogs
- tauri-plugin-store - Persistent storage
- tauri-plugin-log - Logging
- **[Rust](https://www.rust-lang.org/)** - Systems programming language
- **[serde](https://serde.rs/)** - Serialization/deserialization framework
- **[tokio](https://tokio.rs/)** - Async runtime
- **[thiserror](https://github.com/dtolnay/thiserror)** - Error handling derive macro
### Testing Tools
- **[vitest](https://vitest.dev/)** - Fast unit testing framework
- **[MSW](https://mswjs.io/)** - API mocking tool
- **[@testing-library/react](https://testing-library.com/react)** - React testing utilities
## Project Structure ## Project Structure
``` ```
├── src/ # Frontend code (React + TypeScript) ├── src/ # Frontend (React + TypeScript)
│ ├── components/ # React components │ ├── components/ # UI components (providers/settings/mcp/ui)
│ ├── providers/ # Provider management components │ ├── hooks/ # Custom hooks (business logic)
│ │ │ ├── forms/ # Form sub-components (Claude/Codex fields)
│ │ │ ├── ProviderList.tsx
│ │ │ ├── ProviderForm.tsx
│ │ │ ├── AddProviderDialog.tsx
│ │ │ └── EditProviderDialog.tsx
│ │ ├── settings/ # Settings related components
│ │ │ ├── SettingsDialog.tsx
│ │ │ ├── DirectorySettings.tsx
│ │ │ └── ImportExportSection.tsx
│ │ ├── mcp/ # MCP management components
│ │ │ ├── McpPanel.tsx
│ │ │ ├── McpFormModal.tsx
│ │ │ └── McpWizard.tsx
│ │ └── ui/ # shadcn/ui base components
│ ├── hooks/ # Custom Hooks (business logic layer)
│ │ ├── useProviderActions.ts # Provider operations
│ │ ├── useMcpActions.ts # MCP operations
│ │ ├── useSettings.ts # Settings management
│ │ ├── useImportExport.ts # Import/export
│ │ └── useDirectorySettings.ts # Directory config
│ ├── lib/ │ ├── lib/
│ │ ├── api/ # Tauri API wrapper (type-safe) │ │ ├── api/ # Tauri API wrapper (type-safe)
│ │ │ ├── providers.ts # Provider API
│ │ │ ├── settings.ts # Settings API
│ │ │ ├── mcp.ts # MCP API
│ │ │ └── usage.ts # Usage query API
│ │ └── query/ # TanStack Query config │ │ └── query/ # TanStack Query config
│ ├── queries.ts # Query definitions ├── i18n/locales/ # Translations (zh/en)
│ ├── mutations.ts # Mutation definitions ├── config/ # Presets (providers/mcp)
│ └── queryClient.ts └── types/ # TypeScript definitions
│ ├── i18n/ # Internationalization resources ├── src-tauri/ # Backend (Rust)
│ └── locales/ │ └── src/
│ ├── zh/ # Chinese translations │ ├── commands/ # Tauri command layer (by domain)
── en/ # English translations ── services/ # Business logic layer
├── config/ # Config & presets ├── app_config.rs # Config data models
├── claudeProviderPresets.ts # Claude provider presets ├── provider.rs # Provider domain models
├── codexProviderPresets.ts # Codex provider presets ├── mcp.rs # MCP sync & validation
└── mcpPresets.ts # MCP server templates └── lib.rs # App entry & tray menu
│ ├── utils/ # Utility functions ├── tests/ # Frontend tests
│ ├── postChangeSync.ts # Config sync utility │ ├── hooks/ # Unit tests
│ └── ... │ └── components/ # Integration tests
│ └── types/ # TypeScript type definitions └── assets/ # Screenshots & partner resources
├── src-tauri/ # Backend code (Rust)
│ ├── src/
│ │ ├── commands/ # Tauri command layer (split by domain)
│ │ │ ├── provider.rs # Provider commands
│ │ │ ├── mcp.rs # MCP commands
│ │ │ ├── config.rs # Config query commands
│ │ │ ├── settings.rs # Settings commands
│ │ │ ├── plugin.rs # Plugin commands
│ │ │ ├── import_export.rs # Import/export commands
│ │ │ └── misc.rs # Misc commands
│ │ ├── services/ # Service layer (business logic)
│ │ │ ├── provider.rs # ProviderService
│ │ │ ├── mcp.rs # McpService
│ │ │ ├── config.rs # ConfigService
│ │ │ └── speedtest.rs # SpeedtestService
│ │ ├── app_config.rs # Config data models
│ │ ├── provider.rs # Provider domain models
│ │ ├── store.rs # Global state management
│ │ ├── mcp.rs # MCP sync & validation
│ │ ├── error.rs # Unified error type
│ │ ├── usage_script.rs # Usage script execution
│ │ ├── claude_plugin.rs # Claude plugin management
│ │ └── lib.rs # App entry point
│ ├── capabilities/ # Tauri permission config
│ └── icons/ # App icons
├── tests/ # Frontend tests (v3.6 new)
│ ├── hooks/ # Hooks unit tests
│ ├── components/ # Component integration tests
│ └── setup.ts # Test config
└── assets/ # Static resources
├── screenshots/ # Interface screenshots
└── partners/ # Partner resources
├── logos/ # Partner logos
└── banners/ # Partner banners/promotional images
``` ```
## Changelog ## Changelog

View File

@@ -12,105 +12,59 @@
</div> </div>
## ❤️ 赞助商 ## ❤️赞助商
![智谱 GLM](assets/partners/banners/glm-zh.jpg) ![智谱 GLM](assets/partners/banners/glm-zh.jpg)
感谢智谱AI的 GLM CODING PLAN 赞助了本项目! 感谢智谱AI的 GLM CODING PLAN 赞助了本项目!
GLM CODING PLAN 是专为AI编码打造的订阅套餐每月最低仅需20元即可在十余款主流AI编码工具如 Claude Code、Cline 中畅享智谱旗舰模型 GLM-4.6,为开发者提供顶尖、高速、稳定的编码体验。 GLM CODING PLAN 是专为AI编码打造的订阅套餐,每月最低仅需20元即可在十余款主流AI编码工具如 Claude Code、Cline 中畅享智谱旗舰模型 GLM-4.6,为开发者提供顶尖、高速、稳定的编码体验。
CC Switch 已经预设了智谱GLM只需要填写 key 即可一键导入编程工具。智谱AI为本软件的用户提供了特别优惠使用[此链接](https://www.bigmodel.cn/claude-code?ic=RRVJPB5SII)购买可以享受九折优惠。 CC Switch 已经预设了智谱GLM只需要填写 key 即可一键导入编程工具。智谱AI为本软件的用户提供了特别优惠使用[此链接](https://www.bigmodel.cn/claude-code?ic=RRVJPB5SII)购买可以享受九折优惠。
## 更新记录 ---
> **v3.6.0** 新增编辑模式供应商复制、手动排序、自定义端点管理、使用量查询等功能优化配置目录切换体验WSL 环境完美支持新增多个供应商预设DMXAPI、Azure Codex、AnyRouter、AiHubMix、MiniMax完成全栈架构重构和测试体系建设。 <table>
<tr>
> v3.5.0 :新增 MCP 管理、配置导入/导出、端点速度测试功能,完善国际化覆盖,新增 Longcat、kat-coder 预设,标准化发布文件命名规范。 <td width="120"><img src="assets/partners/logos/packycode.png" alt="PackyCode" width="100"></td>
<td>感谢 PackyCode 赞助了本项目PackyCode 是一家稳定、高效的API中转服务商提供 Claude Code、Codex、Gemini 等多种中转服务。PackyCode 为本软件的用户提供了特别优惠,使用<a href="https://www.packyapi.com/register?aff=cc-switch">此链接</a>注册并在充值时填写"cc-switch"优惠码可以享受9折优惠。</td>
> v3.4.0 :新增 i18next 国际化、对新模型qwen-3-max, GLM-4.6, DeepSeek-V3.2-Exp的支持、Claude 插件、单实例守护、托盘最小化及安装器优化等。 </tr>
</table>
> v3.3.0 VS Code Codex 插件一键配置/移除默认自动同步、Codex 通用配置片段与自定义向导增强、WSL 环境支持、跨平台托盘与 UI 优化。(该 VS Code 写入功能已在 v3.4.x 停用)
> v3.2.0 :全新 UI、macOS系统托盘、内置更新器、原子写入与回滚、改进暗色样式、单一事实源SSOT与一次性迁移/归档。
> v3.1.0 :新增 Codex 供应商管理与一键切换,支持导入当前 Codex 配置为默认供应商,并在内部配置从 v1 → v2 迁移前自动备份(详见下文“迁移与归档”)。
> v3.0.0 重大更新:从 Electron 完全迁移到 Tauri 2.0,应用体积显著降低、启动性能大幅提升。
## 功能特性v3.6.0
### 核心功能
- **MCP (Model Context Protocol) 管理**:完整的 MCP 服务器配置管理系统
- 支持 stdio 和 http 服务器类型,并提供命令校验
- 内置常用 MCP 服务器模板(如 mcp-fetch 等)
- 实时启用/禁用 MCP 服务器,原子文件写入防止配置损坏
- **配置导入/导出**:备份和恢复你的供应商配置
- 一键导出所有配置到 JSON 文件
- 导入配置时自动验证并备份,自动轮换备份(保留最近 10 个)
- 导入后自动同步到 live 配置文件,确保立即生效
- **端点速度测试**:测试 API 端点响应时间
- 测量不同供应商端点的延迟,可视化连接质量指示器
- 帮助用户选择最快的供应商
- **国际化与语言切换**:完整的 i18next 国际化覆盖(包含错误消息、托盘菜单、所有 UI 组件)
- **Claude 插件同步**:内置按钮可一键应用或恢复 Claude 插件配置,切换供应商后立即生效。
### v3.6 新增功能
- **供应商复制功能**:快速复制现有供应商配置,轻松创建变体配置
- **手动排序功能**:通过拖拽来对供应商进行手动排序
- **自定义端点管理**:支持聚合类供应商的多端点配置
- **自定义配置目录(云同步支持)**
- 自定义 CC Switch 的配置存储位置
- 指定到云同步文件夹Dropbox、OneDrive、iCloud、坚果云等即可实现跨设备配置自动同步
- 通过 Tauri Store 独立管理
- **Claude 配置数据结构增强**
- **细粒度模型配置**:从双键系统升级到四键系统,以匹配官方最新数据结构
- 新增字段:`ANTHROPIC_DEFAULT_HAIKU_MODEL``ANTHROPIC_DEFAULT_SONNET_MODEL``ANTHROPIC_DEFAULT_OPUS_MODEL``ANTHROPIC_MODEL`
- 替换旧版 `ANTHROPIC_SMALL_FAST_MODEL`,支持自动迁移
- 后端在首次读写时自动规范化旧配置,带有智能回退链
- UI 从 2 个模型输入字段扩展到 4 个,具有智能默认值
- 支持 `ANTHROPIC_API_KEY` 字段(除 `ANTHROPIC_AUTH_TOKEN` 外)
- 模板变量系统,支持动态配置替换(如 KAT-Coder 的 ENDPOINT_ID
- 端点候选列表,用于速度测试和端点管理
- 视觉主题配置(供应商卡片自定义图标和颜色)
- 合作伙伴推广机制与国际化支持
- **供应商模型更新**
- Kimi更新到最新的 `kimi-k2-thinking`
- **使用量查询功能**
- 自动刷新间隔:支持定时自动查询使用量
- 测试脚本 API测试 JavaScript 脚本是否正确
- 模板系统扩展:自定义空白模板、支持 access token 和 user ID 参数
- **配置编辑器改进**
- 新增 JSON 格式化按钮
- 实时 TOML 语法验证Codex 配置)
- **配置目录切换自动同步**:切换 Claude/Codex 配置目录(如切换到 WSL 环境)时,自动同步当前供应商到新目录,避免冲突导致配置文件混乱
- **编辑当前供应商时加载 live 配置**:编辑正在使用的供应商时,优先显示实际生效的配置,保护用户手动修改
- **新增供应商预设**DMXAPI、Azure Codex、AnyRouter、AiHubMix、MiniMax
- **合作伙伴推广机制**:支持生态合作伙伴推广(如智谱 GLM Z.ai
### v3.6 架构改进
- **后端重构**:完成 5 阶段重构(统一错误处理 → 命令层拆分 → 集成测试 → Service 层提取 → 并发优化)
- **前端重构**:完成 4 阶段重构(测试基础设施 → Hooks 提取 → 组件拆分 → 代码清理)
- **测试体系**Hooks 单元测试 100% 覆盖集成测试覆盖关键流程vitest + MSW + @testing-library/react
### 系统功能
- **系统托盘与窗口行为**窗口关闭可最小化到托盘macOS 支持托盘模式下隐藏/显示 Dock托盘切换时同步 Claude/Codex/插件状态。
- **单实例**:保证同一时间仅运行一个实例,避免多开冲突。
- **标准化发布命名**所有平台发布文件使用一致的版本标签命名macOS: `.tar.gz` / `.zip`Windows: `.msi` / `-Portable.zip`Linux: `.AppImage` / `.deb`)。
## 界面预览 ## 界面预览
### 主界面 | 主界面 | 添加供应商 |
| :---------------------------------------: | :------------------------------------------: |
| ![主界面](assets/screenshots/main-zh.png) | ![添加供应商](assets/screenshots/add-zh.png) |
![主界面](assets/screenshots/main-zh.png) ## 功能特性
### 添加供应商 ### 当前版本v3.6.0 | [完整更新日志](CHANGELOG.md)
![添加供应商](assets/screenshots/add-zh.png) **核心功能**
- **供应商管理**:一键切换 Claude Code 与 Codex 的 API 配置
- **MCP 集成**:集中管理 MCP 服务器,支持 stdio/http 类型和实时同步
- **速度测试**:测量 API 端点延迟,可视化连接质量指示器
- **导入导出**:备份和恢复配置,自动轮换(保留最近 10 个)
- **国际化支持**完整的中英文本地化UI、错误、托盘
- **Claude 插件同步**:一键应用或恢复 Claude 插件配置
**v3.6 亮点**
- 供应商复制 & 拖拽排序
- 多端点管理 & 自定义配置目录(支持云同步)
- 细粒度模型配置四层Haiku/Sonnet/Opus/自定义)
- WSL 环境支持,配置目录切换自动同步
- 100% hooks 测试覆盖 & 完整架构重构
- 新增预设DMXAPI、Azure Codex、AnyRouter、AiHubMix、MiniMax
**系统功能**
- 系统托盘快速切换
- 单实例守护
- 内置自动更新器
- 原子写入与回滚保护
## 下载安装 ## 下载安装
@@ -149,148 +103,95 @@ brew upgrade --cask cc-switch
从 [Releases](../../releases) 页面下载最新版本的 `CC-Switch-v{版本号}-Linux.deb` 包或者 `CC-Switch-v{版本号}-Linux.AppImage` 安装包。 从 [Releases](../../releases) 页面下载最新版本的 `CC-Switch-v{版本号}-Linux.deb` 包或者 `CC-Switch-v{版本号}-Linux.AppImage` 安装包。
## 使用说明 ## 快速开始
1. 点击"添加供应商"添加你的 API 配置 ### 基本使用
2. 切换方式:
- 在主界面选择供应商后点击切换
- 或通过“系统托盘(菜单栏)”直接选择目标供应商,立即生效
3. 切换会写入对应应用的“live 配置文件”Claude`settings.json`Codex`auth.json` + `config.toml`
4. 重启或新开终端以确保生效
5. 若需切回官方登录,在预设中选择“官方登录”并切换即可;重启终端后按官方流程登录
### MCP 配置说明v3.5.x 1. **添加供应商**:点击"添加供应商" → 选择预设或创建自定义配置
2. **切换供应商**
- 主界面:选择供应商 → 点击"启用"
- 系统托盘:直接点击供应商名称(立即生效)
3. **生效方式**:重启终端或 Claude Code/Codex 以应用更改
4. **恢复官方登录**:选择"官方登录"预设,重启终端后使用 `/login`Claude或官方登录流程Codex
- 管理位置:所有 MCP 服务器定义集中保存在 `~/.cc-switch/config.json`(按客户端 `claude` / `codex` 分类) ### MCP 管理
- 同步机制:
- 启用的 Claude MCP 会投影到 `~/.claude.json`(路径可随覆盖目录而变化)
- 启用的 Codex MCP 会投影到 `~/.codex/config.toml`
- 校验与归一化:新增/导入时自动校验字段合法性stdio/http并自动修复/填充 `id` 等键名
- 导入来源:支持从 `~/.claude.json``~/.codex/config.toml` 导入;已存在条目只强制 `enabled=true`,不覆盖其他字段
### 检查更新 - **位置**:点击右上角"MCP"按钮
- **添加服务器**使用内置模板mcp-fetch、mcp-filesystem或自定义配置
- **启用/禁用**:切换开关以控制哪些服务器同步到 live 配置
- **同步**:启用的服务器自动同步到 `~/.claude.json`Claude`~/.codex/config.toml`Codex
- 在“设置”中点击“检查更新”,若内置 Updater 配置可用将直接检测与下载;否则会回退打开 Releases 页面 ### 配置文件
### Codex 说明SSOT **Claude Code**
- 配置目录:`~/.codex/` - Live 配置:`~/.claude/settings.json`(或 `claude.json`
- live 主配置:`auth.json`(必需)、`config.toml`(可为空) - API key 字段:`env.ANTHROPIC_AUTH_TOKEN``env.ANTHROPIC_API_KEY`
- API Key 字段:`auth.json` 中使用 `OPENAI_API_KEY` - MCP 服务器:`~/.claude.json``mcpServers`
- 切换行为(不再写“副本文件”):
- 供应商配置统一保存在 `~/.cc-switch/config.json`
- 切换时将目标供应商写回 live 文件(`auth.json` + `config.toml`
- 采用“原子写入 + 失败回滚”,避免半写状态;`config.toml` 可为空
- 导入默认:当该应用无任何供应商时,从现有 live 主配置创建一条默认项并设为当前
- 官方登录可切换到预设“Codex 官方登录”,重启终端后按官方流程登录
### Claude Code 说明SSOT **Codex**
- 配置目录:`~/.claude/` - Live 配置:`~/.codex/auth.json`(必需)+ `config.toml`(可选)
- live 主配置:`settings.json`(优先)或历史兼容 `claude.json` - API key 字段:`auth.json` 中的 `OPENAI_API_KEY`
- API Key 字段:`env.ANTHROPIC_AUTH_TOKEN` - MCP 服务器:`~/.codex/config.toml``[mcp.servers]`
- 切换行为(不再写“副本文件”):
- 供应商配置统一保存在 `~/.cc-switch/config.json`
- 切换时将目标供应商 JSON 直接写入 live 文件(优先 `settings.json`
- 编辑当前供应商时,先写 live 成功,再更新应用主配置,保证一致性
- 导入默认:当该应用无任何供应商时,从现有 live 主配置创建一条默认项并设为当前
- 官方登录可切换到预设“Claude 官方登录”,重启终端后可使用 `/login` 完成登录
### 迁移与归档 **CC Switch 存储**
#### v3.6 技术改进 - 主配置SSOT`~/.cc-switch/config.json`
- 设置:`~/.cc-switch/settings.json`
- 备份:`~/.cc-switch/backups/`(自动轮换,保留 10 个)
**内部优化(用户无感知)** ### 云同步设置
- **移除遗留迁移逻辑**v3.6 移除了 v1 配置自动迁移和副本文件扫描逻辑 1. 前往设置 → "自定义配置目录"
- **影响**:启动性能提升,代码更简洁 2. 选择您的云同步文件夹Dropbox、OneDrive、iCloud、坚果云等
- **兼容性**v2 格式配置完全兼容,无需任何操作 3. 重启应用以应用
- ⚠️ **注意**:从 v3.1.0 或更早版本升级的用户,请先升级到 v3.2.x 或 v3.5.x 完成一次性迁移,再升级到 v3.6 4. 在其他设备上重复操作以启用跨设备同步
- **命令参数标准化**:后端统一使用 `app` 参数(取值:`claude``codex` > **注意**:首次启动会自动导入现有 Claude/Codex 配置作为默认供应商。
- **影响**:代码更规范,错误提示更友好
- **兼容性**:前端已完全适配,用户无需关心此变更
#### 启动失败与恢复 ## 架构总览
- 触发条件:`~/.cc-switch/config.json` 不存在、损坏或解析失败时触发。 ### 设计原则
- 用户动作:根据弹窗提示检查 JSON 语法,或从备份文件恢复。
- 备份位置与轮换:`~/.cc-switch/backups/backup_YYYYMMDD_HHMMSS.json`(最多保留 10 个,参见 `src-tauri/src/services/config.rs`)。
- 退出策略:为保护数据安全,出现上述错误时应用会弹窗提示并强制退出;修复后重新启动即可。
#### v3.2.0 起的迁移机制 ```
┌─────────────────────────────────────────────────────────────┐
│ 前端 (React + TS) │
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────────┐ │
│ │ Components │ │ Hooks │ │ TanStack Query │ │
│ │ (UI) │──│ (业务逻辑) │──│ (缓存/同步) │ │
│ └─────────────┘ └──────────────┘ └──────────────────┘ │
└────────────────────────┬────────────────────────────────────┘
│ Tauri IPC
┌────────────────────────▼────────────────────────────────────┐
│ 后端 (Tauri + Rust) │
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────────┐ │
│ │ Commands │ │ Services │ │ Models/Config │ │
│ │ (API 层) │──│ (业务层) │──│ (数据) │ │
│ └─────────────┘ └──────────────┘ └──────────────────┘ │
└─────────────────────────────────────────────────────────────┘
```
- 一次性迁移:首次启动 3.2.0 及以上版本会扫描旧的"副本文件"并合并到 `~/.cc-switch/config.json` **核心设计模式**
- Claude`~/.claude/settings-*.json`(排除 `settings.json` / 历史 `claude.json`
- Codex`~/.codex/auth-*.json``config-*.toml`(按名称成对合并)
- 去重与当前项:按"名称(忽略大小写)+ API Key"去重;若当前为空,将 live 合并项设为当前
- 归档与清理:
- 归档目录:`~/.cc-switch/archive/<timestamp>/<category>/...`
- 归档成功后删除原副本;失败则保留原文件(保守策略)
- v1 → v2 结构升级:会额外生成 `~/.cc-switch/config.v1.backup.<timestamp>.json` 以便回滚
- 注意:迁移后不再持续归档日常切换/编辑操作,如需长期审计请自备备份方案
## 架构总览v3.6 - **SSOT**(单一事实源):所有供应商配置存储在 `~/.cc-switch/config.json`
- **双向同步**:切换时写入 live 文件,编辑当前供应商时从 live 回填
- **原子写入**:临时文件 + 重命名模式防止配置损坏
- **并发安全**RwLock 与作用域守卫避免死锁
- **分层架构**清晰分离Commands → Services → Models
### 架构重构亮点v3.6 **核心组件**
**后端重构Rust**:完成 5 阶段重构 - **ProviderService**:供应商增删改查、切换、回填、排序
- **McpService**MCP 服务器管理、导入导出、live 文件同步
- **ConfigService**:配置导入导出、备份轮换
- **SpeedtestService**API 端点延迟测量
- **Phase 1**:统一错误处理(`AppError` + 国际化错误消息) **v3.6 重构**
- **Phase 2**:命令层按领域拆分(`commands/{provider,mcp,config,settings,plugin,misc}.rs`
- **Phase 3**:引入集成测试和事务机制(配置快照 + 失败回滚)
- **Phase 4**:提取 Service 层(`services/{provider,mcp,config,speedtest}.rs`
- **Phase 5**:并发优化(`RwLock` 替代 `Mutex`,作用域 guard 避免死锁)
**前端重构React + TypeScript**:完成 4 阶段重构 - 后端5 阶段重构(错误处理 → 命令拆分 → 测试 → 服务 → 并发)
- 前端4 阶段重构(测试基础 → hooks → 组件 → 清理)
- **Stage 1**建立测试基础设施vitest + MSW + @testing-library/react - 测试100% hooks 覆盖 + 集成测试vitest + MSW
- **Stage 2**:提取自定义 hooks`useProviderActions`, `useMcpActions`, `useSettings`, `useImportExport` 等)
- **Stage 3**:组件拆分和业务逻辑提取
- **Stage 4**:代码清理和格式化统一
**测试覆盖**
- Hooks 单元测试 100% 覆盖
- 集成测试覆盖关键流程App、SettingsDialog、MCP 面板)
- MSW 模拟后端 API确保测试独立性
### 分层架构
- **前端Renderer**
- 技术栈TypeScript + React 18 + Vite + TailwindCSS 4
- 数据层TanStack React Query 统一查询与变更(`@/lib/query`Tauri API 统一封装(`@/lib/api`
- 业务逻辑层:自定义 Hooks`@/hooks`)承载领域逻辑,组件保持简洁
- 事件流:监听后端 `provider-switched` 事件,驱动 UI 刷新与托盘状态一致
- 组织结构:按领域拆分组件(`providers/settings/mcp/ui`
- **后端Tauri + Rust**
- **Commands 层**(接口层):`src-tauri/src/commands/*` 按领域拆分,仅负责参数解析和权限校验
- **Services 层**(业务层):`src-tauri/src/services/*` 承载核心逻辑,可复用和测试
- `ProviderService`:供应商增删改查、切换、回填、排序
- `McpService`MCP 服务器管理、导入导出、同步
- `ConfigService`:配置文件导入导出、备份恢复
- `SpeedtestService`API 端点延迟测试
- **模型与状态**
- `provider.rs`:领域模型(`Provider`, `ProviderManager`, `ProviderMeta`
- `app_config.rs`:多应用配置(`MultiAppConfig`, `AppId`, `McpRoot`
- `store.rs`:全局状态(`AppState` + `RwLock<MultiAppConfig>`
- **可靠性**
- 统一错误类型 `AppError`(包含本地化消息)
- 事务式变更(配置快照 + 失败回滚)
- 原子写入(临时文件 + 重命名,避免半写入)
- 托盘菜单与事件:切换后重建菜单并向前端发射 `provider-switched` 事件
- **设计要点SSOT + 双向同步)**
- **单一事实源**:供应商配置集中存放于 `~/.cc-switch/config.json`
- **切换时写入**:将目标供应商配置写入 live 文件Claude: `settings.json`Codex: `auth.json` + `config.toml`
- **回填机制**:切换后立即读回 live 文件,更新 SSOT保护用户手动修改
- **目录切换同步**修改配置目录时自动同步当前供应商到新目录WSL 环境完美支持)
- **编辑时优先 live**:编辑当前供应商时,优先加载 live 配置,确保显示实际生效的配置
- **兼容性与变更**
- 命令参数统一Tauri 命令仅接受 `app`(值为 `claude` / `codex`
- 前端类型统一:使用 `AppId` 表达应用标识(替代历史 `AppType` 导出)
## 开发 ## 开发
@@ -363,12 +264,12 @@ cargo test --features test-hooks
**测试覆盖** **测试覆盖**
- Hooks 单元测试100% 覆盖) - Hooks 单元测试100% 覆盖)
- `useProviderActions` - 供应商操作 - `useProviderActions` - 供应商操作
- `useMcpActions` - MCP 管理 - `useMcpActions` - MCP 管理
- `useSettings` 系列 - 设置管理 - `useSettings` 系列 - 设置管理
- `useImportExport` - 导入导出 - `useImportExport` - 导入导出
- 集成测试 - 集成测试
- App 主应用流程 - App 主应用流程
- SettingsDialog 完整交互 - SettingsDialog 完整交互
- MCP 面板功能 - MCP 面板功能
@@ -388,120 +289,36 @@ pnpm test:unit --coverage
## 技术栈 ## 技术栈
### 前端 **前端**React 18 · TypeScript · Vite · TailwindCSS 4 · TanStack Query v5 · react-i18next · react-hook-form · zod · shadcn/ui · @dnd-kit
- **[React 18](https://react.dev/)** - 用户界面库 **后端**Tauri 2.8 · Rust · serde · tokio · thiserror · tauri-plugin-updater/process/dialog/store/log
- **[TypeScript](https://www.typescriptlang.org/)** - 类型安全的 JavaScript
- **[Vite](https://vitejs.dev/)** - 极速的前端构建工具
- **[TailwindCSS 4](https://tailwindcss.com/)** - 实用优先的 CSS 框架
- **[TanStack Query v5](https://tanstack.com/query/latest)** - 强大的数据获取与缓存
- **[react-i18next](https://react.i18next.com/)** - React 国际化框架
- **[react-hook-form](https://react-hook-form.com/)** - 高性能表单库
- **[zod](https://zod.dev/)** - TypeScript 优先的模式验证
- **[shadcn/ui](https://ui.shadcn.com/)** - 可复用的 React 组件
- **[@dnd-kit](https://dndkit.com/)** - 现代拖拽工具包
### 后端 **测试**vitest · MSW · @testing-library/react
- **[Tauri 2.8](https://tauri.app/)** - 跨平台桌面应用框架
- tauri-plugin-updater - 自动更新
- tauri-plugin-process - 进程管理
- tauri-plugin-dialog - 文件对话框
- tauri-plugin-store - 持久化存储
- tauri-plugin-log - 日志记录
- **[Rust](https://www.rust-lang.org/)** - 系统级编程语言
- **[serde](https://serde.rs/)** - 序列化/反序列化框架
- **[tokio](https://tokio.rs/)** - 异步运行时
- **[thiserror](https://github.com/dtolnay/thiserror)** - 错误处理派生宏
### 测试工具
- **[vitest](https://vitest.dev/)** - 快速的单元测试框架
- **[MSW](https://mswjs.io/)** - API mock 工具
- **[@testing-library/react](https://testing-library.com/react)** - React 测试工具
## 项目结构 ## 项目结构
``` ```
├── src/ # 前端代码 (React + TypeScript) ├── src/ # 前端 (React + TypeScript)
│ ├── components/ # React 组件 │ ├── components/ # UI 组件 (providers/settings/mcp/ui)
│ ├── providers/ # 供应商管理组件 │ ├── hooks/ # 自定义 hooks (业务逻辑)
│ │ │ ├── forms/ # 表单子组件Claude/Codex 字段)
│ │ │ ├── ProviderList.tsx
│ │ │ ├── ProviderForm.tsx
│ │ │ ├── AddProviderDialog.tsx
│ │ │ └── EditProviderDialog.tsx
│ │ ├── settings/ # 设置相关组件
│ │ │ ├── SettingsDialog.tsx
│ │ │ ├── DirectorySettings.tsx
│ │ │ └── ImportExportSection.tsx
│ │ ├── mcp/ # MCP 管理组件
│ │ │ ├── McpPanel.tsx
│ │ │ ├── McpFormModal.tsx
│ │ │ └── McpWizard.tsx
│ │ └── ui/ # shadcn/ui 基础组件
│ ├── hooks/ # 自定义 Hooks业务逻辑层
│ │ ├── useProviderActions.ts # 供应商操作
│ │ ├── useMcpActions.ts # MCP 操作
│ │ ├── useSettings.ts # 设置管理
│ │ ├── useImportExport.ts # 导入导出
│ │ └── useDirectorySettings.ts # 目录配置
│ ├── lib/ │ ├── lib/
│ │ ├── api/ # Tauri API 封装(类型安全) │ │ ├── api/ # Tauri API 封装(类型安全)
│ │ │ ├── providers.ts # 供应商 API
│ │ │ ├── settings.ts # 设置 API
│ │ │ ├── mcp.ts # MCP API
│ │ │ └── usage.ts # 用量查询 API
│ │ └── query/ # TanStack Query 配置 │ │ └── query/ # TanStack Query 配置
│ ├── queries.ts # 查询定义 ├── i18n/locales/ # 翻译 (zh/en)
│ ├── mutations.ts # 变更定义 ├── config/ # 预设 (providers/mcp)
│ │ └── queryClient.ts
│ ├── i18n/ # 国际化资源
│ │ └── locales/
│ │ ├── zh/ # 中文翻译
│ │ └── en/ # 英文翻译
│ ├── config/ # 配置与预设
│ │ ├── claudeProviderPresets.ts # Claude 供应商预设
│ │ ├── codexProviderPresets.ts # Codex 供应商预设
│ │ └── mcpPresets.ts # MCP 服务器模板
│ ├── utils/ # 工具函数
│ │ ├── postChangeSync.ts # 配置同步工具
│ │ └── ...
│ └── types/ # TypeScript 类型定义 │ └── types/ # TypeScript 类型定义
├── src-tauri/ # 后端代码 (Rust) ├── src-tauri/ # 后端 (Rust)
── src/ ── src/
├── commands/ # Tauri 命令层(按领域拆分 ├── commands/ # Tauri 命令层(按领域)
│ │ ├── provider.rs # 供应商命令 ├── services/ # 业务逻辑层
│ │ ├── mcp.rs # MCP 命令 ├── app_config.rs # 配置数据模型
│ │ ├── config.rs # 配置查询命令 ├── provider.rs # 供应商领域模型
│ │ ├── settings.rs # 设置命令 ├── mcp.rs # MCP 同步与校验
│ ├── plugin.rs # 插件命令 └── lib.rs # 应用入口 & 托盘菜单
├── import_export.rs # 导入导出命令 ├── tests/ # 前端测试
└── misc.rs # 杂项命令 ├── hooks/ # 单元测试
│ ├── services/ # Service 层(业务逻辑) └── components/ # 集成测试
├── provider.rs # ProviderService └── assets/ # 截图 & 合作商资源
│ │ │ ├── mcp.rs # McpService
│ │ │ ├── config.rs # ConfigService
│ │ │ └── speedtest.rs # SpeedtestService
│ │ ├── app_config.rs # 配置数据模型
│ │ ├── provider.rs # 供应商领域模型
│ │ ├── store.rs # 全局状态管理
│ │ ├── mcp.rs # MCP 同步与校验
│ │ ├── error.rs # 统一错误类型
│ │ ├── usage_script.rs # 用量脚本执行
│ │ ├── claude_plugin.rs # Claude 插件管理
│ │ └── lib.rs # 应用入口
│ ├── capabilities/ # Tauri 权限配置
│ └── icons/ # 应用图标
├── tests/ # 前端测试v3.6 新增)
│ ├── hooks/ # Hooks 单元测试
│ ├── components/ # 组件集成测试
│ └── setup.ts # 测试配置
└── assets/ # 静态资源
├── screenshots/ # 界面截图
└── partners/ # 合作商资源
├── logos/ # 合作商 Logo
└── banners/ # 合作商横幅/宣传图
``` ```
## 更新日志 ## 更新日志

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

View File

@@ -248,7 +248,7 @@ export const providerPresets: ProviderPreset[] = [
{ {
name: "PackyCode", name: "PackyCode",
websiteUrl: "https://www.packyapi.com", websiteUrl: "https://www.packyapi.com",
apiKeyUrl: "https://www.packyapi.com", apiKeyUrl: "https://www.packyapi.com/register?aff=cc-switch",
settingsConfig: { settingsConfig: {
env: { env: {
ANTHROPIC_BASE_URL: "https://www.packyapi.com", ANTHROPIC_BASE_URL: "https://www.packyapi.com",
@@ -261,6 +261,8 @@ export const providerPresets: ProviderPreset[] = [
"https://api-slb.packyapi.com", "https://api-slb.packyapi.com",
], ],
category: "third_party", category: "third_party",
isPartner: true, // 合作伙伴
partnerPromotionKey: "packycode", // 促销信息 i18n key
}, },
{ {
name: "AnyRouter", name: "AnyRouter",

View File

@@ -128,6 +128,7 @@ requires_openai_auth = true`,
{ {
name: "PackyCode", name: "PackyCode",
websiteUrl: "https://www.packyapi.com", websiteUrl: "https://www.packyapi.com",
apiKeyUrl: "https://www.packyapi.com/register?aff=cc-switch",
category: "third_party", category: "third_party",
auth: generateThirdPartyAuth(""), auth: generateThirdPartyAuth(""),
config: generateThirdPartyConfig( config: generateThirdPartyConfig(
@@ -139,6 +140,8 @@ requires_openai_auth = true`,
"https://www.packyapi.com/v1", "https://www.packyapi.com/v1",
"https://api-slb.packyapi.com/v1", "https://api-slb.packyapi.com/v1",
], ],
isPartner: true, // 合作伙伴
partnerPromotionKey: "packycode", // 促销信息 i18n key
}, },
{ {
name: "AnyRouter", name: "AnyRouter",

View File

@@ -241,7 +241,8 @@
"officialHint": "💡 Official provider uses browser login, no API Key needed", "officialHint": "💡 Official provider uses browser login, no API Key needed",
"getApiKey": "Get API Key", "getApiKey": "Get API Key",
"partnerPromotion": { "partnerPromotion": {
"zhipu": "Zhipu GLM is an official partner of CC Switch. Use this link to top up and get a 10% discount" "zhipu": "Zhipu GLM is an official partner of CC Switch. Use this link to top up and get a 10% discount",
"packycode": "PackyCode is an official partner of CC Switch. Register using this link and enter \"cc-switch\" promo code during recharge to get 10% off"
}, },
"parameterConfig": "Parameter Config - {{name}} *", "parameterConfig": "Parameter Config - {{name}} *",
"mainModel": "Main Model (optional)", "mainModel": "Main Model (optional)",

View File

@@ -241,7 +241,8 @@
"officialHint": "💡 官方供应商使用浏览器登录,无需配置 API Key", "officialHint": "💡 官方供应商使用浏览器登录,无需配置 API Key",
"getApiKey": "获取 API Key", "getApiKey": "获取 API Key",
"partnerPromotion": { "partnerPromotion": {
"zhipu": "智谱 GLM 是 CC Switch 的官方合作伙伴使用此链接充值可以获得9折优惠" "zhipu": "智谱 GLM 是 CC Switch 的官方合作伙伴使用此链接充值可以获得9折优惠",
"packycode": "PackyCode 是 CC Switch 的官方合作伙伴,使用此链接注册并在充值时填写 \"cc-switch\" 优惠码可以享受9折优惠"
}, },
"parameterConfig": "参数配置 - {{name}} *", "parameterConfig": "参数配置 - {{name}} *",
"mainModel": "主模型 (可选)", "mainModel": "主模型 (可选)",