mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-07-27 16:26:16 +08:00
d30562954a
* feat(components): add reusable full-screen panel components
Add new full-screen panel components to support the UI refactoring:
- FullScreenPanel: Reusable full-screen layout component with header,
content area, and optional footer. Provides consistent layout for
settings, prompts, and other full-screen views.
- PromptFormPanel: Dedicated panel for creating and editing prompts
with markdown preview support. Features real-time validation and
integrated save/cancel actions.
- AgentsPanel: Panel component for managing agent configurations.
Provides a consistent interface for agent CRUD operations.
- RepoManagerPanel: Full-featured repository manager panel for Skills.
Supports repository listing, addition, deletion, and configuration
management with integrated validation.
These components establish the foundation for the upcoming settings
page migration from dialog-based to full-screen layout.
* refactor(settings): migrate from dialog to full-screen page layout
Complete migration of settings from modal dialog to dedicated full-screen
page, improving UX and providing more space for configuration options.
Changes:
- Remove SettingsDialog component (legacy modal-based interface)
- Add SettingsPage component with full-screen layout using FullScreenPanel
- Refactor App.tsx routing to support dedicated settings page
* Add settings route handler
* Update navigation logic from dialog-based to page-based
* Integrate with existing app switcher and provider management
- Update ImportExportSection to work with new page layout
* Improve spacing and layout for better readability
* Enhanced error handling and user feedback
* Better integration with page-level actions
- Enhance useSettings hook to support page-based workflow
* Add navigation state management
* Improve settings persistence logic
* Better error boundary handling
Benefits:
- More intuitive navigation with dedicated settings page
- Better use of screen space for complex configurations
- Improved accessibility with clearer visual hierarchy
- Consistent with modern desktop application patterns
- Easier to extend with new settings sections
This change is part of the larger UI refactoring initiative to modernize
the application interface and improve user experience.
* refactor(forms): simplify and modernize form components
Comprehensive refactoring of form components to reduce complexity,
improve maintainability, and enhance user experience.
Provider Forms:
- CodexCommonConfigModal & CodexConfigSections
* Simplified state management with reduced boilerplate
* Improved field validation and error handling
* Better layout with consistent spacing
* Enhanced model selection with visual indicators
- GeminiCommonConfigModal & GeminiConfigSections
* Streamlined authentication flow (OAuth vs API Key)
* Cleaner form layout with better grouping
* Improved validation feedback
* Better integration with parent components
- CommonConfigEditor
* Reduced from 178 to 68 lines (-62% complexity)
* Extracted reusable form patterns
* Improved JSON editing with syntax validation
* Better error messages and recovery options
- EndpointSpeedTest
* Complete rewrite for better UX
* Real-time testing progress indicators
* Enhanced error handling with retry logic
* Visual feedback for test results (color-coded latency)
MCP & Prompts:
- McpFormModal
* Simplified from 581 to ~360 lines
* Better stdio/http server type handling
* Improved form validation
* Enhanced multi-app selection (Claude/Codex/Gemini)
- PromptPanel
* Cleaner integration with PromptFormPanel
* Improved list/grid view switching
* Better state management for editing workflows
* Enhanced delete confirmation with safety checks
Code Quality Improvements:
- Reduced total lines by ~251 lines (-24% code reduction)
- Eliminated duplicate validation logic
- Improved TypeScript type safety
- Better component composition and separation of concerns
- Enhanced accessibility with proper ARIA labels
These changes make forms more intuitive, responsive, and easier to
maintain while reducing bundle size and improving runtime performance.
* style(ui): modernize component layouts and visual design
Update UI components with improved layouts, visual hierarchy, and
modern design patterns for better user experience.
Navigation & Brand Components:
- AppSwitcher
* Enhanced visual design with better spacing
* Improved active state indicators
* Smoother transitions and hover effects
* Better mobile responsiveness
- BrandIcons
* Optimized icon rendering performance
* Added support for more provider icons
* Improved SVG handling and fallbacks
* Better scaling across different screen sizes
Editor Components:
- JsonEditor
* Enhanced syntax highlighting
* Better error visualization
* Improved code formatting options
* Added line numbers and code folding support
- UsageScriptModal
* Complete layout overhaul (1239 lines refactored)
* Better script editor integration
* Improved template selection UI
* Enhanced preview and testing panels
* Better error feedback and validation
Provider Components:
- ProviderCard
* Redesigned card layout with modern aesthetics
* Better information density and readability
* Improved action buttons placement
* Enhanced status indicators (active/inactive)
- ProviderList
* Better grid/list view layouts
* Improved drag-and-drop visual feedback
* Enhanced sorting indicators
- ProviderActions
* Streamlined action menu
* Better icon consistency
* Improved tooltips and accessibility
Usage & Footer:
- UsageFooter
* Redesigned footer layout
* Better quota visualization
* Improved refresh controls
* Enhanced error states
Design System Updates:
- dialog.tsx (shadcn/ui component)
* Updated to latest design tokens
* Better overlay animations
* Improved focus management
- index.css
* Added 65 lines of global utility classes
* New animation keyframes
* Enhanced color variables for dark mode
* Improved typography scale
- tailwind.config.js
* Extended theme with new design tokens
* Added custom animations and transitions
* New spacing and sizing utilities
* Enhanced color palette
Visual Improvements:
- Consistent border radius across components
- Unified shadow system for depth perception
- Better color contrast for accessibility (WCAG AA)
- Smoother animations and transitions
- Improved dark mode support
These changes create a more polished, modern interface while
maintaining consistency with the application's design language.
* chore: update dialogs, i18n and improve component integration
Various functional updates and improvements across provider dialogs,
MCP panel, skills page, and internationalization.
Provider Dialogs:
- AddProviderDialog
* Simplified form state management
* Improved preset selection workflow
* Better validation error messages
* Enhanced template variable handling
- EditProviderDialog
* Streamlined edit flow with better state synchronization
* Improved handling of live config backfilling
* Better error recovery for failed updates
* Enhanced integration with parent components
MCP & Skills:
- UnifiedMcpPanel
* Reduced complexity from 140+ to ~95 lines
* Improved multi-app server management
* Better server type detection (stdio/http)
* Enhanced server status indicators
* Cleaner integration with MCP form modal
- SkillsPage
* Simplified navigation and state management
* Better integration with RepoManagerPanel
* Improved error handling for repository operations
* Enhanced loading states
- SkillCard
* Minor layout adjustments
* Better action button placement
Environment & Configuration:
- EnvWarningBanner
* Improved conflict detection messages
* Better visual hierarchy for warnings
* Enhanced dismissal behavior
- tauri.conf.json
* Updated build configuration
* Added new window management options
Internationalization:
- en.json & zh.json
* Added 17 new translation keys for new features
* Updated existing keys for better clarity
* Added translations for new settings page
* Improved consistency across UI text
Code Cleanup:
- mutations.ts
* Removed 14 lines of unused mutation definitions
* Cleaned up deprecated query invalidation logic
* Better type safety for mutation parameters
Overall Impact:
- Reduced total lines by 51 (-10% in affected files)
- Improved component integration and data flow
- Better error handling and user feedback
- Enhanced i18n coverage for new features
These changes improve the overall polish and integration of various
components while removing technical debt and unused code.
* feat(backend): add auto-launch functionality
Implement system auto-launch feature to allow CC-Switch to start
automatically on system boot, improving user convenience.
Backend Implementation:
- auto_launch.rs: New module for auto-launch management
* Cross-platform support using auto-launch crate
* Enable/disable auto-launch with system integration
* Proper error handling for permission issues
* Platform-specific implementations (macOS/Windows/Linux)
Command Layer:
- Add get_auto_launch command to check current status
- Add set_auto_launch command to toggle auto-start
- Integrate commands with settings API
Settings Integration:
- Extend Settings struct with auto_launch field
- Persist auto-launch preference in settings store
- Automatic state synchronization on app startup
Dependencies:
- Add auto-launch ^0.5.0 to Cargo.toml
- Update Cargo.lock with new dependency tree
Technical Details:
- Uses platform-specific auto-launch mechanisms:
* macOS: Login Items via LaunchServices
* Windows: Registry Run key
* Linux: XDG autostart desktop files
- Handles edge cases like permission denials gracefully
- Maintains settings consistency across app restarts
This feature enables users to have CC-Switch readily available
after system boot without manual intervention, particularly useful
for users who frequently switch between API providers.
* refactor(settings): enhance settings page with auto-launch integration
Complete refactoring of settings page architecture to integrate auto-launch
feature and improve overall settings management workflow.
SettingsPage Component:
- Integrate auto-launch toggle with WindowSettings section
- Improve layout and spacing for better visual hierarchy
- Enhanced error handling for settings operations
- Better loading states during settings updates
- Improved accessibility with proper ARIA labels
WindowSettings Component:
- Add auto-launch switch with real-time status
- Integrate with backend auto-launch commands
- Proper error feedback for permission issues
- Visual indicators for current auto-launch state
- Tooltip guidance for auto-launch functionality
useSettings Hook (Major Refactoring):
- Complete rewrite reducing complexity by ~30%
- Better separation of concerns with dedicated handlers
- Improved state management using React Query
- Enhanced auto-launch state synchronization
* Fetch auto-launch status on mount
* Real-time updates on toggle
* Proper error recovery
- Optimized re-renders with better memoization
- Cleaner API for component integration
- Better TypeScript type safety
Settings API:
- Add getAutoLaunch() method
- Add setAutoLaunch(enabled: boolean) method
- Type-safe Tauri command invocations
- Proper error propagation to UI layer
Architecture Improvements:
- Reduced hook complexity from 197 to ~140 effective lines
- Eliminated redundant state management logic
- Better error boundaries and fallback handling
- Improved testability with clearer separation
User Experience Enhancements:
- Instant visual feedback on auto-launch toggle
- Clear error messages for permission issues
- Loading indicators during async operations
- Consistent behavior across all platforms
This refactoring provides a solid foundation for future settings
additions while maintaining code quality and user experience.
* refactor(ui): optimize FullScreenPanel, Dialog and App routing
Comprehensive refactoring of core UI components to improve code quality,
maintainability, and user experience.
FullScreenPanel Component:
- Enhanced props interface with better TypeScript types
- Improved layout flexibility with customizable padding
- Better header/footer composition patterns
- Enhanced scroll behavior for long content
- Added support for custom actions in header
- Improved responsive design for different screen sizes
- Better integration with parent components
- Cleaner prop drilling with context where appropriate
Dialog Component (shadcn/ui):
- Updated to latest component patterns
- Improved animation timing and easing
- Better focus trap management
- Enhanced overlay styling with backdrop blur
- Improved accessibility (ARIA labels, keyboard navigation)
- Better close button positioning and styling
- Enhanced mobile responsiveness
- Cleaner composition with DialogHeader/Footer
App Component Routing:
- Refactored routing logic for better clarity
- Improved state management for navigation
- Better integration with settings page
- Enhanced error boundary handling
- Cleaner separation of layout concerns
- Improved provider context propagation
- Better handling of deep links
- Optimized re-renders with React.memo where appropriate
Code Quality Improvements:
- Reduced prop drilling with better component composition
- Improved TypeScript type safety
- Better separation of concerns
- Enhanced code readability with clearer naming
- Eliminated redundant logic
Performance Optimizations:
- Reduced unnecessary re-renders
- Better memoization of callbacks
- Optimized component tree structure
- Improved event handler efficiency
User Experience:
- Smoother transitions and animations
- Better visual feedback for interactions
- Improved loading states
- More consistent behavior across features
These changes create a more maintainable and performant foundation
for the application's UI layer while improving the overall user
experience with smoother interactions and better visual polish.
* refactor(features): modernize Skills, Prompts and Agents components
Major refactoring of feature components to improve code quality,
user experience, and maintainability.
SkillsPage Component (299 lines refactored):
- Complete rewrite of layout and state management
- Better integration with RepoManagerPanel
- Improved navigation between list and detail views
- Enhanced error handling with user-friendly messages
- Better loading states with skeleton screens
- Optimized re-renders with proper memoization
- Cleaner separation between list and form views
- Improved skill card interactions
- Better responsive design for different screen sizes
RepoManagerPanel Component (370 lines refactored):
- Streamlined repository management workflow
- Enhanced form validation with real-time feedback
- Improved repository list with better visual hierarchy
- Better handling of git operations (clone, pull, delete)
- Enhanced error recovery for network issues
- Cleaner state management reducing complexity
- Improved TypeScript type safety
- Better integration with Skills backend API
- Enhanced loading indicators for async operations
PromptPanel Component (249 lines refactored):
- Modernized layout with FullScreenPanel integration
- Better separation between list and edit modes
- Improved prompt card design with better readability
- Enhanced search and filter functionality
- Cleaner state management for editing workflow
- Better integration with PromptFormPanel
- Improved delete confirmation with safety checks
- Enhanced keyboard navigation support
PromptFormPanel Component (238 lines refactored):
- Streamlined form layout and validation
- Better markdown editor integration
- Real-time preview with syntax highlighting
- Improved validation error display
- Enhanced save/cancel workflow
- Better handling of large prompt content
- Cleaner form state management
- Improved accessibility features
AgentsPanel Component (33 lines modified):
- Minor layout adjustments for consistency
- Better integration with FullScreenPanel
- Improved placeholder states
- Enhanced error boundaries
Type Definitions (types.ts):
- Added 10 new type definitions
- Better type safety for Skills/Prompts/Agents
- Enhanced interfaces for repository management
- Improved typing for form validations
Architecture Improvements:
- Reduced component coupling
- Better prop interfaces with explicit types
- Improved error boundaries
- Enhanced code reusability
- Better testing surface
User Experience Enhancements:
- Smoother transitions between views
- Better visual feedback for actions
- Improved error messages
- Enhanced loading states
- More intuitive navigation flows
- Better responsive layouts
Code Quality:
- Net reduction of 29 lines while adding features
- Improved code organization
- Better naming conventions
- Enhanced documentation
- Cleaner control flow
These changes significantly improve the maintainability and user
experience of core feature components while establishing consistent
patterns for future development.
* style(ui): refine component layouts and improve visual consistency
Comprehensive UI polish across multiple components to enhance visual
design, improve user experience, and maintain consistency.
UsageScriptModal Component (1302 lines refactored):
- Complete layout overhaul for better usability
- Improved script editor with syntax highlighting
- Better template selection interface
- Enhanced test/preview panels with clearer separation
- Improved error feedback and validation messages
- Better modal sizing and responsiveness
- Cleaner tab navigation between sections
- Enhanced code formatting and readability
- Improved loading states for async operations
- Better integration with parent components
MCP Components:
- McpFormModal (42 lines):
* Streamlined form layout
* Better server type selection (stdio/http)
* Improved field grouping and labels
* Enhanced validation feedback
- UnifiedMcpPanel (14 lines):
* Minor layout adjustments
* Better list item spacing
* Improved server status indicators
* Enhanced action button placement
Provider Components:
- ProviderCard (11 lines):
* Refined card layout and spacing
* Better visual hierarchy
* Improved badge placement
* Enhanced hover effects
- ProviderList (5 lines):
* Minor grid layout adjustments
* Better drag-and-drop visual feedback
- GeminiConfigSections (4 lines):
* Field label alignment
* Improved spacing consistency
Editor & Footer Components:
- JsonEditor (13 lines):
* Better editor height management
* Improved error display
* Enhanced syntax highlighting
- UsageFooter (10 lines):
* Refined footer layout
* Better quota display
* Improved refresh button placement
Settings & Environment:
- ImportExportSection (24 lines):
* Better button layout
* Improved action grouping
* Enhanced visual feedback
- EnvWarningBanner (4 lines):
* Refined alert styling
* Better dismiss button placement
Global Styles (index.css):
- Added 11 lines of utility classes
- Improved transition timing
- Better focus indicators
- Enhanced scrollbar styling
- Refined spacing utilities
Design Improvements:
- Consistent spacing using design tokens
- Unified color palette application
- Better typography hierarchy
- Improved shadow system for depth
- Enhanced interactive states (hover, active, focus)
- Better border radius consistency
- Refined animation timings
Accessibility:
- Improved focus indicators
- Better keyboard navigation
- Enhanced screen reader support
- Improved color contrast ratios
Code Quality:
- Net increase of 68 lines due to UsageScriptModal improvements
- Better component organization
- Cleaner style application
- Reduced style duplication
These visual refinements create a more polished and professional
interface while maintaining excellent usability and accessibility
standards across all components.
* chore(i18n): add auto-launch translation keys
Add translation keys for new auto-launch feature to support
multi-language interface.
Translation Keys Added:
- autoLaunch: Label for auto-launch toggle
- autoLaunchDescription: Explanation of auto-launch functionality
- autoLaunchEnabled: Status message when enabled
Languages Updated:
- Chinese (zh.json): 简体中文翻译
- English (en.json): English translations
The translations maintain consistency with existing terminology
and provide clear, user-friendly descriptions of the auto-launch
feature across both supported languages.
* test: update test suites to match component refactoring
Comprehensive test updates to align with recent component refactoring
and new auto-launch functionality.
Component Tests:
- AddProviderDialog.test.tsx (10 lines):
* Updated test cases for new dialog behavior
* Enhanced mock data for preset selection
* Improved assertions for validation
- ImportExportSection.test.tsx (16 lines):
* Updated for new settings page integration
* Enhanced test coverage for error scenarios
* Better mock state management
- McpFormModal.test.tsx (60 lines):
* Extensive updates for form refactoring
* New test cases for multi-app selection
* Enhanced validation testing
* Better coverage of stdio/http server types
- ProviderList.test.tsx (11 lines):
* Updated for new card layout
* Enhanced drag-and-drop testing
- SettingsDialog.test.tsx (96 lines):
* Major updates for SettingsPage migration
* New test cases for auto-launch functionality
* Enhanced integration test coverage
* Better async operation testing
Hook Tests:
- useDirectorySettings.test.tsx (32 lines):
* Updated for refactored hook logic
* Enhanced test coverage for edge cases
- useDragSort.test.tsx (36 lines):
* Simplified test cases
* Better mock implementation
* Improved assertions
- useImportExport tests (16 lines total):
* Updated for new error handling
* Enhanced test coverage
- useMcpValidation.test.tsx (23 lines):
* Updated validation test cases
* Better coverage of error scenarios
- useProviderActions.test.tsx (48 lines):
* Extensive updates for hook refactoring
* New test cases for provider operations
* Enhanced mock data
- useSettings.test.tsx (12 lines):
* New test cases for auto-launch
* Enhanced settings state testing
* Better async operation coverage
Integration Tests:
- App.test.tsx (41 lines):
* Updated for new routing logic
* Enhanced navigation testing
* Better component integration coverage
- SettingsDialog.test.tsx (88 lines):
* Complete rewrite for SettingsPage
* New integration test scenarios
* Enhanced user workflow testing
Mock Infrastructure:
- handlers.ts (117 lines):
* Major updates for MSW handlers
* New handlers for auto-launch commands
* Enhanced error simulation
* Better request/response mocking
- state.ts (37 lines):
* Updated mock state structure
* New state for auto-launch
* Enhanced state reset functionality
- tauriMocks.ts (10 lines):
* Updated mock implementations
* Better type safety
- server.ts & testQueryClient.ts:
* Minor cleanup (2 lines removed)
Test Infrastructure Improvements:
- Better test isolation
- Enhanced mock data consistency
- Improved async operation testing
- Better error scenario coverage
- Enhanced integration test patterns
Coverage Improvements:
- Net increase of 195 lines of test code
- Better coverage of edge cases
- Enhanced error path testing
- Improved integration test scenarios
- Better mock infrastructure
All tests now pass with the refactored components while maintaining
comprehensive coverage of functionality and edge cases.
* style(ui): improve window dragging and provider card styles
* fix(skills): resolve third-party skills installation failure
- Add skills_path field to Skill struct
- Use skills_path to construct correct source path during installation
- Fix installation for repos with custom skill subdirectories
* feat(icon): add icon type system and intelligent inference logic
Introduce a new icon system for provider customization:
- Add IconMetadata and IconPreset interfaces in src/types/icon.ts
- Define structure for icon name, display name, category, keywords
- Support default color configuration per icon
- Implement smart icon inference in src/config/iconInference.ts
- Create iconMappings for 25+ AI providers and cloud platforms
- Include Claude, DeepSeek, Qwen, Kimi, Google, AWS, Azure, etc.
- inferIconForPreset(): match provider name to icon config
- addIconsToPresets(): batch apply icons to preset arrays
- Support fuzzy matching for flexible name recognition
This foundation enables automatic icon assignment when users add
providers, improving visual identification in the provider list.
* feat(ui): add icon picker, color picker and provider icon components
Implement comprehensive icon selection system for provider customization:
## New Components
### ProviderIcon (src/components/ProviderIcon.tsx)
- Render SVG icons by name with automatic fallback
- Display provider initials when icon not found
- Support custom sizing via size prop
- Use dangerouslySetInnerHTML for inline SVG rendering
### IconPicker (src/components/IconPicker.tsx)
- Grid-based icon selection with visual preview
- Real-time search filtering by name and keywords
- Integration with icon metadata for display names
- Responsive grid layout (6-10 columns based on screen)
### ColorPicker (src/components/ColorPicker.tsx)
- 12 preset colors for quick selection
- Native color input for custom color picking
- Hex input field for precise color entry
- Visual feedback for selected color state
## Icon Assets (src/icons/extracted/)
- 38 high-quality SVG icons for AI providers and platforms
- Includes: OpenAI, Claude, DeepSeek, Qwen, Kimi, Gemini, etc.
- Cloud platforms: AWS, Azure, Google Cloud, Cloudflare
- Auto-generated index.ts with getIcon/hasIcon helpers
- Metadata system with searchable keywords per icon
## Build Scripts
- scripts/extract-icons.js: Extract icons from simple-icons
- scripts/generate-icon-index.js: Generate TypeScript index file
* feat(provider): integrate icon system into provider UI components
Add icon customization support to provider management interface:
## Type System Updates
### Provider Interface (src/types.ts)
- Add optional `icon` field for icon name (e.g., "openai", "anthropic")
- Add optional `iconColor` field for hex color (e.g., "#00A67E")
### Form Schema (src/lib/schemas/provider.ts)
- Extend providerSchema with icon and iconColor optional fields
- Maintain backward compatibility with existing providers
## UI Components
### ProviderCard (src/components/providers/ProviderCard.tsx)
- Display ProviderIcon alongside provider name
- Add icon container with hover animation effect
- Adjust layout spacing for icon placement
- Update translate offsets for action buttons
### BasicFormFields (src/components/providers/forms/BasicFormFields.tsx)
- Add icon preview section showing current selection
- Implement fullscreen icon picker dialog
- Auto-apply default color from icon metadata on selection
- Display provider name and icon status in preview
### AddProviderDialog & EditProviderDialog
- Pass icon fields through form submission
- Preserve icon data during provider updates
This enables users to visually distinguish providers in the list
with custom icons, improving UX for multi-provider setups.
* feat(backend): add icon fields to Provider model and default mappings
Extend Rust backend to support provider icon customization:
## Provider Model (src-tauri/src/provider.rs)
- Add `icon: Option<String>` field for icon name
- Add `icon_color: Option<String>` field for hex color
- Use serde rename `iconColor` for frontend compatibility
- Apply skip_serializing_if for clean JSON output
- Update Provider::new() to initialize icon fields as None
## Provider Defaults (src-tauri/src/provider_defaults.rs) [NEW]
- Define ProviderIcon struct with name and color fields
- Create DEFAULT_PROVIDER_ICONS static HashMap with 23 providers:
- AI providers: OpenAI, Anthropic, Claude, Google, Gemini,
DeepSeek, Kimi, Moonshot, Zhipu, MiniMax, Baidu, Alibaba,
Tencent, Meta, Microsoft, Cohere, Perplexity, Mistral, HuggingFace
- Cloud platforms: AWS, Azure, Huawei, Cloudflare
- Implement infer_provider_icon() with exact and fuzzy matching
- Add unit tests for matching logic (exact, fuzzy, case-insensitive)
## Deep Link Support (src-tauri/src/deeplink.rs)
- Initialize icon fields when creating Provider from deep link import
## Module Registration (src-tauri/src/lib.rs)
- Register provider_defaults module
## Dependencies (Cargo.toml)
- Add once_cell for lazy static initialization
This backend support enables icon persistence and future features
like auto-icon inference during provider creation.
* chore(i18n): add translations for icon picker and provider icon
Add Chinese and English translations for icon customization feature:
## Icon Picker (iconPicker)
- search: "Search Icons" / "搜索图标"
- searchPlaceholder: "Enter icon name..." / "输入图标名称..."
- noResults: "No matching icons found" / "未找到匹配的图标"
- category.aiProvider: "AI Providers" / "AI 服务商"
- category.cloud: "Cloud Platforms" / "云平台"
- category.tool: "Dev Tools" / "开发工具"
- category.other: "Other" / "其他"
## Provider Icon (providerIcon)
- label: "Icon" / "图标"
- colorLabel: "Icon Color" / "图标颜色"
- selectIcon: "Select Icon" / "选择图标"
- preview: "Preview" / "预览"
These translations support the new icon picker UI components
and provider form icon selection interface.
* style(ui): refine header layout and AppSwitcher color scheme
Improve application header and component styling:
## App.tsx Header Layout
- Wrap title and settings button in flex container with gap
- Add vertical divider between title and settings icon
- Apply responsive padding (pl-1 sm:pl-2)
- Reformat JSX for better readability (prettier)
- Fix string template formatting in className
## AppSwitcher Color Update
- Change Claude tab gradient from orange/amber to teal/emerald/green
- Update shadow color to match new teal theme
- Change hover color from orange-500 to teal-500
- Align visual style with emerald/teal brand colors
## Dialog Component Cleanup
- Remove default close button (X icon) from DialogContent
- Allow parent components to control close button placement
- Remove unused lucide-react X import
## index.css Header Border
- Add top border (2px solid) to glass-header
- Apply to both light and dark mode variants
- Improve visual separation of header area
These changes enhance visual consistency and modernize the UI
appearance with a cohesive teal color scheme.
* chore(deps): add icon library and update preset configurations
Add dependencies and utility scripts for icon system:
## Dependencies (package.json)
- Add @lobehub/icons-static-svg@1.73.0
- High-quality SVG icon library for AI providers
- Source for extracted icons in src/icons/extracted/
- Update pnpm-lock.yaml accordingly
## Provider Preset Updates (src/config/claudeProviderPresets.ts)
- Add optional `icon` and `iconColor` fields to ProviderPreset interface
- Apply to Anthropic Official preset as example:
- icon: "anthropic"
- iconColor: "#D4915D"
- Future presets can include default icon configurations
## Utility Script (scripts/filter-icons.js) [NEW]
- Helper script for filtering and managing icon assets
- Supports icon discovery and validation workflow
- Complements extract-icons.js and generate-icon-index.js
This completes the icon system infrastructure, providing all
necessary tools and dependencies for icon customization.
* refactor(ui): simplify AppSwitcher styles and migrate to local SVG icons
- Replace complex gradient animations with clean, minimal tab design
- Migrate from @lobehub/icons CDN to local SVG assets for better reliability
- Fix clippy warning in error.rs (use inline format args)
- Improve code formatting in skill service and commands
- Reduce CSS complexity in AppSwitcher component (removed blur effects and gradients)
- Update BrandIcons to use imported local SVG files instead of dynamic image loading
This improves performance, reduces external dependencies, and provides a cleaner UI experience.
* style(ui): hide scrollbars across all browsers and optimize form layout
- Hide scrollbars globally with cross-browser support:
* WebKit browsers (Chrome, Safari, Edge): ::-webkit-scrollbar { display: none }
* Firefox: scrollbar-width: none
* IE 10+: -ms-overflow-style: none
- Remove custom scrollbar styling (width, colors, hover states)
- Reorganize BasicFormFields layout:
* Move icon picker to top center as a clickable preview (80x80)
* Change name and notes fields to horizontal grid layout (md:grid-cols-2)
* Remove icon preview section from bottom
* Improve visual hierarchy and space efficiency
This provides a cleaner, more modern UI with hidden scrollbars while maintaining full scroll functionality.
* refactor(layout): standardize max-width to 60rem and optimize padding structure
- Unify container max-width across components:
* Replace max-w-4xl with max-w-[60rem] in App.tsx provider list
* Replace max-w-5xl with max-w-[60rem] in PromptPanel
* Move padding from header element to inner container for consistent spacing
- Optimize padding hierarchy:
* Remove px-6 from header element, add to inner header container
* Remove px-6 from main element, keep it only in provider list container
* Consolidate PromptPanel padding: move px-6 from nested divs to outer container
* Remove redundant pl-1 sm:pl-2 from logo/title area
- Benefits:
* Consistent 60rem max-width provides better readability on wide screens
* Simplified padding structure reduces CSS complexity
* Cleaner responsive behavior with unified spacing rules
This creates a more maintainable and visually consistent layout system.
* refactor(ui): unify layout system with 60rem max-width and consistent spacing
- Standardize container max-width across all panels:
* Replace max-w-4xl and max-w-5xl with unified max-w-[60rem]
* Apply to SettingsPage, UnifiedMcpPanel, SkillsPage, and FullScreenPanel
* Ensures consistent reading width and visual balance on wide screens
- Optimize padding hierarchy and structure:
* Move px-6 from parent elements to content containers
* FullScreenPanel: Add max-w-[60rem] wrapper to header, content, and footer
* Add border separators (border-t/border-b) to header and footer sections
* Consolidate nested padding in MCP, Skills, and Prompts panels
* Remove redundant padding layers for cleaner CSS
- Simplify component styling:
* MCP list items: Replace card-based layout with modern group-based design
* Remove unnecessary wrapper divs and flatten DOM structure
* Update card hover effects with smooth transitions
* Simplify icon selection dialog (remove description text in BasicFormFields)
- Benefits:
* Consistent 60rem max-width provides optimal readability
* Unified spacing rules reduce maintenance complexity
* Cleaner component hierarchy improves performance
* Better responsive behavior across different screen sizes
* More cohesive visual design language throughout the app
This creates a maintainable, scalable design system foundation.
* feat(deeplink): add Claude model fields support and enhance import dialog
- Add Claude-specific model field support in deeplink import:
* Support model (ANTHROPIC_MODEL) - general default model
* Support haikuModel (ANTHROPIC_DEFAULT_HAIKU_MODEL)
* Support sonnetModel (ANTHROPIC_DEFAULT_SONNET_MODEL)
* Support opusModel (ANTHROPIC_DEFAULT_OPUS_MODEL)
* Backend: Update DeepLinkImportRequest struct to include optional model fields
* Frontend: Add TypeScript type definitions for new model parameters
- Enhance deeplink demo page (deplink.html):
* Add 5 new Claude configuration examples showcasing different model setups
* Add parameter documentation with required/optional tags
* Include basic config (no models), single model, complete 4-model, partial models, and third-party provider examples
* Improve visual design with param-list component and color-coded badges
* Add detailed descriptions for each configuration scenario
- Redesign DeepLinkImportDialog layout:
* Switch from 3-column to compact 2-column grid layout
* Reduce dialog width from 500px to 650px for better content display
* Add dedicated section for Claude model configurations with blue highlight box
* Use uppercase labels and smaller text for more information density
* Add truncation and tooltips for long URLs
* Improve visual hierarchy with spacing and grouping
* Increase z-index to 9999 to ensure dialog appears on top
- Minor UI refinements:
* Update App.tsx layout adjustments
* Optimize McpFormModal styling
* Refine ProviderCard and BasicFormFields components
This enables users to import Claude providers with precise model configurations via deeplink.
* feat(deeplink): add config file support for deeplink import
Support importing provider configuration from embedded or remote config files.
- Add base64 dependency for config content encoding
- Support config, configFormat, and configUrl parameters
- Make homepage/endpoint/apiKey optional when config is provided
- Add config parsing and merging logic
* feat(deeplink): enhance dialog with config file preview
Add config file parsing and preview in deep link import dialog.
- Support Base64 encoded config display
- Add config file source indicator (embedded/remote)
- Parse and display config fields by app type (Claude/Codex/Gemini)
- Mask sensitive values in config preview
- Improve dialog layout and content organization
* refactor(ui): unify dialog styles and improve layout consistency
Standardize dialog and panel components across the application.
- Update dialog background to use semantic color tokens
- Adjust FullScreenPanel max-width to 56rem for better alignment
- Add drag region and prevent body scroll in full-screen panels
- Optimize button sizes and spacing in panel headers
- Apply consistent styling to all dialog-based components
* i18n: add deeplink config preview translations
Add missing translation keys for config file preview feature.
- Add configSource, configEmbedded, configRemote labels
- Add configDetails and configUrl display strings
- Support both Chinese and English versions
* feat(deeplink): enhance test page with v3.8 config file examples
Improve deeplink test page with comprehensive config file import examples.
- Add version badge for v3.8 features
- Add copy-to-clipboard functionality for all deep links
- Add Claude config file import examples (embedded/remote)
- Add Codex config file import examples (auth.json + config.toml)
- Add Gemini config file import examples (.env format)
- Add config generator tool for easy testing
- Update UI with better styling and layout
* feat(settings): add autoSaveSettings for lightweight auto-save
Add optimized auto-save function for General tab settings.
- Add autoSaveSettings method for non-destructive auto-save
- Only trigger system APIs when values actually change
- Avoid unnecessary auto-launch and plugin config updates
- Update tests to cover new functionality
* refactor(settings): simplify settings page layout and auto-save
Reorganize settings page structure and integrate autoSaveSettings.
- Move save button inline within Advanced tab content
- Remove sticky footer for cleaner layout
- Use autoSaveSettings for General tab settings
- Simplify dialog close behavior
- Refactor ImportExportSection layout
* style(providers): optimize card layout and action button sizes
Improve provider card visual density and action buttons.
- Reduce icon button sizes for compact layout
- Adjust drag handle and icon sizes
- Tighten spacing between action buttons
- Update hover translate values for better alignment
* refactor(mcp): improve form modal layout with adaptive height editor
Restructure MCP form modal for better space utilization.
- Split form into upper form fields and lower JSON editor sections
- Add full-height mode support for JsonEditor component
- Use flex layout for editor to fill available space
- Update PromptFormPanel to use full-height editor
- Fix locale text formatting
* style: unify list item styles with semantic colors
Apply consistent styling to list items across components.
- Replace hardcoded colors with semantic tokens in MCP and Prompt list items
- Add glass effect container to EndpointSpeedTest panel
- Format code for better readability
* style: format template literals for better readability
Improve code formatting for conditional className expressions.
- Break long template literals across multiple lines
- Maintain consistent formatting in MCP form and endpoint test components
* feat(deeplink): add config merge command for preview
Expose config merging functionality to frontend for preview.
- Add merge_deeplink_config Tauri command
- Make parse_and_merge_config public for reuse
- Enable frontend to display complete config before import
* feat(deeplink): merge and display config in import dialog
Enhance import dialog to fetch and display complete config.
- Call mergeDeeplinkConfig API when config is present
- Add UTF-8 base64 decoding support for config content
- Add scrollable content area with custom scrollbar styling
- Show complete configuration before user confirms import
* i18n: add config merge error message
Add translation for config file merge error handling.
* style(deeplink): format test page HTML for better readability
Improve HTML formatting in deeplink test page.
- Format multiline attributes for better readability
- Add consistent indentation to nested elements
- Break long lines in buttons and links
* refactor(usage): improve footer layout with two-row design
Reorganize usage footer for better readability and space efficiency.
- Split into two rows: update time + refresh button (row 1), usage stats (row 2)
- Move refresh button to top row next to update time
- Remove card background for cleaner look
- Add fallback text when never updated
- Improve spacing and alignment
- Format template literals for consistency
* feat(database): add SQLite database infrastructure
- Add rusqlite dependency (v0.32.1) and r2d2 connection pooling
- Implement Database module with CRUD operations for providers, MCP servers, prompts, and skills
- Add schema initialization with proper indexes
- Include data migration utilities from JSON config to SQLite
- Support timestamp tracking (created_at, updated_at)
* refactor(core): integrate SQLite database into application core
- Initialize database on app startup with migration from JSON config
- Update AppState to include Database instance alongside MultiAppConfig
- Simplify store module by removing unused session management code
- Add database initialization to app setup flow
- Support both database and legacy config during transition
* refactor(services): migrate service layer to use SQLite database
- Refactor ProviderService to use database queries instead of in-memory config
- Update McpService to fetch and store MCP servers in database
- Migrate PromptService to database-backed storage
- Simplify ConfigService by removing complex transaction logic
- Remove 648 lines of redundant code through database abstraction
* refactor(commands): update command layer to use database API
- Update config commands to query database for providers and settings
- Modify provider commands to pass database handle to services
- Update MCP commands to use database-backed operations
- Refactor prompt and skill commands to leverage database storage
- Simplify import/export commands with database integration
* refactor(backend): update supporting modules for database compatibility
- Add DatabaseError variant to AppError enum
- Update provider module to support database-backed operations
- Modify codex_config to work with new database structure
- Ensure error handling covers database operations
* refactor(frontend): update UI components for database migration
- Update UsageFooter component to handle new data structure
- Modify SkillsPage to work with database-backed skills management
- Ensure frontend compatibility with refactored backend
* feat(skills): add search functionality to Skills page
- Add search input with Search icon in SkillsPage component
- Implement useMemo-based filtering by skill name, description, and directory
- Display search results count when filtering is active
- Show "no results" message when no skills match the search query
- Add i18n translations for search UI (zh/en)
- Maintain responsive layout and consistent styling with existing UI
* refactor(backend): replace unsafe unwrap calls with proper error handling
- Add to_json_string helper for safe JSON serialization
- Add lock_conn macro for safe Mutex locking
- Replace 41 unwrap() calls with proper error handling:
- database.rs: JSON serialization and Mutex operations (31 fixes)
- lib.rs: macOS NSWindow and tray icon handling (3 fixes)
- services/provider.rs: Claude model normalization (1 fix)
- services/prompt.rs: timestamp generation (3 fixes)
- services/skill.rs: directory name extraction (2 fixes)
- mcp.rs: HashMap initialization and type conversions (5 fixes)
- app_config.rs: timestamp fallback (1 fix)
This improves application stability and prevents potential panics.
* feat(init): implement automatic data import on first launch
Add comprehensive first-launch data import system:
Database layer:
- Add is_empty_for_first_import() to detect empty database
- Add init_default_skill_repos() to initialize 3 default skill repositories
Services layer:
- Implement McpService::import_from_claude/codex/gemini()
to import MCP servers from existing config files
- Implement PromptService::import_from_file_on_first_launch()
to import prompt files (CLAUDE.md, AGENTS.md, GEMINI.md)
Startup flow (lib.rs):
- Check if database is empty on startup
- Import existing configurations if detected:
1. Initialize default skill repositories
2. Import provider configurations from live settings
3. Import MCP servers from config files
4. Import prompt files
- All imports are fault-tolerant and logged
This ensures seamless migration from file-based configs to database.
* fix(skills): auto-sync locally installed skills to database
Add automatic synchronization in get_skills command:
- Detect locally installed skills in ~/.claude/skills/
- Auto-add to database if not already tracked
- Ensures existing skills are recognized on first launch
This fixes the issue where user's existing skills were not
imported into the database on initial application run.
* docs(frontend): add code comments and improve formatting
- Add explanatory comment in EditProviderDialog about config assembly
- Improve import formatting in SkillsPage for better readability
* feat(deeplink): display all four Claude model fields in import dialog
- Show haiku/sonnet/opus/multiModel fields conditionally for Claude
- Maintain single model field display for Codex and Gemini
- Add i18n translations for new model field labels (zh/en)
* feat(backend): add database SQL export/import with backup
- Enable rusqlite backup feature for SQL dump support
- Implement export_sql to generate SQLite-compatible SQL dumps
- Implement import_sql with automatic backup before import
- Add snapshot_to_memory to avoid long-held database locks
- Add backup rotation to retain latest 10 backups
- Support atomic import with rollback on failure
* refactor(backend): migrate import/export to use SQL backup
- Reimplement export_config_to_file to use database.export_sql
- Reimplement import_config_from_file to use database.import_sql
- Add sync_current_from_db to sync live configs after import
- Add settings database binding on app initialization
- Remove deprecated JSON-based config import logic
* refactor(backend): migrate settings storage to database
- Add bind_db function to initialize database-backed settings
- Implement load_initial_settings with database fallback
- Replace direct file save with settings store management
- Add SETTINGS_DB static for database binding
- Maintain backward compatibility with file-based settings
- Keep settings.json for legacy migration support
* feat(frontend): update import/export UI for SQL backup
- Change default export filename from .json to .sql
- Update file format to timestamp format (YYYYMMDD_HHMMSS)
- Update error messages to reference SQL files
- Align with backend SQL export/import implementation
* feat(i18n): update translations for SQL backup feature
- Update Chinese translations for SQL import/export
- Update English translations for SQL import/export
- Change terminology from 'config file' to 'SQL backup'
- Update error messages and UI hints
* fix(backend): remove unnecessary dereference in backup operation
- Simplify Backup::new call by removing redundant dereference
- MutexGuard already implements DerefMut
1147 lines
41 KiB
Rust
1147 lines
41 KiB
Rust
use serde_json::{json, Value};
|
||
use std::collections::HashMap;
|
||
|
||
use crate::app_config::{AppType, McpConfig, MultiAppConfig};
|
||
use crate::error::AppError;
|
||
|
||
/// 基础校验:允许 stdio/http/sse;或省略 type(视为 stdio)。对应必填字段存在
|
||
fn validate_server_spec(spec: &Value) -> Result<(), AppError> {
|
||
if !spec.is_object() {
|
||
return Err(AppError::McpValidation(
|
||
"MCP 服务器连接定义必须为 JSON 对象".into(),
|
||
));
|
||
}
|
||
let t_opt = spec.get("type").and_then(|x| x.as_str());
|
||
// 支持三种:stdio/http/sse;若缺省 type 则按 stdio 处理(与社区常见 .mcp.json 一致)
|
||
let is_stdio = t_opt.map(|t| t == "stdio").unwrap_or(true);
|
||
let is_http = t_opt.map(|t| t == "http").unwrap_or(false);
|
||
let is_sse = t_opt.map(|t| t == "sse").unwrap_or(false);
|
||
|
||
if !(is_stdio || is_http || is_sse) {
|
||
return Err(AppError::McpValidation(
|
||
"MCP 服务器 type 必须是 'stdio'、'http' 或 'sse'(或省略表示 stdio)".into(),
|
||
));
|
||
}
|
||
|
||
if is_stdio {
|
||
let cmd = spec.get("command").and_then(|x| x.as_str()).unwrap_or("");
|
||
if cmd.trim().is_empty() {
|
||
return Err(AppError::McpValidation(
|
||
"stdio 类型的 MCP 服务器缺少 command 字段".into(),
|
||
));
|
||
}
|
||
}
|
||
if is_http {
|
||
let url = spec.get("url").and_then(|x| x.as_str()).unwrap_or("");
|
||
if url.trim().is_empty() {
|
||
return Err(AppError::McpValidation(
|
||
"http 类型的 MCP 服务器缺少 url 字段".into(),
|
||
));
|
||
}
|
||
}
|
||
if is_sse {
|
||
let url = spec.get("url").and_then(|x| x.as_str()).unwrap_or("");
|
||
if url.trim().is_empty() {
|
||
return Err(AppError::McpValidation(
|
||
"sse 类型的 MCP 服务器缺少 url 字段".into(),
|
||
));
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
#[allow(dead_code)] // v3.7.0: 旧的验证逻辑,保留用于未来可能的迁移
|
||
fn validate_mcp_entry(entry: &Value) -> Result<(), AppError> {
|
||
let obj = entry
|
||
.as_object()
|
||
.ok_or_else(|| AppError::McpValidation("MCP 服务器条目必须为 JSON 对象".into()))?;
|
||
|
||
let server = obj
|
||
.get("server")
|
||
.ok_or_else(|| AppError::McpValidation("MCP 服务器条目缺少 server 字段".into()))?;
|
||
validate_server_spec(server)?;
|
||
|
||
for key in ["name", "description", "homepage", "docs"] {
|
||
if let Some(val) = obj.get(key) {
|
||
if !val.is_string() {
|
||
return Err(AppError::McpValidation(format!(
|
||
"MCP 服务器 {key} 必须为字符串"
|
||
)));
|
||
}
|
||
}
|
||
}
|
||
|
||
if let Some(tags) = obj.get("tags") {
|
||
let arr = tags
|
||
.as_array()
|
||
.ok_or_else(|| AppError::McpValidation("MCP 服务器 tags 必须为字符串数组".into()))?;
|
||
if !arr.iter().all(|item| item.is_string()) {
|
||
return Err(AppError::McpValidation(
|
||
"MCP 服务器 tags 必须为字符串数组".into(),
|
||
));
|
||
}
|
||
}
|
||
|
||
if let Some(enabled) = obj.get("enabled") {
|
||
if !enabled.is_boolean() {
|
||
return Err(AppError::McpValidation(
|
||
"MCP 服务器 enabled 必须为布尔值".into(),
|
||
));
|
||
}
|
||
}
|
||
|
||
Ok(())
|
||
}
|
||
|
||
fn normalize_server_keys(map: &mut HashMap<String, Value>) -> usize {
|
||
let mut change_count = 0usize;
|
||
let mut renames: Vec<(String, String)> = Vec::new();
|
||
|
||
for (key_ref, value) in map.iter_mut() {
|
||
let key = key_ref.clone();
|
||
let Some(obj) = value.as_object_mut() else {
|
||
continue;
|
||
};
|
||
|
||
let id_value = obj.get("id").cloned();
|
||
|
||
let target_id: String;
|
||
|
||
match id_value {
|
||
Some(id_val) => match id_val.as_str() {
|
||
Some(id_str) => {
|
||
let trimmed = id_str.trim();
|
||
if trimmed.is_empty() {
|
||
obj.insert("id".into(), json!(key.clone()));
|
||
change_count += 1;
|
||
target_id = key.clone();
|
||
} else {
|
||
if trimmed != id_str {
|
||
obj.insert("id".into(), json!(trimmed));
|
||
change_count += 1;
|
||
}
|
||
target_id = trimmed.to_string();
|
||
}
|
||
}
|
||
None => {
|
||
obj.insert("id".into(), json!(key.clone()));
|
||
change_count += 1;
|
||
target_id = key.clone();
|
||
}
|
||
},
|
||
None => {
|
||
obj.insert("id".into(), json!(key.clone()));
|
||
change_count += 1;
|
||
target_id = key.clone();
|
||
}
|
||
}
|
||
|
||
if target_id != key {
|
||
renames.push((key, target_id));
|
||
}
|
||
}
|
||
|
||
for (old_key, new_key) in renames {
|
||
if old_key == new_key {
|
||
continue;
|
||
}
|
||
if map.contains_key(&new_key) {
|
||
log::warn!("MCP 条目 '{old_key}' 的内部 id '{new_key}' 与现有键冲突,回退为原键");
|
||
if let Some(value) = map.get_mut(&old_key) {
|
||
if let Some(obj) = value.as_object_mut() {
|
||
if obj
|
||
.get("id")
|
||
.and_then(|v| v.as_str())
|
||
.map(|s| s != old_key)
|
||
.unwrap_or(true)
|
||
{
|
||
obj.insert("id".into(), json!(old_key.clone()));
|
||
change_count += 1;
|
||
}
|
||
}
|
||
}
|
||
continue;
|
||
}
|
||
if let Some(mut value) = map.remove(&old_key) {
|
||
if let Some(obj) = value.as_object_mut() {
|
||
obj.insert("id".into(), json!(new_key.clone()));
|
||
}
|
||
log::info!("MCP 条目键名已自动修复: '{old_key}' -> '{new_key}'");
|
||
map.insert(new_key, value);
|
||
change_count += 1;
|
||
}
|
||
}
|
||
|
||
change_count
|
||
}
|
||
|
||
pub fn normalize_servers_for(config: &mut MultiAppConfig, app: &AppType) -> usize {
|
||
let servers = &mut config.mcp_for_mut(app).servers;
|
||
normalize_server_keys(servers)
|
||
}
|
||
|
||
fn extract_server_spec(entry: &Value) -> Result<Value, AppError> {
|
||
let obj = entry
|
||
.as_object()
|
||
.ok_or_else(|| AppError::McpValidation("MCP 服务器条目必须为 JSON 对象".into()))?;
|
||
let server = obj
|
||
.get("server")
|
||
.ok_or_else(|| AppError::McpValidation("MCP 服务器条目缺少 server 字段".into()))?;
|
||
|
||
if !server.is_object() {
|
||
return Err(AppError::McpValidation(
|
||
"MCP 服务器 server 字段必须为 JSON 对象".into(),
|
||
));
|
||
}
|
||
|
||
Ok(server.clone())
|
||
}
|
||
|
||
/// 返回已启用的 MCP 服务器(过滤 enabled==true)
|
||
fn collect_enabled_servers(cfg: &McpConfig) -> HashMap<String, Value> {
|
||
let mut out = HashMap::new();
|
||
for (id, entry) in cfg.servers.iter() {
|
||
let enabled = entry
|
||
.get("enabled")
|
||
.and_then(|v| v.as_bool())
|
||
.unwrap_or(false);
|
||
if !enabled {
|
||
continue;
|
||
}
|
||
match extract_server_spec(entry) {
|
||
Ok(spec) => {
|
||
out.insert(id.clone(), spec);
|
||
}
|
||
Err(err) => {
|
||
log::warn!("跳过无效的 MCP 条目 '{id}': {err}");
|
||
}
|
||
}
|
||
}
|
||
out
|
||
}
|
||
|
||
#[allow(dead_code)] // v3.7.0: 旧的分应用 API,保留用于未来可能的迁移
|
||
pub fn get_servers_snapshot_for(
|
||
config: &mut MultiAppConfig,
|
||
app: &AppType,
|
||
) -> (HashMap<String, Value>, usize) {
|
||
let normalized = normalize_servers_for(config, app);
|
||
let mut snapshot = config.mcp_for(app).servers.clone();
|
||
snapshot.retain(|id, value| {
|
||
let Some(obj) = value.as_object_mut() else {
|
||
log::warn!("跳过无效的 MCP 条目 '{id}': 必须为 JSON 对象");
|
||
return false;
|
||
};
|
||
|
||
obj.entry(String::from("id")).or_insert(json!(id));
|
||
|
||
match validate_mcp_entry(value) {
|
||
Ok(()) => true,
|
||
Err(err) => {
|
||
log::error!("config.json 中存在无效的 MCP 条目 '{id}': {err}");
|
||
false
|
||
}
|
||
}
|
||
});
|
||
(snapshot, normalized)
|
||
}
|
||
|
||
#[allow(dead_code)] // v3.7.0: 旧的分应用 API,保留用于未来可能的迁移
|
||
pub fn upsert_in_config_for(
|
||
config: &mut MultiAppConfig,
|
||
app: &AppType,
|
||
id: &str,
|
||
spec: Value,
|
||
) -> Result<bool, AppError> {
|
||
if id.trim().is_empty() {
|
||
return Err(AppError::InvalidInput("MCP 服务器 ID 不能为空".into()));
|
||
}
|
||
normalize_servers_for(config, app);
|
||
validate_mcp_entry(&spec)?;
|
||
|
||
let mut entry_obj = spec
|
||
.as_object()
|
||
.cloned()
|
||
.ok_or_else(|| AppError::McpValidation("MCP 服务器条目必须为 JSON 对象".into()))?;
|
||
if let Some(existing_id) = entry_obj.get("id") {
|
||
let Some(existing_id_str) = existing_id.as_str() else {
|
||
return Err(AppError::McpValidation("MCP 服务器 id 必须为字符串".into()));
|
||
};
|
||
if existing_id_str != id {
|
||
return Err(AppError::McpValidation(format!(
|
||
"MCP 服务器条目中的 id '{existing_id_str}' 与参数 id '{id}' 不一致"
|
||
)));
|
||
}
|
||
} else {
|
||
entry_obj.insert(String::from("id"), json!(id));
|
||
}
|
||
|
||
let value = Value::Object(entry_obj);
|
||
|
||
let servers = &mut config.mcp_for_mut(app).servers;
|
||
let before = servers.get(id).cloned();
|
||
servers.insert(id.to_string(), value);
|
||
|
||
Ok(before.is_none())
|
||
}
|
||
|
||
#[allow(dead_code)] // v3.7.0: 旧的分应用 API,保留用于未来可能的迁移
|
||
pub fn delete_in_config_for(
|
||
config: &mut MultiAppConfig,
|
||
app: &AppType,
|
||
id: &str,
|
||
) -> Result<bool, AppError> {
|
||
if id.trim().is_empty() {
|
||
return Err(AppError::InvalidInput("MCP 服务器 ID 不能为空".into()));
|
||
}
|
||
normalize_servers_for(config, app);
|
||
let existed = config.mcp_for_mut(app).servers.remove(id).is_some();
|
||
Ok(existed)
|
||
}
|
||
|
||
#[allow(dead_code)] // v3.7.0: 旧的分应用 API,保留用于未来可能的迁移
|
||
/// 设置启用状态(不执行落盘或文件同步)
|
||
pub fn set_enabled_flag_for(
|
||
config: &mut MultiAppConfig,
|
||
app: &AppType,
|
||
id: &str,
|
||
enabled: bool,
|
||
) -> Result<bool, AppError> {
|
||
if id.trim().is_empty() {
|
||
return Err(AppError::InvalidInput("MCP 服务器 ID 不能为空".into()));
|
||
}
|
||
normalize_servers_for(config, app);
|
||
if let Some(spec) = config.mcp_for_mut(app).servers.get_mut(id) {
|
||
// 写入 enabled 字段
|
||
let mut obj = spec
|
||
.as_object()
|
||
.cloned()
|
||
.ok_or_else(|| AppError::McpValidation("MCP 服务器定义必须为 JSON 对象".into()))?;
|
||
obj.insert("enabled".into(), json!(enabled));
|
||
*spec = Value::Object(obj);
|
||
} else {
|
||
// 若不存在则直接返回 false
|
||
return Ok(false);
|
||
}
|
||
|
||
Ok(true)
|
||
}
|
||
|
||
/// 将 config.json 中 enabled==true 的项投影写入 ~/.claude.json
|
||
pub fn sync_enabled_to_claude(config: &MultiAppConfig) -> Result<(), AppError> {
|
||
let enabled = collect_enabled_servers(&config.mcp.claude);
|
||
crate::claude_mcp::set_mcp_servers_map(&enabled)
|
||
}
|
||
|
||
/// 从 ~/.claude.json 导入 mcpServers 到统一结构(v3.7.0+)
|
||
/// 已存在的服务器将启用 Claude 应用,不覆盖其他字段和应用状态
|
||
pub fn import_from_claude(config: &mut MultiAppConfig) -> Result<usize, AppError> {
|
||
use crate::app_config::{McpApps, McpServer};
|
||
|
||
let text_opt = crate::claude_mcp::read_mcp_json()?;
|
||
let Some(text) = text_opt else { return Ok(0) };
|
||
|
||
let v: Value = serde_json::from_str(&text)
|
||
.map_err(|e| AppError::McpValidation(format!("解析 ~/.claude.json 失败: {e}")))?;
|
||
let Some(map) = v.get("mcpServers").and_then(|x| x.as_object()) else {
|
||
return Ok(0);
|
||
};
|
||
|
||
// 确保新结构存在
|
||
let servers = config.mcp.servers.get_or_insert_with(HashMap::new);
|
||
|
||
let mut changed = 0;
|
||
let mut errors = Vec::new();
|
||
|
||
for (id, spec) in map.iter() {
|
||
// 校验:单项失败不中止,收集错误继续处理
|
||
if let Err(e) = validate_server_spec(spec) {
|
||
log::warn!("跳过无效 MCP 服务器 '{id}': {e}");
|
||
errors.push(format!("{id}: {e}"));
|
||
continue;
|
||
}
|
||
|
||
if let Some(existing) = servers.get_mut(id) {
|
||
// 已存在:仅启用 Claude 应用
|
||
if !existing.apps.claude {
|
||
existing.apps.claude = true;
|
||
changed += 1;
|
||
log::info!("MCP 服务器 '{id}' 已启用 Claude 应用");
|
||
}
|
||
} else {
|
||
// 新建服务器:默认仅启用 Claude
|
||
servers.insert(
|
||
id.clone(),
|
||
McpServer {
|
||
id: id.clone(),
|
||
name: id.clone(),
|
||
server: spec.clone(),
|
||
apps: McpApps {
|
||
claude: true,
|
||
codex: false,
|
||
gemini: false,
|
||
},
|
||
description: None,
|
||
homepage: None,
|
||
docs: None,
|
||
tags: Vec::new(),
|
||
},
|
||
);
|
||
changed += 1;
|
||
log::info!("导入新 MCP 服务器 '{id}'");
|
||
}
|
||
}
|
||
|
||
if !errors.is_empty() {
|
||
log::warn!("导入完成,但有 {} 项失败: {:?}", errors.len(), errors);
|
||
}
|
||
|
||
Ok(changed)
|
||
}
|
||
|
||
/// 从 ~/.codex/config.toml 导入 MCP 到统一结构(v3.7.0+)
|
||
///
|
||
/// 格式支持:
|
||
/// - 正确格式:[mcp_servers.*](Codex 官方标准)
|
||
/// - 错误格式:[mcp.servers.*](容错读取,用于迁移错误写入的配置)
|
||
///
|
||
/// 已存在的服务器将启用 Codex 应用,不覆盖其他字段和应用状态
|
||
pub fn import_from_codex(config: &mut MultiAppConfig) -> Result<usize, AppError> {
|
||
use crate::app_config::{McpApps, McpServer};
|
||
|
||
let text = crate::codex_config::read_and_validate_codex_config_text()?;
|
||
if text.trim().is_empty() {
|
||
return Ok(0);
|
||
}
|
||
|
||
let root: toml::Table = toml::from_str(&text)
|
||
.map_err(|e| AppError::McpValidation(format!("解析 ~/.codex/config.toml 失败: {e}")))?;
|
||
|
||
// 确保新结构存在
|
||
let servers = config.mcp.servers.get_or_insert_with(HashMap::new);
|
||
|
||
let mut changed_total = 0usize;
|
||
|
||
// helper:处理一组 servers 表
|
||
let mut import_servers_tbl = |servers_tbl: &toml::value::Table| {
|
||
let mut changed = 0usize;
|
||
for (id, entry_val) in servers_tbl.iter() {
|
||
let Some(entry_tbl) = entry_val.as_table() else {
|
||
continue;
|
||
};
|
||
|
||
// type 缺省为 stdio
|
||
let typ = entry_tbl
|
||
.get("type")
|
||
.and_then(|v| v.as_str())
|
||
.unwrap_or("stdio");
|
||
|
||
// 构建 JSON 规范
|
||
let mut spec = serde_json::Map::new();
|
||
spec.insert("type".into(), json!(typ));
|
||
|
||
// 核心字段(需要手动处理的字段)
|
||
let core_fields = match typ {
|
||
"stdio" => vec!["type", "command", "args", "env", "cwd"],
|
||
"http" | "sse" => vec!["type", "url", "http_headers"],
|
||
_ => vec!["type"],
|
||
};
|
||
|
||
// 1. 处理核心字段(强类型)
|
||
match typ {
|
||
"stdio" => {
|
||
if let Some(cmd) = entry_tbl.get("command").and_then(|v| v.as_str()) {
|
||
spec.insert("command".into(), json!(cmd));
|
||
}
|
||
if let Some(args) = entry_tbl.get("args").and_then(|v| v.as_array()) {
|
||
let arr = args
|
||
.iter()
|
||
.filter_map(|x| x.as_str())
|
||
.map(|s| json!(s))
|
||
.collect::<Vec<_>>();
|
||
if !arr.is_empty() {
|
||
spec.insert("args".into(), serde_json::Value::Array(arr));
|
||
}
|
||
}
|
||
if let Some(cwd) = entry_tbl.get("cwd").and_then(|v| v.as_str()) {
|
||
if !cwd.trim().is_empty() {
|
||
spec.insert("cwd".into(), json!(cwd));
|
||
}
|
||
}
|
||
if let Some(env_tbl) = entry_tbl.get("env").and_then(|v| v.as_table()) {
|
||
let mut env_json = serde_json::Map::new();
|
||
for (k, v) in env_tbl.iter() {
|
||
if let Some(sv) = v.as_str() {
|
||
env_json.insert(k.clone(), json!(sv));
|
||
}
|
||
}
|
||
if !env_json.is_empty() {
|
||
spec.insert("env".into(), serde_json::Value::Object(env_json));
|
||
}
|
||
}
|
||
}
|
||
"http" | "sse" => {
|
||
if let Some(url) = entry_tbl.get("url").and_then(|v| v.as_str()) {
|
||
spec.insert("url".into(), json!(url));
|
||
}
|
||
// Read from http_headers (correct Codex format) or headers (legacy) with priority to http_headers
|
||
let headers_tbl = entry_tbl
|
||
.get("http_headers")
|
||
.and_then(|v| v.as_table())
|
||
.or_else(|| entry_tbl.get("headers").and_then(|v| v.as_table()));
|
||
|
||
if let Some(headers_tbl) = headers_tbl {
|
||
let mut headers_json = serde_json::Map::new();
|
||
for (k, v) in headers_tbl.iter() {
|
||
if let Some(sv) = v.as_str() {
|
||
headers_json.insert(k.clone(), json!(sv));
|
||
}
|
||
}
|
||
if !headers_json.is_empty() {
|
||
spec.insert("headers".into(), serde_json::Value::Object(headers_json));
|
||
}
|
||
}
|
||
}
|
||
_ => {
|
||
log::warn!("跳过未知类型 '{typ}' 的 Codex MCP 项 '{id}'");
|
||
return changed;
|
||
}
|
||
}
|
||
|
||
// 2. 处理扩展字段和其他未知字段(通用 TOML → JSON 转换)
|
||
for (key, toml_val) in entry_tbl.iter() {
|
||
// 跳过已处理的核心字段
|
||
if core_fields.contains(&key.as_str()) {
|
||
continue;
|
||
}
|
||
|
||
// 通用 TOML 值到 JSON 值转换
|
||
let json_val = match toml_val {
|
||
toml::Value::String(s) => Some(json!(s)),
|
||
toml::Value::Integer(i) => Some(json!(i)),
|
||
toml::Value::Float(f) => Some(json!(f)),
|
||
toml::Value::Boolean(b) => Some(json!(b)),
|
||
toml::Value::Array(arr) => {
|
||
// 只支持简单类型数组
|
||
let json_arr: Vec<serde_json::Value> = arr
|
||
.iter()
|
||
.filter_map(|item| match item {
|
||
toml::Value::String(s) => Some(json!(s)),
|
||
toml::Value::Integer(i) => Some(json!(i)),
|
||
toml::Value::Float(f) => Some(json!(f)),
|
||
toml::Value::Boolean(b) => Some(json!(b)),
|
||
_ => None,
|
||
})
|
||
.collect();
|
||
if !json_arr.is_empty() {
|
||
Some(serde_json::Value::Array(json_arr))
|
||
} else {
|
||
log::debug!("跳过复杂数组字段 '{key}' (TOML → JSON)");
|
||
None
|
||
}
|
||
}
|
||
toml::Value::Table(tbl) => {
|
||
// 浅层表转为 JSON 对象(仅支持字符串值)
|
||
let mut json_obj = serde_json::Map::new();
|
||
for (k, v) in tbl.iter() {
|
||
if let Some(s) = v.as_str() {
|
||
json_obj.insert(k.clone(), json!(s));
|
||
}
|
||
}
|
||
if !json_obj.is_empty() {
|
||
Some(serde_json::Value::Object(json_obj))
|
||
} else {
|
||
log::debug!("跳过复杂对象字段 '{key}' (TOML → JSON)");
|
||
None
|
||
}
|
||
}
|
||
toml::Value::Datetime(_) => {
|
||
log::debug!("跳过日期时间字段 '{key}' (TOML → JSON)");
|
||
None
|
||
}
|
||
};
|
||
|
||
if let Some(val) = json_val {
|
||
spec.insert(key.clone(), val);
|
||
log::debug!("导入扩展字段 '{key}' = {toml_val:?}");
|
||
}
|
||
}
|
||
|
||
let spec_v = serde_json::Value::Object(spec);
|
||
|
||
// 校验:单项失败继续处理
|
||
if let Err(e) = validate_server_spec(&spec_v) {
|
||
log::warn!("跳过无效 Codex MCP 项 '{id}': {e}");
|
||
continue;
|
||
}
|
||
|
||
if let Some(existing) = servers.get_mut(id) {
|
||
// 已存在:仅启用 Codex 应用
|
||
if !existing.apps.codex {
|
||
existing.apps.codex = true;
|
||
changed += 1;
|
||
log::info!("MCP 服务器 '{id}' 已启用 Codex 应用");
|
||
}
|
||
} else {
|
||
// 新建服务器:默认仅启用 Codex
|
||
servers.insert(
|
||
id.clone(),
|
||
McpServer {
|
||
id: id.clone(),
|
||
name: id.clone(),
|
||
server: spec_v,
|
||
apps: McpApps {
|
||
claude: false,
|
||
codex: true,
|
||
gemini: false,
|
||
},
|
||
description: None,
|
||
homepage: None,
|
||
docs: None,
|
||
tags: Vec::new(),
|
||
},
|
||
);
|
||
changed += 1;
|
||
log::info!("导入新 MCP 服务器 '{id}'");
|
||
}
|
||
}
|
||
changed
|
||
};
|
||
|
||
// 1) 处理 mcp.servers
|
||
if let Some(mcp_val) = root.get("mcp") {
|
||
if let Some(mcp_tbl) = mcp_val.as_table() {
|
||
if let Some(servers_val) = mcp_tbl.get("servers") {
|
||
if let Some(servers_tbl) = servers_val.as_table() {
|
||
changed_total += import_servers_tbl(servers_tbl);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// 2) 处理 mcp_servers
|
||
if let Some(servers_val) = root.get("mcp_servers") {
|
||
if let Some(servers_tbl) = servers_val.as_table() {
|
||
changed_total += import_servers_tbl(servers_tbl);
|
||
}
|
||
}
|
||
|
||
Ok(changed_total)
|
||
}
|
||
|
||
/// 将 config.json 中 Codex 的 enabled==true 项以 TOML 形式写入 ~/.codex/config.toml
|
||
///
|
||
/// 格式策略:
|
||
/// - 唯一正确格式:[mcp_servers] 顶层表(Codex 官方标准)
|
||
/// - 自动清理错误格式:[mcp.servers](如果存在)
|
||
/// - 读取现有 config.toml;若语法无效则报错,不尝试覆盖
|
||
/// - 仅更新 `mcp_servers` 表,保留其它键
|
||
/// - 仅写入启用项;无启用项时清理 mcp_servers 表
|
||
pub fn sync_enabled_to_codex(config: &MultiAppConfig) -> Result<(), AppError> {
|
||
use toml_edit::{Item, Table};
|
||
|
||
// 1) 收集启用项(Codex 维度)
|
||
let enabled = collect_enabled_servers(&config.mcp.codex);
|
||
|
||
// 2) 读取现有 config.toml 文本;保持无效 TOML 的错误返回(不覆盖文件)
|
||
let base_text = crate::codex_config::read_and_validate_codex_config_text()?;
|
||
|
||
// 3) 使用 toml_edit 解析(允许空文件)
|
||
let mut doc = if base_text.trim().is_empty() {
|
||
toml_edit::DocumentMut::default()
|
||
} else {
|
||
base_text
|
||
.parse::<toml_edit::DocumentMut>()
|
||
.map_err(|e| AppError::McpValidation(format!("解析 config.toml 失败: {e}")))?
|
||
};
|
||
|
||
// 4) 清理可能存在的错误格式 [mcp.servers]
|
||
if let Some(mcp_item) = doc.get_mut("mcp") {
|
||
if let Some(tbl) = mcp_item.as_table_like_mut() {
|
||
if tbl.contains_key("servers") {
|
||
log::warn!("检测到错误的 MCP 格式 [mcp.servers],正在清理并迁移到 [mcp_servers]");
|
||
tbl.remove("servers");
|
||
}
|
||
}
|
||
}
|
||
|
||
// 5) 构造目标 servers 表(稳定的键顺序)
|
||
if enabled.is_empty() {
|
||
// 无启用项:移除 mcp_servers 表
|
||
doc.as_table_mut().remove("mcp_servers");
|
||
} else {
|
||
// 构建 servers 表
|
||
let mut servers_tbl = Table::new();
|
||
let mut ids: Vec<_> = enabled.keys().cloned().collect();
|
||
ids.sort();
|
||
for id in ids {
|
||
let spec = enabled.get(&id).expect("spec must exist");
|
||
// 复用通用转换函数(已包含扩展字段支持)
|
||
match json_server_to_toml_table(spec) {
|
||
Ok(table) => {
|
||
servers_tbl[&id[..]] = Item::Table(table);
|
||
}
|
||
Err(err) => {
|
||
log::error!("跳过无效的 MCP 服务器 '{id}': {err}");
|
||
}
|
||
}
|
||
}
|
||
// 使用唯一正确的格式:[mcp_servers]
|
||
doc["mcp_servers"] = Item::Table(servers_tbl);
|
||
}
|
||
|
||
// 6) 写回(仅改 TOML,不触碰 auth.json);toml_edit 会尽量保留未改区域的注释/空白/顺序
|
||
let new_text = doc.to_string();
|
||
let path = crate::codex_config::get_codex_config_path();
|
||
crate::config::write_text_file(&path, &new_text)?;
|
||
Ok(())
|
||
}
|
||
|
||
/// 将 config.json 中 enabled==true 的项投影写入 ~/.gemini/settings.json
|
||
pub fn sync_enabled_to_gemini(config: &MultiAppConfig) -> Result<(), AppError> {
|
||
let enabled = collect_enabled_servers(&config.mcp.gemini);
|
||
crate::gemini_mcp::set_mcp_servers_map(&enabled)
|
||
}
|
||
|
||
/// 从 ~/.gemini/settings.json 导入 mcpServers 到统一结构(v3.7.0+)
|
||
/// 已存在的服务器将启用 Gemini 应用,不覆盖其他字段和应用状态
|
||
pub fn import_from_gemini(config: &mut MultiAppConfig) -> Result<usize, AppError> {
|
||
use crate::app_config::{McpApps, McpServer};
|
||
|
||
let text_opt = crate::gemini_mcp::read_mcp_json()?;
|
||
let Some(text) = text_opt else { return Ok(0) };
|
||
|
||
let v: Value = serde_json::from_str(&text)
|
||
.map_err(|e| AppError::McpValidation(format!("解析 ~/.gemini/settings.json 失败: {e}")))?;
|
||
let Some(map) = v.get("mcpServers").and_then(|x| x.as_object()) else {
|
||
return Ok(0);
|
||
};
|
||
|
||
// 确保新结构存在
|
||
let servers = config.mcp.servers.get_or_insert_with(HashMap::new);
|
||
|
||
let mut changed = 0;
|
||
let mut errors = Vec::new();
|
||
|
||
for (id, spec) in map.iter() {
|
||
// 校验:单项失败不中止,收集错误继续处理
|
||
if let Err(e) = validate_server_spec(spec) {
|
||
log::warn!("跳过无效 MCP 服务器 '{id}': {e}");
|
||
errors.push(format!("{id}: {e}"));
|
||
continue;
|
||
}
|
||
|
||
if let Some(existing) = servers.get_mut(id) {
|
||
// 已存在:仅启用 Gemini 应用
|
||
if !existing.apps.gemini {
|
||
existing.apps.gemini = true;
|
||
changed += 1;
|
||
log::info!("MCP 服务器 '{id}' 已启用 Gemini 应用");
|
||
}
|
||
} else {
|
||
// 新建服务器:默认仅启用 Gemini
|
||
servers.insert(
|
||
id.clone(),
|
||
McpServer {
|
||
id: id.clone(),
|
||
name: id.clone(),
|
||
server: spec.clone(),
|
||
apps: McpApps {
|
||
claude: false,
|
||
codex: false,
|
||
gemini: true,
|
||
},
|
||
description: None,
|
||
homepage: None,
|
||
docs: None,
|
||
tags: Vec::new(),
|
||
},
|
||
);
|
||
changed += 1;
|
||
log::info!("导入新 MCP 服务器 '{id}'");
|
||
}
|
||
}
|
||
|
||
if !errors.is_empty() {
|
||
log::warn!("导入完成,但有 {} 项失败: {:?}", errors.len(), errors);
|
||
}
|
||
|
||
Ok(changed)
|
||
}
|
||
|
||
// ============================================================================
|
||
// v3.7.0 新增:单个服务器同步和删除函数
|
||
// ============================================================================
|
||
|
||
/// 将单个 MCP 服务器同步到 Claude live 配置
|
||
pub fn sync_single_server_to_claude(
|
||
_config: &MultiAppConfig,
|
||
id: &str,
|
||
server_spec: &Value,
|
||
) -> Result<(), AppError> {
|
||
// 读取现有的 MCP 配置
|
||
let current = crate::claude_mcp::read_mcp_servers_map()?;
|
||
|
||
// 创建新的 HashMap,包含现有的所有服务器 + 当前要同步的服务器
|
||
let mut updated = current;
|
||
updated.insert(id.to_string(), server_spec.clone());
|
||
|
||
// 写回
|
||
crate::claude_mcp::set_mcp_servers_map(&updated)
|
||
}
|
||
|
||
/// 从 Claude live 配置中移除单个 MCP 服务器
|
||
pub fn remove_server_from_claude(id: &str) -> Result<(), AppError> {
|
||
// 读取现有的 MCP 配置
|
||
let mut current = crate::claude_mcp::read_mcp_servers_map()?;
|
||
|
||
// 移除指定服务器
|
||
current.remove(id);
|
||
|
||
// 写回
|
||
crate::claude_mcp::set_mcp_servers_map(¤t)
|
||
}
|
||
|
||
/// 通用 JSON 值到 TOML 值转换器(支持简单类型和浅层嵌套)
|
||
///
|
||
/// 支持的类型转换:
|
||
/// - String → TOML String
|
||
/// - Number (i64) → TOML Integer
|
||
/// - Number (f64) → TOML Float
|
||
/// - Boolean → TOML Boolean
|
||
/// - Array[简单类型] → TOML Array
|
||
/// - Object → TOML Inline Table (仅字符串值)
|
||
///
|
||
/// 不支持的类型(返回 None):
|
||
/// - null
|
||
/// - 深度嵌套对象
|
||
/// - 混合类型数组
|
||
fn json_value_to_toml_item(value: &Value, field_name: &str) -> Option<toml_edit::Item> {
|
||
use toml_edit::{Array, InlineTable, Item};
|
||
|
||
match value {
|
||
Value::String(s) => Some(toml_edit::value(s.as_str())),
|
||
|
||
Value::Number(n) => {
|
||
if let Some(i) = n.as_i64() {
|
||
Some(toml_edit::value(i))
|
||
} else if let Some(f) = n.as_f64() {
|
||
Some(toml_edit::value(f))
|
||
} else {
|
||
log::warn!("跳过字段 '{field_name}': 无法转换的数字类型 {n}");
|
||
None
|
||
}
|
||
}
|
||
|
||
Value::Bool(b) => Some(toml_edit::value(*b)),
|
||
|
||
Value::Array(arr) => {
|
||
// 只支持简单类型的数组(字符串、数字、布尔)
|
||
let mut toml_arr = Array::default();
|
||
let mut all_same_type = true;
|
||
|
||
for item in arr {
|
||
match item {
|
||
Value::String(s) => toml_arr.push(s.as_str()),
|
||
Value::Number(n) if n.is_i64() => {
|
||
if let Some(i) = n.as_i64() {
|
||
toml_arr.push(i);
|
||
} else {
|
||
all_same_type = false;
|
||
break;
|
||
}
|
||
}
|
||
Value::Number(n) if n.is_f64() => {
|
||
if let Some(f) = n.as_f64() {
|
||
toml_arr.push(f);
|
||
} else {
|
||
all_same_type = false;
|
||
break;
|
||
}
|
||
}
|
||
Value::Bool(b) => toml_arr.push(*b),
|
||
_ => {
|
||
all_same_type = false;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
if all_same_type && !toml_arr.is_empty() {
|
||
Some(Item::Value(toml_edit::Value::Array(toml_arr)))
|
||
} else {
|
||
log::warn!("跳过字段 '{field_name}': 不支持的数组类型(混合类型或嵌套结构)");
|
||
None
|
||
}
|
||
}
|
||
|
||
Value::Object(obj) => {
|
||
// 只支持浅层对象(所有值都是字符串)→ TOML Inline Table
|
||
let mut inline_table = InlineTable::new();
|
||
let mut all_strings = true;
|
||
|
||
for (k, v) in obj {
|
||
if let Some(s) = v.as_str() {
|
||
// InlineTable 需要 Value 类型,toml_edit::value() 返回 Item,需要提取内部的 Value
|
||
inline_table.insert(k, s.into());
|
||
} else {
|
||
all_strings = false;
|
||
break;
|
||
}
|
||
}
|
||
|
||
if all_strings && !inline_table.is_empty() {
|
||
Some(Item::Value(toml_edit::Value::InlineTable(inline_table)))
|
||
} else {
|
||
log::warn!("跳过字段 '{field_name}': 对象值包含非字符串类型,建议使用子表语法");
|
||
None
|
||
}
|
||
}
|
||
|
||
Value::Null => {
|
||
log::debug!("跳过字段 '{field_name}': TOML 不支持 null 值");
|
||
None
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Helper: 将 JSON MCP 服务器规范转换为 toml_edit::Table
|
||
///
|
||
/// 策略:
|
||
/// 1. 核心字段(type, command, args, url, headers, env, cwd)使用强类型处理
|
||
/// 2. 扩展字段(timeout、retry 等)通过白名单列表自动转换
|
||
/// 3. 其他未知字段使用通用转换器尝试转换
|
||
fn json_server_to_toml_table(spec: &Value) -> Result<toml_edit::Table, AppError> {
|
||
use toml_edit::{Array, Item, Table};
|
||
|
||
let mut t = Table::new();
|
||
let typ = spec.get("type").and_then(|v| v.as_str()).unwrap_or("stdio");
|
||
t["type"] = toml_edit::value(typ);
|
||
|
||
// 定义核心字段(已在下方处理,跳过通用转换)
|
||
let core_fields = match typ {
|
||
"stdio" => vec!["type", "command", "args", "env", "cwd"],
|
||
"http" | "sse" => vec!["type", "url", "http_headers"],
|
||
_ => vec!["type"],
|
||
};
|
||
|
||
// 定义扩展字段白名单(Codex 常见可选字段)
|
||
let extended_fields = [
|
||
// 通用字段
|
||
"timeout",
|
||
"timeout_ms",
|
||
"startup_timeout_ms",
|
||
"startup_timeout_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",
|
||
];
|
||
|
||
// 1. 处理核心字段(强类型)
|
||
match typ {
|
||
"stdio" => {
|
||
let cmd = spec.get("command").and_then(|v| v.as_str()).unwrap_or("");
|
||
t["command"] = toml_edit::value(cmd);
|
||
|
||
if let Some(args) = spec.get("args").and_then(|v| v.as_array()) {
|
||
let mut arr_v = Array::default();
|
||
for a in args.iter().filter_map(|x| x.as_str()) {
|
||
arr_v.push(a);
|
||
}
|
||
if !arr_v.is_empty() {
|
||
t["args"] = Item::Value(toml_edit::Value::Array(arr_v));
|
||
}
|
||
}
|
||
|
||
if let Some(cwd) = spec.get("cwd").and_then(|v| v.as_str()) {
|
||
if !cwd.trim().is_empty() {
|
||
t["cwd"] = toml_edit::value(cwd);
|
||
}
|
||
}
|
||
|
||
if let Some(env) = spec.get("env").and_then(|v| v.as_object()) {
|
||
let mut env_tbl = Table::new();
|
||
for (k, v) in env.iter() {
|
||
if let Some(s) = v.as_str() {
|
||
env_tbl[&k[..]] = toml_edit::value(s);
|
||
}
|
||
}
|
||
if !env_tbl.is_empty() {
|
||
t["env"] = Item::Table(env_tbl);
|
||
}
|
||
}
|
||
}
|
||
"http" | "sse" => {
|
||
let url = spec.get("url").and_then(|v| v.as_str()).unwrap_or("");
|
||
t["url"] = toml_edit::value(url);
|
||
|
||
if let Some(headers) = spec.get("headers").and_then(|v| v.as_object()) {
|
||
let mut h_tbl = Table::new();
|
||
for (k, v) in headers.iter() {
|
||
if let Some(s) = v.as_str() {
|
||
h_tbl[&k[..]] = toml_edit::value(s);
|
||
}
|
||
}
|
||
if !h_tbl.is_empty() {
|
||
t["http_headers"] = Item::Table(h_tbl);
|
||
}
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
|
||
// 2. 处理扩展字段和其他未知字段
|
||
if let Some(obj) = spec.as_object() {
|
||
for (key, value) in obj {
|
||
// 跳过已处理的核心字段
|
||
if core_fields.contains(&key.as_str()) {
|
||
continue;
|
||
}
|
||
|
||
// 尝试使用通用转换器
|
||
if let Some(toml_item) = json_value_to_toml_item(value, key) {
|
||
t[&key[..]] = toml_item;
|
||
|
||
// 记录扩展字段的处理
|
||
if extended_fields.contains(&key.as_str()) {
|
||
log::debug!("已转换扩展字段 '{key}' = {value:?}");
|
||
} else {
|
||
log::info!("已转换自定义字段 '{key}' = {value:?}");
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
Ok(t)
|
||
}
|
||
|
||
/// 将单个 MCP 服务器同步到 Codex live 配置
|
||
/// 始终使用 Codex 官方格式 [mcp_servers],并清理可能存在的错误格式 [mcp.servers]
|
||
pub fn sync_single_server_to_codex(
|
||
_config: &MultiAppConfig,
|
||
id: &str,
|
||
server_spec: &Value,
|
||
) -> Result<(), AppError> {
|
||
use toml_edit::Item;
|
||
|
||
// 读取现有的 config.toml
|
||
let config_path = crate::codex_config::get_codex_config_path();
|
||
|
||
let mut doc = if config_path.exists() {
|
||
let content =
|
||
std::fs::read_to_string(&config_path).map_err(|e| AppError::io(&config_path, e))?;
|
||
content
|
||
.parse::<toml_edit::DocumentMut>()
|
||
.map_err(|e| AppError::McpValidation(format!("解析 Codex config.toml 失败: {e}")))?
|
||
} else {
|
||
toml_edit::DocumentMut::new()
|
||
};
|
||
|
||
// 清理可能存在的错误格式 [mcp.servers]
|
||
if let Some(mcp_item) = doc.get_mut("mcp") {
|
||
if let Some(tbl) = mcp_item.as_table_like_mut() {
|
||
if tbl.contains_key("servers") {
|
||
log::warn!("检测到错误的 MCP 格式 [mcp.servers],正在清理并迁移到 [mcp_servers]");
|
||
tbl.remove("servers");
|
||
}
|
||
}
|
||
}
|
||
|
||
// 确保 [mcp_servers] 表存在
|
||
if !doc.contains_key("mcp_servers") {
|
||
doc["mcp_servers"] = toml_edit::table();
|
||
}
|
||
|
||
// 将 JSON 服务器规范转换为 TOML 表
|
||
let toml_table = json_server_to_toml_table(server_spec)?;
|
||
|
||
// 使用唯一正确的格式:[mcp_servers]
|
||
doc["mcp_servers"][id] = Item::Table(toml_table);
|
||
|
||
// 写回文件
|
||
std::fs::write(&config_path, doc.to_string()).map_err(|e| AppError::io(&config_path, e))?;
|
||
|
||
Ok(())
|
||
}
|
||
|
||
/// 从 Codex live 配置中移除单个 MCP 服务器
|
||
/// 从正确的 [mcp_servers] 表中删除,同时清理可能存在于错误位置 [mcp.servers] 的数据
|
||
pub fn remove_server_from_codex(id: &str) -> Result<(), AppError> {
|
||
let config_path = crate::codex_config::get_codex_config_path();
|
||
|
||
if !config_path.exists() {
|
||
return Ok(()); // 文件不存在,无需删除
|
||
}
|
||
|
||
let content =
|
||
std::fs::read_to_string(&config_path).map_err(|e| AppError::io(&config_path, e))?;
|
||
|
||
let mut doc = content
|
||
.parse::<toml_edit::DocumentMut>()
|
||
.map_err(|e| AppError::McpValidation(format!("解析 Codex config.toml 失败: {e}")))?;
|
||
|
||
// 从正确的位置删除:[mcp_servers]
|
||
if let Some(mcp_servers) = doc.get_mut("mcp_servers").and_then(|s| s.as_table_mut()) {
|
||
mcp_servers.remove(id);
|
||
}
|
||
|
||
// 同时清理可能存在于错误位置的数据:[mcp.servers](如果存在)
|
||
if let Some(mcp_table) = doc.get_mut("mcp").and_then(|t| t.as_table_mut()) {
|
||
if let Some(servers) = mcp_table.get_mut("servers").and_then(|s| s.as_table_mut()) {
|
||
if servers.remove(id).is_some() {
|
||
log::warn!("从错误的 MCP 格式 [mcp.servers] 中清理了服务器 '{id}'");
|
||
}
|
||
}
|
||
}
|
||
|
||
// 写回文件
|
||
std::fs::write(&config_path, doc.to_string()).map_err(|e| AppError::io(&config_path, e))?;
|
||
|
||
Ok(())
|
||
}
|
||
|
||
/// 将单个 MCP 服务器同步到 Gemini live 配置
|
||
pub fn sync_single_server_to_gemini(
|
||
_config: &MultiAppConfig,
|
||
id: &str,
|
||
server_spec: &Value,
|
||
) -> Result<(), AppError> {
|
||
// 读取现有的 MCP 配置
|
||
let current = crate::gemini_mcp::read_mcp_servers_map()?;
|
||
|
||
// 创建新的 HashMap,包含现有的所有服务器 + 当前要同步的服务器
|
||
let mut updated = current;
|
||
updated.insert(id.to_string(), server_spec.clone());
|
||
|
||
// 写回
|
||
crate::gemini_mcp::set_mcp_servers_map(&updated)
|
||
}
|
||
|
||
/// 从 Gemini live 配置中移除单个 MCP 服务器
|
||
pub fn remove_server_from_gemini(id: &str) -> Result<(), AppError> {
|
||
// 读取现有的 MCP 配置
|
||
let mut current = crate::gemini_mcp::read_mcp_servers_map()?;
|
||
|
||
// 移除指定服务器
|
||
current.remove(id);
|
||
|
||
// 写回
|
||
crate::gemini_mcp::set_mcp_servers_map(¤t)
|
||
}
|