Commit Graph

73 Commits

  • refactor(backend): phase 4 - add test hooks and extend service layer
    - 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
  • refactor(backend): phase 4 - extract provider service layer
    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
  • refactor(backend): phase 3 - unify error handling and fix backup timestamp bug
    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
  • refactor(backend): phase 3 - expand integration tests for Codex and MCP sync
    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
  • refactor(backend): phase 3 - add integration tests for config sync (partial)
    Add integration test suite with isolated test environment:
    - New test file: tests/import_export_sync.rs (149 lines, 3 test cases)
      * sync_claude_provider_writes_live_settings: validates SSOT sync to live settings
      * create_backup_skips_missing_file: edge case handling for missing config
      * create_backup_generates_snapshot_file: verifies backup snapshot creation
    - Test infrastructure:
      * OnceLock-based isolated HOME directory in temp folder
      * Mutex guard to ensure sequential test execution (avoid file system race)
      * Automatic cleanup between test runs
    
    Export core APIs for testing (lib.rs):
    - AppType, MultiAppConfig, Provider (data structures)
    - get_claude_settings_path, read_json_file (config utilities)
    - create_backup, sync_current_providers_to_live (sync operations)
    - update_settings, AppSettings (settings management)
    
    Adjust visibility:
    - import_export::sync_current_providers_to_live: fn -> pub fn
    
    Update documentation:
    - Mark Phase 3 as in-progress (🚧) in BACKEND_REFACTOR_PLAN.md
    - Document current test coverage scope and pending scenarios
    
    Test results: 7/7 passed (4 unit + 3 integration)
    Build time: 0.16s
    
    Next steps:
    - Add Codex sync tests (auth.json + config.toml atomic writes)
    - Add MCP sync integration tests
    - Add end-to-end provider switching tests
  • refactor(backend): phase 2 - split commands.rs by domain (100%)
    Split monolithic commands.rs (1525 lines) into 7 domain-focused modules
    to improve maintainability and readability while preserving the external API.
    
    ## Changes
    
    ### Module Structure
    
    Created `commands/` directory with domain-based organization:
    
    - **provider.rs** (946 lines, 15 commands)
      - Provider CRUD operations (get, add, update, delete, switch)
      - Usage query integration
      - Endpoint speed testing and custom endpoint management
      - Sort order management
      - Largest file but highly cohesive (all provider-related)
    
    - **mcp.rs** (235 lines, 13 commands)
      - Claude MCP management (~/.claude.json)
      - SSOT MCP config management (config.json)
      - Sync operations (Claude ↔ Codex)
      - Import/export functionality
    
    - **config.rs** (153 lines, 8 commands)
      - Config path queries (Claude/Codex)
      - Directory operations (open, pick)
      - Config status checks
      - Parameter compatibility layer (app_type/app/appType)
    
    - **settings.rs** (40 lines, 5 commands)
      - App settings management
      - App restart functionality
      - app_config_dir override (Store integration)
    
    - **plugin.rs** (36 lines, 4 commands)
      - Claude plugin management (~/.claude/config.json)
      - Plugin status and config operations
    
    - **misc.rs** (45 lines, 3 commands)
      - External link handling
      - Update checks
      - Portable mode detection
    
    - **mod.rs** (15 lines)
      - Module exports via `pub use`
      - Preserves flat API structure
    
    ### API Preservation
    
    - Used `pub use` pattern to maintain external API
    - All commands still accessible as `commands::function_name`
    - Zero breaking changes for frontend code
    - lib.rs invoke_handler unchanged (48 commands registered)
    
    ## Statistics
    
    - Files: 1 → 7 (modular organization)
    - Lines: 1525 → 1470 (net -55 lines, -3.6%)
    - Commands: 48 → 48 (all preserved)
    - Average file size: 210 lines (excluding provider.rs)
    - Compilation:  Success (6.92s, 0 warnings)
    - Tests:  4/4 passed
    
    ## Benefits
    
    - **Maintainability**: Easier to locate and modify domain-specific code
    - **Readability**: Smaller files (~200 lines) vs monolithic 1500+ lines
    - **Testability**: Can unit test individual modules in isolation
    - **Scalability**: Clear pattern for adding new command groups
    - **Zero Risk**: No API changes, all tests passing
    
    ## Design Decisions
    
    1. **Domain-based split**: Organized by business domain (provider, mcp, config)
       rather than technical layers (crud, query, sync)
    
    2. **Preserved provider.rs size**: Kept at 946 lines to maintain high cohesion
       (all provider-related operations together). Can be further split in Phase 2.1
       if needed.
    
    3. **Parameter compatibility**: Retained multiple parameter names (app_type, app,
       appType) for backward compatibility with different frontend call styles
    
    ## Phase 2 Status:  100% Complete
    
    Ready for Phase 3: Adding integration tests.
    
    Co-authored-by: Claude <noreply@anthropic.com>
  • refactor(backend): phase 1 - unified error handling with thiserror
    Introduce AppError enum to replace Result<T, String> pattern across
    the codebase, improving error context preservation and type safety.
    
    ## Changes
    
    ### Core Infrastructure
    - Add src/error.rs with AppError enum using thiserror
    - Add thiserror dependency to Cargo.toml
    - Implement helper functions: io(), json(), toml() for ergonomic error creation
    - Implement From<PoisonError> for automatic lock error conversion
    - Implement From<AppError> for String to maintain Tauri command compatibility
    
    ### Module Migrations (60% complete)
    - config.rs: Full migration to AppError
      - read_json_file, write_json_file, atomic_write
      - archive_file, copy_file, delete_file
    - claude_mcp.rs: Full migration to AppError
      - get_mcp_status, read_mcp_json, upsert_mcp_server
      - delete_mcp_server, validate_command_in_path
      - set_mcp_servers_map
    - codex_config.rs: Full migration to AppError
      - write_codex_live_atomic with rollback support
      - read_and_validate_codex_config_text
      - validate_config_toml
    - app_config.rs: Partial migration
      - MultiAppConfig::load, MultiAppConfig::save
    - store.rs: Partial migration
      - AppState::save now returns Result<(), AppError>
    - commands.rs: Minimal changes
      - Use .map_err(Into::into) for compatibility
    - mcp.rs: Minimal changes
      - sync_enabled_to_claude uses Into::into conversion
    
    ### Documentation
    - Add docs/BACKEND_REFACTOR_PLAN.md with detailed refactoring roadmap
    
    ## Benefits
    - Type-safe error handling with preserved error chains
    - Better error messages with file paths and context
    - Reduced boilerplate code (118 Result<T, String> instances to migrate)
    - Automatic error conversion for seamless integration
    
    ## Testing
    - All existing tests pass (4/4)
    - Compilation successful with no warnings
    - Build time: 0.61s (no performance regression)
    
    ## Remaining Work
    - claude_plugin.rs (7 functions)
    - migration.rs, import_export.rs
    - Add unit tests for error.rs
    - Complete commands.rs migration after dependent modules
    
    Co-authored-by: Claude <claude@anthropic.com>
  • test: add frontend testing infrastructure with vitest
    - Introduce Vitest + React Testing Library + jsdom environment
    - Add useDragSort hook unit tests covering:
      * Sorting logic (sortIndex → createdAt → name)
      * Successful drag operation (API call + cache invalidation)
      * Failed drag operation (error toast display)
      * Edge case (no valid target, no API call)
    - Configure global test setup (i18n mock, auto cleanup)
    - Update TypeScript configs to include tests/ directory
    - Add test development plan documentation
    
    Test Coverage:
      ✓ Provider drag-and-drop sorting core logic
      ✓ React Query cache refresh
      ✓ Toast notification display
      ✓ Boundary condition handling
    
    Test Results: 4/4 passed (671ms)
    Next Steps: Sprint 2 - component tests with MSW mock layer
  • refactor: consolidate provider form components
    This commit completes Stage 2.5-2.6 of the refactoring plan by:
    
    - Consolidating 8 provider form files (1941+ lines) into a single
      unified ProviderForm component (353 lines), reducing code by ~82%
    - Implementing modern form management with react-hook-form and zod
    - Adding preset provider categorization with grouped select UI
    - Supporting dual-mode operation for both Claude and Codex configs
    - Removing redundant subcomponents:
      - ApiKeyInput.tsx (72 lines)
      - ClaudeConfigEditor.tsx (205 lines)
      - CodexConfigEditor.tsx (667 lines)
      - EndpointSpeedTest.tsx (636 lines)
      - KimiModelSelector.tsx (195 lines)
      - PresetSelector.tsx (119 lines)
    
    Key improvements:
    - Type-safe form values with ProviderFormValues extension
    - Automatic template value application for presets
    - Better internationalization coverage
    - Cleaner separation of concerns
    - Enhanced UX with categorized preset groups
    
    Updates AddProviderDialog and EditProviderDialog to pass appType prop
    and handle preset category metadata.
  • feat: complete stage 4 cleanup and code formatting
    This commit completes stage 4 of the refactoring plan, focusing on cleanup
    and optimization of the modernized codebase.
    
    ## Key Changes
    
    ### Code Cleanup
    - Remove legacy `src/lib/styles.ts` (no longer needed)
    - Remove old modal components (`ImportProgressModal.tsx`, `ProviderList.tsx`)
    - Streamline `src/lib/tauri-api.ts` from 712 lines to 17 lines (-97.6%)
      - Remove global `window.api` pollution
      - Keep only event listeners (`tauriEvents.onProviderSwitched`)
      - All API calls now use modular `@/lib/api/*` layer
    
    ### Type System
    - Clean up `src/vite-env.d.ts` (remove 156 lines of outdated types)
    - Remove obsolete global type declarations
    - All TypeScript checks pass with zero errors
    
    ### Code Formatting
    - Format all source files with Prettier (82 files)
    - Fix formatting issues in 15 files:
      - App.tsx and core components
      - MCP management components
      - Settings module components
      - Provider management components
      - UI components
    
    ### Documentation Updates
    - Update `REFACTORING_CHECKLIST.md` with stage 4 progress
    - Mark completed tasks in `REFACTORING_MASTER_PLAN.md`
    
    ## Impact
    
    **Code Reduction:**
    - Total: -1,753 lines, +384 lines (net -1,369 lines)
    - tauri-api.ts: 712 → 17 lines (-97.6%)
    - Removed styles.ts: -82 lines
    - Removed vite-env.d.ts declarations: -156 lines
    
    **Quality Improvements:**
    -  Zero TypeScript errors
    -  Zero TODO/FIXME comments
    -  100% Prettier compliant
    -  Zero `window.api` references
    -  Fully modular API layer
    
    ## Testing
    - [x] TypeScript compilation passes
    - [x] Code formatting validated
    - [x] No linting errors
    
    Stage 4 completion: 100%
    Ready for stage 5 (testing and bug fixes)
  • docs: add comprehensive refactoring documentation
    Add three key documents to guide the project restructure:
    - REFACTORING_MASTER_PLAN.md: Complete refactoring roadmap with 6 stages
    - REFACTORING_CHECKLIST.md: Detailed task checklist for tracking progress
    - REFACTORING_REFERENCE.md: Technical reference and implementation guide
    
    This refactoring aims to modernize the codebase with React Query,
    react-hook-form, zod validation, and shadcn/ui components while
    maintaining the current Tailwind CSS 4.x stack.
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    Co-Authored-By: Claude <noreply@anthropic.com>
  • chore: bump version to v3.5.0 and update roadmap
    Version Changes:
    - Update version to 3.5.0 in package.json, Cargo.toml, and tauri.conf.json
    
    Changelog Updates:
    - Add v3.5.0 release notes with comprehensive feature list
    - Document MCP management system implementation
    - Document configuration import/export functionality
    - Document endpoint speed testing feature
    - List all improvements, bug fixes, and technical enhancements
    
    Roadmap Updates:
    - Mark MCP manager as completed 
    - Mark i18n (internationalization) as completed 
    - Add new planned features: memory management, cloud sync
    - Reorganize feature priorities
  • refactor: reorganize documentation structure
    - Remove docs/ from .gitignore to track documentation files
    - Delete completed plan documents (encrypted-config-plan.md, updater-plan.md)
    - Add roadmap.md with project milestones and future features
  • feat(ui): implement dark mode with system preference support
    - Add useDarkMode hook for managing theme state and persistence
    - Integrate dark mode toggle button in app header
    - Update all components with dark variant styles using Tailwind v4
    - Create centralized style utilities for consistent theming
    - Support system color scheme preference as fallback
    - Store user preference in localStorage for persistence
  • docs(cleanup): remove 'current' as special provider; align UI/messages and migration naming to 'default' and one-time import rule
    - App: update auto-import message to '默认供应商'
    - README: clarify default import only when providers are empty
    - Plan doc: replace 'current entry' wording with current pointer (manager.current)
    - Migration: name live-imported item 'default' instead of 'current'