Commit Graph

25 Commits

  • refactor(mcp): preserve TOML formatting when syncing to Codex
    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
  • 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>
  • feat: add provider usage query with JavaScript scripting support (#101)
    * feat: add provider usage query functionality
    
    - Updated `Cargo.toml` to include `regex` and `rquickjs` dependencies for usage script execution.
    - Implemented `query_provider_usage` command in `commands.rs` to handle usage queries.
    - Created `UsageScript` and `UsageData` structs in `provider.rs` for managing usage script configurations and results.
    - Added `execute_usage_script` function in `usage_script.rs` to run user-defined scripts for querying usage.
    - Enhanced `ProviderList` component to include a button for configuring usage scripts and a modal for editing scripts.
    - Introduced `UsageFooter` component to display usage information and status.
    - Added `UsageScriptModal` for editing and testing usage scripts with preset templates.
    - Updated Tauri API to support querying provider usage.
    - Modified types in `types.ts` to include structures for usage scripts and results.
    
    * feat(usage): support multi-plan usage display for providers
    
    - 【Feature】
      - Update `UsageResult` to support an array of `UsageData` for displaying multiple usage plans per provider.
      - Refactor `query_provider_usage` command to parse both single `UsageData` objects (for backward compatibility) and arrays of `UsageData`.
      - Enhance `usage_script` validation to accept either a single usage object or an array of usage objects.
    - 【Frontend】
      - Redesign `UsageFooter` to iterate and display details for all available usage plans, introducing `UsagePlanItem` for individual plan rendering.
      - Improve usage display with color-coded remaining balance and clear plan information.
      - Update `UsageScriptModal` test notification to summarize all returned plans.
      - Remove redundant `isCurrent` prop from `UsageFooter` in `ProviderList`.
    - 【Build】
      - Change frontend development server port from `3000` to `3005` in `tauri.conf.json` and `vite.config.mts`.
    
    * feat(usage): enhance query flexibility and display
    - 【`src/types.ts`, `src-tauri/src/provider.rs`】Make `UsageData` fields optional and introduce `extra` and `invalidMessage` for more flexible reporting.
      - `expiresAt` replaced by generic `extra` field.
      - `isValid`, `remaining`, `unit` are now optional.
      - Added `invalidMessage` to provide specific reasons for invalid status.
    - 【`src-tauri/src/usage_script.rs`】Relax usage script result validation to accommodate optional fields in `UsageData`.
    - 【`src/components/UsageFooter.tsx`】Update UI to display `extra` field and `invalidMessage`, and conditionally render `remaining` and `unit` based on availability.
    - 【`src/components/UsageScriptModal.tsx`】
      - Add a new `NewAPI` preset template demonstrating advanced extractor logic for complex API responses.
      - Update script instructions to reflect optional fields and new variable syntax (`{{apiKey}}`).
      - Remove old "DeepSeek" and "OpenAI" templates.
      - Remove basic syntax check for `return` statement.
    - 【`.vscode/settings.json`】Add `dish-ai-commit.base.language` setting.
    - 【`src-tauri/src/commands.rs`】Adjust usage logging to handle optional `remaining` and `unit` fields.
    
    * chore(config): remove VS Code settings from version control
    
    - delete .vscode/settings.json to remove editor-specific configurations
    - add /.vscode to .gitignore to prevent tracking of local VS Code settings
    - ensure personalized editor preferences are not committed to the repository
    
    * fix(provider): preserve usage script during provider update
    
    - When updating a provider, the `usage_script` configuration within `ProviderMeta` was not explicitly merged.
    - This could lead to the accidental loss of `usage_script` settings if the incoming `provider` object in the update request did not contain this field.
    - Ensure `usage_script` is cloned from the existing provider's meta when merging `ProviderMeta` during an update.
    
    * refactor(provider): enforce base_url for usage scripts and update dev ports
    - 【Backend】
        - `src-tauri/src/commands.rs`: Made `ANTHROPIC_BASE_URL` a required field for Claude providers and `base_url` a required field in `config.toml` for Codex providers when extracting credentials for usage script execution. This improves error handling by explicitly failing if these critical URLs are missing or malformed.
    - 【Frontend】
        - `src/App.tsx`, `src/components/ProviderList.tsx`: Passed `appType` prop to `ProviderList` component to ensure `updateProvider` calls within `handleSaveUsageScript` correctly identify the application type.
    - 【Config】
        - `src-tauri/tauri.conf.json`, `vite.config.mts`: Updated development server ports from `3005` to `3000` to standardize local development environment.
    
    * refactor(usage): improve usage data fetching logic
    
    - Prevent redundant API calls by tracking last fetched parameters in `useEffect`.
    - Avoid concurrent API requests by adding a guard in `fetchUsage`.
    - Clear usage data and last fetch parameters when usage query is disabled.
    - Add `queryProviderUsage` API declaration to `window.api` interface.
    
    * fix(usage-script): ensure usage script updates and improve reactivity
    
    - correctly update `usage_script` from new provider meta during updates
    - replace full page reload with targeted provider data refresh after saving usage script settings
    - trigger usage data fetch or clear when `usageEnabled` status changes in `UsageFooter`
    - reduce logging verbosity for usage script execution in backend commands and script execution
    
    * style(usage-footer): adjust usage plan item layout
    
    - Decrease width of extra field column from 35% to 30%
    - Increase width of usage information column from 40% to 45%
    - Improve visual balance and readability of usage plan items
  • 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
  • feat: Implement Speed Test Function
    * feat: add unified endpoint speed test for API providers
    
    Add a comprehensive endpoint latency testing system that allows users to:
    - Test multiple API endpoints concurrently
    - Auto-select the fastest endpoint based on latency
    - Add/remove custom endpoints dynamically
    - View latency results with color-coded indicators
    
    Backend (Rust):
    - Implement parallel HTTP HEAD requests with configurable timeout
    - Handle various error scenarios (timeout, connection failure, invalid URL)
    - Return structured latency data with status codes
    
    Frontend (React):
    - Create interactive speed test UI component with auto-sort by latency
    - Support endpoint management (add/remove custom endpoints)
    - Extract and update Codex base_url from TOML configuration
    - Integrate with provider presets for default endpoint candidates
    
    This feature improves user experience when selecting optimal API endpoints,
    especially useful for users with multiple provider options or proxy setups.
    
    * refactor: convert endpoint speed test to modal dialog
    
    - Transform EndpointSpeedTest component into a modal dialog
    - Add "Advanced" button next to base URL input to open modal
    - Support ESC key and backdrop click to close modal
    - Apply Linear design principles: minimal styling, clean layout
    - Remove unused showBaseUrlInput variable
    - Implement same modal pattern for both Claude and Codex
    
    * fix: prevent modal cascade closing when ESC is pressed
    
    - Add state checks to prevent parent modal from closing when child modals (endpoint speed test or template wizard) are open
    - Update ESC key handler dependencies to track all modal states
    - Ensures only the topmost modal responds to ESC key
    
    * refactor: unify speed test panel UI with project design system
    
    UI improvements:
    - Update modal border radius from rounded-lg to rounded-xl
    - Unify header padding from px-6 py-4 to p-6
    - Change speed test button color to blue theme (bg-blue-500) for consistency
    - Update footer background from bg-gray-50 to bg-gray-100
    - Style "Done" button as primary action button with blue theme
    - Adjust footer button spacing and hover states
    
    Simplify endpoint display:
    - Remove endpoint labels (e.g., "Current Address", "Custom 1")
    - Display only URL for cleaner interface
    - Clean up all label-related logic:
      * Remove label field from EndpointCandidate interface
      * Remove label generation in buildInitialEntries function
      * Remove label handling in useEffect merge logic
      * Remove label generation in handleAddEndpoint
      * Remove label parameters from claudeSpeedTestEndpoints
      * Remove label parameters from codexSpeedTestEndpoints
    
    * refactor: improve endpoint list UI consistency
    
    - Show delete button for all endpoints on hover for uniform UI
    - Change selected state to use blue theme matching main interface:
      * Blue border (border-blue-500) for selected items
      * Light blue background (bg-blue-50/dark:bg-blue-900/20)
      * Blue indicator dot (bg-blue-500/dark:bg-blue-400)
    - Switch from compact list (space-y-px) to card-based layout (space-y-2)
    - Add rounded corners to each endpoint item for better visual separation
    
    * feat: persist custom endpoints to settings.json
    
    - Extend AppSettings to store custom endpoints for Claude and Codex
    - Add Tauri commands: get/add/remove/update custom endpoints
    - Update frontend API with endpoint persistence methods
    - Modify EndpointSpeedTest to load/save custom endpoints via API
    - Track endpoint last used time for future sorting/cleanup
    - Store endpoints per app type in settings.json instead of localStorage
    
    * - feat(types): add Provider.meta and ProviderMeta (snake_case) with custom_endpoints map
    
    - feat(provider-form): persist custom endpoints on provider create by merging EndpointSpeedTest’s custom URLs into meta.custom_endpoints on submit
    
    - feat(endpoint-speed-test): add onCustomEndpointsChange callback emitting normalized custom URLs; wire it for both Claude/Codex modals
    
    - fix(api): send alias param names (app/appType/app_type and provider_id/providerId) in Tauri invokes to avoid “missing providerId” with older backends
    
    - storage: custom endpoints are stored in ~/.cc-switch/config.json under providers[<id>].meta.custom_endpoints (not in settings.json)
    
    - behavior: edit flow remains immediate writes; create flow now writes once via addProvider, removing the providerId dependency during creation
    
    * feat: add endpoint candidates support and code formatting improvements
    
    - Add endpointCandidates field to ProviderPreset and CodexProviderPreset interfaces
    - Integrate preset endpoint candidates into speed test endpoint selection
    - Add multiple endpoint options for PackyCode providers (Claude & Codex)
    - Apply consistent code formatting (trailing commas, line breaks)
    - Improve template value type safety and readability
    
    * refactor: improve endpoint management button UX
    
    Replace ambiguous "Advanced" text with intuitive "Manage & Test" label accompanied by Zap icon, making the endpoint management panel entry point more discoverable and self-explanatory for both Claude and Codex configurations.
    
    * - merge: merge origin/main, resolve conflicts and preserve both feature sets
    - feat(tauri): register import/export and file dialogs; keep endpoint speed test and custom endpoints
    - feat(api): add updateTrayMenu and onProviderSwitched; wire import/export APIs
    - feat(types): extend global API declarations (import/export)
    - chore(presets): GLM preset supports both new and legacy model keys
    - chore(rust): add chrono dependency; refresh lockfile
    
    ---------
    
    Co-authored-by: Jason <farion1231@gmail.com>
  • add: local config import and export (#84)
    * add: local config import and export
    
    * Fix import refresh flow and typings
    
    * Clarify import refresh messaging
    
    * Limit stored import backups
    
    ---------
    
    Co-authored-by: Jason <farion1231@gmail.com>
  • chore: bump version to 3.4.0
    - Add i18next internationalization with Chinese/English support
    - Add Claude plugin sync alongside VS Code integration
    - Extend provider presets with new models (DeepSeek-V3.2-Exp, Qwen3-Max, GLM-4.6)
    - Support portable mode and single instance enforcement
    - Add tray minimize and macOS Dock visibility management
    - Improve Settings UI with scrollable layout and save icon
    - Fix layout shifts and provider toggle consistency
    - Remove unnecessary OpenAI auth requirement
    - Update Windows MSI installer to target per-user LocalAppData
  • release: bump version to v3.3.1
    Add support for DeepSeek-V3.1-Terminus model with emergency hotfix release
  • release: bump version to 3.3.0
    Update version across all package files and add comprehensive changelog for v3.3.0 release featuring VS Code integration, shared config snippets, enhanced Codex wizard, and cross-platform improvements.
  • feat: add config directory override support for WSL
    - Add persistent app settings with custom Claude Code and Codex config directories
    - Add config directory override UI in settings modal with manual input, browse, and reset options
    - Integrate tauri-plugin-dialog for native directory picker
    - Support WSL and other special environments where config paths need manual specification
    
    Changes:
    - settings.rs: Implement settings load/save and directory override logic
    - SettingsModal: Add config directory override UI components
    - API: Add get_config_dir and pick_directory commands
  • feat: add common config snippet management system
    - Add settings module for managing common configuration snippets
    - Implement UI for creating, editing, and deleting snippets
    - Add tauri-plugin-fs for file operations
    - Replace co-authored setting with flexible snippet system
    - Enable users to define custom config snippets for frequently used settings
  • feat(updater): 优化更新体验与 UI
    - ui: UpdateBadge 使用 Tailwind 内置过渡,支持点击打开设置,保留图标动画
    
    - updater: 新增 UpdateContext 首启延迟检查,忽略版本键名命名空间化(含旧键迁移),并发保护
    
    - settings: 去除版本硬编码回退;检测到更新时复用 updateHandle 下载并安装,并新增常显“更新日志”入口
    
    - a11y: 更新徽标支持键盘触达(Enter/Space)
    
    - refactor: 移除未使用的 runUpdateFlow 导出
    
    - chore: 类型检查通过,整体行为与权限边界未改变
  • feat(updater): 集成 Rust 侧 Updater/Process 插件与权限配置
    - Cargo 依赖:tauri-plugin-updater、tauri-plugin-process
    - 插件注册:process 顶层 init,updater 于 setup 中注册
    - 权限配置:capabilities 增加 updater:default、process:allow-restart
    - 配置:tauri.conf.json 启用 createUpdaterArtifacts 与 updater 占位(pubkey/endpoints)
  • security(tauri): remove unused shell plugin and capability
    - Remove tauri-plugin-shell from Cargo.toml
    - Drop tauri_plugin_shell::init() from src-tauri/src/lib.rs
    - Delete "shell:allow-open" from src-tauri/capabilities/default.json
    - No runtime behavior change; opener plugin still handles links/paths
    - Motivation: reduce permissions surface and slightly shrink bundle
  • chore: prepare v3.0.0 release
    - Bump version to 3.0.0 across all files
    - Update Cargo.toml with proper package metadata
    - Rename crate from 'app' to 'cc-switch'
    - Use Rust edition 2024 with minimum rust-version 1.85.0
    - Update library name to cc_switch_lib
  • feat(macos): implement transparent titlebar with custom background color
    - Add transparent titlebar configuration in tauri.conf.json
    - Implement macOS titlebar background color matching main UI banner (#3498db)
    - Replace deprecated cocoa crate with modern objc2-app-kit
    - Preserve native window functionality (drag, traffic lights)
    - Remove all deprecation warnings from build process
    
    The titlebar now seamlessly matches the application's blue theme while
    maintaining all native macOS window management features.
  • chore(tauri): remove dead code warnings and drop unused uuid dep
    - Delete unused Provider::new, ProviderManager::get_current_provider
    - Delete unused AppState::reload
    - Remove uuid crate and related imports
    - Keep functionality unchanged; frontend uses ID string for current provider
  • feat: upgrade Rust code to full Tauri 2.0 compatibility
    - Add tauri-plugin-shell and tauri-plugin-opener dependencies
    - Update permissions configuration to support shell and opener operations
    - Refactor open_config_folder and open_external commands to use secure plugin APIs
    - Remove unsafe direct std::process::Command usage
    - Initialize necessary Tauri plugins
    - Ensure all external operations comply with Tauri 2.0 security standards
  • fix: 修复 Rust 编译错误并成功启动 Tauri 应用
    - 修复 commands.rs 中的重复导入问题
    - 清理未使用的导入
    - 统一 Vite 和 Tauri 配置的端口为 3000
    - 添加 Tauri 前端依赖包
    - 应用已成功编译并运行