Migrate the Claude common config snippet storage from browser localStorage
to the persistent config.json file for better cross-device sync and backup support.
**Backend Changes:**
- Add `claude_common_config_snippet` field to `MultiAppConfig` struct
- Add `get_claude_common_config_snippet` and `set_claude_common_config_snippet` Tauri commands
- Include JSON validation in the setter command
**Frontend Changes:**
- Create new `lib/api/config.ts` API module
- Refactor `useCommonConfigSnippet` hook to use config.json instead of localStorage
- Add automatic one-time migration from localStorage to config.json
- Add loading state during initialization
**Benefits:**
- Cross-device synchronization via backup/restore
- More reliable persistence than browser storage
- Centralized configuration management
- Seamless migration for existing users
Address code review feedback for PR #214:
- Replace hardcoded Chinese strings with English in auto-imported prompts
- Prompt name: "Auto-imported Prompt" instead of "初始提示词"
- Description: "Automatically imported on first launch"
- Remove panic risk by replacing expect() with proper error propagation
- Use AppError::localized for bilingual error messages
- Extract get_base_dir_with_fallback() helper to eliminate code duplication
- Update test assertions to match new English strings
- Suppress false-positive dead_code warning on TempHome.dir field
All 5 tests passing with zero compiler warnings.
- Extract prompt file path logic to dedicated prompt_files module
- Refactor PromptService to use centralized path resolution
- Implement auto-import for existing prompt files on first startup
- Add comprehensive unit tests for auto-import functionality
Allow users to create Gemini provider configurations without API key
and fill it in later. Split validation into two modes:
- validate_gemini_settings: Basic structure check (used when adding)
- validate_gemini_settings_strict: Full validation (used when switching)
This fixes the error 'Gemini config missing required field: GEMINI_API_KEY'
when trying to add Gemini providers from presets like PackyCode or Google.
Changes:
- Add validate_gemini_settings_strict for switching validation
- Update write_gemini_live to use strict validation
- Add comprehensive tests for both validation modes
Refactor tray menu system to support three applications (Claude/Codex/Gemini):
- Introduce generic TrayAppSection structure and TRAY_SECTIONS array
- Implement append_provider_section and handle_provider_tray_event helper functions
- Enhance Gemini provider service with .env config read/write support
- Implement Gemini LiveSnapshot for atomic operations and rollback
- Update README documentation to reflect Gemini tray quick switching feature
* feat(prompts): add prompt management across Tauri service and React UI
- backend: add commands/prompt.rs, services/prompt.rs, register in commands/mod.rs and lib.rs, refine app_config.rs
- frontend: add PromptPanel, PromptFormModal, PromptListItem, MarkdownEditor, usePromptActions, integrate in App.tsx
- api: add src/lib/api/prompts.ts
- i18n: update src/i18n/locales/{en,zh}.json
- build: update package.json and pnpm-lock.yaml
* feat(i18n): improve i18n for prompts and Markdown editor
- update src/i18n/locales/{en,zh}.json keys and strings
- apply i18n in PromptFormModal, PromptPanel, and MarkdownEditor
- align prompt text with src-tauri/src/services/prompt.rs
* feat(prompts): add enable/disable toggle and simplify panel UI
- Add PromptToggle component and integrate in prompt list items
- Implement toggleEnabled with optimistic update; enable via API, disable via upsert with enabled=false;
reload after success
- Simplify PromptPanel: remove file import and current-file preview to keep CRUD flow focused
- Tweak header controls style (use mcp variant) and minor copy: rename “Prompt Management” to “Prompts”
- i18n: add disableSuccess/disableFailed messages
- Backend (Tauri): prevent duplicate backups when importing original prompt content
* style: unify code formatting with trailing commas
* feat(prompts): add Gemini filename support to PromptFormModal
Update filename mapping to use Record<AppId, string> pattern, supporting
GEMINI.md alongside CLAUDE.md and AGENTS.md.
* fix(prompts): sync enabled prompt to file when updating
When updating a prompt that is currently enabled, automatically sync
the updated content to the corresponding live file (CLAUDE.md/AGENTS.md/GEMINI.md).
This ensures the active prompt file always reflects the latest content
when editing enabled prompts.
Add independent credential fields for usage query to support different
query endpoints and authentication methods.
Changes:
- Add `apiKey` and `baseUrl` fields to UsageScript struct
- Remove dependency on provider config credentials in query_usage
- Update test_usage_script to accept independent credential parameters
- Add credential input fields in UsageScriptModal based on template:
* General: apiKey + baseUrl
* NewAPI: baseUrl + accessToken + userId
* Custom: no additional fields (full freedom)
- Auto-clear irrelevant fields when switching templates
- Add i18n text for "credentialsConfig"
Benefits:
- Query API can use different endpoint/key than provider config
- Better separation of concerns
- More flexible for various usage query scenarios
Replace unwrap() calls with safe pattern matching to prevent panics
when handling invalid tray menu item IDs. Now logs errors and returns
gracefully instead of crashing the application.
Ensure that when importing default configuration from live files,
the created provider is properly marked with category "custom" for
correct UI display and filtering.
- Format code in app_config.rs to comply with rustfmt rules
- Remove extra blank line in config.rs
- Format test code in app_config_load.rs for consistency
- Remove 5 unused functions that were left over from migration refactoring:
- get_archive_root, ensure_unique_path, archive_file (config.rs)
- read_config_text_from_path, read_and_validate_config_from_path (codex_config.rs)
- Simplify is_v1 check using is_some_and instead of map_or for better readability
- Remove outdated comments about removed functions
This eliminates all dead_code warnings and improves code maintainability.
Remove the entire migration module (435 lines) that was used for
one-time migration from v3.1.0 to v3.2.0. This cleans up technical
debt and improves startup performance.
Changes:
- Delete src-tauri/src/migration.rs (copy file scanning and merging)
- Remove migration module reference from lib.rs
- Simplify startup logic to only ensure config structure exists
- Remove automatic deduplication and archiving logic
BREAKING CHANGE: Users upgrading from v3.1.0 must first upgrade to
v3.2.x to automatically migrate their configurations.
BREAKING CHANGE: Runtime auto-migration from v1 to v2 config format has been removed.
Changes:
- Remove automatic v1→v2 migration logic from MultiAppConfig::load()
- Improve v1 detection using structural analysis (checks for 'apps' key absence)
- Return clear error with migration instructions when v1 config is detected
- Add comprehensive tests for config loading edge cases
- Fix false positive detection when v1 config contains 'version' or 'mcp' fields
Migration path for users:
1. Install v3.2.x to perform one-time auto-migration, OR
2. Manually edit ~/.cc-switch/config.json to v2 format
Rationale:
- Separates concerns: load() should be read-only, not perform side effects
- Fail-fast principle: unsupported formats should error immediately
- Simplifies code maintenance by removing migration logic from hot path
Tests added:
- load_v1_config_returns_error_and_does_not_write
- load_v1_with_extra_version_still_treated_as_v1
- load_invalid_json_returns_parse_error_and_does_not_write
- load_valid_v2_config_succeeds
Breaking Changes:
- Removed useAutoUsageQuery hook (119 lines)
- Unified all usage queries into single useUsageQuery hook
Technical Improvements:
- Eliminated duplicate state management (React Query + manual useState)
- Fixed single source of truth principle violation
- Replaced manual setInterval with React Query's built-in refetchInterval
- Reduced UsageFooter complexity by 28% (54 → 39 lines)
New Features:
- useUsageQuery now accepts autoQueryInterval option
- Automatic query interval control (0 = disabled, min 1 minute)
- Built-in lastQueriedAt timestamp from dataUpdatedAt
- Auto-query only enabled for currently active provider
Architecture Benefits:
- Single data source: manual and auto queries share same cache
- No more state inconsistency between manual/auto query results
- Leverages React Query's caching, deduplication, and background updates
- Cleaner separation of concerns
Code Changes:
- src/lib/query/queries.ts: Enhanced useUsageQuery with auto-query support
- src/components/UsageFooter.tsx: Simplified to use single query hook
- src/hooks/useAutoUsageQuery.ts: Deleted (redundant)
- All type checks passed
New Features:
- Users can configure auto-query interval in "Configure Usage Query" dialog
- Interval in minutes (0 = disabled, recommend 5-60 minutes)
- Auto-query only enabled for currently active provider
- Display last query timestamp in relative time format (e.g., "5 min ago")
- Execute first query immediately when enabled, then repeat at intervals
Technical Implementation:
- Backend: Add auto_query_interval field to UsageScript struct
- Frontend: Create useAutoUsageQuery Hook to manage timers and query state
- UI: Add auto-query interval input field in UsageScriptModal
- Integration: Display auto-query results and timestamp in UsageFooter
- i18n: Add Chinese and English translations
UX Improvements:
- Minimum interval protection (1 minute) to prevent API abuse
- Auto-cleanup timers on component unmount
- Silent failure handling for auto-queries, non-intrusive to users
- Prioritize auto-query results, fallback to manual query results
- Timestamp display positioned next to refresh button for better clarity
Fixed 5 hardcoded Chinese error messages to support bilingual display:
Backend changes (services):
- provider.rs: Fixed 4 error messages:
* Data format error when deserializing array (line 731)
* Data format error when deserializing single object (line 738)
* Regex initialization failure (line 1163)
* App type not found (line 1191)
- speedtest.rs: Fixed 1 error message:
* HTTP client creation failure (line 104)
All errors now use AppError::localized to provide both Chinese and English messages.
Impact:
- Users will now see properly localized error messages when testing usage scripts
- Error messages respect the application language setting
- Better user experience for English-speaking users
Fully internationalized the usage query feature to support both Chinese and English.
Frontend changes:
- Refactored UsageScriptModal to use i18n translation keys
- Replaced hardcoded Chinese template names with constants
- Implemented dynamic template generation with i18n support
- Internationalized all labels, placeholders, and code comments
- Added template name mapping for translation
Backend changes:
- Replaced all hardcoded Chinese error messages in usage_script.rs
- Converted 33 error instances from AppError::Message to AppError::localized
- Added bilingual error messages for runtime, parsing, HTTP, and validation errors
Translation updates:
- Added 11 new translation key pairs to zh.json and en.json
- Covered template names, field labels, placeholders, and code comments
Impact:
- 100% i18n coverage for usage query functionality
- All user-facing text and error messages now support language switching
- Better user experience for English-speaking users
- Add private helper method `execute_and_format_usage_result` to eliminate code duplication
- Refactor `query_usage` to use helper method instead of duplicating result processing
- Add new `test_usage_script` method to test temporary script without saving
- Add backend command `test_usage_script` accepting script content as parameter
- Register new command in lib.rs invoke_handler
- Add frontend `usageApi.testScript` method to call the new backend API
- Update `UsageScriptModal.handleTest` to test current editor content instead of saved script
- Improve DX: users can now test script changes before saving
Implement Solution A (complete deferred submission) for custom endpoint
management, replacing the dual-mode system with unified local staging.
Changes:
- Remove immediate backend saves from EndpointSpeedTest
* handleAddEndpoint: local state update only
* handleRemoveEndpoint: local state update only
* handleSelect: remove lastUsed timestamp update
- Add explicit clear detection in ProviderForm
* Distinguish "user cleared endpoints" from "user didn't modify"
* Pass empty object {} as clear signal vs null for no-change
- Fix mergeProviderMeta to handle three distinct cases:
* null/undefined: don't modify endpoints (no meta sent)
* empty object {}: explicitly clear endpoints (send empty meta)
* with data: add/update endpoints (overwrite)
Fixed Critical Bug:
When users deleted all custom endpoints, changes were not saved because:
- draftCustomEndpoints=[] resulted in customEndpointsToSave=null
- mergeProviderMeta(meta, null) returned undefined
- Backend interpreted missing meta as "don't modify", preserving old values
Solution:
Detect when user had endpoints and cleared them (hadEndpoints && length===0),
then pass empty object to mergeProviderMeta as explicit clear signal.
Architecture Improvements:
- Transaction atomicity: all fields submitted together on form save
- UX consistency: add/edit modes behave identically
- Cancel button: true rollback with no immediate saves
- Code simplification: removed ~40 lines of immediate save error handling
Testing:
- TypeScript type check: passed
- Rust backend tests: 10/10 passed
- Build: successful
Add optional accessToken and userId fields to usage query scripts,
enabling queries to authenticated endpoints like /api/user/self.
Changes:
- Add accessToken and userId fields to UsageScript type (frontend & backend)
- Extend script engine to support {{accessToken}} and {{userId}} placeholders
- Update NewAPI preset template to use /api/user/self endpoint
- Add UI inputs for access token and user ID in UsageScriptModal
- Pass new parameters through service layer to script executor
This allows users to query usage data from endpoints that require
login credentials, providing more accurate balance information for
services like NewAPI/OneAPI platforms.
The Tauri command `get_init_error` was importing a function with the
same name from `init_status` module, causing a compile-time error:
"the name `get_init_error` is defined multiple times".
Changes:
- Remove `get_init_error` from the use statement in misc.rs
- Use fully qualified path `crate::init_status::get_init_error()`
in the command implementation to call the underlying function
This eliminates the ambiguity while keeping the public API unchanged.
This commit introduces fail-fast error handling for config loading failures,
replacing the previous silent fallback to default config which could cause
data loss (e.g., all user providers disappearing).
Key changes:
Backend (Rust):
- Replace AppState::new() with AppState::try_new() to explicitly propagate errors
- Remove Default trait to prevent accidental empty state creation
- Add init_status module as global error cache (OnceLock + RwLock)
- Implement dual-channel error notification:
1. Event emission (low-latency, may race with frontend subscription)
2. Command-based polling (reliable, guaranteed delivery)
- Remove unconditional save on startup to prevent overwriting corrupted config
Frontend (TypeScript):
- Add event listener for "configLoadError" (fast path)
- Add bootstrap-time polling via get_init_error command (reliable path)
- Display detailed error dialog with recovery instructions
- Prompt user to exit for manual repair
Impact:
- First-time users: No change (load() returns Ok(default) when file missing)
- Corrupted config: Application shows error and exits gracefully
- Prevents accidental config overwrite during initialization
Fixes the only critical issue identified in previous code review (silent
fallback causing data loss).
This commit addresses parameter naming inconsistencies caused by Tauri v2's
requirement for camelCase parameter names in IPC commands.
Backend changes (Rust):
- Updated all command parameters from snake_case to camelCase
- Commands affected:
* provider.rs: providerId (×4), timeoutSecs
* import_export.rs: filePath (×2), defaultName
* config.rs: defaultPath
- Added #[allow(non_snake_case)] attributes for camelCase parameters
- Removed unused QueryUsageParams struct
Frontend changes (TypeScript):
- Removed redundant snake_case parameters from all invoke() calls
- Updated API files:
* usage.ts: removed debug logs, unified to providerId
* vscode.ts: updated 8 functions (providerId, timeoutSecs, filePath, defaultName)
* settings.ts: updated 4 functions (defaultPath, filePath, defaultName)
- Ensured all parameters now use camelCase exclusively
Test updates:
- Updated MSW handlers to accept both old and new parameter formats during transition
- Added i18n mock compatibility for tests
Root cause:
The issue stemmed from Tauri v2 strictly requiring camelCase for command
parameters, while the codebase was using snake_case. This caused parameters
like 'provider_id' to not be recognized by the backend, resulting in
"missing providerId parameter" errors.
BREAKING CHANGE: All Tauri command invocations now require camelCase parameters.
Any external tools or scripts calling these commands must be updated accordingly.
Fixes: Usage query always failing with "missing providerId" error
Fixes: Custom endpoint management not receiving provider ID
Fixes: Import/export dialogs not respecting default paths
Add compatibility for providers that use ANTHROPIC_API_KEY instead of
ANTHROPIC_AUTH_TOKEN, enabling support for AiHubMix and similar services.
Changes:
- Backend: Add fallback to ANTHROPIC_API_KEY in credential extraction
- migration.rs: Support API_KEY during config migration
- services/provider.rs: Extract credentials from either field
- Frontend: Smart API key field detection and management
- getApiKeyFromConfig: Read from either field (AUTH_TOKEN priority)
- setApiKeyInConfig: Write to existing field, preserve user choice
- hasApiKeyField: Detect presence of either field
- Add AiHubMix provider preset with dual endpoint candidates
- Define apiKeyField metadata for provider presets (documentation)
Technical Details:
- Uses or_else() for zero-cost field fallback in Rust
- Runtime field detection ensures correct field name preservation
- Maintains backward compatibility with existing configurations
- Priority: ANTHROPIC_AUTH_TOKEN > ANTHROPIC_API_KEY
Upgrade Claude model configuration from dual-key to quad-key system for
better model tier differentiation.
**Breaking Changes:**
- Replace `ANTHROPIC_SMALL_FAST_MODEL` with three granular keys:
- `ANTHROPIC_DEFAULT_HAIKU_MODEL`
- `ANTHROPIC_DEFAULT_SONNET_MODEL`
- `ANTHROPIC_DEFAULT_OPUS_MODEL`
**Backend (Rust):**
- Add `normalize_claude_models_in_value()` for automatic migration
- Implement fallback chain: `DEFAULT_* || SMALL_FAST || MODEL`
- Auto-cleanup: remove legacy `SMALL_FAST` key after normalization
- Apply normalization across 6 critical paths:
- Add/update provider
- Read from live config
- Write to live config
- Refresh config snapshot
**Frontend (React):**
- Expand UI from 2 to 4 model input fields
- Implement smart fallback in `useModelState` hook
- Update `useKimiModelSelector` for Kimi model picker
- Add i18n keys for Haiku/Sonnet/Opus labels (zh/en)
**Configuration:**
- Update all 7 provider presets to new format
- DeepSeek/Qwen/Moonshot: use same model for all tiers
- Zhipu: preserve tier differentiation (glm-4.5-air for Haiku)
**Backward Compatibility:**
- Old configs auto-upgrade on first read/write
- Fallback chain ensures graceful degradation
- No manual migration required
Closes #[issue-number]
This commit implements a three-layer fix to restore the "Sync to other side"
feature when adding or editing MCP servers across Claude and Codex.
Root Cause Analysis:
1. Frontend issue: New MCP entries had their `enabled` field deleted
2. Backend issue: Default value was `false` when `enabled` was missing
3. Core issue: MCP entries were never copied to the other app's servers
Changes:
Frontend (McpFormModal.tsx):
- Set `enabled=true` by default for new MCP entries
- Preserve existing `enabled` state when editing
Backend (services/mcp.rs):
- Change default value from `unwrap_or(false)` to `unwrap_or(true)`
- Implement cross-app MCP replication when `sync_other_side=true`
- Clone MCP entry to other app's servers before syncing to live files
Impact:
- "Sync to Codex" checkbox now correctly adds MCP to both Claude and Codex
- "Sync to Claude" checkbox now correctly adds MCP to both Codex and Claude
- Both config.json and live files (~/.claude.json, ~/.codex/config.toml) are updated
- Fixes regression introduced during project restructure
Tested:
- TypeScript type checking passed
- Rust clippy linting passed
- Manual testing: MCP sync works bidirectionally
- Implement TrayTexts struct to manage multilingual tray menu text
- Auto-refresh tray menu when language settings change
- Add missing notification message translations
- Format code for consistency
Replace the previous dual-parameter approach (app_type/app/appType) with a single required `app: String` parameter across all Tauri commands. This change:
- Introduces unified `parse_app()` helper replacing complex `resolve_app_type()` logic
- Updates all backend commands in config, mcp, and provider modules
- Aligns frontend API calls to use consistent `app` parameter naming
- Simplifies MSW test handlers by removing optional parameter handling
This improves API clarity and reduces parameter ambiguity while maintaining backward compatibility through error handling.
Switch from `toml` to `toml_edit` crate for incremental TOML editing,
preserving user-written comments, whitespace, and key ordering in
Codex config.toml.
Changes:
- Add toml_edit 0.22 dependency for preserving-style TOML editing
- Refactor sync_enabled_to_codex() to use toml_edit::DocumentMut API
- Implement smart style detection: inherit existing mcp.servers or
mcp_servers style, with fallback to sensible defaults
- Add deduplication logic to prevent both styles coexisting
- Add tests for format preservation and style inheritance
- Fix unused_mut and nonminimal_bool compiler warnings
- Apply cargo fmt to all modified files
Benefits:
- User comments and formatting are no longer lost during sync
- Respects user's preferred TOML structure (nested vs toplevel)
- Non-MCP fields in config.toml remain untouched
- Minimal surprise principle: only modifies necessary sections
Testing:
- All 47 tests passing (unit + integration)
- Clippy clean (0 warnings, 0 errors)
- Release build successful
- New tests verify comment preservation and style detection
Add `resolve_app_type` helper to support both enum and string-based app type
parameters across all provider commands. This change:
- Eliminates implicit default to Claude (previously used `unwrap_or`)
- Supports two parameter forms: `app_type` (enum, priority 1) and `app` (string, priority 2)
- Provides explicit error handling when both parameters are missing
- Updates all 14 provider command functions with consistent parameter validation
- Fixes tray menu provider switching to pass the new `app` parameter
This dual-parameter approach maintains backward compatibility while enabling
future CLI tool integration and more flexible API usage patterns.
Technical details:
- Priority order: `app_type` enum > `app` string > error
- Invalid `app` strings now return errors instead of defaulting
- All existing tests pass (45/45)
This commit continues the backend refactoring initiative by extracting
configuration management and API speedtest logic into dedicated service
layers, completing phase 4 of the architectural improvement plan.
## Changes
### New Service Layers
- **ConfigService** (`services/config.rs`): Consolidates all config
import/export, backup management, and live sync operations
- `create_backup()`: Creates timestamped backups with auto-cleanup
- `export_config_to_path()`: Exports config to specified path
- `load_config_for_import()`: Loads and validates imported config
- `import_config_from_path()`: Full import with state update
- `sync_current_providers_to_live()`: Syncs current providers to live files
- Private helpers for Claude/Codex-specific sync logic
- **SpeedtestService** (`services/speedtest.rs`): Encapsulates endpoint
latency testing with proper validation and error handling
- `test_endpoints()`: Tests multiple URLs concurrently
- URL validation now unified in service layer
- Includes 3 unit tests for edge cases (empty list, invalid URLs, timeout clamping)
### Command Layer Refactoring
- Move all import/export commands to `commands/import_export.rs`
- Commands become thin wrappers: parse params → call service → return JSON
- Maintain `spawn_blocking` for I/O operations (phase 5 optimization)
- Lock acquisition happens after I/O completes (minimize contention)
### File Organization
- Delete: `import_export.rs`, `speedtest.rs` (root-level modules)
- Create: `commands/import_export.rs`, `services/config.rs`, `services/speedtest.rs`
- Update: Module declarations in `lib.rs`, `commands/mod.rs`, `services/mod.rs`
### Test Updates
- Update 20 integration tests in `import_export_sync.rs` to use `ConfigService` APIs
- All existing test cases pass without modification to test logic
- Add 3 new unit tests for `SpeedtestService`:
- `sanitize_timeout_clamps_values`: Boundary value testing
- `test_endpoints_handles_empty_list`: Empty input handling
- `test_endpoints_reports_invalid_url`: Invalid URL error reporting
## Benefits
1. **Improved Testability**: Service methods are `pub fn`, easily callable
from tests without Tauri runtime
2. **Better Separation of Concerns**: Business logic isolated from
command/transport layer
3. **Enhanced Maintainability**: Related operations grouped in cohesive
service structs
4. **Consistent Error Handling**: Services return `Result<T, AppError>`,
commands convert to `Result<T, String>`
5. **Performance**: I/O operations run in `spawn_blocking`, locks released
before file operations
## Testing
- ✅ All 43 tests passing (7 unit + 36 integration)
- ✅ `cargo fmt --check` passes
- ✅ `cargo clippy -- -D warnings` passes (zero warnings)
## Documentation
Updated `BACKEND_REFACTOR_PLAN.md` to reflect completion of config and
speedtest service extraction, marking phase 4 substantially complete.
Co-authored-by: Claude Code <code@anthropic.com>
Extract all MCP business logic from command layer into `services/mcp.rs`,
implementing snapshot isolation pattern to optimize lock granularity after
RwLock migration in Phase 5.
## Key Changes
### Service Layer (`services/mcp.rs`)
- Add `McpService` with 7 methods: `get_servers`, `upsert_server`,
`delete_server`, `set_enabled`, `sync_enabled`, `import_from_claude`,
`import_from_codex`
- Implement snapshot isolation: acquire write lock only for in-memory
modifications, clone config snapshot, release lock, then perform file I/O
with snapshot
- Use conditional cloning: only clone config when sync is actually needed
(e.g., when `enabled` flag is true or `sync_other_side` is requested)
### Command Layer (`commands/mcp.rs`)
- Reduce to thin wrappers: parse parameters and delegate to `McpService`
- Remove all `*_internal` and `*_test_hook` functions (-94 lines)
- Each command now 5-10 lines (parameter parsing + service call + error mapping)
### Core Logic Refactoring (`mcp.rs`)
- Rename `set_enabled_and_sync_for` → `set_enabled_flag_for`
- Remove file sync logic from low-level function, move sync responsibility
to service layer for better separation of concerns
### Test Adaptation (`tests/mcp_commands.rs`)
- Replace test hooks with direct `McpService` calls
- All 5 MCP integration tests pass
### Additional Fixes
- Add `Default` impl for `AppState` (clippy suggestion)
- Remove unnecessary auto-deref in `commands/provider.rs` and `lib.rs`
- Update Phase 4/5 progress in `BACKEND_REFACTOR_PLAN.md`
## Performance Impact
**Before**: Write lock held during file I/O (~10ms), blocking all readers
**After**: Write lock held only for memory ops (~100μs), file I/O lock-free
Estimated throughput improvement: ~2x in high-concurrency read scenarios
## Testing
- ✅ All tests pass: 5 MCP commands + 7 provider service tests
- ✅ Zero clippy warnings with `-D warnings`
- ✅ No behavioral changes, maintains original save semantics
Part of Phase 4 (Service Layer Abstraction) of backend refactoring roadmap.
Replace Mutex with RwLock for AppState.config to enable concurrent reads,
improving performance for tray menu building and query operations that
previously blocked each other unnecessarily.
Key changes:
- Migrate AppState.config from Mutex<MultiAppConfig> to RwLock<MultiAppConfig>
- Distinguish read-only operations (read()) from mutations (write()) across
all command handlers and service layers
- Offload blocking file I/O in import/export commands to spawn_blocking threads,
minimizing lock hold time and preventing main thread blocking
- Extract load_config_for_import() to separate I/O logic from state updates
- Update all integration tests to use RwLock semantics
Performance impact:
- Concurrent reads: Multiple threads can now query config simultaneously
(tray menu, provider list, MCP config)
- Reduced contention: Write locks only acquired during actual mutations
- Non-blocking I/O: Config import/export no longer freezes UI thread
All existing tests pass with new locking semantics.
- Extract internal functions in commands/mcp.rs and commands/provider.rs
to enable unit testing without Tauri context
- Add test hooks: set_mcp_enabled_test_hook, import_mcp_from_claude_test_hook,
import_mcp_from_codex_test_hook, import_default_config_test_hook
- Migrate error types from String to AppError for precise error matching in tests
- Extend ProviderService with delete() method to unify Codex/Claude cleanup logic
- Add comprehensive test coverage:
- tests/mcp_commands.rs: command-level tests for MCP operations
- tests/provider_service.rs: service-level tests for switch/delete operations
- Run cargo fmt to fix formatting issues (EOF newlines)
- Update BACKEND_REFACTOR_PLAN.md to mark phase 3 complete
Architecture improvements:
- Extract ProviderService with switch/backfill/write methods
- Reduce command layer from 160 to 13 lines via delegation
- Separate business logic (services) from state management (commands)
- Introduce precise error handling with structured validation
Refactoring details:
- Split Codex/Claude switching into symmetric private methods
- Add multi-layer validation for Codex auth field (existence + type)
- Extract import_config_from_path for command and test reuse
- Expose export_config_to_file and ProviderService in public API
Test coverage:
- Add 10+ integration tests for Claude/Codex switching flows
- Cover import/export success and failure scenarios (JSON parse, missing file)
- Verify state consistency on error paths (current remains unchanged)
- Test snapshot backfill for both old and new providers after switching
Key improvements:
- Extract switch_provider_internal() returning AppError for better testability
- Fix backup mtime inheritance: use read+write instead of fs::copy to ensure latest backup survives cleanup
- Add 15+ integration tests covering provider commands, atomic writes, and rollback scenarios
- Expose write_codex_live_atomic, AppState, and test hooks in public API
- Extract tests/support.rs with isolated HOME and mutex utilities
Test coverage:
- Provider switching with live config backfill and MCP sync
- Codex atomic write success and failure rollback
- Backup retention policy with proper mtime ordering
- Negative cases: missing auth field, invalid provider ID
Expand test suite from 3 to 11 integration tests, adding comprehensive coverage
for Codex dual-file atomicity and bidirectional MCP synchronization:
New Codex sync tests:
- sync_codex_provider_writes_auth_and_config: validates atomic write of auth.json
and config.toml, plus SSOT backfill of latest toml content
- sync_enabled_to_codex_writes_enabled_servers: MCP projection to config.toml
- sync_enabled_to_codex_removes_servers_when_none_enabled: cleanup when all disabled
- sync_enabled_to_codex_returns_error_on_invalid_toml: error handling for malformed TOML
New Codex MCP import tests:
- import_from_codex_adds_servers_from_mcp_servers_table: imports new servers from live config
- import_from_codex_merges_into_existing_entries: smart merge preserving SSOT server configs
New Claude MCP tests:
- sync_claude_enabled_mcp_projects_to_user_config: enabled/disabled filtering for .claude.json
- import_from_claude_merges_into_config: intelligent merge preserving existing configurations
Expand lib.rs API exports:
- Codex paths: get_codex_auth_path, get_codex_config_path
- Claude MCP: get_claude_mcp_path
- MCP sync: sync_enabled_to_claude, sync_enabled_to_codex
- MCP import: import_from_claude, import_from_codex
- Error type: AppError (for test assertions)
Test infrastructure improvements:
- Enhanced reset_test_fs() to clean .claude.json
- All tests use isolated HOME directory with sequential execution via mutex
Test results: 11/11 passed
Files changed: 3 (+394/-6 lines)
Next steps: Command layer integration tests and error recovery scenarios