Commit Graph

648 Commits

Author SHA1 Message Date
YoVinchen
3d69da5b66 feat: add model configuration support and fix Gemini deeplink bug (#251)
* feat(providers): add notes field for provider management

- Add notes field to Provider model (backend and frontend)
- Display notes with higher priority than URL in provider card
- Style notes as non-clickable text to differentiate from URLs
- Add notes input field in provider form
- Add i18n support (zh/en) for notes field

* chore: format code and clean up unused props

- Run cargo fmt on Rust backend code
- Format TypeScript imports and code style
- Remove unused appId prop from ProviderPresetSelector
- Clean up unused variables in tests
- Integrate notes field handling in provider dialogs

* feat(deeplink): implement ccswitch:// protocol for provider import

Add deep link support to enable one-click provider configuration import via ccswitch:// URLs.

Backend:
- Implement URL parsing and validation (src-tauri/src/deeplink.rs)
- Add Tauri commands for parse and import (src-tauri/src/commands/deeplink.rs)
- Register ccswitch:// protocol in macOS Info.plist
- Add comprehensive unit tests (src-tauri/tests/deeplink_import.rs)

Frontend:
- Create confirmation dialog with security review UI (src/components/DeepLinkImportDialog.tsx)
- Add API wrapper (src/lib/api/deeplink.ts)
- Integrate event listeners in App.tsx

Configuration:
- Update Tauri config for deep link handling
- Add i18n support for Chinese and English
- Include test page for deep link validation (deeplink-test.html)

Files: 15 changed, 1312 insertions(+)

* chore(deeplink): integrate deep link handling into app lifecycle

Wire up deep link infrastructure with app initialization and event handling.

Backend Integration:
- Register deep link module and commands in mod.rs
- Add URL handling in app setup (src-tauri/src/lib.rs:handle_deeplink_url)
- Handle deep links from single instance callback (Windows/Linux CLI)
- Handle deep links from macOS system events
- Add tauri-plugin-deep-link dependency (Cargo.toml)

Frontend Integration:
- Listen for deeplink-import/deeplink-error events in App.tsx
- Update DeepLinkImportDialog component imports

Configuration:
- Enable deep link plugin in tauri.conf.json
- Update Cargo.lock for new dependencies

Localization:
- Add Chinese translations for deep link UI (zh.json)
- Add English translations for deep link UI (en.json)

Files: 9 changed, 359 insertions(+), 18 deletions(-)

* refactor(deeplink): enhance Codex provider template generation

Align deep link import with UI preset generation logic by:
- Adding complete config.toml template matching frontend defaults
- Generating safe provider name from sanitized input
- Including model_provider, reasoning_effort, and wire_api settings
- Removing minimal template that only contained base_url
- Cleaning up deprecated test file deeplink-test.html

* style: fix clippy uninlined_format_args warnings

Apply clippy --fix to use inline format arguments in:
- src/mcp.rs (8 fixes)
- src/services/env_manager.rs (10 fixes)

* style: apply code formatting and cleanup

- Format TypeScript files with Prettier (App.tsx, EnvWarningBanner.tsx, formatters.ts)
- Organize Rust imports and module order alphabetically
- Add newline at end of JSON files (en.json, zh.json)
- Update Cargo.lock for dependency changes

* feat: add model name configuration support for Codex and fix Gemini model handling

- Add visual model name input field for Codex providers
  - Add model name extraction and update utilities in providerConfigUtils
  - Implement model name state management in useCodexConfigState hook
  - Add conditional model field rendering in CodexFormFields (non-official only)
  - Integrate model name sync with TOML config in ProviderForm

- Fix Gemini deeplink model injection bug
  - Correct environment variable name from GOOGLE_GEMINI_MODEL to GEMINI_MODEL
  - Add test cases for Gemini model injection (with/without model)
  - All tests passing (9/9)

- Fix Gemini model field binding in edit mode
  - Add geminiModel state to useGeminiConfigState hook
  - Extract model value during initialization and reset
  - Sync model field with geminiEnv state to prevent data loss on submit
  - Fix missing model value display when editing Gemini providers

Changes:
  - 6 files changed, 245 insertions(+), 13 deletions(-)
2025-11-19 09:03:18 +08:00
Jason
0ae9ed5a17 fix: resolve JSON syntax error in i18n locale files
Fixed missing closing braces in the error object of both en.json and zh.json locale files that caused Vite parse errors. The envManager.error object was not properly closed, causing the subsequent skills object to be parsed incorrectly.
2025-11-19 08:52:26 +08:00
冰子
5ff689af82 Add Gemini environment variable detection (#250)
* feat(env): add environment variable conflict detection and management

实现了系统环境变量冲突检测与管理功能:

核心功能:
- 自动检测会影响 Claude/Codex 的系统环境变量
- 支持 Windows 注册表和 Unix shell 配置文件检测
- 提供可视化的环境变量冲突警告横幅
- 支持批量选择和删除环境变量
- 删除前自动备份,支持后续恢复

技术实现:
- Rust 后端: 跨平台环境变量检测与管理
- React 前端: EnvWarningBanner 组件交互界面
- 国际化支持: 中英文界面
- 类型安全: 完整的 TypeScript 类型定义

* refactor(env): remove unused imports and function

Remove unused HashMap and PathBuf imports, and delete the unused get_source_description function to clean up the code.

* feat: Add Gemini environment variable detection
2025-11-19 08:33:02 +08:00
冰子
b9412ece0b 添加Claude和Codex环境变量检查 (#242)
* feat(env): add environment variable conflict detection and management

实现了系统环境变量冲突检测与管理功能:

核心功能:
- 自动检测会影响 Claude/Codex 的系统环境变量
- 支持 Windows 注册表和 Unix shell 配置文件检测
- 提供可视化的环境变量冲突警告横幅
- 支持批量选择和删除环境变量
- 删除前自动备份,支持后续恢复

技术实现:
- Rust 后端: 跨平台环境变量检测与管理
- React 前端: EnvWarningBanner 组件交互界面
- 国际化支持: 中英文界面
- 类型安全: 完整的 TypeScript 类型定义

* refactor(env): remove unused imports and function

Remove unused HashMap and PathBuf imports, and delete the unused get_source_description function to clean up the code.
2025-11-18 23:44:44 +08:00
YoVinchen
ec303544ca Feat/claude skills management (#237)
* feat(skills): add Claude Skills management feature

Implement complete Skills management system with repository discovery,
installation, and lifecycle management capabilities.

Backend:
- Add SkillService with GitHub integration and installation logic
- Implement skill commands (list, install, uninstall, check updates)
- Support multiple skill repositories with caching

Frontend:
- Add Skills management page with repository browser
- Create SkillCard and RepoManager components
- Add badge, card, table UI components
- Integrate Skills API with Tauri commands

Files: 10 files changed, 1488 insertions(+)

* feat(skills): integrate Skills feature into application

Integrate Skills management feature with complete dependency updates,
configuration structure extensions, and internationalization support.

Dependencies:
- Add @radix-ui/react-visually-hidden for accessibility
- Add anyhow, zip, serde_yaml, tempfile for Skills backend
- Enable chrono serde feature for timestamp serialization

Backend Integration:
- Extend MultiAppConfig with SkillStore field
- Implement skills.json migration from legacy location
- Register SkillService and skill commands in main app
- Export skill module in commands and services

Frontend Integration:
- Add Skills page route and dialog in App
- Integrate Skills UI with main navigation

Internationalization:
- Add complete Chinese translations for Skills UI
- Add complete English translations for Skills UI

Code Quality:
- Remove redundant blank lines in gemini_mcp.rs
- Format log statements in mcp.rs

Tests:
- Update import_export_sync tests for SkillStore
- Update mcp_commands tests for new structure

Files: 16 files changed, 540 insertions(+), 39 deletions(-)

* style(skills): improve SkillsPage typography and spacing

Optimize visual hierarchy and readability of Skills page:
- Reduce title size from 2xl to lg with tighter tracking
- Improve description spacing and color contrast
- Enhance empty state with better text hierarchy
- Use explicit gray colors for better dark mode support

* feat(skills): support custom subdirectory path for skill scanning

Add optional skillsPath field to SkillRepo to enable scanning skills
from subdirectories (e.g., "skills/") instead of repository root.

Changes:
- Backend: Add skillsPath field with subdirectory scanning logic
- Frontend: Add skillsPath input field and display in repo list
- Presets: Add cexll/myclaude repo with skills/ subdirectory
- Code quality: Fix clippy warnings (dedup logic, string formatting)

Backward compatible: skillsPath is optional, defaults to root scanning.

* refactor(skills): improve repo manager dialog layout

Optimize dialog structure with fixed header and scrollable content:
- Add flexbox layout with fixed header and scrollable body
- Remove outer border wrapper for cleaner appearance
- Match SkillsPage design pattern for consistency
- Improve UX with better content hierarchy
2025-11-18 22:05:54 +08:00
Jason
023726c59d docs: add Codex MCP raw TOML refactor plan
Add comprehensive implementation plan for v3.7.0 refactor that
separates Codex MCP configuration from unified MCP structure.

Key design decisions:
- Codex MCP stored as raw TOML string in codexMcp.rawToml
- Unified MCP (mcp.servers) only supports Claude/Gemini
- Complete isolation: no apps.codex in unified structure
- Migration clears mcp.codex.servers to prevent pollution

Architecture improvements:
- Single responsibility: each data source has one purpose
- No priority conflicts: completely independent data paths
- Simplified switching logic: no conditional branches
- UI constraints: Tab1 limited to claude/gemini only

Implementation phases:
- Phase 0: Setup (0.5d)
- Phase 1: Backend foundation (1.5d)
- Phase 2: Command layer (1d)
- Phase 3: Switching logic (1d)
- Phase 4: Frontend API (0.5d)
- Phase 5: UI implementation (2d)
- Phase 6: Enhancements (1d, optional)
- Phase 7: Testing & docs (1d)

Total: 8.5 days (MVP: 7 days)

Addresses TOML-JSON conversion data loss issue by preserving
raw TOML format for Codex while maintaining structured approach
for Claude/Gemini.
2025-11-18 16:08:31 +08:00
Jason
8d2c067814 feat(window): center window on screen by default
Add `center: true` to main window configuration to improve initial
window positioning on Windows and other platforms. This addresses
user feedback about the window appearing in the top-left corner.
2025-11-17 23:25:13 +08:00
Jason
a00eb764f7 fix(provider): sync MCP config for all apps on provider switch
Previously, only Codex provider switches triggered MCP synchronization,
which could cause MCP configuration loss when switching Claude or Gemini
providers.

Changes:
- Enable MCP sync for all app types (Claude, Codex, Gemini) during provider switch
- Migrate to v3.7.0 unified MCP sync mechanism using McpService::sync_all_enabled()
- Replace app-specific sync_enabled_to_codex() with unified sync for all apps
- Remove unused mcp module import

This ensures MCP servers remain properly configured across all applications
after provider switches, preventing configuration loss.
2025-11-17 23:17:21 +08:00
Jason
67bd8f5c11 fix(mcp): correct Codex MCP configuration format to [mcp_servers]
BREAKING CHANGE: The [mcp.servers] format was completely incorrect and not
any official Codex format. The only correct format is [mcp_servers] at the
top level of config.toml.

Changes:
- Remove incorrect [mcp.servers] nested table support
- Always use [mcp_servers] top-level table (official Codex format)
- Auto-migrate and cleanup erroneous [mcp.servers] entries on write
- Preserve error-tolerant import for migrating old incorrect configs
- Simplify sync logic by removing format selection branches (~60 lines)
- Update all documentation and tests to reflect correct format
- Add warning logs when detecting and cleaning incorrect format

Backend (Rust):
- mcp.rs: Simplify sync_enabled_to_codex by removing Target enum
- mcp.rs: sync_single_server_to_codex now always uses [mcp_servers]
- mcp.rs: remove_server_from_codex cleans both locations
- mcp.rs: Update import_from_codex comments to clarify format status
- tests: Rename test to sync_enabled_to_codex_migrates_erroneous_*
- tests: Update assertions to verify migration behavior

Frontend (TypeScript):
- tomlUtils.ts: Prioritize [mcp_servers] format in parsing
- tomlUtils.ts: Update error messages to guide correct format

Documentation:
- README.md: Correct MCP format reference to [mcp_servers]
- CLAUDE.md: Add comprehensive format specification with examples

All 79 tests pass. This ensures backward compatibility while enforcing
the correct Codex official standard going forward.

Refs: https://github.com/openai/codex/issues/3441
2025-11-17 22:57:04 +08:00
Jason
3051743bd3 feat(mcp): support extended fields for Codex TOML conversion
## Problem
Previously, the Codex MCP configuration used a whitelist-only approach
for TOML conversion, which caused custom fields (like `timeout`,
`startup_timeout_ms`, etc.) to be silently dropped during JSON → TOML
conversion. Only Claude and Gemini (JSON format) could preserve
arbitrary fields.

## Solution
Implemented a three-tier field handling strategy:

1. **Core fields** (type, command, args, url, headers, env, cwd)
   - Strong-typed manual processing (existing behavior preserved)

2. **Extended fields** (19 common optional fields)
   - White-listed fields with automatic type conversion:
     - General: timeout, timeout_ms, startup_timeout_ms/sec,
       connection_timeout, read_timeout, debug, log_level, disabled
     - stdio: shell, encoding, working_dir, restart_on_exit,
       max_restart_count
     - http/sse: retry_count, max_retry_attempts, retry_delay,
       cache_tools_list, verify_ssl, insecure, proxy

3. **Custom fields** (generic converter)
   - Automatic type inference for:
     - String → TOML String
     - Number (i64/f64) → TOML Integer/Float
     - Boolean → TOML Boolean
     - Simple arrays → TOML Array
     - Shallow objects (string values only) → TOML Inline Table
   - Unsupported types (null, mixed arrays, nested objects) are
     gracefully skipped with debug logging

## Changes

### Core Implementation
- **json_value_to_toml_item()** (mcp.rs:843-947)
  Generic JSON → TOML value converter with smart type inference

- **json_server_to_toml_table()** (mcp.rs:949-1072)
  Refactored to use three-tier strategy, processes all fields beyond
  core whitelist

- **build_servers_table()** (mcp.rs:616-633)
  Now reuses the generic converter for consistency

- **import_from_codex()** (mcp.rs:432-605)
  Extended with generic TOML → JSON converter for bidirectional
  field preservation

### Logging
- DEBUG: Extended field conversions
- INFO: Custom field conversions
- WARN: Skipped unsupported types (with reason)

## Testing
-  All 24 integration tests pass
-  Compilation clean (zero errors)
-  Backward compatible with existing configs

## Design Decision: No Auto Field Mapping
Explicitly NOT implementing automatic field mapping (e.g., Claude's
`timeout` → Codex's `startup_timeout_ms`) due to:
- Unit ambiguity (seconds vs milliseconds)
- Semantic ambiguity (same field name, different meanings)
- Risk of data corruption (30s → 30ms causes immediate timeout)
- Breaks user expectation of "what you see is what you get"

Recommendation: Use application-specific field names as documented.

## Example
User adds `timeout: 30` in MCP panel:

**Claude/Gemini** (~/.claude.json):
```json
{"mcpServers": {"srv": {"timeout": 30}}}
```

**Codex** (~/.codex/config.toml):
```toml
[mcp.servers.srv]
timeout = 30  #  Now preserved!
```

Fixes the whitelist limitation reported in user feedback.
2025-11-17 17:23:09 +08:00
qixing-jk
883cf0346b fix(password input): disable Edge/IE reveal and clear buttons (#232)
Hide default password reveal and clear controls in Microsoft browsers
for improved consistency and security.
2025-11-17 15:30:46 +08:00
Jason
1805ed586e fix(mcp): improve format/submit UX and fix validation errors
Fixes two critical issues with the MCP JSON input:
1. Format button failed with wrapped format like "server": {...}
2. Submit button failed despite input validation passing

Changes:
- Updated formatJSON to use smart parser (supports wrapped format)
- Simplified submit validation logic (removed redundant validateJsonConfig call)
- Improved UX: input preserves original format, cleanup happens on format/submit
  * Prevents confusing "instant disappearance" when pasting wrapped JSON
  * Auto-fills ID/Name fields while keeping input unchanged
  * Format button now strips wrapper key and formats cleanly
  * Submit button correctly extracts config regardless of format

Code quality:
- Reduced code by 5 lines (20 changes, 11 insertions, 16 deletions)
- Consistent use of parseSmartMcpJson across all JSON operations
- No type errors introduced
2025-11-16 20:40:16 +08:00
Jason
98a1305684 feat(mcp): add smart JSON parser for flexible input formats
Support multiple MCP configuration input formats:
- Pure config object: { "command": "npx", ... }
- Key-value pair fragment: "server-name": { "command": "npx", ... }
- Wrapped object: { "server-name": { "command": "npx", ... } }

The parser automatically:
- Detects and wraps JSON fragments into complete objects
- Extracts server name from single-key objects
- Auto-fills ID and Name fields when applicable
- Formats the config for display

This improves UX by allowing users to paste configs directly from
.claude.json or .codex/config.toml without manual editing.
2025-11-16 20:08:04 +08:00
Jason
f79efb86cd refactor(mcp): improve form label layout and simplify text
- Simplify config label from "Full JSON configuration or use" to "Full JSON Configuration"
- Align wizard button to the right using justify-between layout
- Apply same pattern to TOML configuration label
- Improve visual balance with cleaner left-right alignment
2025-11-16 16:59:23 +08:00
Jason
ed59420a83 feat(mcp): enhance form UX with default apps and JSON formatter
- Enable all apps (Claude, Codex, Gemini) by default when adding MCP servers
- Improve config label with clearer wording: "Full JSON configuration or use [Config Wizard]"
- Add JSON format button to beautify configuration with 2-space indentation
- Update tests to reflect new default behavior
- Clean up redundant explicit prop passing

This provides a more streamlined experience by enabling all apps out of the box
and making it easier to format JSON configurations.
2025-11-16 16:50:07 +08:00
Jason
bfc27349b3 feat(mcp): add SSE (Server-Sent Events) transport type support
Add comprehensive support for SSE transport type to MCP server configuration,
enabling real-time streaming connections alongside existing stdio and http types.

Backend Changes:
- Add SSE type validation in mcp.rs validate_server_spec()
- Extend Codex TOML import/export to handle SSE servers
- Update claude_mcp.rs legacy API for backward compatibility
- Unify http/sse handling in json_server_to_toml_table()

Frontend Changes:
- Extend McpServerSpec type definition to include "sse"
- Add SSE radio button to configuration wizard UI
- Update wizard form logic to handle SSE url and headers
- Add SSE validation in McpFormModal submission

Validation & Error Handling:
- Add SSE support in useMcpValidation hook (TOML/JSON)
- Extend tomlUtils normalizeServerConfig for SSE parsing
- Update Zod schemas (common.ts, mcp.ts) with SSE enum
- Add SSE error message mapping in errorUtils

Internationalization:
- Add "typeSse" translations (zh: "sse", en: "sse")

Tests:
- Add SSE validation test cases in useMcpValidation.test.tsx

SSE Configuration Format:
{
  "type": "sse",
  "url": "https://api.example.com/sse",
  "headers": { "Authorization": "Bearer token" }
}
2025-11-16 16:15:17 +08:00
Jason
4fc7413ffa refactor(codex): simplify custom template with minimal config
**Changes:**
- Remove all comments from custom template (align with Claude/Gemini)
- Remove base_url field from template (user fills in form instead)
- Simplify getCodexCustomTemplate() - no locale parameter needed
- Keep preset configurations unchanged with their baseUrl values

**Template now contains only:**
- model_provider, model, model_reasoning_effort
- disable_response_storage
- [model_providers.custom] section with minimal fields

**Benefits:**
-  Cleaner, more focused template
-  Consistent with other apps (no comments)
-  Forces users to fill base_url via form field
-  Reduced template size from 35+ lines to 12 lines

Net change: -74 lines (codexTemplates.ts)
2025-11-16 13:36:33 +08:00
Jason
12112e9d7d refactor(codex): extract template to config with i18n support
**Changes:**
- Create src/config/codexTemplates.ts with getCodexCustomTemplate factory
- Support both Chinese and English templates based on i18n.language
- Remove 70 lines of duplicated template strings from ProviderForm.tsx
- Update both useEffect and handlePresetChange to use template factory
- Clean up unused "Custom (Blank Template)" preset entry

**Benefits:**
-  Eliminates code duplication (35-line template repeated twice)
-  Adds internationalization support for English users
-  Follows project architecture (templates in config/ directory)
-  Improves maintainability (single source of truth)
-  Net reduction: 34 lines (81 additions, 115 deletions)

**Technical Details:**
- Template selection logic: (i18n.language || "zh").startsWith("zh") ? "zh" : "en"
- Templates are identical except for comments language
- Both auth and config are returned as a single CodexTemplate object

Addresses DRY principle violation and architectural concerns identified
in code review.
2025-11-16 13:23:53 +08:00
Jason
6a6980c82c refactor(codex): remove configuration wizard and unify provider setup experience
- Remove CodexQuickWizardModal component (~300 lines)
- Add "Custom (Blank Template)" preset with annotated TOML template
- Unify configuration experience across Claude/Codex/Gemini
- Remove wizard-related i18n keys, keep apiUrlLabel for CodexFormFields
- Simplify component integration by removing wizard state management

This change reduces code complexity by ~250 lines while providing better
user education through commented configuration templates in Chinese.

Users can now:
1. Select "Custom (Blank Template)" preset
2. See annotated TOML template with inline documentation
3. Follow step-by-step comments to configure custom providers

BREAKING CHANGE: Configuration wizard UI removed, replaced with template-based approach
2025-11-16 12:29:18 +08:00
Jason
031ea3a58f style(mcp): refine panel layout for better visual hierarchy and compactness
- Replace checkboxes with toggle switches for app selection (more intuitive for enable/disable actions)
- Change switch color from blue to emerald to match MCP button theme
- Stack app options vertically with labels on left to save horizontal space
- Reduce panel width from max-w-4xl to max-w-3xl for more compact design
- Move docs button next to server name for better information grouping
2025-11-16 11:31:27 +08:00
Jason
9d431cc7ae style(ui): migrate color scheme to macOS native design system
- Update primary blue from Linear style (#3498db) to macOS system blue (#0A84FF)
- Align gray scale with macOS dark mode palette (#1C1C1E, #2C2C2E, etc.)
- Adjust dark mode background to match macOS systemBackground (HSL 240 5% 12%)
- Refine scrollbar colors to use native macOS gray tones
- Remove transparent titleBarStyle for better stability
2025-11-16 10:44:15 +08:00
Jason
685a1138e4 refactor(mcp): complete form refactoring for unified MCP management
Complete the v3.7.0 MCP refactoring by updating the form layer to match
the unified architecture already implemented in data/service/API layers.

**Breaking Changes:**
- Remove confusing `appId` parameter from McpFormModal
- Replace with `defaultFormat` (json/toml) and `defaultEnabledApps` (array)

**Form Enhancements:**
- Add app enablement checkboxes (Claude/Codex/Gemini) directly in the form
- Smart defaults: new servers default to Claude enabled, editing preserves state
- Support "draft" mode: servers can be created without enabling any apps

**Architecture Improvements:**
- Eliminate semantic confusion: format selection separate from app targeting
- One-step workflow: configure and enable apps in single form submission
- Consistent with unified backend: `apps: { claude, codex, gemini }`

**Testing:**
- Update test mocks to use `useUpsertMcpServer` hook
- Add test case for creating servers with no apps enabled
- Fix parameter references from `appId` to `defaultFormat`

**i18n:**
- Add `mcp.form.enabledApps` translation (zh/en)
- Add `mcp.form.noAppsWarning` translation (zh/en)

This completes the MCP management refactoring, ensuring all layers
(data, service, API, UI) follow the same unified architecture pattern.
2025-11-15 23:47:35 +08:00
Jason
154ff4c819 feat(config): unify common config snippets persistence across all apps
- Add unified `common_config_snippets` structure to MultiAppConfig
- Implement `get_common_config_snippet` and `set_common_config_snippet` commands
- Replace localStorage with config.json persistence for Codex and Gemini
- Auto-migrate legacy `claude_common_config_snippet` to new unified structure
- Deprecate individual API methods in favor of unified interface
- Add automatic migration from localStorage on first load

BREAKING CHANGE: Common config snippets now stored in unified `common_config_snippets` object instead of separate fields
2025-11-15 19:52:49 +08:00
Jason
2540f6ba08 refactor(prompt): optimize auto-import logic with unified save
- Change auto_import_prompt_if_exists return type to Result<bool>
- Remove redundant save() calls by introducing updated flag
- Eliminate unnecessary clone() in app type iterations
- Remove semantic contradiction in let _ = ...? pattern
- Improve code semantics and maintainability

Performance: Reduce disk I/O by 50%+ through unified save logic
2025-11-15 16:47:08 +08:00
YoVinchen
d32ceb9b80 fix(prompt): correct live file backfill priority in enable flow (#225)
Fix backfill logic in prompt enable workflow:
- Prioritize backfilling live file content to currently enabled prompt (prevent data loss)
- Create backup only when no enabled prompt exists and content is new (avoid duplicate backups)
- Implement staged persistence (save after backfill + save after enable)
- Add explicit logging for backfill/backup operations

Also simplify string formatting in prompt_files.rs with inline format strings.
2025-11-15 16:09:00 +08:00
Jason
e11c7d84cd test(mcp): update import tests for v3.7.0 unified structure
- Fix import_from_claude_merges_into_config: check unified mcp.servers
- Fix import_from_codex_adds_servers_from_mcp_servers_table: verify apps.codex enabled
- Fix import_from_codex_merges_into_existing_entries: test smart merge preserves existing config
- Replace cc_switch_lib::app_config:: with public exports (McpServer, McpApps)

All 24 import_export_sync tests now passing.
2025-11-14 23:39:34 +08:00
Jason
ea8f2095e2 fix(mcp): migrate import functions to unified v3.7.0 structure
- Rewrite import_from_claude/codex/gemini to write directly to mcp.servers
- Implement skip-on-error strategy for fault tolerance (single invalid item no longer aborts entire batch)
- Smart merge logic: existing servers only enable corresponding app, preserve other configs
- Remove deprecated markers from service layer
- Export McpApps type for test usage
- Update mcp_commands tests to use unified structure

Fixes runtime import issue where data was written to legacy structure (mcp.claude/codex.servers)
but unified panel reads from new structure (mcp.servers), causing "imported but invisible" bug.
2025-11-14 23:33:54 +08:00
Jason
09f80d82bc fix(mcp): initialize McpRoot with v3.7.0 unified structure by default
Problem:
- On first launch, McpRoot::default() created `servers: None`
- McpService::get_all_servers() would incorrectly return error "old structure detected"
- This confused new users who had no legacy MCP data

Root Cause:
- Derived Default trait sets Option<T> fields to None
- New installations should start with v3.7.0 structure immediately

Solution:
- Explicitly implement Default for McpRoot
- Initialize `servers: Some(HashMap::new())` for v3.7.0+ structure
- Legacy fields (claude/codex/gemini) remain empty, only used for deserializing old configs

Impact:
- First-time users get correct v3.7.0 structure immediately
- migrate_mcp_to_unified() correctly detects already-migrated state
- No false "old structure" errors on fresh installs
2025-11-14 22:55:46 +08:00
Jason
2f18d6ec00 refactor(mcp): complete v3.7.0 cleanup - remove legacy code and warnings
This commit finalizes the v3.7.0 unified MCP architecture migration by
removing all deprecated code paths and eliminating compiler warnings.

Frontend Changes (~950 lines removed):
- Remove deprecated components: McpPanel, McpListItem, McpToggle
- Remove deprecated hook: useMcpActions
- Remove unused API methods: importFrom*, syncEnabledTo*, syncAllServers
- Simplify McpFormModal by removing dual-mode logic (unified/legacy)
- Remove syncOtherSide checkbox and conflict detection
- Clean up unused imports and state variables
- Delete associated test files

Backend Changes (~400 lines cleaned):
- Remove unused Tauri commands: import_mcp_from_*, sync_enabled_mcp_to_*
- Delete unused Gemini MCP functions: get_mcp_status, upsert/delete_mcp_server
- Add #[allow(deprecated)] to compatibility layer commands
- Add #[allow(dead_code)] to legacy helper functions for future migration
- Simplify boolean expression in mcp.rs per Clippy suggestion

API Deprecation:
- Mark legacy APIs with @deprecated JSDoc (getConfig, upsertServerInConfig, etc.)
- Preserve backward compatibility for v3.x, planned removal in v4.0

Verification:
-  Zero TypeScript errors (pnpm typecheck)
-  Zero Clippy warnings (cargo clippy)
-  All code formatted (prettier + cargo fmt)
-  Builds successfully

Total cleanup: ~1,350 lines of code removed/marked
Breaking changes: None (all legacy APIs still functional)
2025-11-14 22:43:25 +08:00
Jason
fafca841cb refactor(frontend): remove redundant 'Sync All' button from MCP panel
All MCP operations already auto-sync to live configs:
- upsert_server() → sync_server_to_apps()
- toggle_app() → sync_server_to_app() or remove_server_from_app()
- delete_server() → remove_server_from_all_apps()

The manual 'Sync All' button was redundant and could confuse users
into thinking they need to manually sync after each change.

Changes:
- Remove 'Sync All' button from UnifiedMcpPanel header
- Remove useSyncAllMcpServers hook
- Remove handleSyncAll function and syncAllMutation state
- Remove RefreshCw icon import
- Remove sync-related i18n translations (en/zh)

Note: Backend sync_all_mcp_servers command remains for potential
future use (e.g., recovery tool), but is no longer exposed in UI.
2025-11-14 15:52:01 +08:00
Jason
f4b8aed29a refactor(frontend): remove MCP import functionality for v3.7.0
Auto-migration at startup is sufficient for upgrading from v3.6.x.
Manual import adds unnecessary complexity since:
- Gemini MCP support launches with v3.7.0 (no legacy data)
- Existing Claude/Codex MCP configs are auto-migrated on first run
- All MCP management should happen within CC Switch

Changes:
- Remove McpImportDialog component
- Remove "Import" button from UnifiedMcpPanel
- Remove import-related i18n translations (en/zh)
- Simplify user experience with single management interface

Note: Backend import commands (import_mcp_from_*) remain for
backward compatibility but are no longer exposed in UI.
2025-11-14 15:47:04 +08:00
Jason
9663b4251e feat(frontend): add MCP import dialog for v3.7.0
Implement import functionality to migrate MCP servers from existing configs:

**New Component:**
- src/components/mcp/McpImportDialog.tsx: Import dialog with card-based source selection

**Features:**
- Import from Claude (~/.claude/claude.json or settings.json)
- Import from Codex (~/.codex/config.toml)
- Import from Gemini (config file)
- Card-based UI with icons and descriptions
- Loading states with spinner animation
- Auto-refresh after successful import

**Integration:**
- Add import button to UnifiedMcpPanel header
- Handle import completion with refetch
- Toast notifications for success/info/error cases

**I18n:**
- Add mcp.unifiedPanel.import namespace (zh/en)
- Import button, dialog title, descriptions
- Success/error messages with count interpolation

**UX:**
- Smart disable: other sources disabled during import
- Clear feedback: count of imported servers
- Friendly messages: "No servers found" when empty

TypeScript type check passes 
2025-11-14 15:29:16 +08:00
Jason
9e8abf5f26 feat(frontend): implement unified MCP panel for v3.7.0
Complete Phase 3 (P0) frontend implementation for unified MCP management:

**New Files:**
- src/hooks/useMcp.ts: React Query hooks for unified MCP operations
- src/components/mcp/UnifiedMcpPanel.tsx: Unified MCP management panel
- src/components/ui/checkbox.tsx: Checkbox component from shadcn/ui

**Features:**
- Unified panel with three-column layout: server info + app checkboxes + actions
- Multi-app control: Claude/Codex/Gemini checkboxes for each server
- Real-time stats: Show enabled server counts per app
- Full CRUD operations: Add, edit, delete, sync all servers

**Integration:**
- Replace old app-specific McpPanel with UnifiedMcpPanel in App.tsx
- Update McpFormModal to support unified mode with apps field
- Add i18n support: mcp.unifiedPanel namespace (zh/en)

**Type Safety:**
- Ensure McpServer.apps field always initialized
- Fix all test files to include apps field
- TypeScript type check passes 

**Architecture:**
- Single source of truth: mcp.servers manages all MCP configs
- Per-server app control: apps.claude/codex/gemini boolean flags
- Backward compatible: McpFormModal supports both unified and legacy modes

Next: P1 tasks (import dialogs, sub-components, tests)
2025-11-14 15:24:48 +08:00
Jason
32a6de074c docs: add comprehensive v3.7.0 unified MCP refactor plan
## Document Overview
Created detailed refactoring plan document covering:
- Project goals and architecture changes
- Data structure migration strategy (v3.6.x → v3.7.0)
- Complete development progress tracking
- Frontend remaining tasks roadmap
- Testing plan and delivery checklist

## Completed Work (Documented)
 Phase 1: Backend data structure migration
  - McpApps, McpServer, McpRoot definitions
  - Automatic migration logic
  - Integration into load() method

 Phase 2: Backend services refactor
  - Complete McpService rewrite
  - Single-server sync functions
  - New Tauri commands
  - Backward compatibility layer
  - All compilation errors fixed

 Phase 3 (Partial): Frontend types and API
  - Updated TypeScript types (McpApps, McpServer)
  - New API methods (getAllServers, toggleApp, etc.)

## Remaining Work (Documented)
📝 React Query hooks (useMcp.ts)
📝 UnifiedMcpPanel component
📝 i18n translations
📝 Main app integration
📝 Sub-components (table, form, import dialog)

## Key Highlights
- Detailed UI wireframes and component structure
- Step-by-step migration flow documentation
- Risk assessment and mitigation strategies
- Technical insights and architecture benefits

Related: v3.7.0 unified MCP management
2025-11-14 15:09:22 +08:00
Jason
ac09551563 feat(frontend): add unified MCP types and API layer for v3.7.0
## Type Definitions
- Update McpServer interface with new apps field (McpApps)
- Add McpApps interface for multi-app enable state
- Add McpServersMap type for server collections
- Mark enabled field as deprecated (use apps instead)
- Maintain backward compatibility with optional fields

## API Layer Updates
- Add unified MCP management methods to mcpApi:
  * getAllServers() - retrieve all servers with apps state
  * upsertUnifiedServer() - add/update server with apps
  * deleteUnifiedServer() - remove server
  * toggleApp() - enable/disable server for specific app
  * syncAllServers() - sync all enabled servers to live configs
- Import new McpServersMap type

## Code Organization
- Keep all types in src/types.ts (removed duplicate types/mcp.ts)
- Follow existing project structure conventions

Related: v3.7.0 unified MCP management
2025-11-14 13:01:47 +08:00
Jason
7ae2a9f556 fix(mcp): resolve compilation errors and add backward compatibility
## Compilation Fixes
- Add deprecated compatibility methods to McpService:
  * get_servers() - filters servers by app
  * set_enabled() - delegates to toggle_app()
  * sync_enabled() - syncs enabled servers for specific app
  * import_from_claude/codex/gemini() - wraps mcp:: functions
- Fix toml_edit type conversion in sync_single_server_to_codex():
  * Add json_server_to_toml_table() helper function
  * Manually construct toml_edit::Table instead of invalid serde conversion
- Fix get_codex_config_path() calls (returns PathBuf, not Result)
- Update upsert_mcp_server_in_config() to work with unified structure:
  * Converts old per-app API to unified McpServer structure
  * Preserves existing server data when updating
  * Supports sync_other_side parameter for multi-app enable
- Update delete_mcp_server_in_config() to ignore app parameter

## Backward Compatibility
- All old v3.6.x commands continue to work with deprecation warnings
- Frontend migration can be done incrementally
- Old commands transparently use new unified backend

## Status
 Backend compiles successfully (cargo check passes)
⚠️ 16 warnings (8 deprecation + 8 unused functions - expected)
2025-11-14 12:57:14 +08:00
Jason
c985db8f3d feat(mcp): implement unified MCP management for v3.7.0
BREAKING CHANGE: Migrate from app-specific MCP storage to unified structure

## Phase 1: Data Structure Migration
- Add McpApps struct with claude/codex/gemini boolean fields
- Add McpServer struct for unified server definition
- Add migration logic in MultiAppConfig::migrate_mcp_to_unified()
- Integrate automatic migration into MultiAppConfig::load()
- Support backward compatibility through Optional fields

## Phase 2: Backend Services Refactor
- Completely rewrite services/mcp.rs for unified management:
  * get_all_servers() - retrieve all MCP servers
  * upsert_server() - add/update unified server
  * delete_server() - remove server
  * toggle_app() - enable/disable server for specific app
  * sync_all_enabled() - sync to all live configs
- Add single-server sync functions to mcp.rs:
  * sync_single_server_to_claude/codex/gemini()
  * remove_server_from_claude/codex/gemini()
- Add read_mcp_servers_map() to claude_mcp.rs and gemini_mcp.rs
- Add new Tauri commands to commands/mcp.rs:
  * get_mcp_servers, upsert_mcp_server, delete_mcp_server
  * toggle_mcp_app, sync_all_mcp_servers
- Register new commands in lib.rs

## Migration Strategy
- Detects old structure (mcp.claude/codex/gemini.servers)
- Merges into unified mcp.servers with apps markers
- Handles conflicts by merging enabled apps
- Clears old structures after migration
- Saves migrated config automatically

## Known Issues
- Old commands still need compatibility layer (WIP)
- toml_edit type conversion needs fixing (WIP)
- Frontend not yet implemented (Phase 3 pending)

Related: v3.6.2 -> v3.7.0
2025-11-14 12:51:24 +08:00
Jason
c7b235bb98 fix(i18n): add missing Gemini MCP panel title and fix ternary logic
- Add mcp.geminiTitle to both zh.json and en.json
- Fix McpPanel title logic to handle all three apps (claude/codex/gemini)
- Previous logic would incorrectly display codexTitle for gemini
2025-11-14 10:35:55 +08:00
Jason
1616c63c0b feat(gemini): implement full MCP management functionality
- Add gemini_mcp.rs module for Gemini MCP file I/O operations
- Implement sync_enabled_to_gemini to export enabled MCPs to ~/.gemini/settings.json
- Implement import_from_gemini to import MCPs from Gemini config
- Add Gemini sync logic in services/mcp.rs (upsert_server, delete_server, set_enabled)
- Register Tauri commands for Gemini MCP sync and import
- Update frontend API calls and McpPanel to support Gemini

Fixes the issue where adding MCP servers in Gemini tab would not sync to ~/.gemini/settings.json
2025-11-14 10:02:27 +08:00
Jason
146b42fb68 feat(gemini): add config.json editor and common config functionality
Implements dual-editor pattern for Gemini providers, following the Codex architecture:
- Environment variables (.env format) editor
- Extended configuration (config.json) editor with common config support

New Components:
- GeminiConfigSections: Separate sections for env and config editing
- GeminiCommonConfigModal: Modal for editing common config snippets

New Hooks:
- useGeminiConfigState: Manages env/config separation and conversion
  - Converts between .env string format and JSON object
  - Validates JSON config structure
  - Extracts API Key and Base URL from env
- useGeminiCommonConfig: Handles common config snippets
  - Deep merge algorithm for combining configs
  - Remove common config logic for toggling off
  - localStorage persistence for snippets

Features:
- Format buttons for both env and config editors
- Common config toggle with deep merge/remove
- Error validation and display
- Auto-open modal on common config errors

Configuration Structure:
{
  "env": {
    "GOOGLE_GEMINI_BASE_URL": "https://...",
    "GEMINI_API_KEY": "sk-...",
    "GEMINI_MODEL": "gemini-2.5-pro"
  },
  "config": {
    "timeout": 30000,
    "maxRetries": 3
  }
}

This brings Gemini providers to feature parity with Claude and Codex.
2025-11-14 08:32:30 +08:00
Jason
0ea434a485 fix(i18n): deduplicate category labels by reusing providerForm keys
- Change ProviderForm to use providerForm.category* instead of providerPreset.category*
- Remove duplicate category keys from providerPreset namespace in both zh.json and en.json
- Fix naming inconsistency: use categoryAggregation (not categoryAggregator)
- Fixes issue where English UI would show Chinese defaultValue fallbacks

This ensures single source of truth for category labels and improves maintainability.
2025-11-14 08:31:09 +08:00
Jason
21fd7cc9fd feat: migrate Claude common config snippet from localStorage to config.json
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
2025-11-13 22:45:58 +08:00
Jason
434c64f38d fix(ui): prevent URL overflow in provider cards
Add max-width constraint to URL display to prevent long URLs from breaking card layout.
2025-11-13 17:14:49 +08:00
Jason
6d8e822f8d refactor(i18n): remove unnecessary translation for brand names
- Use hardcoded "Claude", "Codex", "Gemini" instead of i18n keys
- Brand names should not be translated across different locales
- Simplifies code by removing useTranslation hook from AppSwitcher
- Reduces maintenance overhead in translation files
2025-11-13 17:08:05 +08:00
Jason
2fae8c9275 fix(i18n): add internationalization support for app names
- Add i18n for Claude/Codex/Gemini app names in AppSwitcher
- Use useTranslation hook with existing translation keys
- Fix ASCII diagram alignment in README files
2025-11-13 16:37:58 +08:00
Jason
30c763ffe3 fix(prompt): improve i18n and error handling for auto-import
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.
2025-11-13 15:43:37 +08:00
YoVinchen
e4d7999294 refactor(prompt): extract file path logic and implement auto-import on first launch (#214)
- 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
2025-11-13 15:15:58 +08:00
YoVinchen
34f7139fda fix(usage-script): add input validation and boundary checks (#208)
- Backend: validate auto-query interval ≤ 1440 minutes (24 hours)
- Frontend: add number input sanitization and blur validation
- Add user-friendly error messages for invalid inputs
- Support auto-clamping to valid ranges with toast notifications
2025-11-13 11:28:48 +08:00
YoVinchen
a85f24f616 fix(gemini): relax validation when adding providers (#210)
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
2025-11-13 11:28:28 +08:00
YoVinchen
b9743a463d feat(tray): add Gemini support to system tray menu (#209)
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
2025-11-12 23:38:43 +08:00