Compare commits

...

275 Commits

Author SHA1 Message Date
suyao
67f726afb7 feat: implement API client with SWR integration for catalog management
- Added a new Textarea component for user input.
- Configured ESLint with custom rules and global ignores.
- Developed a comprehensive API client with CRUD operations and error handling.
- Defined catalog types and schemas using Zod for type safety.
- Created utility functions for class name merging and validation.
- Established Next.js configuration for API rewrites and static file headers.
- Set up package.json with necessary dependencies and scripts.
- Configured PostCSS for Tailwind CSS integration.
- Added SVG assets for UI components.
- Configured TypeScript with strict settings and module resolution.
2025-12-01 13:07:23 +08:00
suyao
d98d69e28d simplify config 2025-11-24 14:48:02 +08:00
suyao
3f671ba6be initial migrate 2025-11-24 08:55:12 +08:00
suyao
78e593fac4 feat: Add comprehensive type test
- Introduced unified export for all catalog schemas and types in `index.ts`.
- Defined model configuration schemas in `model.ts`, including modalities, capabilities, reasoning, parameter support, and pricing.
- Created provider model override schemas in `override.ts` to manage provider-specific configurations.
- Established provider configuration schemas in `provider.ts`, detailing endpoint types, authentication methods, pricing models, and behavior characteristics.
- Implemented utility functions for JSON value validation and parsing in `json-value` and `parse-json` modules.
- Developed a schema validation utility in `SchemaValidator.ts` to validate model, provider, and override configurations with detailed error handling and warnings.
2025-11-24 07:36:33 +08:00
suyao
9933b0b12f feat: Add comprehensive schema definitions for catalog system
- Introduced common types and validation utilities in common.types.ts
- Unified export of all schemas in index.ts for easier access
- Defined model configuration schemas including capabilities, pricing, and reasoning in model.schema.ts
- Created provider model override schemas to manage provider-specific configurations in override.schema.ts
- Established provider configuration schemas detailing metadata, capabilities, and behaviors in provider.schema.ts
2025-11-24 06:12:45 +08:00
suyao
bceeef5190 Initial Prompt 2025-11-24 01:40:20 +08:00
fullex
cf7b4dd07b Merge branch 'main' into v2 2025-11-22 08:48:07 +08:00
fullex
fe88cfe106 feat: initialize database in app startup and enhance DbService
- Added an init method to DbService for database initialization, ensuring it is called before migrations.
- Updated the migrateDb and migrateSeed methods to check if the database is initialized, improving error handling.
- Called dbService.init() in the app's whenReady event to ensure proper database setup during startup.
2025-11-21 23:46:51 +08:00
MyPrototypeWhat
e3bf63d7a0 chore: remove DmxapiToImg component and related assets
- Deleted the DmxapiToImg SVG file and its corresponding React component to streamline the icon library.
- Updated index.ts and Logos.stories.tsx to remove references to DmxapiToImg, ensuring consistency across the codebase.
2025-11-21 18:27:30 +08:00
MyPrototypeWhat
9a356cb27d style(tabs.stories):lint 2025-11-21 17:26:14 +08:00
MyPrototypeWhat
53883a27be feat: add Tabs component and related subcomponents
- Introduced a new Tabs component along with TabsList, TabsTrigger, and TabsContent for improved content organization.
- Updated package.json and yarn.lock to include @radix-ui/react-tabs dependency.
- Enhanced index.ts to export the new Tabs components for easier access in the UI library.
- Created stories for the Tabs component in Storybook to demonstrate various usage scenarios.
2025-11-21 17:09:29 +08:00
fullex
24c9c157f9 chore: format 2025-11-21 16:58:04 +08:00
fullex
55727e2adf feat: configure WAL mode for improved database performance
- Introduced a new method to configure Write-Ahead Logging (WAL) mode for better concurrency during database operations.
- Ensured WAL mode is set only once, with error handling to fall back to default settings if configuration fails.
- Updated the migrateDb method to call the new configuration method on the first database operation.
2025-11-21 16:36:15 +08:00
MyPrototypeWhat
1e4239d189 feat: update UI component stories to use centralized imports from @cherrystudio/ui
- Added a new Breadcrumb.stories.tsx file to showcase the Breadcrumb component and its variations.
- Refactored existing stories for Button, Checkbox, Combobox, Kbd, Pagination, RadioGroup, Select, and Spinner components to import directly from @cherrystudio/ui instead of relative paths.
- Enhanced the organization and accessibility of component stories in the Storybook environment.
2025-11-21 13:34:02 +08:00
MyPrototypeWhat
5ccb16a0be feat: add Breadcrumb component and related subcomponents
- Introduced a new Breadcrumb component along with BreadcrumbList, BreadcrumbItem, BreadcrumbLink, BreadcrumbPage, BreadcrumbSeparator, and BreadcrumbEllipsis.
- Updated index.ts to export the new Breadcrumb components for easier access in the UI library.
2025-11-21 13:34:02 +08:00
MyPrototypeWhat
34c9a6b350 docs: update CLAUDE.md to reflect UI component migration to Tailwind CSS and Shadcn UI
- Revised guidelines to specify the use of Tailwind CSS and Shadcn UI components from `@packages/ui` for new UI development.
- Updated project documentation to clarify the prohibition of `antd` and `styled-components` in favor of the new UI libraries.
2025-11-21 13:34:02 +08:00
fullex
ab99366a0a feat: enhance DbService with improved error handling and documentation
- Added detailed JSDoc comments for better understanding of DbService methods and usage.
- Implemented error handling during database initialization and migration processes to ensure robustness.
- Introduced a method to check if the database is initialized before accessing it.
- Updated the migrateSeed method to throw errors on failure, improving error reporting.
2025-11-21 13:29:24 +08:00
fullex
7419cadd80 Merge branch 'main' into v2 2025-11-20 23:12:55 +08:00
fullex
46f2726a63 refactor: remove obsolete data refactor migration components and related tests
- Deleted the DataRefactorMigrateService and associated HTML files, as they are no longer needed.
- Removed test components and files related to data refactor migration, streamlining the codebase.
- Updated configuration files to reflect the removal of the data refactor migration functionality.
2025-11-20 23:03:00 +08:00
fullex
7bd3e047d2 docs: add README.md for data migration infra 2025-11-20 22:54:06 +08:00
fullex
1ea19adfec refactor: update migration types and imports for consistency
- Replaced core types with shared types in migration files to ensure consistency across the application.
- Deleted obsolete core types file and updated imports in migrator and window components to reference the new shared types.
- Enhanced the migration process by streamlining type definitions and improving code maintainability.
2025-11-20 22:42:43 +08:00
fullex
1685590a07 feat: integrate i18n support into migration process
- Added internationalization support to the MigrationApp component, enabling dynamic language changes.
- Updated button labels and informational texts to use translation keys for better localization.
- Introduced a language selector to allow users to switch between languages during the migration process.
- Ensured that the migration process waits for i18n initialization before rendering the main application.
2025-11-20 22:08:22 +08:00
fullex
db10bdd539 feat: enhance migration process with new 'migration_completed' stage
- Added 'migration_completed' stage to the migration process for better tracking of completion.
- Updated relevant components and hooks to handle the new stage, including UI changes to confirm migration completion.
- Adjusted messages and progress indicators to reflect the new stage in the migration workflow.
2025-11-20 20:32:33 +08:00
fullex
d79602325d Merge branch 'v2' of github.com:CherryHQ/cherry-studio into v2 2025-11-20 19:48:27 +08:00
fullex
a19419e597 feat: add migration v2 support and update dependencies
- Integrated migration v2 functionality by importing necessary modules and registering IPC handlers.
- Updated the migration process to check for data migration needs and handle the migration window.
- Added new dependencies for stream-json and its types in package.json.
- Updated electron.vite.config.ts to include the new migration window HTML file.
2025-11-20 19:48:19 +08:00
MyPrototypeWhat
a7686f61c7 style: enhance PaginationLink styles with rounded corners
- Updated the PaginationLink component to include rounded corners in its hover styles, improving the overall visual appearance and user experience.
2025-11-20 15:39:18 +08:00
MyPrototypeWhat
e694ae68e3 feat: add Pagination component exports and enhance PaginationLink styles
- Exported the new Pagination component from the index file to make it available for use.
- Updated the PaginationLink styles to improve hover effects and active state visibility, enhancing user experience.
2025-11-20 15:27:06 +08:00
MyPrototypeWhat
02a65daa27 feat: update @radix-ui/react-slot to version 1.2.4 and add Pagination component with stories
- Updated the @radix-ui/react-slot dependency in package.json and yarn.lock to version 1.2.4.
- Introduced a new Pagination component with associated subcomponents (PaginationContent, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious, PaginationEllipsis).
- Added stories for the Pagination component to demonstrate various use cases and configurations.
2025-11-20 14:49:22 +08:00
fullex
1a9fd77599 feat: implement garbage collection in CacheService and update cleanup interval in PreferenceService
- Added a garbage collection mechanism in CacheService to automatically remove expired cache entries every 10 minutes.
- Introduced a cleanup interval in PreferenceService, adjusting the frequency to every 5 minutes for better resource management.
- Enhanced cleanup methods in both services to ensure proper resource release during shutdown.
2025-11-19 22:23:09 +08:00
MyPrototypeWhat
7fa97f8a2b feat: add new Tooltip component with enhanced functionality
- Introduced a new Tooltip component along with TooltipProvider, TooltipTrigger, and TooltipContent for improved user interface interactions.
- Implemented NormalTooltip for easier usage with customizable content and positioning options.
- Integrated Radix UI's tooltip primitives for better accessibility and performance.
2025-11-18 18:07:28 +08:00
MyPrototypeWhat
838bb385fd refactor: comment out Tooltip integration in Kbd stories for cleanup
- Removed the InTooltip story from Kbd.stories.tsx to declutter the examples.
- Kept the Tooltip-related imports commented out for potential future use.
2025-11-18 17:59:36 +08:00
MyPrototypeWhat
583e4e9db7 feat: add Kbd component for keyboard shortcuts and integrate with Tooltip
- Introduced a new Kbd component to display keyboard shortcuts, supporting both single keys and key combinations.
- Added KbdGroup for grouping multiple Kbd components together.
- Updated package.json to include @radix-ui/react-tooltip version 1.2.8.
- Created stories for Kbd component showcasing various use cases, including integration with Tooltip for enhanced user guidance.
2025-11-18 16:50:10 +08:00
fullex
5fdfa5a594 Merge branch 'main' of into v2 2025-11-17 19:51:07 +08:00
MyPrototypeWhat
ad939f4b77 Refactor index.ts to update icon component documentation and remove commented-out selector exports
- Updated comments for brand logo icons to reflect the current count and recommended import path.
- Removed deprecated selector component exports to clean up the index file.
2025-11-17 11:10:12 +08:00
MyPrototypeWhat
6abe5ab8c3 Remove deprecated icon components and their associated stories
- Deleted the FilePngIcon and FileSvgIcon components from the icons directory due to low usage.
- Removed the ToolsCallingIcon component and its related stories, as it did not meet the UI library extraction criteria.
- Updated the index.ts file to reflect these removals and cleaned up the export list accordingly.
- Ensured that all related story files for the removed icons were also deleted to maintain a clean codebase.
2025-11-17 11:07:11 +08:00
fullex
1156b12ac6 Merge remote-tracking branch 'origin/main' into v2 2025-11-14 21:38:00 +08:00
MyPrototypeWhat
4410599dfa Remove DmxapiLogo icon and update icon export list
- Deleted the DmxapiLogo SVG file from the icons directory.
- Updated the icon export list to reflect the removal of DmxapiLogo, reducing the total icon count from 81 to 80.
- Adjusted related stories to exclude DmxapiLogo from the showcased icons.
2025-11-14 18:25:27 +08:00
MyPrototypeWhat
bce8e5cc7f Update Electron and TypeScript configurations to include new icon package
- Added '@cherrystudio/ui/icons' to the Electron Vite configuration for improved icon management.
- Updated TypeScript configuration to include type definitions for the new icon package.
- Removed unused dependencies from yarn.lock to streamline package management.
2025-11-14 18:02:47 +08:00
MyPrototypeWhat
9d75b0972e Refactor icon management and update dependencies
- Removed the ICON_IMPLEMENTATION_GUIDE.md file and several unused SVG icons from the `icons/` directory.
- Added new SVG icons to enhance the icon library, including various brand logos.
- Updated package.json to reflect the new version of the `tsx` dependency.
- Introduced a script for generating icons and improved the structure of the icons module for better organization and accessibility.
- Updated the stories for icons to showcase the new additions and ensure proper documentation.
2025-11-14 17:55:44 +08:00
MyPrototypeWhat
a3062d6e38 Add ICON_IMPLEMENTATION_GUIDE and new SVG icons
- Created ICON_IMPLEMENTATION_GUIDE.md to document icon usage and common issues.
- Added multiple new SVG icons to the `icons/` directory, enhancing the icon library.
- Updated tailwind.css for improved styling consistency across components.
2025-11-14 13:31:17 +08:00
MyPrototypeWhat
43fb232cca Update tailwind.css to use glob pattern for component imports 2025-11-13 17:28:02 +08:00
SuYao
d610943f0f Fix/merge-main (#11262)
* merge branch 'main'

* fix: lint error

* fix yarn lock

* fix: lock

* fix: ci

* fix: yarn lock
2025-11-12 22:49:58 +08:00
fullex
680fcb4b9d Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-11-12 20:41:05 +08:00
MyPrototypeWhat
d82e004f57 feat(design-reference): restructure color tokens and remove outdated conversion log
- Deleted the outdated CONVERSION_LOG.md file to streamline documentation.
- Introduced new HSLA color files for primitive, semantic, and status colors, enhancing color management.
- Updated theme and token files to utilize Oklch color format for improved color representation.
- Refactored radius and color tokens for consistency and maintainability across the design system.
2025-11-12 18:14:18 +08:00
MyPrototypeWhat
aa13ad4fac feat(checkbox): export CheckedState type and add checkbox/combobox to component index
- Exported CheckedState type from the checkbox component for better type management.
- Added checkbox and combobox components to the main component index for easier access.
- Updated Storybook examples to utilize the CheckedState type for controlled checkbox states.
2025-11-12 15:04:50 +08:00
MyPrototypeWhat
02d79f47b3 feat(checkbox): add Radix UI checkbox component with Storybook examples
- Introduced a new checkbox component utilizing Radix UI, allowing for customizable sizes and states.
- Implemented styles using class-variance-authority for consistent design across different sizes (sm, md, lg).
- Added comprehensive Storybook stories demonstrating various use cases, including default, checked, disabled, and controlled states.
- Updated package.json and yarn.lock to include the new Radix UI checkbox dependency.
2025-11-12 14:58:14 +08:00
MyPrototypeWhat
75c0923636 feat(radioGroup): enhance RadioGroup component with size variants and add Storybook examples
- Introduced size variants for RadioGroupItem using class-variance-authority for better customization.
- Updated RadioGroupItem to accept size prop and adjusted styles accordingly.
- Added comprehensive Storybook stories for various use cases, including default, disabled, and size variations, to demonstrate component functionality and usage.
2025-11-12 14:26:25 +08:00
MyPrototypeWhat
7dd1ecd4a5 feat(storybook): add background options for light and dark themes
- Introduced background parameters in Storybook preview configuration to support light and dark themes.
- Defined specific color values for each theme to enhance visual consistency during component development.
2025-11-12 14:26:09 +08:00
MyPrototypeWhat
a2299fa2ab style(combobox, select): update styles to use Tailwind CSS utility classes
- Refactored the combobox and select components to utilize Tailwind CSS utility classes for consistent styling.
- Added 'text-foreground' class to enhance text visibility in both components.
- Streamlined the default styles for better maintainability and adherence to the new design system.
2025-11-11 17:24:47 +08:00
MyPrototypeWhat
a830d05790 fix(tailwind): dynamically import Tailwind CSS in Vite config
- Updated the Electron Vite configuration to dynamically import Tailwind CSS for improved performance.
- Removed the direct import of Tailwind CSS from the plugins array to streamline the build process.
2025-11-11 17:17:23 +08:00
MyPrototypeWhat
8429e678bc style(tailwind): migrate to Tailwind CSS and update theme handling
- Integrated Tailwind CSS into the project by adding necessary imports and configurations.
- Updated CSS files to reflect the transition to Tailwind, including commenting out old styles and adjusting theme-related attributes.
- Changed theme mode handling in the ThemeProvider and CitationBlock components for consistency with the new class-based approach.
2025-11-11 17:03:14 +08:00
MyPrototypeWhat
91215c899d style(tailwind): add source import for UI components in tailwind.css
- Included a new source import statement for UI components to enhance styling capabilities.
- Maintained existing imports while ensuring compatibility with the updated structure.
2025-11-11 13:56:58 +08:00
fullex
1309b194e9 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-11-11 12:03:35 +08:00
MyPrototypeWhat
1b1f85b35f fix(navbar): remove duplicate placement attribute in Tooltip component
- Simplified Tooltip component in ChatNavbar and Navbar by removing redundant 'placement' attribute.
- Ensured consistent behavior across both components while maintaining functionality.
2025-11-11 11:31:43 +08:00
fullex
4407c0f675 refactor(oauth): update language retrieval in OAuth callback
- Replaced the configManager.getLanguage() method with getAppLanguage() for improved language handling.
- Adjusted imports to reflect the new language utility structure.
2025-11-11 11:19:06 +08:00
MyPrototypeWhat
30947c6bc1 refactor(select): replace Selector component with new Select implementation in SettingsTab
- Updated SettingsTab to utilize the new Select component instead of the deprecated Selector.
- Enhanced Select integration with SelectTrigger, SelectContent, SelectItem, and SelectValue for improved functionality.
- Removed Selector imports and related code to streamline the component structure.
- Adjusted styles and layout for better user experience in the settings interface.
2025-11-11 11:01:48 +08:00
MyPrototypeWhat
0b3cefb125 style(select): update styles for Select component items and content
- Adjusted border radius for SelectContent to 'rounded-2xs' for a more modern look.
- Enhanced SelectItem styles to include a background color for checked state.
- Updated CheckIcon color to 'text-primary' for better visibility in the SelectItem.
2025-11-11 10:46:20 +08:00
MyPrototypeWhat
b382b06c57 feat(select): introduce new Select component and related features
- Added a new Select component based on Radix UI, including SelectTrigger, SelectContent, SelectItem, and SelectValue.
- Implemented support for groups and separators within the Select component.
- Updated package.json to include @radix-ui/react-select as a dependency.
- Removed deprecated Selector and SearchableSelector components to streamline the codebase.
- Added stories for the Select component to showcase various use cases and configurations.
2025-11-10 19:42:33 +08:00
MyPrototypeWhat
8246f46e7d fix(Button): update import path for Button component to reflect new structure 2025-11-10 19:35:46 +08:00
fullex
f32fa08c41 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-11-10 18:44:02 +08:00
kangfenmao
56df52d850 Merge branch 'main' into v2
# Conflicts:
#	src/renderer/src/pages/settings/MCPSettings/BuiltinMCPServerList.tsx
#	src/renderer/src/pages/settings/MCPSettings/McpProviderSettings.tsx
#	src/renderer/src/pages/settings/MCPSettings/McpServersList.tsx
#	src/renderer/src/pages/settings/MCPSettings/McpSettingsNavbar.tsx
#	src/renderer/src/pages/settings/MCPSettings/index.tsx
#	src/renderer/src/pages/settings/MCPSettings/providers/config.ts
2025-11-07 19:34:45 +08:00
MyPrototypeWhat
846a7f5ecf refactor(button & combobox): enhance styling and accessibility
- Updated button variants for improved hover effects and accessibility, including aria-loading support.
- Refined combobox trigger styles for better visibility and consistency, including adjustments to error state styling and input placeholder appearance.
- Improved overall class management and organization for both components.
2025-11-07 19:29:06 +08:00
MyPrototypeWhat
f2c2a27622 refactor(combobox & tailwind): update styling and variable management
- Modified default combobox trigger styles for improved visibility and consistency.
- Updated background and text colors in the combobox options for better accessibility.
- Cleaned up unused CSS variables in tailwind.css, retaining only those necessary for theme usage.
- Enhanced comments for clarity in the CSS files.
2025-11-07 17:30:12 +08:00
MyPrototypeWhat
348e0dfc80 fix(theme.css): standardize import syntax for tailwindcss 2025-11-07 17:17:24 +08:00
MyPrototypeWhat
77c848035d feat(tokens): introduce design tokens for colors, spacing, typography, and radius
- Added new CSS files for design tokens including colors, spacing, typography, and border radius.
- Updated theme.css to import the new tokens and ensure proper usage in the UI.
- Enhanced the theme structure to support light and dark modes with semantic color mappings.
- Introduced a build script to generate theme from tokens for easier management.
2025-11-07 17:12:34 +08:00
MyPrototypeWhat
cd6a38ebeb fix(tailwindCSS): add experimental classRegex for improved class management 2025-11-07 11:26:00 +08:00
MyPrototypeWhat
b57ed07d00 refactor(button & combobox): improve styling and class management
- Adjusted button outline variant for consistency in dark mode styling.
- Removed unnecessary background color from combobox trigger for cleaner appearance.
- Updated comments in the theme CSS file for clarity and consistency.
2025-11-07 11:04:12 +08:00
kangfenmao
f7c8fb8d56 refactor: update component imports and styling for consistency
- Removed the 'no-restricted-imports' rule from ESLint configuration.
- Updated `AgentSessionInputbar` to use `icon` prop for `ActionIconButton`.
- Cleaned up imports in `AssistantsTab`, `SessionItem`, and `DataSettings` components.
- Adjusted button styling in `UnifiedAddButton` and `AboutSettings` for improved layout.
- Fixed test assertions in `WebviewSearch.test.tsx` for better accuracy.
2025-11-06 20:23:38 +08:00
kangfenmao
dae10cf673 Merge branch 'v2' of github.com:CherryHQ/cherry-studio into v2 2025-11-06 19:53:20 +08:00
kangfenmao
a50da9fc80 Merge branch 'main' into v2
# Conflicts:
#	CLAUDE.md
#	package.json
#	packages/ui/src/components/primitives/toast.ts
#	src/main/services/AppMenuService.ts
#	src/renderer/src/assets/styles/tailwind.css
#	src/renderer/src/components/Avatar/EmojiAvatarWithPicker.tsx
#	src/renderer/src/components/Buttons/ActionIconButton.tsx
#	src/renderer/src/components/ConfirmDialog.tsx
#	src/renderer/src/components/ErrorBoundary.tsx
#	src/renderer/src/components/Popups/ExportToPhoneLanPopup.tsx
#	src/renderer/src/components/Popups/agent/AgentModal.tsx
#	src/renderer/src/components/Popups/agent/SessionModal.tsx
#	src/renderer/src/components/TopView/index.tsx
#	src/renderer/src/components/UpdateDialog.tsx
#	src/renderer/src/context/HeroUIProvider.tsx
#	src/renderer/src/env.d.ts
#	src/renderer/src/hero.ts
#	src/renderer/src/hooks/useUserTheme.ts
#	src/renderer/src/pages/home/Chat.tsx
#	src/renderer/src/pages/home/Inputbar/AgentSessionInputbar.tsx
#	src/renderer/src/pages/home/Messages/Blocks/ErrorBlock.tsx
#	src/renderer/src/pages/home/Messages/Message.tsx
#	src/renderer/src/pages/home/Messages/Tools/ToolPermissionRequestCard.tsx
#	src/renderer/src/pages/home/Tabs/AssistantsTab.tsx
#	src/renderer/src/pages/home/Tabs/SessionSettingsTab.tsx
#	src/renderer/src/pages/home/Tabs/components/AddButton.tsx
#	src/renderer/src/pages/home/Tabs/components/AgentItem.tsx
#	src/renderer/src/pages/home/Tabs/components/AssistantItem.tsx
#	src/renderer/src/pages/home/Tabs/components/SessionItem.tsx
#	src/renderer/src/pages/home/Tabs/components/Sessions.tsx
#	src/renderer/src/pages/home/Tabs/components/TagGroup.tsx
#	src/renderer/src/pages/home/Tabs/components/Topics.tsx
#	src/renderer/src/pages/home/Tabs/components/UnifiedAddButton.tsx
#	src/renderer/src/pages/home/Tabs/index.tsx
#	src/renderer/src/pages/home/components/ChatNavbarContent.tsx
#	src/renderer/src/pages/home/components/SelectAgentBaseModelButton.tsx
#	src/renderer/src/pages/home/components/UpdateAppButton.tsx
#	src/renderer/src/pages/minapps/components/WebviewSearch.tsx
#	src/renderer/src/pages/notes/HeaderNavbar.tsx
#	src/renderer/src/pages/settings/AboutSettings.tsx
#	src/renderer/src/pages/settings/AgentSettings/AccessibleDirsSetting.tsx
#	src/renderer/src/pages/settings/AgentSettings/components/InstalledPluginsList.tsx
#	src/renderer/src/pages/settings/AgentSettings/components/PluginBrowser.tsx
#	src/renderer/src/pages/settings/AgentSettings/components/PluginCard.tsx
#	src/renderer/src/pages/settings/DataSettings/DataSettings.tsx
#	src/renderer/src/pages/settings/ToolSettings/ApiServerSettings/ApiServerSettings.tsx
#	src/renderer/src/pages/translate/TranslateSettings.tsx
#	src/renderer/src/services/ApiService.ts
#	src/renderer/src/store/runtime.ts
#	src/renderer/src/windows/mini/MiniWindowApp.tsx
#	src/renderer/src/windows/selection/action/entryPoint.tsx
#	yarn.lock
2025-11-06 19:53:09 +08:00
MyPrototypeWhat
7d5d9964d7 refactor(combobox): simplify default styling and enhance class management
- Removed unnecessary background color from default combobox trigger variant for cleaner styling.
- Added a white background to the combobox trigger for improved visibility.
- Updated comments in the CSS file to enhance clarity and consistency in English.
2025-11-06 18:36:12 +08:00
MyPrototypeWhat
059f821584 refactor(button & combobox): update size properties and improve styling
- Changed button size properties to use min-height for better layout consistency.
- Simplified combobox size properties by removing height specifications.
- Enhanced combobox option rendering with improved class management for better styling.
- Updated comments in ComboboxProps to English for clarity.
2025-11-06 18:20:43 +08:00
MyPrototypeWhat
1c38e31e9e feat(theme): enhance color tokens with brand colors and update primary color references
- Added new brand color tokens for Cherry Studio ranging from 50 to 950.
- Updated primary color references to use brand colors for improved consistency.
- Introduced hover states for primary and destructive colors to enhance UI interactivity.
2025-11-06 17:45:40 +08:00
MyPrototypeWhat
12e3a22726 feat: add Combobox component with search and multi-select functionality
- Introduced a new Combobox component that supports single and multiple selections, search functionality, and customizable rendering of options.
- Implemented variants for different states (default, error, disabled) and sizes (small, default, large).
- Added a demo and Storybook stories to showcase various use cases and states of the Combobox.
2025-11-06 17:24:45 +08:00
MyPrototypeWhat
2b1269af92 chore: update Storybook dependencies to version 10.0.5 and refactor Storybook configuration for absolute paths 2025-11-06 17:24:28 +08:00
MyPrototypeWhat
c4fa975b89 style(tailwind): add cursor pointer for non-disabled buttons 2025-11-06 17:24:12 +08:00
fullex
1b67b851b7 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-11-05 16:24:06 +08:00
fullex
811e702568 fix: i18n 2025-11-05 16:14:28 +08:00
MyPrototypeWhat
4ef4297391 refactor: update imports and button event handlers in story files
- Refactored import statements in CodeEditor, ThinkingEffect, ErrorBoundary, and Spinner story files for consistency and clarity.
- Changed button event handlers from `onPress` to `onClick` to align with standard React practices.
- Improved type imports for better organization and maintainability.
2025-11-03 19:17:50 +08:00
MyPrototypeWhat
292f7f7b75 chore: remove unused CSS files and update Storybook configurations
- Deleted the todocss.css file as it was no longer needed.
- Updated Storybook main.ts to include path aliasing for better module resolution.
- Removed deprecated stories and components, streamlining the codebase.
- Added new stories for CodeEditor, Ellipsis, ExpandableText, and other components to enhance documentation and showcase functionality.
2025-11-03 18:31:48 +08:00
MyPrototypeWhat
e56edbaa4f feat: enhance Button component with loading state and custom loading icon
- Added loading state support to the Button component, allowing for a spinner to be displayed when the button is in a loading state.
- Introduced props for custom loading icons and adjusted button behavior to disable when loading.
- Updated various components to utilize the new loading feature for better user experience during asynchronous actions.
2025-11-03 16:30:45 +08:00
MyPrototypeWhat
e06142b89a chore: remove deprecation comments from EditableNumber and Sortable components
- Removed deprecation comments from EditableNumber and Sortable components, as they were previously marked for removal due to low usage and dependency conflicts.
2025-11-03 14:24:22 +08:00
MyPrototypeWhat
fb6b326947 chore: mark multiple components and icons as deprecated
- Added deprecation comments to several components and icons due to low usage (≤2 times), indicating plans for removal in future versions.
- Components affected include EditableNumber, MaxContextCount, Sortable, ThinkingEffect, FileIcons, ToolIcon, and others.
- Suggested alternatives or direct usage of other components where applicable.
2025-11-03 13:41:00 +08:00
MyPrototypeWhat
f9b7ff7d0e refactor: comment out unused CSS imports and styles
- Commented out the import of color.css in index.css.
- Commented out the universal selector in tailwind.css to prevent unintended styling, with a note for future removal after migration.
2025-11-03 11:30:58 +08:00
fullex
14706ec4d7 fix: typecheck 2025-11-01 19:11:17 +08:00
fullex
09f2fb6538 fix: lint errors 2025-11-01 18:47:20 +08:00
fullex
62aedcaa23 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-11-01 18:46:38 +08:00
fullex
62ccb6105d feat: enhance CacheService and DataApiService documentation and structure
- Added detailed file overview comments to CacheService and DataApiService, clarifying their roles as infrastructure components rather than business services.
- Updated README.md to reflect the new structure and naming conventions, emphasizing the distinction between infrastructure and business logic components.
- Introduced a new TestService for API testing scenarios, providing mock data and various test cases.
- Created IBaseService interface to standardize service operations across the codebase.
- Improved organization of API handlers and services for better clarity and maintainability.
2025-11-01 18:36:28 +08:00
fullex
5101488d65 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-11-01 11:01:56 +08:00
fullex
7c0b03dbdc Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-11-01 09:46:47 +08:00
fullex
b3dc2d0422 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-10-31 19:35:45 +08:00
MyPrototypeWhat
1828ef8997 fix: update muted foreground color variable in theme.css
- Changed the variable for muted foreground color from `--cs-foreground-secondary` to `--cs-foreground-muted` for improved clarity and consistency in styling.
2025-10-31 19:33:58 +08:00
fullex
b3f88a7fc2 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-10-31 18:29:44 +08:00
MyPrototypeWhat
2c07ea0dd8 chore: update Tailwind CSS imports and adjust source paths
- Replaced the import of `theme.css` with `tailwindcss` for improved styling management.
- Adjusted the source path to include components specifically, enhancing clarity in file structure.
- Retained the import of `tw-animate-css` for animation support.
2025-10-31 16:25:11 +08:00
MyPrototypeWhat
6042ee8ca8 chore: remove outdated DESIGN_SYSTEM.md and update migration documentation
- Deleted the obsolete DESIGN_SYSTEM.md file to streamline documentation.
- Updated MIGRATION_STATUS.md to reflect the new design token namespace (`--cs-*`) and improved clarity on migration phases and principles.
- Revised README.md to correct the number of import methods and enhance usage instructions for the updated design system.
2025-10-31 15:54:29 +08:00
MyPrototypeWhat
d164d7c8bf refactor: update CSS structure and improve theme integration
- Changed the main CSS file reference from `globals.css` to `theme.css` in `components.json` for better theme management.
- Introduced `index.css` to export only CSS variables, allowing npm users to utilize design tokens without overriding Tailwind defaults.
- Removed `globals.css` as it is no longer needed with the new structure.
- Updated `package.json` to reflect changes in CSS file paths.
- Enhanced `README.md` to clarify installation and configuration steps for the new styling approach.
2025-10-31 15:31:51 +08:00
fullex
23f7b39753 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-10-31 11:12:49 +08:00
MyPrototypeWhat
fe188ba8fb feat: enhance design token management and documentation
- Added new design token files including design-tokens.css and theme.css to standardize styling across the UI.
- Introduced a conversion log (CONVERSION_LOG.md) detailing the migration from todocss.css to design-tokens.css, including variable updates and deprecations.
- Updated package.json to include new CSS files for easier imports.
- Enhanced README.md to provide clear guidelines on the design reference and usage of design tokens.
- Improved globals.css to integrate with the new design token structure and ensure consistency in styling.
2025-10-30 19:40:19 +08:00
MyPrototypeWhat
cf008ca22e feat: update migration status documentation for Cherry Studio UI
- Expanded the migration status document to outline the comprehensive plan for transitioning from antd + styled-components to shadcn/ui + Tailwind CSS.
- Introduced detailed migration strategies, principles, and component classification guidelines.
- Added extraction criteria and migration steps to ensure a structured approach to component migration and optimization.
- Emphasized collaboration with UI designers for maintaining design consistency throughout the migration process.
2025-10-29 18:06:30 +08:00
MyPrototypeWhat
851ff8992f style: format color variables in todocss.css for improved readability
- Reformatted color variable definitions in todocss.css to enhance readability by breaking long lines into multiple lines.
- Ensured consistency in the formatting of HSLA values across the file.
2025-10-29 16:56:31 +08:00
MyPrototypeWhat
91f9088436 feat: add design system documentation and todocss.css file
- Introduced a comprehensive design system document outlining integration strategies for Tailwind CSS v4, usage guidelines, and UI library balance strategies.
- Added todocss.css file containing typography, spacing, sizing, and color variables for the design system.
- Established naming conventions and core transformation rules for design tokens to enhance consistency and usability across the UI components.
2025-10-29 16:52:05 +08:00
fullex
c971daf23c Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-10-29 16:43:40 +08:00
fullex
0c7cee2700 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-10-29 16:37:54 +08:00
fullex
3e9d9f16d6 fix: test 2025-10-29 14:45:55 +08:00
fullex
f3a279d8de Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-10-29 14:28:03 +08:00
MyPrototypeWhat
b9a947d2fd refactor: restructure UI components and remove deprecated files
- Added new components including CodeEditor, CollapsibleSearchBar, and DraggableList.
- Removed obsolete components such as Button, CustomCollapse, and StatusTag.
- Updated migration status documentation and adjusted component exports.
- Enhanced package.json dependencies for better compatibility.
2025-10-28 14:27:05 +08:00
fullex
57b9ca111a fix: format 2025-10-28 09:12:51 +08:00
fullex
709f264ac9 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-10-28 09:02:09 +08:00
fullex
736aef22c4 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-10-23 18:30:32 +08:00
fullex
d0ed4cc1f2 Merge pull request #10913 from CherryHQ/v2-merge-main
Merge branch 'main' into v2
2025-10-23 18:14:19 +08:00
icarus
8c6a577cca fix: correct model logo source to use message.model directly 2025-10-23 17:48:33 +08:00
icarus
27b6ad75df refactor: use type-only import for Model type 2025-10-23 17:44:30 +08:00
icarus
c617a0b51a Merge branch 'main' into v2 2025-10-23 17:41:21 +08:00
fullex
75d7ed075b fix: update snapshot styles for InputEmbeddingDimension and Spinner components
- Adjusted the flex style for the InputEmbeddingDimension component to improve layout consistency.
- Removed the unset color style from the Spinner component to ensure default styling is applied.
2025-10-22 01:01:21 +08:00
fullex
b5b577dc79 fix: yarn.lock 2025-10-22 00:39:08 +08:00
fullex
e754b5a863 style: format InfoTooltip component in GeneralSettings for improved readability 2025-10-21 18:01:02 +08:00
fullex
82dd771110 fix: replace Tooltip with InfoTooltip in GeneralSettings for improved clarity
- Updated the proxy bypass tooltip to use InfoTooltip component for better styling and functionality.
- Maintained existing behavior while enhancing the user interface.
2025-10-21 17:40:17 +08:00
fullex
8a4a34a946 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-10-21 17:38:15 +08:00
beyondkmp
fb62ae18b7 chores: remove config manager (#10856)
* refactor: migrate from configManager to preferenceService

- Replace configManager with preferenceService for app settings
- Update zoom factor management to use preferenceService
- Migrate spell check settings to preferenceService
- Update language subscription in NodeTraceService
- Move client ID generation to systemInfo utility
- Keep shortcuts management in configManager (not migrated)
- Mark legacy Config_Set/Config_Get as deprecated
- Update AppUpdater test mock to include getClientId

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: migrate from configManager to preferenceService

- Replace configManager with preferenceService for app settings
- Update zoom factor management to use preferenceService
- Migrate spell check settings to preferenceService
- Update language subscription in NodeTraceService
- Move client ID generation to systemInfo utility
- Keep shortcuts management in configManager (not migrated)
- Mark legacy Config_Set/Config_Get as deprecated
- Update AppUpdater test mock to include getClientId

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-21 13:46:05 +08:00
fullex
e59990d24e Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-10-21 10:09:13 +08:00
kangfenmao
b08228bdb5 refactor: update LaunchpadPage to use useSettings hook
- Replaced usePreference with useSettings in LaunchpadPage for improved state management.
- This change aligns with recent updates to enhance consistency across components.
2025-10-18 18:42:29 +08:00
kangfenmao
d2b6433609 feat: add Radix UI radio group component and update MCP settings UI
- Introduced a new RadioGroup component using Radix UI for better UI consistency.
- Updated MCPProviderSettings to utilize the new RadioGroup and adjusted button styles for improved UX.
- Added Radix UI radio group dependency to package.json and yarn.lock.
2025-10-18 18:31:00 +08:00
kangfenmao
3417acafe2 refactor: mcp servers settings 2025-10-18 18:07:52 +08:00
kangfenmao
f42afe28d7 refactor: update Chat, AgentItem, and LaunchpadPage components to use preference hooks
- Replaced useSettings with usePreference in AgentItem and LaunchpadPage for better state management.
- Adjusted Chat component's Main element to include width styling for improved layout consistency.
2025-10-18 18:07:43 +08:00
fullex
0da9252eb7 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-10-18 17:45:44 +08:00
fullex
de5fa5e09c fix: test snapshot 2025-10-16 17:33:14 +08:00
fullex
8d64bb0316 fix: lint error 2025-10-16 17:13:30 +08:00
fullex
d7eb88f7e2 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-10-16 17:07:52 +08:00
MyPrototypeWhat
b41e1d712f chore: refactor UI package paths and imports for consistency
- Updated tsconfig files to standardize module resolution paths for the UI package.
- Modified component import paths in components.json to align with the new structure.
- Refactored import statements in various UI components to use the updated paths from '@cherrystudio/ui'.
- Added new exports for UI components in the index file to enhance accessibility.
2025-10-16 15:18:35 +08:00
MyPrototypeWhat
c258035f6a chore: enhance type checking and update UI package configuration
- Added a new typecheck command for the UI package in package.json to ensure type safety.
- Updated tsconfig.web.json to include UI paths for better module resolution.
- Modified the type-check command in the UI package to specify the tsconfig.json file.
- Adjusted the include paths in the UI tsconfig.json to focus on specific component directories.
2025-10-14 14:43:49 +08:00
MyPrototypeWhat
569572bfdc style: standardize import syntax in globals.css
- Updated import statements in globals.css to use single quotes for consistency across the codebase.
2025-10-14 14:20:21 +08:00
MyPrototypeWhat
b821ac5390 fix: update import path for RequireSome type in Toast component
- Changed the import path for RequireSome type from '@types' to '@/types' to align with the project's directory structure.
2025-10-14 14:12:55 +08:00
MyPrototypeWhat
534c2ce485 feat: update UI components and styles with Radix and Tailwind integration
- Added new UI components including Button, Command, Dialog, Popover, and Dropzone using Radix UI.
- Introduced global styles with Tailwind CSS for consistent theming and design.
- Updated existing components to utilize new utility functions for class name management.
- Enhanced Tooltip component with inline-block display for better layout.
- Updated package dependencies in package.json and yarn.lock to include new Radix and Tailwind packages.
2025-10-14 14:12:48 +08:00
Phantom
bab1a5445c ci: allow v2 branch to run PR CI workflow (#10698) 2025-10-13 23:31:46 +08:00
fullex
742f901052 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-10-13 23:18:32 +08:00
Pleasure1234
cb12bb5137 fix: v2 merge error (#10658)
* fix: v2 merge error

* fix: review improve

* fix: ci error

* fix: review

* Update index.tsx

* Update index.tsx
2025-10-13 09:24:32 +08:00
fullex
06b6f2b9d8 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-10-11 09:56:42 +08:00
fullex
2c102ed3b4 refactor: update imports to use 'type' for type-only imports across multiple files
- Changed imports to use 'type' for type-only imports in various files, improving clarity and potentially optimizing the build process.
- Adjusted imports in files related to agents, models, and types to ensure consistency in type usage.
2025-10-09 12:45:17 +08:00
fullex
767e22c58d Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-10-09 12:10:37 +08:00
fullex
dee397f6ac Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-10-08 19:10:15 +08:00
Pleasure1234
a00aba23bd refactor: migrate all antd Tooltip components to HeroUI Tooltip (#10295)
* refactor: migrate tooltip components to @cherrystudio/ui

- Replace all antd Tooltip + InfoCircleOutlined patterns with InfoTooltip component
- Replace all antd Tooltip + QuestionCircleOutlined patterns with HelpTooltip component
- Migrate all WarnTooltip imports to @cherrystudio/ui
- Add onClick support to InfoTooltip and HelpTooltip components
- Remove local tooltip components from renderer
- Update eslint config to restrict antd Tooltip imports
- Clean up unused imports and styled components

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: replace tooltip

* fix: yarn format

* fix: type check

* Update QuickModelPopup.tsx

* fix: yarn test

* fix: ci error

* Update TabContainer.tsx

* fix: ci error

* fix: ci error

* fix: issue

* fix: ci

* fix: again

* refactor(ui): replace Tooltip title prop with content for consistency

* refactor(Tooltip): improve Tooltip component by extending props and simplifying implementation

- Extend TooltipProps from HeroUITooltipProps instead of redefining
- Remove redundant props and use spread operator for classNames
- Export TooltipProps type for better type support

* refactor(HelpTooltip): rename title prop to content and simplify component

Update HelpTooltip component to use TooltipProps interface and rename title prop to content for consistency
Update all instances where HelpTooltip is used to reflect the prop name change

* refactor(IconTooltips): consolidate tooltip components into unified module

Move HelpTooltip, InfoTooltip, and WarnTooltip into a single IconTooltips directory with shared types
Update exports in components index to use new module structure

* refactor(tooltip): update InfoTooltip prop from title to content and simplify component

Consolidate tooltip props interface and update all instances to use content prop instead of title for consistency. Remove redundant interface definitions and simplify InfoTooltip component implementation.

* refactor(ui): rename WarnTooltip prop from title to content for consistency

Update all instances of WarnTooltip component to use content prop instead of title for better consistency with Tooltip component interface. Also simplify the component props by extending IconTooltipProps type.

* fix(tooltip): update tooltip usage

- Replace deprecated props like `mouseEnterDelay` and `mouseLeaveDelay` with `delay` and `closeDelay`
- Rename `arrow` prop to `showArrow` for better semantics
- Update styling props to use `classNames` instead of inline styles
- Remove unnecessary props like `fresh` and `destroyOnHidden`

* refactor(components): remove redundant placement="top" from Tooltip components

The placement="top" prop was removed from all Tooltip components since it's the default value and redundant. This change improves code cleanliness without affecting functionality.

* fix(HeaderNavbar): add tooltip placement for sidebar toggle buttons

* fix(ui): add delay to tooltip components for better user experience

* refactor(tooltip): adjust tooltip behavior and styling across components

- Remove default delay values from base Tooltip component
- Add delay and closeDelay props to specific tooltip instances
- Fix tooltip compatibility issue with Antd Dropdown
- Adjust tooltip placement and styling in various components

* fix(ui): set closeDelay to 0 for Tooltip components to improve responsiveness

Prevent tooltip delay from causing poor user experience by making them close immediately when mouse leaves the element

* refactor(ui): remove redundant tooltip placement prop

The 'placement="top"' prop was removed from Tooltip components as it's the default value and doesn't need to be explicitly set.

* fix(ui): adjust tooltip delays for better user experience

- Set consistent default delay of 1000ms for window controls
- Increase delay for sidebar toggle tooltips to 2000ms
- Adjust various message action tooltip delays between 600-1200ms

* fix(SelectModelPopup): add delay props to provider settings tooltip

Add delay and closeDelay props to Tooltip component to improve user experience by preventing accidental triggers

* style(HelpTooltip): add cursor help style to improve UX

* fix(components): add tooltip delay and placement props for better UX

Add delay prop to CustomTag and ModelIdWithTags tooltips to prevent flickering
Set placement prop for LocalBackupManager tooltip to top-start
Add closeDelay prop to HelpTooltip in SaveToKnowledgePopup for immediate closing

* refactor(ModelSelectButton): simplify tooltip props by using TooltipProps type

Replace individual tooltip placement props with TooltipProps type from ui library for better maintainability

* fix(ui): remove tooltip close delay for better user experience

* docs(tooltip): add jsdoc comments explaining tooltip wrapper behavior

* refactor(Tooltip): clarify showArrow prop

* fix(Inputbar): set closeDelay to 0 for pause tooltip to improve UX

Prevent tooltip from staying visible after interaction by removing the close delay

* style(InputbarTools): improve tooltip consistency and css formatting

- Add closeDelay to new topic tooltip for consistency
- Remove redundant line breaks in tooltip props
- Format css transition properties for better readability

* chore: add tailwindCSS class attributes to vscode settings

* fix(tooltips): improve tooltip behavior and styling across components

- Add closeDelay=0 to most tooltips for instant closing
- Add custom styling to CitationTooltip and ChatFlowHistory tooltips
- Adjust delay times for navigation tooltips
- Remove conflicting Tooltip wrappers around Popconfirm actions

* refactor(ui): adjust tooltip delays and placements across components

- Remove redundant isOpen prop from CustomNode tooltip
- Standardize tooltip delays and placements in MessageGroupMenuBar, MessageTokens, ChatNavbar
- Simplify tooltip wrapper structure in HeaderNavbar
- Add consistent tooltip delays in MessageGroupModelList
- Set tooltip placements in MinimalToolbar

* refactor(Tooltip): enhance tooltip structure and props

- Add className prop to Tooltip component for better customization
- Wrap children in a div with relative positioning to improve layout

* refactor(Tooltip): enhance props structure for improved customization

- Update Tooltip component to allow optional classNames with a placeholder property
- Modify child wrapper to utilize classNames for better styling control

* refactor(IconTooltips): consolidate icon props into single iconProps object

Replace individual icon styling props (iconColor, iconSize, iconStyle) with a unified iconProps object using LucideProps type. This simplifies the component API and improves maintainability by using a standardized props structure across all icon tooltip components.

* feat(JoplinSettings): add help button to open Joplin documentation

Add a help button in Joplin settings that opens the official Joplin documentation in a minapp popup when clicked. This provides users with quick access to Joplin's help resources.

* feat(NotionSettings): add help link click handler for notion title

Add click handler to open help documentation when clicking on Notion title in settings

* feat(S3Settings): add help link to S3 settings title

Add click handler to open documentation for S3 settings when title is clicked

* feat(settings): add help button for siyuan integration

Add click handler to open help documentation for siyuan integration settings

* feat(yuque-settings): add help button to open yuque token guide

Add a help button in Yuque settings that opens a minapp popup with Yuque's token guide. This helps users easily access documentation for generating API tokens.

* fix(ui): adjust tooltip delay settings for better user experience

Set closeDelay to 0 for reset button tooltip to prevent lingering
Add delay of 500ms for api key list tooltip to avoid accidental triggers

* fix(ModelList): set closeDelay to 0 for all Tooltip components

Prevent tooltips from staying open longer than necessary by immediately closing them on mouse leave

* fix(ui): improve tooltip placement and delay settings

adjust tooltip placement and delay for better user experience

* refactor(tests): update tooltip mock implementation and snapshots

- Consolidate tooltip mock to handle both title and content props
- Remove deprecated placement attributes from snapshots
- Clean up test tooltip content assertions

* refactor: remove unnecessary whitespace and simplify tooltip components

clean up code by removing redundant whitespace and simplifying tooltip component usage across multiple files

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: icarus <eurfelux@gmail.com>
Co-authored-by: MyPrototypeWhat <daoquqiexing@gmail.com>
2025-10-05 18:33:21 +08:00
one
de5fb03efb feat(CodeEditor): enable readOnly for CodeEditor (v2) (#10517)
* feat(CodeEditor): enable readOnly for CodeEditor (v2)

* docs: update prop comments
2025-10-05 18:32:31 +08:00
MyPrototypeWhat
a6e58776d2 feat(tailwind): add source for UI package to Tailwind CSS configuration
- Included a new source path for the UI package in the Tailwind CSS configuration to enhance styling capabilities.
- This addition allows for better integration of UI components with Tailwind's utility classes, improving overall design consistency.
2025-09-30 15:12:33 +08:00
MyPrototypeWhat
bebe745e69 refactor(ProviderAvatar): update props for clarity and consistency
- Changed the `name` prop to directly use `providerName` for better readability.
- Updated the `getInitials` prop to use `getFirstCharacter` for improved clarity in the component's functionality.

These changes enhance the maintainability and understanding of the ProviderAvatar component.
2025-09-30 15:07:27 +08:00
MyPrototypeWhat
ec8c24a1c2 refactor: update Avatar components for improved styling and functionality
- Refactored ProviderAvatar to use the name prop for better clarity.
- Updated ModelAvatar to apply consistent styling using Tailwind CSS for width and height.
- Adjusted useOcrProvider hook to standardize Avatar component usage with dynamic sizing.

These changes enhance the overall consistency and maintainability of the Avatar components across the application.
2025-09-30 15:03:58 +08:00
MyPrototypeWhat
db4fcac768 feat: enhance Selector component with SearchableSelector and update exports
- Introduced a new SearchableSelector component for improved item selection with search functionality.
- Updated the Selector component to streamline item selection and added type exports for better type safety.
- Refactored the preferenceSchemas to use the new MathEngine type for better clarity.
- Added comprehensive README documentation for the Selector component detailing usage and features.
- Updated various components and stories to utilize the new Selector and SearchableSelector components.
2025-09-30 14:59:33 +08:00
MyPrototypeWhat
6c71b92d1d refactor: remove ProviderAvatar component and related files
- Deleted the ProviderAvatar component and its associated utility functions and stories to streamline the codebase.
- Updated index.ts to remove the export of ProviderAvatar, ensuring a cleaner component structure.
2025-09-29 18:58:46 +08:00
MyPrototypeWhat
d470fd8b88 refactor: remove unused ProviderLogo styled component from multiple pages
- Deleted the ProviderLogo styled component from CodeToolsPage, AihubmixPage, and PreprocessProviderSettings to streamline the codebase and eliminate redundancy.
2025-09-29 17:48:01 +08:00
MyPrototypeWhat
99962b740c feat: add EmojiAvatar component and update component exports
- Introduced a new EmojiAvatar component for enhanced avatar functionality.
- Updated index.ts to export the new EmojiAvatar alongside existing components.
- Removed the old display/EmojiAvatar component to streamline the codebase.
- Adjusted various components to utilize the new Avatar structure and styling.
2025-09-29 17:47:17 +08:00
MyPrototypeWhat
ef4bede062 feat: introduce DescriptionSwitch component and update component exports
- Added a new DescriptionSwitch component to enhance the Switch functionality with a description feature.
- Updated the exports in index.ts to include the new DescriptionSwitch alongside existing components.
- Refactored the SettingsTab to utilize DescriptionSwitch for improved UI consistency.
- Removed the InfoPopover component as part of the cleanup process.
2025-09-29 12:47:36 +08:00
Phantom
e6e1fb0404 refactor(button): migrate button from antd to heroui (#10292)
* fix(eslint): add Button to restricted antd imports

* feat(ui): add Button component with Storybook stories

Implement a reusable Button component wrapping HeroUIButton with proper TypeScript props.
Add comprehensive Storybook stories demonstrating all button variants, colors, sizes and states.

* refactor(components): update ActionIconButton implementation and usage

Replace onClick with onPress prop and move icon into icon prop
Update component to use @cherrystudio/ui Button instead of antd
Simplify props interface and add displayName

* refactor(ui): migrate antd buttons to @cherrystudio/ui components

update button components across multiple files to use @cherrystudio/ui's Button component
replace antd button props with equivalent @cherrystudio/ui props

* refactor(InputEmbeddingDimension): replace antd Button with custom Button component

Update the Button component to use the custom @cherrystudio/ui Button with updated props for better consistency and maintainability

* refactor(components): migrate buttons from antd to @cherrystudio/ui

Update button components in LocalBackupModals and LocalBackupManager to use @cherrystudio/ui instead of antd
Add flex styling to modal footers for better button alignment

* refactor(ProviderSetting): migrate Button components from antd to @cherrystudio/ui

Update Button components to use @cherrystudio/ui implementation with new props like variant, color, and startContent
Replace onClick handlers with onPress and adjust disabled states

* refactor(ui): migrate antd buttons to cherrystudio ui buttons

Update button components across multiple files to use @cherrystudio/ui Button instead of antd Button
Standardize button props and behavior while maintaining existing functionality

* refactor(NutstorePathSelector): update button props to use cherrystudio ui

Replace antd Button with cherrystudio ui Button component and update props

* refactor(S3BackupManager): migrate antd buttons to @cherrystudio/ui

Update button components from antd to @cherrystudio/ui library
Change button props to match new library's API (variant, color, onPress, etc)
Adjust table props for consistency with new component library

* refactor(TranslateButton): replace styled Button with cherrystudio Button component

The custom styled Button was replaced with the cherrystudio Button component to maintain consistency across the UI and reduce custom styling code. The functionality remains the same but uses the library's built-in props for styling.

* refactor(WebdavBackupManager): replace antd buttons with cherrystudio ui buttons

Update button components to use cherrystudio ui library for consistency

* refactor(ui): migrate buttons from antd to @cherrystudio/ui

Update button components across multiple editor components to use @cherrystudio/ui's Button component instead of antd's. This includes updating props like size, variant, and event handlers to match the new component's API.

* refactor(components): migrate buttons from antd to @cherrystudio/ui

Update button components in HtmlArtifactsCard and HtmlArtifactsPopup to use @cherrystudio/ui's Button component instead of antd's Button. This includes updating props like icon to startContent, onClick to onPress, and type to variant/color.

* refactor(ui): migrate button components from antd to hero ui

- replace antd Button with hero ui Button component
- update button props interface to extend hero ui props
- adjust button props in OAuthButton and MinappPopupContainer

* refactor(MultiSelectionPopup): migrate button components to @cherrystudio/ui

Update button props to match new component library requirements

* refactor(ApiKeyItem): migrate antd buttons to cherrystudio ui components

Update button components in ApiKeyItem to use cherrystudio ui library instead of antd

* refactor(ApiKeyListPopup): update button props to use new UI library syntax

Update button components to use the new syntax from @cherrystudio/ui library, replacing antd Button props with the new variant, color, and isDisabled props. Also adjust icon placement and button types to match the new library's API.

* refactor(SelectModelButton): replace antd Button with custom Button component

Simplify button implementation by using custom Button component from ui library instead of antd. Remove unused styled component and event handling.

* refactor(Preview): migrate ImageToolButton to use @cherrystudio/ui

Update ImageToolButton component to use Button from @cherrystudio/ui instead of antd
Change onClick prop to onPress to match new Button component API
Update related usage in ImageToolbar component

* refactor(ui): migrate buttons from antd to cherrystudio ui components

Update button components across multiple files to use cherrystudio's Button component instead of antd's. This includes updating props like onClick to onPress and adjusting button styling props to match the new component's API.

* refactor(ui): migrate antd buttons to @cherrystudio/ui buttons

Update button components from antd to @cherrystudio/ui library
Adjust button props to match new component API

* refactor(components): update prop names and component usage

- Rename onClick to onPress in ImageToolButton test props
- Update isLoading to loading in S3BackupManager table props
- Change ghost to variant in ProviderSetting button props
- Replace antd Button with cherrystudio Button in PreferenceBasicTests

* refactor(ImageToolButton): migrate from antd to @cherrystudio/ui

* refactor(FilesPage): migrate Button components from antd to @cherrystudio/ui

* refactor(SearchMessage): migrate Button components from antd to @cherrystudio/ui

* refactor(TopicMessages): migrate Button components from antd to @cherrystudio/ui

* refactor(TopicsHistory): migrate Button components from antd to @cherrystudio/ui

* refactor(ChatNavigation): migrate Button components from antd to @cherrystudio/ui

* refactor(CitationsList): migrate Button components from antd to @cherrystudio/ui

* refactor(MessageGroupMenuBar): migrate Button components from antd to @cherrystudio/ui

* refactor: reorganize button imports and adjust class order

Consolidate Button imports from @cherrystudio/ui to be grouped with other imports
Standardize className order for consistency across components

* refactor(SelectModelPopup): replace HStack with Flex component for layout

* feat: migrate PrivacyPopup from antd Button to @cherrystudio/ui Button

- Replace antd Button import with @cherrystudio/ui Button
- Update onClick to onPress event handler
- Update type="primary" to variant="solid" color="primary"
- Maintain existing functionality while following Hero UI API

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate NewTopicButton from antd Button to @cherrystudio/ui Button

- Replace antd Button import with @cherrystudio/ui Button
- Update size="small" to size="sm"
- Update icon prop to startContent for Hero UI API
- Update onClick to onPress event handler
- Maintain existing styled-components with StyledButton wrapper

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate MessageMcpTool Buttons from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update two Button components with Hero UI API:
  - size="small" to size="sm"
  - onClick to onPress
  - variant="filled" to variant="solid"
  - Move icons to startContent prop
- Maintain Dropdown.Button as antd component (not migrated)

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate SettingsTab Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update settings icon button with Hero UI API:
  - type="text" to variant="light"
  - size="small" to size="sm"
  - icon prop to isIconOnly with child content
  - onClick to onPress event handler

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate AssistantTagsPopup Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update delete tag button with Hero UI API:
  - type="text" to variant="light"
  - danger prop to color="danger"
  - icon prop to isIconOnly with child content
  - onClick to onPress event handler

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate UpdateAppButton from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update styled Button component with Hero UI API:
  - onClick to onPress event handler
  - icon prop to startContent
  - color="orange" to color="warning" (closest equivalent)
  - variant="outlined" to variant="bordered"
  - size="small" to size="sm"

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(NewTopicButton): replace styled-components with cn utility

Simplify component styling by removing styled-components in favor of the cn utility

* refactor: organize imports and remove unused event handlers

remove duplicate Button imports and clean up stopPropagation handlers

* feat: migrate KnowledgeContent Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update settings icon Button with Hero UI API:
  - type="text" to variant="light"
  - size="small" to size="sm"
  - icon prop to isIconOnly with child content
  - onClick to onPress event handler
- Update ResponsiveButton styled component selector:
  - .ant-btn-icon + span to [data-slot="icon"] + [data-slot="label"]

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate KnowledgeDirectories Buttons from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update three Button components with Hero UI API:
  - Refresh button: type="text" to variant="light", icon to isIconOnly, onClick to onPress
  - Delete button: type="text" danger to variant="light" color="danger", icon to isIconOnly, onClick to onPress
  - Add directory button: type="primary" to variant="solid" color="primary", icon to startContent, disabled to isDisabled
- Remove stopPropagation from add directory button as not needed with onPress

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate KnowledgeFiles Buttons from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update three Button components with Hero UI API:
  - Add file button: type="primary" to variant="solid" color="primary", icon to startContent, disabled to isDisabled
  - Refresh button: type="text" to variant="light", icon to isIconOnly, onClick to onPress
  - Delete button: type="text" danger to variant="light" color="danger", icon to isIconOnly, onClick to onPress
- Remove stopPropagation from add file button as not needed with onPress

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate KnowledgeNotes Buttons from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update three Button components with Hero UI API:
  - Add note button: type="primary" to variant="solid" color="primary", icon to startContent, disabled to isDisabled
  - Edit button: type="text" to variant="light", icon to isIconOnly, onClick to onPress
  - Delete button: type="text" danger to variant="light" color="danger", icon to isIconOnly, onClick to onPress
- Remove stopPropagation from add note button as not needed with onPress

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate KnowledgeSitemaps Buttons from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update three Button components with Hero UI API:
  - Add sitemap button: type="primary" to variant="solid" color="primary", icon to startContent, disabled to isDisabled
  - Refresh button: type="text" to variant="light", icon to isIconOnly, onClick to onPress
  - Delete button: type="text" danger to variant="light" color="danger", icon to isIconOnly, onClick to onPress
- Remove stopPropagation from add sitemap button as not needed with onPress

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate KnowledgeUrls Buttons from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update three Button components with Hero UI API:
  - Add URL button: type="primary" to variant="solid" color="primary", icon to startContent, disabled to isDisabled
  - Refresh button: type="text" to variant="light", icon to isIconOnly, onClick to onPress
  - Delete button: type="text" danger to variant="light" color="danger", icon to isIconOnly, onClick to onPress
- Remove stopPropagation from add URL button as not needed with onPress

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate KnowledgeVideos Buttons from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update three Button components with Hero UI API:
  - Add video button: type="primary" to variant="solid" color="primary", icon to startContent, disabled to isDisabled
  - Refresh button: type="text" to variant="light", icon to isIconOnly, onClick to onPress
  - Delete button: type="text" danger to variant="light" color="danger", icon to isIconOnly, onClick to onPress
- Remove stopPropagation from add video button as not needed with onPress

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate MinAppsPage Buttons from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update two settings Button components with Hero UI API:
  - type="text" to variant="light"
  - icon prop to isIconOnly with child content
  - onClick to onPress event handler
  - Maintain className="nodrag" for draggable interface

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate MiniAppSettings Buttons from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update two Button components with Hero UI API:
  - Swap button: onClick to onPress event handler
  - Reset button: onClick to onPress event handler
- Buttons use default Hero UI styling without additional props

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate NewAppButton from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update two Button components with Hero UI API:
  - Upload button: icon to startContent
  - Save button: type="primary" htmlType="submit" to variant="solid" color="primary" type="submit"
- Maintain form submission functionality with type="submit"

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: standardize button imports from @cherrystudio/ui

* refactor(KnowledgeContent): replace icon prop with startContent in Button

Improve consistency with component library by using startContent prop instead of children for icons

* refactor(KnowledgeVideos): update button components to use startContent prop

Use startContent prop for icons in buttons to improve consistency with the design system

* refactor(MinAppsPage): improve button component structure by using startContent prop

* feat: migrate AihubmixPage Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update Button props with Hero UI API:
  - size="small" to size="sm"
  - icon to startContent
  - onClick to onPress

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate DmxapiPage Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update Button props with Hero UI API:
  - size="small" to size="sm"
  - icon to startContent
  - onClick to onPress

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate NewApiPage Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update Button props with Hero UI API:
  - size="small" to size="sm"
  - icon to startContent
  - onClick to onPress
  - type="primary" to variant="solid" color="primary"

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate SiliconPage Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update Button props with Hero UI API:
  - size="small" to size="sm"
  - icon to startContent
  - onClick to onPress

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate TokenFluxPage Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update Button props with Hero UI API:
  - size="small" to size="sm"
  - icon to startContent
  - onClick to onPress

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate ZhipuPage Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update Button props with Hero UI API:
  - type="text" to variant="light"
  - icon to startContent
  - onClick to onPress
  - disabled to isDisabled

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate Artboard Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update Button props with Hero UI API:
  - onClick to onPress for NavigationButton and CancelButton
  - type="link" to variant="light"
- Maintain styled-components usage for NavigationButton and CancelButton

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate DynamicFormRender Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update Button props with Hero UI API:
  - icon to startContent
  - onClick to onPress
  - size="small" to size="sm"
  - danger to color="danger"

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: convert Button inline styles to Tailwind CSS

- Replace style={{borderTopLeftRadius: 0, borderBottomLeftRadius: 0, height: '32px'}} with className="rounded-l-none h-8"
- Replace style={{flexShrink: 0, minWidth: 'auto', padding: '0 8px'}} with className="shrink-0 min-w-0 px-2"

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate ImageUploader Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update Button props with Hero UI API:
  - size="small" to size="sm"
  - onClick to onPress

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(Artboard): replace inline styles with tailwind classes

Use tailwind classes for consistent styling of navigation buttons instead of inline styles

* feat: migrate AboutSettings Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update Button props with Hero UI API:
  - onClick to onPress for all Button components
  - loading to isLoading for CheckUpdateButton
  - disabled to isDisabled for CheckUpdateButton
- Maintain CheckUpdateButton styled component

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate AssistantMemorySettings Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update Button props with Hero UI API:
  - type="text" to variant="light" + isIconOnly
  - icon to startContent
  - onClick to onPress
  - size="small" to size="sm"

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate AssistantModelSettings Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update Button props with Hero UI API:
  - icon to startContent
  - onClick to onPress
  - variant="filled" to variant="solid"
  - danger + type="primary" to color="danger" variant="solid"
  - Add isIconOnly for icon-only buttons
- Maintain ModelSelectButton styled component

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate AssistantPromptSettings Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update Button props with Hero UI API:
  - type="primary" to variant="solid" color="primary"
  - icon to startContent
  - onClick to onPress
- Convert inline styles to Tailwind CSS:
  - style={{fontSize: 18, padding: '4px', minWidth: '28px', height: '28px'}} to className="text-lg p-1 min-w-7 h-7"

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: consolidate Button imports from @cherrystudio/ui

Move all Button imports from @cherrystudio/ui to be grouped with other imports from the same package for better consistency and maintainability

* feat: migrate AssistantRegularPromptsSettings Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update Button props with Hero UI API:
  - type="text" to variant="light"
  - icon to startContent
  - onClick to onPress
  - Add isIconOnly for icon-only buttons
  - danger to color="danger"

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: migrate DataSettings Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Update Button props with Hero UI API:
  - onClick to onPress for all buttons
  - icon to startContent for backup/restore buttons
  - danger to color="danger" for reset button

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(NutstoreSettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handlers
- Update type/danger props to variant/color system
- Convert loading to isLoading prop
- Convert disabled to isDisabled prop
- Update ghost prop to variant="ghost"
- Add isIconOnly for folder icon button
- Migrate startContent pattern for icons

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(S3Settings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handlers
- Convert icon props to startContent pattern
- Convert loading to isLoading prop
- Convert disabled to isDisabled prop

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(SiyuanSettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(WebDavSettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handlers
- Convert icon props to startContent pattern
- Convert loading to isLoading prop
- Convert disabled to isDisabled prop

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(YuqueSettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(DisplaySettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handlers
- Convert icon props to startContent pattern
- Convert variant="text" to variant="light"
- Add isIconOnly for icon-only buttons
- Replace inline styles with Tailwind CSS classes

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(PreprocessProviderSettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler
- Convert type="text" to variant="light"
- Convert size="small" to size="sm"
- Convert icon to startContent pattern
- Add isIconOnly for icon-only button

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(NotionSettings): replace antd Button with cherrystudio Button and update prop

Update the Button import to use cherrystudio's component instead of antd's

* refactor(settings): migrate Button props to use startContent and isDisabled

Update Button components in LocalBackupSettings to use startContent instead of icon and isDisabled instead of disabled for consistency with the updated UI library

* refactor(JoplinSettings): replace Button import and update onPress prop

Use Button component from @cherrystudio/ui instead of antd
Update onClick to onPress for consistency with component API

* refactor(MarkdownExportSettings): replace antd Button with cherrystudio Button in markdown export

Update the Button component import and props to use the cherrystudio UI library version instead of antd for consistency

* refactor: organize imports in settings components

Move Button import from cherrystudio/ui to be grouped with other imports from the same package for better consistency and readability

* refactor(AddMcpServerModal): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert icon prop to startContent pattern

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(BuiltinMCPServerList): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler
- Convert type="text" to variant="light"
- Convert size="small" to size="sm"
- Convert icon to startContent pattern
- Convert disabled to isDisabled prop
- Add isIconOnly for icon-only button

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(InstallNpxUv): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handlers
- Convert type="primary" to variant="solid" color="primary"
- Convert type="link" to variant="light"
- Convert shape="circle" to radius="full"
- Convert size="small" to size="sm"
- Convert loading/disabled to isLoading/isDisabled
- Convert icon to startContent pattern
- Add isIconOnly for icon-only button
- Convert green color to success color

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(McpServerCard): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handlers (removing e.stopPropagation)
- Convert type="text" to variant="light"
- Convert size="small" to size="sm"
- Convert shape="circle" to radius="full"
- Convert danger to color="danger"
- Convert icon to startContent pattern
- Add isIconOnly for icon-only buttons

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(MCPSettings): reorder Button imports for consistency

Move Button imports to be grouped with other UI component imports for better readability and maintainability

* refactor(McpServersList): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handlers
- Convert type="default" to variant="solid"
- Convert shape="round" to radius="full"
- Convert icon to startContent pattern

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(McpServerCard): remove unused event parameter from click handlers

The event parameter was not being used in handleOpenUrl and onClickDetails handlers, so it was removed to simplify the code.

* refactor(McpServerCard): remove data-no-dnd attribute from Button

* refactor(McpSettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handlers
- Convert danger to color="danger"
- Convert type="text" to variant="light"
- Convert type="primary" to variant="solid" color="primary"
- Convert shape="round" to radius="full"
- Convert loading/disabled to isLoading/isDisabled
- Convert icon to startContent pattern
- Add isIconOnly for icon-only button

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(McpSettingsNavbar): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler
- Convert type="text" to variant="light"
- Convert size="small" to size="sm"
- Convert icon to startContent pattern
- Replace inline styles with Tailwind CSS classes

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(NpxSearch): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler
- Convert type="text" to variant="light"
- Convert size="small" to size="sm"
- Convert icon to startContent pattern
- Add isIconOnly for icon-only button

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(SyncServersPopup): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handlers
- Convert type="default" to variant="solid"
- Convert type="primary" to variant="solid" color="primary"
- Convert loading/disabled to isLoading/isDisabled

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(MCPSettings/index): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert type="default" to variant="solid"
- Convert shape="circle" to radius="full"
- Convert icon to startContent pattern
- Add isIconOnly for icon-only button

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(MemorySettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handlers
- Convert type="text" to variant="light"
- Convert type="primary" to variant="solid" color="primary"
- Convert size="large" to size="lg"
- Convert size="small" to size="sm"
- Convert loading/disabled to isLoading/isDisabled
- Convert danger to color="danger"
- Convert icon to startContent pattern
- Add isIconOnly for icon-only buttons

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(UserSelector): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler
- Convert type="default" to variant="solid"
- Convert icon to startContent pattern
- Add isIconOnly for icon-only button

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(DefaultAssistantSettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler
- Convert type="text" to variant="light"
- Convert icon to startContent pattern
- Add isIconOnly for icon-only button
- Replace inline styles with Tailwind CSS classes

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(QuickModelPopup): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler
- Change icon prop to startContent
- Update type="text" to variant="light"
- Add isIconOnly prop for icon-only button

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(NotesSettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler for all buttons
- Change type="default" to variant="solid"
- Change type="primary" to color="primary"
- Update loading to isLoading prop
- Update disabled to isDisabled prop
- Change icon prop to startContent
- Replace inline style with Tailwind CSS class (ml-2)

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(AnthropicSettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler
- Change type="primary" to color="primary"
- Update loading to isLoading prop

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(ModelEditContent): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler for all buttons
- Change size="small" to size="sm"
- Update icon prop to startContent for save and reset buttons
- Change iconPosition="end" to endContent for more settings toggle
- Update type="text" to variant="light" and add isIconOnly for reset button
- Change type="primary" to color="primary"
- Replace htmlType="submit" with type="submit"
- Update variant="filled" to variant="solid"

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(ModelTypeSelector): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler
- Change size="small" to size="sm"

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(GithubCopilotSettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler for all buttons
- Change type="primary" to color="primary"
- Change type="primary" danger to color="danger"
- Update size="small" to size="sm"
- Update loading to isLoading prop
- Update disabled to isDisabled prop
- Change icon prop to startContent for copy button

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(AddModelPopup): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Change type="primary" to color="primary"
- Replace htmlType="submit" with type="submit"
- Change size="middle" to size="md"

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(ModelList): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler for all buttons
- Change type="text" to variant="light" and add isIconOnly for icon button
- Change type="primary" to color="primary"
- Change type="default" to variant="solid"
- Update disabled to isDisabled prop
- Change icon prop to startContent for all buttons

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(ModelListGroup): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler
- Change type="text" to variant="light"
- Update disabled to isDisabled prop
- Change icon prop to startContent
- Remove e.stopPropagation() as no longer needed
- Add isIconOnly prop for icon-only button

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(ModelListItem): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler for both buttons
- Change type="text" to variant="light"
- Update disabled to isDisabled prop
- Change icon prop to startContent for both buttons
- Add isIconOnly prop for icon-only buttons

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(NewApiAddModelPopup): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Change type="primary" to color="primary"
- Replace htmlType="submit" with type="submit"
- Change size="middle" to size="md"

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(NewApiBatchAddModelPopup): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Change type="primary" to color="primary"
- Replace htmlType="submit" with type="submit"
- Change size="middle" to size="md"

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(ProviderList): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler
- Update disabled to isDisabled prop
- Change icon prop to startContent
- Keep existing style attributes for custom styling

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(ProviderOAuth): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler for both buttons
- Change shape="round" to radius="full"
- Change icon prop to startContent for both buttons

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(UrlSchemaInfoPopup): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler
- Change type="link" to variant="light"
- Change size="small" to size="sm"
- Change icon prop to startContent
- Add isIconOnly prop for icon-only button

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(QuickAssistantSettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler for both styled buttons
- Change type="primary" to color="primary"
- Change type="default" to color="default"
- Update styled component to use new Button from @cherrystudio/ui

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(QuickPhraseSettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler for all buttons
- Change type="text" to variant="light"
- Change icon prop to startContent for all buttons
- Change danger prop to color="danger"
- Add isIconOnly prop for all icon-only buttons

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(SelectionAssistantSettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler for both buttons
- Change type="link" to variant="light"
- Change icon prop to startContent
- Keep existing style attributes for custom styling

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(ActionsListItem): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler for all buttons
- Change type="link" to variant="light"
- Change size="small" to size="sm"
- Change danger prop to color="danger"
- Add isIconOnly prop for all icon-only buttons

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(MacProcessTrustHintModal): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler for both buttons
- Change type="link" to variant="light"
- Change type="primary" to color="primary"
- Keep existing style attributes for custom styling

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(SelectionActionSearchModal): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler
- Change type="link" to variant="light"
- Change size="small" to size="sm"
- Keep existing style attributes for custom styling

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(SelectionFilterListModal): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handler for both modal buttons
- Change type="primary" to color="primary"
- Keep existing key attributes for modal footer

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(SettingsActionsListHeader): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handlers
- Update icon prop to startContent with Plus icon
- Change disabled to isDisabled
- Add color="primary" for primary button style
- Update styled ResetButton to use variant="light"

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(ShortcutSettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handlers for all buttons
- Update icon prop to startContent for icon buttons
- Change disabled to isDisabled
- Convert size="small" to size="sm"
- Replace shape="circle" with isIconOnly for circular buttons
- Migrate reset undo button, clear button, and reset all button

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(ApiServerSettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handlers for all buttons
- Update icon prop to startContent for documentation and copy buttons
- Change type="primary" to color="primary"
- Convert type="link" to variant="light" for regenerate button
- Change disabled to isDisabled for input button and regenerate button

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(CustomLanguageModal): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handlers for modal footer buttons
- Change type="primary" to color="primary" for save button
- Convert icon prop to startContent with isIconOnly for emoji button
- Migrate cancel, save, and emoji picker buttons to Hero UI API

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(CustomLanguageSettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handlers for all buttons
- Update icon prop to startContent for edit, delete, and add buttons
- Change type="primary" to color="primary" for add button
- Convert danger prop to color="danger" for delete button
- Migrate table action buttons and primary add button to Hero UI API

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(AddSubscribePopup): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert type="primary" to color="primary" for submit button
- Change htmlType="submit" to type="submit" following Hero UI API
- Migrate form submit button from antd to Hero UI

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(BlacklistSettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handlers for all buttons
- Change type="primary" to color="primary" for subscribe buttons
- Convert ghost prop to variant="ghost"
- Change disabled to isDisabled for all button states
- Migrate save, add subscribe, update subscribe, and delete buttons

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(WebSearchProviderSetting): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handlers for API key list and check buttons
- Change type="text" to variant="light" for API key list button
- Convert icon prop to startContent with isIconOnly for list button
- Update size="small" to size="sm"
- Change ghost prop to variant="ghost" and type to color for check button
- Convert disabled to isDisabled for API checking state

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(TranslateSettings): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress for more settings button
- Simple migration for modal footer button

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(MigrateApp): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handlers for all migration buttons
- Change type="primary" to color="primary" for primary buttons
- Convert disabled to isDisabled for migration in progress button
- Change size="small" to size="sm" for debug button
- Convert type="dashed" to variant="bordered" for styled buttons
- Migrate all buttons in migration workflow stages

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(SelectionActionApp): migrate Button from antd to @cherrystudio/ui

- Replace antd Button import with @cherrystudio/ui Button
- Convert onClick to onPress handlers for all window control buttons
- Change type="text" to variant="light" for all title bar buttons
- Update icon prop to startContent for pin, opacity, minimize, and close buttons
- Add isIconOnly prop for all icon-only buttons in the title bar
- Migrate styled WinButton component to use Hero UI Button as base

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* style(ActionIconButton): remove fixed dimensions and add size prop

Simplify button styling by removing fixed height/width and using size="sm" prop instead

* refactor(AssistantPromptSettings): migrate from antd Popover to hero-ui components

Replace antd Popover with hero-ui Popover and Tooltip components for better consistency
Rename EmojiButtonWrapper to EmojiDeleteButtonWrapper for clarity

* style(AssistantModelSettings): add size prop to delete button in model settings

* style(settings): standardize button sizes and replace Space.Compact with Flex

Consistently apply 'sm' size to buttons across settings components and replace deprecated Space.Compact with Flex component for better layout consistency

* refactor(ApiServerSettings): replace custom buttons with standard Button component

remove custom styled InputButton and RegenerateButton components in favor of using the standard Button component with appropriate props

* style(ProviderSetting): make settings button icon-only for consistency

* style(ui): update icon styling and button props

remove global lucide icon color override
update button components to use consistent props

* style(ProviderList): adjust button size to match design

* feat(theme): add foreground color calculation for primary theme

Calculate and set foreground color based on primary theme color to ensure proper contrast

* style(KnowledgeFiles): make button size consistent with other buttons

* test: update test snapshots for button components

Update test snapshots to reflect changes in button styling and accessibility attributes. The changes include updated class names, ripple effects, and focus states.

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: fullex <106392080+0xfullex@users.noreply.github.com>
Co-authored-by: MyPrototypeWhat <daoquqiexing@gmail.com>
2025-09-29 12:04:03 +08:00
fullex
e6696def10 chore: update TypeScript configuration and refactor AppUpdater tests
- Added tests mock path to tsconfig.node.json for improved test coverage.
- Refactored AppUpdater to use preferenceService for language retrieval instead of configManager.
- Updated AppUpdater tests to mock preferenceService and ensure correct language handling in release notes.
- Changed import statements to use type imports for better clarity in MessageMcpTool component.
2025-09-29 10:11:40 +08:00
fullex
e5a3363021 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-09-29 10:01:04 +08:00
fullex
f6ff436294 refactor: replace keyv with cacheService 2025-09-25 11:38:05 +08:00
fullex
8a9b633af2 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-09-24 22:30:56 +08:00
Phantom
0a37146ba8 refactor(SelectModelPopup): replace HStack with Flex component (#10337)
refactor(SelectModelPopup): replace HStack with Flex component for layout
2025-09-24 20:10:12 +08:00
fullex
ac3dfcbfbe Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-09-24 13:13:58 +08:00
Phantom
5ac09d5311 refactor: migrate to toast from antd message (#10233)
* style(eslint): reorganize eslint config comments and rules

Move comments to consistent positions above their corresponding rules
Update antd import restriction to include 'message' component

* fix(eslint): reorganize eslint config to enable custom rules

* fix(eslint): update antd import restriction to include message

Prevent direct imports of both Flex and message from antd, enforcing usage of custom components

* feat(migration): add toast utilities to migrate and test apps

Initialize toast utilities on window object for both migration and test applications to enable toast notifications

* build(ui): add path aliases for types and utils modules

* refactor(toast): move toast utilities to ui package for better reusability

Centralize toast utilities in the @cherrystudio/ui package to improve code organization and reuse across multiple components. This change includes:
- Moving toast implementation to ui package
- Updating all imports to use the new location
- Adding proper type definitions

* refactor: replace antd message with window.toast for consistency

Replace all instances of antd's message component with window.toast throughout the application to maintain consistent notification behavior. Also add an ignore rule for dataRefactorTest files in eslint config.
2025-09-20 16:58:41 +08:00
MyPrototypeWhat
d4fd8ffdcc refactor(SettingsTab): update Selector component usage for consistency
- Simplified Selector component usage in SettingsTab by removing deprecated props and updating to the new API.
- Added size and label props to enhance accessibility and user experience.
- Ensured consistent handling of selected keys and selection change events across multiple instances of Selector.
2025-09-19 12:10:33 +08:00
fullex
84274d9d85 Merge branches 'v2' and 'main' of github.com:CherryHQ/cherry-studio into v2 2025-09-19 11:19:29 +08:00
Phantom
a72feebead refactor: migrate Switch from antd to heroui (#10237)
* refactor(eslint): reorganize eslint config for better maintainability

Move ignores section and oxlint configs to be grouped with other configurations

* fix(eslint): update antd import restriction to include Switch

Add Switch to restricted imports from antd to enforce using custom components

* feat(ui): add Switch component wrapper and update imports

Add a wrapper for the Switch component from @heroui/react and export it through @cherrystudio/ui. Update eslint rules to prevent direct imports from @heroui/react and update imports in TranslateSettings to use the new wrapper

* refactor(ui): replace antd Switch with custom Switch component

Migrate all instances of antd Switch component to the custom Switch component from @cherrystudio/ui. This includes updating props from `checked` to `isSelected` and `onChange` to `onValueChange` to match the new component's API. Also updates size prop from `small` to `sm` where applicable.

The change ensures consistency across the UI and reduces dependency on antd components. All affected files have been updated to use the new Switch component with proper prop mappings.

* feat(ui): enhance Switch component with loading state

Add loading state support to Switch component by showing a spinner when isLoading is true and disabling interaction during loading. Update all Switch component usages to use the new isLoading prop instead of loading.

* fix(Switch): prevent thumbIcon override when isLoading is true

Implement type constraints to disallow thumbIcon when isLoading is true
Add ref forwarding support and export enhanced props type

* fix(settings): update Switch component props to use consistent naming

Change deprecated 'defaultChecked' and 'disabled' props to 'defaultSelected' and 'isDisabled' respectively to match component library updates

* refactor(Switch): simplify type definition by removing redundant ref prop

* refactor(Switch): simplify props type definition for loading state

Remove complex union type in favor of simpler interface extending SwitchProps

* docs(ui): add jsdoc for CustomizedSwitch component

Add documentation for the CustomizedSwitch component to clarify its purpose and the isLoading prop usage

* fix(eslint): comment out heroui import restriction rule

Temporarily disable the heroui import restriction to allow direct imports while wrapped components are being updated

* style: fix formatting and spacing in settings components
2025-09-18 19:16:53 +08:00
MyPrototypeWhat
e930d3de43 refactor: update imports to use type-only imports for WebSearchPluginConfig and CherryWebSearchConfig
- Changed imports of WebSearchPluginConfig and CherryWebSearchConfig to type-only imports for better clarity and to optimize TypeScript compilation.
2025-09-17 18:40:38 +08:00
MyPrototypeWhat
ecc9923050 Merge remote-tracking branch 'origin/main' into v2 2025-09-17 18:37:22 +08:00
MyPrototypeWhat
e469016775 style(Selector.stories): simplify Selector component stories by condensing JSX structure
- Refactored the Selector component stories to use a more concise JSX format, improving readability.
- Ensured consistent formatting across size variations for better maintainability.
2025-09-17 18:33:14 +08:00
MyPrototypeWhat
15569387c7 feat(ui): implement new Selector component with enhanced functionality
- Replaced the existing Selector component with a new implementation using HeroUI's Select and SelectItem.
- Updated the props structure to support items and selection change handling.
- Added a new story file for the Selector component, showcasing various use cases including single and multiple selection modes, size variations, and disabled states.
- Improved type definitions for better clarity and usability.
2025-09-17 18:31:11 +08:00
Phantom
4f746842a5 refactor: migrate Flex from antd to custom Flex component (#10083)
* refactor(components): rename HStack and VStack to RowFlex and ColFlex for clarity

rename HStack to RowFlex and VStack to ColFlex across all components to better reflect their purpose as flex containers with row and column directions. This improves code readability and maintainability while keeping the same functionality. All references to these components have been updated accordingly.

* refactor(layout): migrate layout components from .ts to .tsx

The layout components have been moved from TypeScript (.ts) to TypeScript with JSX (.tsx) to better support JSX syntax and improve type safety. The functionality remains unchanged.

* refactor(Layout): convert styled Box component to functional component

Improve maintainability by converting styled-component to a functional component with explicit style props. This provides better type safety through CSSProperties interface and makes the component easier to debug.

* refactor(Layout): restructure Box component and convert styled components to functional

- Replace styled-components with functional components for Stack and Center
- Rename style variable to _style in Box component to avoid naming conflict
- Add style prop to Box component to allow external style overrides

* refactor(components): rename HSpaceBetweenStack to SpaceBetweenRowFlex for clarity

* refactor(Layout): pass through props in Stack components

Allow additional props to be passed to Stack and its variants for better flexibility. Convert RowFlex from styled component to regular component for consistency.

* refactor(Layout): convert SpaceBetweenRowFlex from styled to component

Improve maintainability by converting styled component to a regular component that explicitly passes justifyContent prop

* refactor(Layout): convert ColFlex to component and type RowFlex props

Improve type safety by explicitly omitting flexDirection from StackProps and convert ColFlex from styled component to regular component for consistency

* refactor(Layout): convert BaseTypography from styled to component

Improve type safety and maintainability by converting styled component to regular React component with TypeScript interface

* refactor(Layout): remove unused BaseTypography component

* refactor(Layout): remove unused Container component and interface

* refactor(layout): rename Stack to Flex and use CSSProperties types

The Stack component was renamed to Flex to better reflect its purpose and align with common naming conventions. The interface properties were also updated to use CSSProperties types for better type safety and consistency with CSS standards.

* refactor(Layout): move FlexProps interface and comment out unused ButtonProps

Clean up component interfaces by moving FlexProps closer to its usage and commenting out unused ButtonProps interface to reduce clutter

* refactor(layout): standardize flex props from alignItems/justifyContent to align/justify

The changes standardize the flex-related props in the Layout component and across multiple files from using alignItems/justifyContent to the shorter align/justify. This improves consistency and reduces verbosity in the codebase while maintaining the same functionality.

All instances of alignItems have been replaced with align and justifyContent with justify in Flex, RowFlex, ColFlex and related components. The changes are purely syntactic and do not affect the actual layout behavior.

This refactoring makes the code more maintainable by using a consistent naming convention for flex properties throughout the application.

* refactor(Layout): extend BoxProps with React div props

* feat(Layout): add flexWrap prop to Flex component interface

Add flexWrap property to FlexProps interface to support CSS flex-wrap functionality. Also replace antd Flex with custom Flex component in TagFilterSection.

* refactor(components): replace antd Flex with custom Layout components

Consolidate Flex component usage across multiple files by replacing antd's Flex with custom Layout components (Flex, ColFlex, RowFlex) for better maintainability and consistency

* refactor(components):  migrate antd Flex tu custom Flex

* refactor(components): update layout component usage for consistency

replace RowFlex with ColFlex where appropriate and align prop names

* refactor(tests): rename HStack to RowFlex in test components

Update test snapshots and mock components to reflect the component name change from HStack to RowFlex
Remove unused data-vertical attribute from preview container

* refactor(Layout): pass through props and merge styles in Box and Flex components

Improve component flexibility by allowing additional props to pass through and properly merging style objects in both Box and Flex components

* refactor(Layout): make Flex component props optional with undefined defaults

* test: update TagFilterSection snapshot to include wrap style

* perf(Layout): optimize Box component style calculation with useMemo

* docs: fix typo in Layout component comment

* refactor(Layout): update BoxProps to use CSSProperties types

Standardize prop types by using CSSProperties for style-related props to improve type safety and consistency with React's style system

* feat(Layout): add wrap prop to Flex component

* style(TagFilterSection): update snapshot styling to use flex-wrap property

* refactor(Layout): simplify layout components by using Tailwind CSS classes

Remove custom style calculations and props in favor of Tailwind utility classes

* refactor: replace inline styles with Tailwind CSS classes for consistent styling

style: update spacing and alignment utilities across components

* refactor(tests): update test snapshots to use tailwind classes

Replace inline styles with tailwind classes in test snapshots and update test assertions to match. This improves consistency with the codebase's styling approach.

* style: adjust spacing and gaps in UI components for consistency

* style: replace inline styles with tailwind classes for consistency

Refactor various components to use tailwind classes instead of inline styles to maintain consistency and improve readability. Changes include:
- Replacing style attributes with tailwind classes for spacing, margins, and padding
- Standardizing gap sizes across components
- Using tailwind for width, height, and other layout properties
- Updating test files to match new class names

* style(settings): replace inline styles with tailwind classes for consistency

Refactor settings components to use tailwind gap utility instead of inline styles for better maintainability and consistency across the codebase

* refactor(styles): replace inline styles with tailwind classes for consistency

* feat(eslint): add rule to restrict antd Flex imports

Enforce using custom Layout components instead of antd's Flex by adding a restricted import rule

* refactor: migrate flex layout from antd props to tailwind classes

- Replace antd Flex component props with tailwind classes for consistency
- Update gap and alignment values to use tailwind's spacing scale
- Remove unused antd Flex imports to clean up dependencies

* style(settings): adjust spacing and layout in various settings components

- Add gap spacing between elements in multiple settings components
- Remove redundant flex class in some components
- Standardize gap sizes across related components

* refactor(ui): replace inline styles with tailwind classes for consistency

Replace various inline style attributes with equivalent tailwind classes across multiple components to maintain consistent styling approach. Changes include margin, padding, width, and flex properties.

- Convert style attributes to tailwind classes
- Standardize spacing values using tailwind's spacing scale
- Improve maintainability by using utility classes

* style(ui): adjust spacing in model list group header

* style(css): wrap base styles in @layer for better organization

* style(css): fix indentation and nesting in global styles

* style(settings): adjust spacing in model list and convert subtitle to cn

Refactor SettingSubtitle to use cn utility for better className handling
Add gap spacing between model list items for improved layout

* style(css): move some styles from base layer to outer in index.css

* refactor(components): replace HStack with RowFlex for consistency

Update layout components to use RowFlex instead of HStack to maintain consistent naming

* style: reorder imports in useAppInit and BaseApiClient files

* fix(MinAppTabsPool): wrong import path

* refactor: update style file extensions from scss to css

Update file extensions and comments to reflect the change from SCSS to CSS stylesheets

* feat(layout): add Flex component and its variants

Introduce new Flex component with Box, RowFlex, SpaceBetweenRowFlex, ColFlex and Center variants to provide reusable layout components

* refactor: migrate layout components to @cherrystudio/ui package

This commit updates all imports of layout components (Box, Flex, RowFlex, ColFlex, etc.) from '@renderer/components/Layout' to '@cherrystudio/ui' across the codebase. The change also includes updating related test files and eslint configuration to reflect this migration. This refactoring aims to centralize layout components in a shared package for better maintainability and consistency.

* docs(eslint): update comment and restricted imports rule

Update comment to clarify the purpose of the rule and add a TODO note for future migration

* docs(ui): update migration status for layout components

Mark Layout/* components as migrated and refactored in both Chinese and English documentation

* docs: update migration status for Layout components
2025-09-17 18:17:17 +08:00
one
aab941d89c refactor: migrate sortable (#10204)
* refactor: rename sortable dir

* refactor: migrate Sortable to the ui package

* feat: add stories for Sortable

* refactor: add scroller to the vertical story

* refactor: improve hints and width

* refactor: simplify item style

* fix: lint errors

* chore: dependencies

* refactor: move hooks

* fix: import errors

* style: format

* style: format
2025-09-17 17:26:40 +08:00
MyPrototypeWhat
1b04fd065d refactor(ui): enhance CustomCollapse and ToolsCallingIcon components
- Refactored CustomCollapse to utilize Accordion and AccordionItem from HeroUI, simplifying props and improving functionality.
- Updated ToolsCallingIcon to accept TooltipProps for better customization.
- Revised stories for CustomCollapse to reflect new prop structure and added examples for various use cases.
- Cleaned up unnecessary props and improved documentation in story files.
2025-09-17 15:45:22 +08:00
MyPrototypeWhat
76b3ba5d7e feat(ui): integrate @storybook/addon-themes and enhance CustomCollapse component
- Added @storybook/addon-themes to package.json and yarn.lock for theme support in Storybook.
- Updated CustomCollapse component to utilize HeroUI's Accordion and AccordionItem for improved functionality and styling.
- Removed the ReasoningIcon component as it was deemed unnecessary.
- Enhanced ProviderAvatar component to ensure consistent className handling.
- Added new stories for FileIcons, SvgSpinners180Ring, and ToolsCallingIcon to showcase their usage and variations.
2025-09-17 14:53:34 +08:00
fullex
355e5b269d Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-09-17 14:28:36 +08:00
Phantom
d4b0272fe7 refactor: prefer import type (#10190)
* style(linter): enable consistent-type-imports rule in typescript

* chore: add biome to lint script for improved code formatting

* chore: add oxlint-specific lint script for faster linting

* refactor: use type-only imports for better type safety and clarity
2025-09-17 12:32:53 +08:00
MyPrototypeWhat
59bf94b118 refactor(ui): update migration status and enhance component implementations
- Increased the refactored component count to 18 and reduced pending migrations to 184 in the migration status files.
- Improved the Ellipsis, ListItem, MaxContextCount, and ThinkingEffect components by simplifying their structure and enhancing styling.
- Updated the tsconfig.json to adjust the root directory for better project organization.
- Removed unnecessary alias configurations in tsdown.config.ts for cleaner setup.
- Added new stories for Ellipsis and ListItem components to improve documentation and showcase their usage.
2025-09-16 19:20:04 +08:00
fullex
bd7cd22220 refactor: update data management documentation and structure
- Renamed "State Management" to "Data Management" in CLAUDE.md for clarity.
- Enhanced data management section with detailed descriptions of Cache System, Preference System, and User Data API.
- Updated README.md in shared/data to reflect new directory structure and provide clearer organization of type definitions and schemas.
- Added guidelines for selecting appropriate data access patterns based on data characteristics.
2025-09-16 17:30:02 +08:00
MyPrototypeWhat
f48674b2c7 refactor(ui): clean up component code and improve styling
- Refactored EmojiIcon, ExpandableText, and ProviderAvatar components for better readability and consistency.
- Simplified JSX structure and improved styling in ExpandableText and EmojiAvatar stories.
- Enhanced code formatting in various files for improved maintainability.
2025-09-16 17:21:01 +08:00
MyPrototypeWhat
56af6f43c0 refactor(ui): update button elements to include type attribute
- Added type="button" to button elements in DividerWithText and Icon stories for better accessibility and to prevent unintended form submissions.
- Improved code consistency across button components in the UI stories.
2025-09-16 17:15:40 +08:00
MyPrototypeWhat
f83c3e171e chore(ui): update migration status and component files
- Updated migration status to reflect the migration of additional components, reducing the total migrated count to 34 and increasing the refactored count to 14.
- Enhanced component files by refactoring several components to improve structure and styling, including CopyButton, CustomTag, and IndicatorLight.
- Added new stories for components such as CopyButton, CustomCollapse, and DividerWithText to improve documentation and showcase usage.
- Adjusted TypeScript configuration to include story files for better type checking.
2025-09-16 17:12:10 +08:00
fullex
d397a43806 fix: typecheck/test:lint/format:check
feat: add data related test
2025-09-16 15:26:36 +08:00
fullex
8353f331f1 test: update tests to use usePreference hook and improve snapshot consistency
- Refactored tests in MainTextBlock and ThinkingBlock to utilize the usePreference hook for managing user settings.
- Updated snapshots in DraggableVirtualList test to reflect changes in class names.
- Enhanced export tests to ensure proper handling of markdown formatting and citation footnotes.
- Mocked additional dependencies globally for improved test reliability.
2025-09-16 14:07:54 +08:00
MyPrototypeWhat
8cc6b08831 chore(ui): update package.json and migration status files
- Reformatted keywords and files array in package.json for better readability.
- Updated migration status to reflect the migration of additional components, increasing the total migrated count to 46 and reducing pending migrations to 190.
- Added new components to the migration status table, including ErrorBoundary and ProviderAvatar, while removing deprecated components like ErrorTag, SuccessTag, and WarnTag.
2025-09-16 13:32:25 +08:00
fullex
ffe897d58c chore: update yarn.lock and refactor SettingsTab component
- Added "@typescript-eslint/visitor-keys@npm:8.43.0" to yarn.lock.
- Refactored getVirtualIndexes in DraggableVirtualList to use item.index.
- Replaced useSettings with usePreference for codeFancyBlock in SettingsTab.
- Updated Switch component to use setCodeFancyBlock directly.
2025-09-16 11:56:10 +08:00
fullex
182ac3bc98 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-09-16 11:35:18 +08:00
fullex
c0cca4ae44 chore: update configuration and improve cache management
- Added "packages/ui/scripts/**" to .oxlintrc.json for linting.
- Excluded ".claude/**" from biome.jsonc.
- Refactored API path types in apiPaths.ts for better clarity.
- Updated error handling in errorCodes.ts to ensure stack trace is always available.
- Modified preferenceSchemas.ts to include new features and updated generated timestamp.
- Cleaned up tsconfig.json for better organization.
- Adjusted CustomTag component to improve rendering logic.
- Enhanced CodeEditor utility functions for better type safety.
- Improved Scrollbar story for better readability.
- Refactored CacheService to streamline comments and improve documentation.
- Updated useCache and useSharedCache hooks for better clarity and functionality.
- Cleaned up selectionStore and settings.ts by commenting out deprecated actions.
- Updated DataApiHookTests for better optimistic update handling.
2025-09-16 11:27:18 +08:00
one
8981d0a09d refactor(CodeEditor): decouple CodeEditor and global settings (#10163)
* refactor(CodeEditor): decouple CodeEditor and global settings

* refactor: improve language extension fallbacks

* refactor: make a copy of CodeEditor in the ui package

* refactor: update ui CodeEditor and language list

* refactor: use CodeEditor from the ui package

* feat: add a story for CodeEditor
2025-09-16 10:11:36 +08:00
Phantom
de44938d9b fix: ui package env (#10191)
* ci: add ui package to oxlint configuration

* chore: update vscode settings for oxlintrc.json association
2025-09-16 10:08:52 +08:00
fullex
75d5dcf275 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-09-16 00:46:42 +08:00
fullex
d8f4825e5e Merge branch 'v2' of github.com:CherryHQ/cherry-studio into v2 2025-09-16 00:40:48 +08:00
fullex
c242abd81a feat: refactor cache management and update component dependencies
- Updated package.json to version 2.0.0-alpha, reflecting significant changes.
- Refactored cache management by integrating useCache hooks across various components, enhancing state management and performance.
- Replaced useRuntime references with useMinapps in multiple components to streamline minapp state handling.
- Improved type safety in cache schemas and updated related components to utilize new types.
- Removed deprecated runtime actions and streamlined the codebase for better maintainability.
2025-09-16 00:40:36 +08:00
MyPrototypeWhat
79c9ed963f feat: update UI package with Storybook integration and Tailwind CSS v4 configuration
- Added Storybook scripts for development and building the UI components.
- Updated package.json to include new dependencies for Storybook and styled-components.
- Revised README to reflect changes in Tailwind CSS configuration, transitioning to v4 and removing the tailwind.config.js file.
- Enhanced the tsdown configuration to mark additional peer dependencies as external.
- Removed outdated Tailwind CSS configuration file to streamline the setup.
2025-09-15 19:26:23 +08:00
fullex
6079961f44 feat: enhance testing framework for CacheService and PreferenceService
- Updated README.md to reflect the expanded testing framework for CacheService, including detailed test modules and scenarios.
- Added CacheService tests for direct API, hooks, advanced features, and stress testing.
- Refactored TestApp to incorporate CacheService tests alongside existing PreferenceService tests, improving organization and accessibility.
- Adjusted component styling to support dark mode and ensure consistent UI across test components.
2025-09-15 17:36:14 +08:00
MyPrototypeWhat
04ef5edea2 feat: update migration status and add new UI components
- Updated migration status documentation to reflect the migration of 43 components, with 193 pending.
- Enhanced the component status table with new entries for MaxContextCount, CollapsibleSearchBar, ImageToolButton, and InfoPopover.
- Added implementations for the new components, improving the UI library's functionality.
- Updated index.ts to export the newly added components for better accessibility.
2025-09-15 16:08:35 +08:00
MyPrototypeWhat
046ed3edef feat: update migration status and add ListItem and EditableNumber components
- Updated migration status documentation to reflect the migration of 38 components, with 198 pending.
- Enhanced the component status table with new entries for ListItem and EditableNumber.
- Added ListItem and EditableNumber components with their respective implementations and styles.
- Updated index.ts to export the newly added components for improved accessibility.
2025-09-15 15:23:03 +08:00
MyPrototypeWhat
6eb9ab30b0 feat: update migration status and add new UI components
- Updated migration status documentation to reflect the migration of 36 components, with 200 pending.
- Enhanced the component status table with new entries for CustomCollapse, EmojiAvatar, ResetIcon, OcrIcon, ToolIcon, WrapIcon, UnWrapIcon, HelpTooltip, Selector, and WarnTooltip.
- Updated index.ts to export the newly added components for improved accessibility.
2025-09-15 15:12:28 +08:00
MyPrototypeWhat
1c27481813 feat: update migration status and add new UI components
- Updated migration status documentation to reflect the migration of 26 components, with 210 pending.
- Enhanced the component status table with detailed descriptions and categorized components.
- Introduced new components: CustomTag, ErrorTag, SuccessTag, WarnTag, CopyIcon, DeleteIcon, EditIcon, and RefreshIcon.
- Updated index.ts to export the newly added components for improved accessibility.
2025-09-15 14:59:52 +08:00
fullex
a6e19f7757 refactor: consolidate CacheService implementation and update references
- Moved CacheService functionality to a new implementation in @data/CacheService, enhancing modularity.
- Updated all references across the codebase to utilize the new cacheService instance.
- Removed the old CacheService files from both main and renderer directories to streamline the codebase.
2025-09-15 14:47:30 +08:00
fullex
6d89f94335 feat: CacheService & useCache Hooks 2025-09-15 14:12:41 +08:00
MyPrototypeWhat
2e07b4ea58 feat: add migration status documentation and new UI components
- Introduced migration status documentation in both English and Chinese to track the progress of the UI component library migration.
- Added new UI components including CopyButton, DividerWithText, EmojiIcon, IndicatorLight, Spinner, TextBadge, and various display and icon components.
- Updated the index.ts file to export the newly added components for easier access.
- Enhanced the directory structure and component classification guidelines for better organization and clarity.
2025-09-15 14:10:49 +08:00
MyPrototypeWhat
bf2f6ddd7f chore: update CODEOWNERS to include new UI package ownership
- Added ownership for the /packages/ui/ directory to @MyPrototypeWhat.
- Ensured consistent ownership assignment across relevant directories.
2025-09-15 12:34:56 +08:00
MyPrototypeWhat
c936bddfe7 feat: add index.ts type definitions for UI components
- Introduced a new TypeScript definition file (index.ts) to support the newly added UI component library.
- This file will facilitate better type checking and autocompletion for developers using the library.
2025-09-15 12:33:47 +08:00
MyPrototypeWhat
d3028f1dd1 feat: add @cherrystudio/ui component library
- Introduced a new UI component library for Cherry Studio, including various components such as buttons, inputs, and layout elements.
- Updated configuration files to include the new library and its dependencies.
- Enhanced the project structure to support modular imports and TypeScript definitions for better development experience.
2025-09-15 12:03:39 +08:00
MyPrototypeWhat
0038280fba refactor: update import paths for styles and navbar position
- Changed the import of navbar position hook from useSettings to useNavbarPosition for better clarity.
- Updated style imports from index.scss to index.css for consistency across components.
2025-09-15 11:45:12 +08:00
fullex
0a94609f78 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-09-15 00:06:06 +08:00
fullex
f9f8390540 Merge branch 'v2' of github.com:CherryHQ/cherry-studio into v2 2025-09-14 21:01:07 +08:00
fullex
91dd6482ce chore: add CODEOWNERS file to define ownership for specific directories
- Created a CODEOWNERS file to specify ownership for migrations and data directories.
- Assigned ownership to @0xfullex for the specified paths to streamline code review and management.
2025-09-14 21:00:57 +08:00
fullex
016bbff79f Update pr-ci.yml 2025-09-14 18:52:58 +08:00
fullex
32f41391c4 Merge branch 'main' of github.com:CherryHQ/cherry-studio into v2 2025-09-14 17:39:42 +08:00
fullex
78a8ebc777 feat(preferences): update user theme settings and add new preferences
- Updated preferences configuration with new user theme options including font family and code font family.
- Added new preferences for chat and export menus.
- Adjusted default preferences to include new settings for user theme.
- Enhanced useUserTheme hook to manage new font family preferences.
2025-09-14 17:05:31 +08:00
fullex
57fd73e51a Merge branch 'main' of github.com:CherryHQ/cherry-studio into wip/data-refactor 2025-09-14 17:05:14 +08:00
fullex
bd448b5108 refactor: remove AbortSignal support from DataApiService and related components
- Eliminated AbortSignal handling from ApiClient interface and DataApiService to streamline request processing.
- Updated IpcAdapter to remove event sender logic for responses, aligning with the new direct IPC approach.
- Adjusted tests to reflect the removal of cancellation capabilities, emphasizing that direct IPC requests cannot be cancelled.
- Cleaned up related code and comments to enhance clarity and maintainability.
2025-09-13 13:50:59 +08:00
fullex
a7d12abd1f feat: add Data API channels and integrate swr for data fetching
- Introduced new IPC channels for Data API requests and responses in IpcChannel.
- Added swr library to package.json for improved data fetching capabilities.
- Updated preload API to include Data API related methods for handling requests and subscriptions.
- Removed deprecated pending_default_values.ts file as part of data refactor.
2025-09-13 00:55:15 +08:00
fullex
9e3618bc17 refactor: update selection preferences and enums for improved consistency
- Removed deprecated selection IPC channels from IpcChannel.
- Replaced string literals with enums for SelectionTriggerMode and SelectionFilterMode in preference management.
- Updated the SelectionService and selectionStore to utilize the new enum types for better type safety and clarity.
- Marked selectionStore as deprecated for future removal after data refactoring.
2025-09-09 12:14:29 +08:00
fullex
8cb270ca86 fix: restore LANG_DETECT_PROMPT import in translate utility and reorder imports in MiniWindowApp 2025-09-06 18:44:26 +08:00
fullex
d321cd23ef chore: format 2025-09-06 18:32:33 +08:00
fullex
9da3e82c47 refactor: update preference management in AI components
- Replaced instances of useSettings with usePreference for better preference handling across various components.
- Updated function signatures to support async operations where necessary.
- Adjusted imports to utilize shared configuration for prompts, enhancing consistency in prompt management.
- Improved error handling and logging in AI-related functionalities.
2025-09-06 18:21:11 +08:00
fullex
2931e558b3 Merge branch 'main' of github.com:CherryHQ/cherry-studio into wip/data-refactor 2025-09-06 18:20:53 +08:00
fullex
9a847dc5a3 refactor: update Minapp components to use preference management
- Replaced useSettings with usePreference in PinnedMinapps and useMinappPopup components for better preference handling.
- Added external dependency for Electron in electron.vite.config.ts and set output format to CommonJS.
2025-09-06 17:23:19 +08:00
fullex
c2a1178dff refactor: update preferences management and enhance PreferenceService documentation
- Updated preferences types in preferences.ts to use PreferenceTypes for better type safety.
- Added new preference keys related to notes features in preferences.ts.
- Enhanced documentation in PreferenceService.ts and usePreference.ts to clarify usage and update strategies.
- Improved caching and subscription mechanisms in PreferenceService for better performance and reliability.
2025-09-04 12:47:22 +08:00
fullex
7f114ade4d Merge branch 'main' of github.com:CherryHQ/cherry-studio into wip/data-refactor 2025-09-03 21:21:38 +08:00
fullex
7b633641d1 Merge branch 'main' of github.com:CherryHQ/cherry-studio into wip/data-refactor 2025-09-03 16:58:15 +08:00
fullex
1dacdc3178 refactor: expand settings state with comprehensive user preferences
- Introduced a detailed SettingsState interface, incorporating various user preferences such as showAssistants, language settings, proxy configurations, and more.
- Updated initialState to reflect the new comprehensive settings structure, ensuring all preferences are initialized correctly.
- Cleaned up commented-out code and organized settings for improved clarity and maintainability.
- Enhanced type safety by integrating new types for various settings, aligning with recent refactoring efforts in preference management.
2025-09-03 16:53:29 +08:00
fullex
566dd14fed refactor: enhance preference management and streamline component integrations
- Updated various components to utilize the usePreference hook, replacing previous useSettings references for improved consistency and maintainability.
- Introduced new preference types for ChatMessageStyle, ChatMessageNavigationMode, and MultiModelMessageStyle to enhance type safety.
- Refactored preference handling in multiple files, ensuring a more streamlined approach to managing user preferences.
- Cleaned up unused code and comments related to previous settings for better clarity and maintainability.
- Updated auto-generated preference mappings to reflect recent changes in preference structure.
2025-09-03 16:48:04 +08:00
fullex
68cd87e069 refactor: update UpgradeChannel handling and improve preference integration
- Commented out the UpgradeChannel enum in constant.ts and moved it to preferenceTypes.ts for better organization.
- Updated various components to utilize the new UpgradeChannel type from preferenceTypes, enhancing type safety and consistency.
- Refactored preference handling across multiple files to streamline the use of the usePreference hook, replacing previous settings references.
- Cleaned up unused code and comments related to previous settings for improved maintainability.
- Updated auto-generated preference mappings to reflect recent changes in preference structure.
2025-09-03 14:31:15 +08:00
fullex
1b57ffeb56 refactor: enhance preference management and update component integrations
- Updated preference handling to utilize the usePreference hook across various components, improving consistency and maintainability.
- Introduced new preference types for ProxyMode and MultiModelFoldDisplayMode to enhance type safety.
- Refactored components to replace useSettings with usePreference, streamlining preference management.
- Cleaned up unused code and comments related to previous settings for better clarity.
- Updated auto-generated preference mappings to reflect recent changes in preference structure.
2025-09-02 22:11:15 +08:00
fullex
5d789ef394 refactor: enhance preference management and update sidebar icon handling
- Updated preferences to include new confirmation settings for message actions, allowing users to customize action confirmations.
- Refactored components to utilize the usePreference hook for improved preference handling, replacing previous useSettings references.
- Introduced new types for AssistantIconType and SidebarIcon to enhance type safety.
- Cleaned up unused code and comments related to previous settings for better maintainability.
- Updated auto-generated preference mappings to reflect recent changes in preference structure.
2025-09-02 17:24:38 +08:00
fullex
820d6a6e96 refactor: update preference keys and enhance preference management
- Updated preference keys from 'app.theme.*' to 'ui.*' for better organization and clarity.
- Introduced new preferences for assistant tab sorting and visibility.
- Refactored components to utilize the updated preference keys, improving consistency across the codebase.
- Cleaned up unused code and comments related to previous settings for maintainability.
- Updated auto-generated preference mappings to reflect the new structure.
2025-09-02 15:37:30 +08:00
fullex
0a67ab4103 refactor: enhance preference management and update mappings
- Updated preferences to utilize the new SendMessageShortcut type for better type safety.
- Refactored components to use the usePreference hook instead of useSettings for improved preference handling.
- Added new preferences for target language and send message shortcut in various components.
- Cleaned up unused code and comments related to settings for better maintainability.
- Updated auto-generated preference mappings to reflect recent changes in preference structure.
2025-09-02 13:24:41 +08:00
fullex
5cc7390bb6 Merge branch 'main' of github.com:CherryHQ/cherry-studio into wip/data-refactor 2025-09-02 11:50:00 +08:00
fullex
2ce4fabc7d refactor: update preference handling and remove unused settings
- Commented out the App_SetDisableHardwareAcceleration IPC channel and related code for hardware acceleration settings.
- Updated preferences to utilize the new WindowStyle type for window style settings.
- Refactored components to use the usePreference hook instead of useSettings for better preference management.
- Cleaned up unused code and comments related to hardware acceleration and window style for improved maintainability.
2025-09-02 11:45:33 +08:00
fullex
7b2570974e refactor: update language handling and remove unused locales
- Commented out the App_SetLanguage IPC channel and related language management code.
- Updated preferences to use LanguageVarious type for language settings.
- Removed the locales utility file and adjusted imports to utilize preferenceService for language management.
- Cleaned up unused code and comments related to language handling for improved maintainability.
2025-09-02 01:39:04 +08:00
fullex
0ef3852029 refactor: update theme handling and preference types
- Removed the App_SetTheme IPC channel and related theme management code.
- Updated imports to use preferenceTypes for theme and selection action items.
- Refactored preference service to preload preferences and adjusted related components.
- Cleaned up unused code and comments related to theme management.
- Enhanced the organization of preference-related types and actions for better maintainability.
2025-09-01 23:49:17 +08:00
fullex
0dce1c57fc Merge branch 'main' of github.com:CherryHQ/cherry-studio into wip/data-refactor 2025-09-01 09:44:12 +08:00
fullex
190ee76cf1 refactor(preload): update action item type to SelectionActionItem
Replaced the ActionItem type with SelectionActionItem in the processAction method for better type safety. Removed unused imports related to ActionItem in ActionTranslate component.
2025-08-28 10:54:12 +08:00
fullex
83fea49ed2 Merge branch 'main' of https://github.com/CherryHQ/cherry-studio into wip/data-refactor 2025-08-28 10:52:05 +08:00
fullex
ccc50dbf2b Merge branch 'main' of https://github.com/CherryHQ/cherry-studio into wip/data-refactor 2025-08-19 23:04:35 +08:00
fullex
6b503c4080 Merge branch 'main' of https://github.com/CherryHQ/cherry-studio into wip/data-refactor 2025-08-16 21:52:19 +08:00
fullex
40fe381aa5 refactor(preferences): replace empty action items with default values and remove unused hook
- Updated the preferences configuration to use `defaultActionItems` instead of an empty array for `feature.selection.action_items`, enhancing default behavior.
- Removed the `useSelectionAssistant` hook as it was no longer needed, streamlining the codebase.
2025-08-16 21:51:58 +08:00
fullex
65c24a2f4b fix(selection): disable sandbox mode in SelectionService and clean up imports in ActionTranslate component
- Changed sandbox mode from true to false in SelectionService to improve security and functionality.
- Removed unnecessary blank line in entryPoint.tsx for cleaner code.
- Updated ActionTranslate component to use the new SelectionActionItem type for better type safety.
2025-08-16 18:52:46 +08:00
fullex
b15778b16b feat(preferences): enhance selection management with type safety and refactor preferences structure
- Introduced new types for selection management: `SelectionActionItem`, `SelectionFilterMode`, and `SelectionTriggerMode` to improve type safety across the application.
- Updated `PreferencesType` to utilize these new types, ensuring better consistency and clarity in preference definitions.
- Refactored `SelectionService` and related components to adopt the new types, enhancing the handling of selection actions and preferences.
- Cleaned up deprecated types and improved the overall structure of preference management, aligning with recent updates in the preference system.
2025-08-16 08:57:48 +08:00
fullex
087e825086 feat(preferences): implement custom notifier for preference change management
- Introduced `PreferenceNotifier` class to replace `EventEmitter`, enhancing performance and memory efficiency for preference change notifications.
- Refactored `PreferenceService` to utilize the new notifier for managing subscriptions and notifications.
- Updated `SelectionService` to adopt the new subscription model, improving the handling of preference changes and ensuring proper cleanup of listeners.
- Enhanced subscription statistics and debugging capabilities within the notifier.
2025-08-15 19:45:13 +08:00
fullex
3dd2bc1a40 feat(preferences): enhance preference subscription and notification system
- Updated `PreferenceService` to notify change listeners immediately upon fetching uncached values.
- Refactored subscription logic to simplify auto-subscribing to preference keys.
- Modified `usePreference` and `useMultiplePreferences` hooks to improve handling of default values and subscription behavior.
- Enhanced `SelectionAssistantSettings` to include detailed logging of preference states for better debugging.
2025-08-15 18:27:36 +08:00
fullex
9bde833419 feat(preferences): implement optimistic and pessimistic update strategies in PreferenceService
- Introduced `PreferenceUpdateOptions` interface to configure update behavior.
- Enhanced `set` and `setMultiple` methods in `PreferenceService` to support both optimistic and pessimistic update strategies, allowing for immediate UI feedback or database-first updates.
- Updated `usePreference` and `useMultiplePreferences` hooks to accept options for flexible update strategies.
- Improved handling of concurrent updates with request queues and rollback mechanisms for optimistic updates.
- Enhanced documentation in hooks to clarify usage of update strategies.
2025-08-15 16:48:22 +08:00
fullex
e15005d1cf feat(preferences): update preferences structure and enhance shortcut management
- Updated the preferences configuration with new shortcut definitions and types for better management.
- Introduced a method to get and subscribe to preference changes in the PreferenceService, improving reactivity.
- Refactored SelectionService to utilize the new preference management system, enhancing code clarity and maintainability.
- Updated SelectionAssistantSettings to use the new preference hooks for managing selection settings.
- Adjusted the generated preferences file to reflect the latest configuration changes.
2025-08-15 12:54:24 +08:00
fullex
30e6883333 refactor(preferences): consolidate IPC handlers into PreferenceService
- Moved IPC handler logic for preference operations from ipc.ts to PreferenceService.
- Introduced a unified method for registering IPC handlers, improving code organization and maintainability.
- Enhanced preference change notification system with optimized performance and added support for main process listeners.
2025-08-14 18:01:22 +08:00
fullex
99be38c325 Merge branch 'main' of https://github.com/CherryHQ/cherry-studio into wip/refactor/databases 2025-08-13 13:24:26 +08:00
fullex
df876651b9 feat(preferences): enhance testing framework with real-time UI synchronization and slider controls
This commit updates the dataRefactorTest README to include new features such as real-time UI linkage for theme, language, and zoom preferences, as well as interactive slider controls for various settings. The TestApp component is modified to support dynamic window identification and theme monitoring. Additionally, the PreferenceBasicTests, PreferenceMultipleTests, and PreferenceServiceTests components are enhanced with slider functionality for numerical preferences, improving the testing capabilities for cross-window synchronization and user experience.
2025-08-12 23:42:10 +08:00
fullex
85bdcdc206 refactor(preferences): improve PreferenceService and related hooks with enhanced type safety and listener management
This commit refactors the PreferenceService to improve type safety for preference handling and updates the listener management system. It renames methods for clarity, ensuring that preference changes are properly notified to all relevant listeners. Additionally, the usePreference hook is updated to align with these changes, enhancing the overall consistency and reliability of preference management in the application.
2025-08-12 21:23:02 +08:00
fullex
2860935e5b refactor(preferences): enhance PreferenceService with public access modifiers and improve caching logic
This commit updates the PreferenceService by adding public access modifiers to several methods, improving code clarity and consistency. It also refines the caching logic to eliminate unnecessary type assertions and streamline the handling of preference values. Additionally, minor formatting adjustments are made for better readability across the service and related hooks.
2025-08-12 18:14:39 +08:00
fullex
b219e96544 feat(preferences): integrate PreferenceService and enhance testing capabilities
This commit refactors the PreferenceService to use named exports for better consistency and updates the DbService import accordingly. It introduces a testing mechanism for the PreferenceService by creating test windows to facilitate cross-window preference synchronization testing. Additionally, improvements are made to the usePreference hook for better performance and stability, ensuring efficient preference management in the application.
2025-08-12 13:44:41 +08:00
fullex
c02f93e6b9 feat(preferences): add data path alias and update TypeScript configuration
This commit introduces a new alias '@data' in the Electron Vite configuration for easier access to the data directory. Additionally, the TypeScript configuration is updated to include path mapping for '@data/*', enhancing module resolution. Several test files related to the PreferenceService have been removed, streamlining the test suite and focusing on essential functionality.
2025-08-12 11:35:09 +08:00
fullex
72f32e4b8f feat(preferences): add getAll method and IPC handler for retrieving all preferences
This commit introduces a new IPC channel and handler for fetching all user preferences at once, enhancing the efficiency of preference management. The PreferenceService is updated with a getAll method to retrieve all preferences from the memory cache, and the renderer-side PreferenceService is adjusted to support this new functionality. Additionally, type safety improvements are made across the preference handling code, ensuring better consistency and reducing potential errors.
2025-08-12 01:01:22 +08:00
fullex
a81f13848c refactor(preferences): enhance preference handling with type safety and improved IPC methods
This commit refines the preference management system by introducing type safety for preference keys and values, ensuring better consistency across the application. It updates IPC handlers for getting and setting preferences to utilize the new types, improving code clarity and reducing potential errors. Additionally, the PreferenceService is adjusted to align with these changes, enhancing the overall robustness of preference operations.
2025-08-11 22:58:30 +08:00
fullex
81538d5709 feat(preferences): add IPC channels and handlers for preference management
This commit introduces new IPC channels for getting, setting, and subscribing to preferences, enhancing the application's ability to manage user preferences. It also updates the preferences interface to use a consistent naming convention and refactors the preference seeding and migration processes to align with these changes. Additionally, the PrefService has been removed as it is no longer needed.
2025-08-11 20:40:50 +08:00
fullex
54449e7130 feat(migration): implement transaction handling and batch migration for preferences
This commit introduces a new transaction method in DbService to manage database operations with automatic rollback on error and commit on success. It enhances the PreferencesMigrator to support batch migration operations, improving the efficiency of migrating preferences from multiple sources. Additionally, the migration UI is updated to reflect progress during backup and migration stages, providing clearer feedback to users.
2025-08-10 23:25:28 +08:00
fullex
c217a0bf02 feat(migration): add Redux data handling to migration process
This commit introduces new IPC channels for sending and retrieving Redux persist data during the migration process. It enhances the DataRefactorMigrateService with methods to cache and manage Redux data, ensuring a smoother migration experience. Additionally, the MigrateApp component is updated to extract Redux data from localStorage and send it to the main process, improving the overall migration flow and user experience.
2025-08-10 20:58:43 +08:00
fullex
39257f64b1 feat(migration): enhance migration UI and refactor layout
This commit updates the migration window dimensions for improved usability, sets explicit entry points for preload scripts, and enhances the overall layout of the migration interface. It introduces new styles for buttons and alerts, improves the structure of the migration steps, and refines the user experience with clearer feedback and options during the migration process.
2025-08-10 13:51:08 +08:00
fullex
06dab978f7 feat(migration): update migration UI and enhance user experience
This commit modifies the migration window dimensions and properties for improved usability, allowing for resizing and maximizing. It also introduces new icons for different migration stages, updates localized messages for clarity, and enhances the overall layout of the migration interface, including adjustments to the alert messages and step indicators for better user guidance during the migration process.
2025-08-10 02:09:52 +08:00
fullex
c3f61533f7 feat(migration): enhance migration flow with new stages and error handling
This commit introduces additional stages to the migration process, including 'backup_required', 'backup_progress', and 'backup_confirmed', improving user guidance during data migration. It also adds new IPC channels for proceeding to backup and retrying migration, along with enhanced error handling and logging throughout the migration flow. The user interface has been updated to reflect these changes, providing clearer feedback and options during the migration process.
2025-08-10 01:40:03 +08:00
fullex
8715eb1f41 feat(migration): add new IPC channels and enhance migration flow
This commit introduces new IPC channels for starting the migration flow, restarting the application, and closing the migration window. It also updates the migration logic to improve user interaction and error handling during the migration process. Additionally, the migration interface has been enhanced with a step indicator and localized messages for better user experience.
2025-08-10 00:19:09 +08:00
fullex
92eb5aed7f refactor(migration): rename data migration files and update migration logic
This commit renames the data migration files for clarity, changing `dataMigrate.html` to `dataRefactorMigrate.html` and updating the corresponding service imports. It also enhances the migration logic by implementing a new `app_state` table structure and removing deprecated migration files, streamlining the overall migration process.
2025-08-09 22:37:20 +08:00
fullex
ff965402cd refactor(migration): streamline migration process and enhance IPC handling
This commit refines the data migration process by ensuring that migration checks occur before window creation and improves the logging of migration events. It also consolidates IPC handlers specific to migration within the MigrateService, allowing for better management of migration-related tasks. Additionally, the HTML for the data migration interface has been updated to enhance security policies.
2025-08-09 20:56:21 +08:00
fullex
973f26f9dd feat(migration): implement data migration service and update database architecture
This commit introduces a new data migration service with various IPC channels for migration tasks, including checking if migration is needed, starting the migration, and tracking progress. Additionally, the database architecture section has been added to the documentation, detailing the use of SQLite with Drizzle ORM, migration standards, and JSON field handling. Legacy migration files for ElectronStore and Redux have been removed as they are now deprecated.
2025-08-09 20:19:41 +08:00
fullex
4e3f8a8f76 feat(preferences): auto-generate preferences configuration from classification.json
This commit introduces an auto-generated preferences configuration file, replacing the previous manual definitions. The new structure is based on the latest classification.json and includes comprehensive settings for various application features. The auto-generation process ensures that the preferences are up-to-date and consistent with the defined classifications.
2025-08-09 16:44:35 +08:00
fullex
21e40db086 mv dir to data 2025-08-09 14:30:24 +08:00
fullex
92cd012037 Merge branch 'main' of https://github.com/CherryHQ/cherry-studio into wip/refactor/databases 2025-08-09 09:44:28 +08:00
fullex
7cd937888e Merge branch 'main' of https://github.com/CherryHQ/cherry-studio into wip/refactor/databases 2025-08-06 19:53:07 +08:00
fullex
ec491f5f24 更新 Preferences 接口以使用排序的对象键,并调整默认偏好设置的结构。同时,在 preference.ts 文件中添加了关于 scope 字段的注释,说明其未来用途。此更改旨在提高代码的可读性和一致性。 2025-08-02 00:22:22 +08:00
fullex
c0efb46c2b format 2025-07-28 22:40:19 +08:00
fullex
aa47fc3ed7 更新 yarn.lock 文件,添加了多个新依赖项,包括 @drizzle-team/brocli、@esbuild-kit/core-utils、@esbuild-kit/esm-loader 及其相关版本,同时更新了 esbuild 和 esbuild-register 的版本,确保依赖项的兼容性和稳定性。 2025-07-26 21:46:44 +08:00
fullex
c3c9f9b3f2 Merge branch 'main' of https://github.com/CherryHQ/cherry-studio into wip/refactor/databases 2025-07-26 21:46:02 +08:00
fullex
d486b56595 chore: update dependencies in package.json and yarn.lock 2025-07-03 12:21:31 +08:00
fullex
4bb5ff8086 Merge branch 'main' of https://github.com/CherryHQ/cherry-studio into wip/refactor/databases 2025-07-03 12:13:49 +08:00
fullex
a748162e67 chore: update yarn.lock and refactor database schema
- Added `get-tsconfig` dependency version 4.10.1 to yarn.lock.
- Updated schema path in sqlite-drizzle.config.ts from './src/main/db/schema/*' to './src/main/db/schemas/*'.
- Removed unused files: columnHelpers.ts, preference.ts, seed/index.ts, and seed/preferenceSeed.ts to clean up the codebase.
2025-05-27 12:09:08 +08:00
fullex
610e7481b3 Merge branch 'main' of https://github.com/CherryHQ/cherry-studio into wip/refactor/databases 2025-05-26 22:52:23 +08:00
fullex
9105e0f5c1 db init 2025-05-26 08:30:22 +08:00
fullex
a248517520 Merge branch 'main' of https://github.com/CherryHQ/cherry-studio into wip/refactor/databases 2025-05-23 11:01:19 +08:00
fullex
d31f35b16d feat: update dependencies in package.json and yarn.lock
- Added better-sqlite3, drizzle-orm, drizzle-kit, and their respective type definitions.
- Updated various esbuild-related packages to their latest versions.
- Enhanced package management for improved compatibility and performance.
2025-05-20 12:40:17 +08:00
939 changed files with 127187 additions and 7773 deletions

8
.github/CODEOWNERS vendored
View File

@@ -3,4 +3,12 @@
/src/main/services/ConfigManager.ts @0xfullex
/packages/shared/IpcChannel.ts @0xfullex
/src/main/ipc.ts @0xfullex
/migrations/ @0xfullex
/packages/shared/data/ @0xfullex
/src/main/data/ @0xfullex
/src/renderer/src/data/ @0xfullex
/packages/ui/ @MyPrototypeWhat
/app-upgrade-config.json @kangfenmao

View File

@@ -17,7 +17,7 @@ jobs:
runs-on: ubuntu-latest
env:
PRCI: true
if: github.event.pull_request.draft == false
if: github.event.pull_request.draft == false || github.head_ref == 'v2'
steps:
- name: Check out Git repository

View File

@@ -26,7 +26,7 @@
"env": {
"node": true
},
"files": ["src/main/**", "resources/scripts/**", "scripts/**", "playwright.config.ts", "electron.vite.config.ts"]
"files": ["src/main/**", "resources/scripts/**", "scripts/**", "playwright.config.ts", "electron.vite.config.ts", "packages/ui/scripts/**"]
},
{
"env": {
@@ -35,7 +35,8 @@
"files": [
"src/renderer/**/*.{ts,tsx}",
"packages/aiCore/**",
"packages/extension-table-plus/**"
"packages/extension-table-plus/**",
"packages/ui/**"
]
},
{

View File

@@ -31,7 +31,8 @@
},
"editor.formatOnSave": true,
"files.associations": {
"*.css": "tailwindcss"
"*.css": "tailwindcss",
".oxlintrc.json": "jsonc"
},
"files.eol": "\n",
// "i18n-ally.displayLanguage": "zh-cn", // 界面显示语言
@@ -50,6 +51,9 @@
},
"tailwindCSS.classAttributes": [
"className",
"classNames",
"classNames"
],
"tailwindCSS.experimental.classRegex": [
["cva\\(([^;]*)[\\);]", "[`'\"`]([^'\"`;]*)[`'\"`]"]
]
}

113
CLAUDE.md
View File

@@ -7,6 +7,7 @@ This file provides guidance to AI coding assistants when working with code in th
- **Keep it clear**: Write code that is easy to read, maintain, and explain.
- **Match the house style**: Reuse existing patterns, naming, and conventions.
- **Search smart**: Prefer `ast-grep` for semantic queries; fall back to `rg`/`grep` when needed.
- **Build with Tailwind CSS & Shadcn UI**: Use components from `@packages/ui` (Shadcn UI + Tailwind CSS) for every new UI component; never add `antd` or `styled-components`.
- **Log centrally**: Route all logging through `loggerService` with the right context—no `console.log`.
- **Research via subagent**: Lean on `subagent` for external docs, APIs, news, and references.
- **Always propose before executing**: Before making any changes, clearly explain your planned approach and wait for explicit user approval to ensure alignment and prevent unwanted modifications.
@@ -34,13 +35,113 @@ This file provides guidance to AI coding assistants when working with code in th
- **Renderer Process** (`src/renderer/`): React UI with Redux state management
- **Preload Scripts** (`src/preload/`): Secure IPC bridge
### Key Components
- **AI Core** (`src/renderer/src/aiCore/`): Middleware pipeline for multiple AI providers.
- **Services** (`src/main/services/`): MCPService, KnowledgeService, WindowService, etc.
- **Build System**: Electron-Vite with experimental rolldown-vite, yarn workspaces.
- **State Management**: Redux Toolkit (`src/renderer/src/store/`) for predictable state.
### Key Architectural Components
#### Main Process Services (`src/main/services/`)
- **MCPService**: Model Context Protocol server management
- **KnowledgeService**: Document processing and knowledge base management
- **FileStorage/S3Storage/WebDav**: Multiple storage backends
- **WindowService**: Multi-window management (main, mini, selection windows)
- **ProxyManager**: Network proxy handling
- **SearchService**: Full-text search capabilities
#### AI Core (`src/renderer/src/aiCore/`)
- **Middleware System**: Composable pipeline for AI request processing
- **Client Factory**: Supports multiple AI providers (OpenAI, Anthropic, Gemini, etc.)
- **Stream Processing**: Real-time response handling
#### Data Management
- **Cache System**: Three-layer caching (memory/shared/persist) with React hooks integration
- **Preferences**: Type-safe configuration management with multi-window synchronization
- **User Data**: SQLite-based storage with Drizzle ORM for business data
#### Knowledge Management
- **Embeddings**: Vector search with multiple providers (OpenAI, Voyage, etc.)
- **OCR**: Document text extraction (system OCR, Doc2x, Mineru)
- **Preprocessing**: Document preparation pipeline
- **Loaders**: Support for various file formats (PDF, DOCX, EPUB, etc.)
### Build System
- **Electron-Vite**: Development and build tooling (v4.0.0)
- **Rolldown-Vite**: Using experimental rolldown-vite instead of standard vite
- **Workspaces**: Monorepo structure with `packages/` directory
- **Multiple Entry Points**: Main app, mini window, selection toolbar
- **Styled Components**: CSS-in-JS styling with SWC optimization
### Testing Strategy
- **Vitest**: Unit and integration testing
- **Playwright**: End-to-end testing
- **Component Testing**: React Testing Library
- **Coverage**: Available via `yarn test:coverage`
### Key Patterns
- **IPC Communication**: Secure main-renderer communication via preload scripts
- **Service Layer**: Clear separation between UI and business logic
- **Plugin Architecture**: Extensible via MCP servers and middleware
- **Multi-language Support**: i18n with dynamic loading
- **Theme System**: Light/dark themes with custom CSS variables
### UI Design
The project is in the process of migrating from antd & styled-components to Tailwind CSS and Shadcn UI. Please use components from `@packages/ui` to build UI components. The use of antd and styled-components is prohibited.
UI Library: `@packages/ui`
### Database Architecture
- **Database**: SQLite (`cherrystudio.sqlite`) + libsql driver
- **ORM**: Drizzle ORM with comprehensive migration system
- **Schemas**: Located in `src/main/data/db/schemas/` directory
#### Database Standards
- **Table Naming**: Use singular form with snake_case (e.g., `topic`, `message`, `app_state`)
- **Schema Exports**: Export using `xxxTable` pattern (e.g., `topicTable`, `appStateTable`)
- **Field Definition**: Drizzle auto-infers field names, no need to add default field names
- **JSON Fields**: For JSON support, add `{ mode: 'json' }`, refer to `preference.ts` table definition
- **JSON Serialization**: For JSON fields, no need to manually serialize/deserialize when reading/writing to database, Drizzle handles this automatically
- **Timestamps**: Use existing `crudTimestamps` utility
- **Migrations**: Generate via `yarn run migrations:generate`
## Data Access Patterns
The application uses three distinct data management systems. Choose the appropriate system based on data characteristics:
### Cache System
- **Purpose**: Temporary data that can be regenerated
- **Lifecycle**: Component-level (memory), window-level (shared), or persistent (survives restart)
- **Use Cases**: API response caching, computed results, temporary UI state
- **APIs**: `useCache`, `useSharedCache`, `usePersistCache` hooks, or `cacheService`
### Preference System
- **Purpose**: User configuration and application settings
- **Lifecycle**: Permanent until user changes
- **Use Cases**: Theme, language, editor settings, user preferences
- **APIs**: `usePreference`, `usePreferences` hooks, or `preferenceService`
### User Data API
- **Purpose**: Core business data (conversations, files, notes, etc.)
- **Lifecycle**: Permanent business records
- **Use Cases**: Topics, messages, files, knowledge base, user-generated content
- **APIs**: `useDataApi` hook or `dataApiService` for direct calls
### Selection Guidelines
- **Use Cache** for data that can be lost without impact (computed values, API responses)
- **Use Preferences** for user settings that affect app behavior (UI configuration, feature flags)
- **Use User Data API** for irreplaceable business data (conversations, documents, user content)
## Logging Standards
### Usage
### Logging
```typescript
import { loggerService } from '@logger'
const logger = loggerService.withContext('moduleName')

View File

@@ -14,7 +14,7 @@
}
},
"enabled": true,
"includes": ["**/*.json", "!*.json", "!**/package.json"]
"includes": ["**/*.json", "!*.json", "!**/package.json", "!packages/**/*.json"]
},
"css": {
"formatter": {
@@ -42,6 +42,7 @@
"!.github/**",
"!.husky/**",
"!.vscode/**",
"!.claude/**",
"!*.yaml",
"!*.yml",
"!*.mjs",

View File

@@ -66,9 +66,10 @@ asarUnpack:
- resources/**
- "**/*.{metal,exp,lib}"
- "node_modules/@img/sharp-libvips-*/**"
# copy from node_modules/claude-code-plugins/plugins to resources/data/claude-code-pluginso
extraResources:
- from: "migrations/sqlite-drizzle"
to: "migrations/sqlite-drizzle"
# copy from node_modules/claude-code-plugins/plugins to resources/data/claude-code-pluginso
- from: "./node_modules/claude-code-plugins/plugins/"
to: "claude-code-plugins"

View File

@@ -22,6 +22,7 @@ export default defineConfig({
alias: {
'@main': resolve('src/main'),
'@types': resolve('src/renderer/src/types'),
'@data': resolve('src/main/data'),
'@shared': resolve('packages/shared'),
'@logger': resolve('src/main/services/LoggerService'),
'@mcp-trace/trace-core': resolve('packages/mcp-trace/trace-core'),
@@ -61,7 +62,20 @@ export default defineConfig({
}
},
build: {
sourcemap: isDev
sourcemap: isDev,
rollupOptions: {
// Unlike renderer which auto-discovers entries from HTML files,
// preload requires explicit entry point configuration for multiple scripts
input: {
index: resolve(__dirname, 'src/preload/index.ts'),
simplest: resolve(__dirname, 'src/preload/simplest.ts') // Minimal preload
},
external: ['electron'],
output: {
entryFileNames: '[name].js',
format: 'cjs'
}
}
}
},
renderer: {
@@ -90,13 +104,17 @@ export default defineConfig({
'@shared': resolve('packages/shared'),
'@types': resolve('src/renderer/src/types'),
'@logger': resolve('src/renderer/src/services/LoggerService'),
'@data': resolve('src/renderer/src/data'),
'@mcp-trace/trace-core': resolve('packages/mcp-trace/trace-core'),
'@mcp-trace/trace-web': resolve('packages/mcp-trace/trace-web'),
'@cherrystudio/ai-core/provider': resolve('packages/aiCore/src/core/providers'),
'@cherrystudio/ai-core/built-in/plugins': resolve('packages/aiCore/src/core/plugins/built-in'),
'@cherrystudio/ai-core': resolve('packages/aiCore/src'),
'@cherrystudio/extension-table-plus': resolve('packages/extension-table-plus/src'),
'@cherrystudio/ai-sdk-provider': resolve('packages/ai-sdk-provider/src')
'@cherrystudio/ai-sdk-provider': resolve('packages/ai-sdk-provider/src'),
'@cherrystudio/ui/icons': resolve('packages/ui/src/components/icons'),
'@cherrystudio/ui': resolve('packages/ui/src'),
'@cherrystudio/catalog': resolve('packages/catalog/src')
}
},
optimizeDeps: {
@@ -116,7 +134,8 @@ export default defineConfig({
miniWindow: resolve(__dirname, 'src/renderer/miniWindow.html'),
selectionToolbar: resolve(__dirname, 'src/renderer/selectionToolbar.html'),
selectionAction: resolve(__dirname, 'src/renderer/selectionAction.html'),
traceWindow: resolve(__dirname, 'src/renderer/traceWindow.html')
traceWindow: resolve(__dirname, 'src/renderer/traceWindow.html'),
migrationV2: resolve(__dirname, 'src/renderer/migrationV2.html')
},
onwarn(warning, warn) {
if (warning.code === 'COMMONJS_VARIABLE_IN_ESM') return

View File

@@ -72,8 +72,9 @@ export default defineConfig([
...oxlint.configs['flat/eslint'],
...oxlint.configs['flat/typescript'],
...oxlint.configs['flat/unicorn'],
// Custom rules should be after oxlint to overwrite
// LoggerService Custom Rules - only apply to src directory
{
// LoggerService Custom Rules - only apply to src directory
files: ['src/**/*.{ts,tsx,js,jsx}'],
ignores: ['src/**/__tests__/**', 'src/**/__mocks__/**', 'src/**/*.test.*', 'src/preload/**'],
rules: {
@@ -87,6 +88,7 @@ export default defineConfig([
]
}
},
// i18n
{
files: ['**/*.{ts,tsx,js,jsx}'],
languageOptions: {
@@ -134,4 +136,25 @@ export default defineConfig([
'i18n/no-template-in-t': 'warn'
}
},
// ui migration
{
// Component Rules - prevent importing antd components when migration completed
files: ['**/*.{ts,tsx,js,jsx}'],
ignores: [],
rules: {
// 'no-restricted-imports': [
// 'error',
// {
// paths: [
// {
// name: 'antd',
// importNames: ['Flex', 'Switch', 'message', 'Button', 'Tooltip'],
// message:
// '❌ Do not import this component from antd. Use our custom components instead: import { ... } from "@cherrystudio/ui"'
// }
// ]
// }
// ]
}
},
])

6
migrations/README.md Normal file
View File

@@ -0,0 +1,6 @@
**THIS DIRECTORY IS NOT FOR RUNTIME USE**
- Using `libsql` as the `sqlite3` driver, and `drizzle` as the ORM and database migration tool
- `migrations/sqlite-drizzle` contains auto-generated migration data. Please **DO NOT** modify it.
- If table structure changes, we should run migrations.
- To generate migrations, use the command `yarn run migrations:generate`

View File

@@ -0,0 +1,7 @@
import { defineConfig } from 'drizzle-kit'
export default defineConfig({
out: './migrations/sqlite-drizzle',
schema: './src/main/data/db/schemas/*',
dialect: 'sqlite',
casing: 'snake_case'
})

View File

@@ -0,0 +1,17 @@
CREATE TABLE `app_state` (
`key` text PRIMARY KEY NOT NULL,
`value` text NOT NULL,
`description` text,
`created_at` integer,
`updated_at` integer
);
--> statement-breakpoint
CREATE TABLE `preference` (
`scope` text NOT NULL,
`key` text NOT NULL,
`value` text,
`created_at` integer,
`updated_at` integer
);
--> statement-breakpoint
CREATE INDEX `scope_name_idx` ON `preference` (`scope`,`key`);

View File

@@ -0,0 +1,114 @@
{
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
},
"dialect": "sqlite",
"enums": {},
"id": "de8009d7-95b9-4f99-99fa-4b8795708f21",
"internal": {
"indexes": {}
},
"prevId": "00000000-0000-0000-0000-000000000000",
"tables": {
"app_state": {
"checkConstraints": {},
"columns": {
"created_at": {
"autoincrement": false,
"name": "created_at",
"notNull": false,
"primaryKey": false,
"type": "integer"
},
"description": {
"autoincrement": false,
"name": "description",
"notNull": false,
"primaryKey": false,
"type": "text"
},
"key": {
"autoincrement": false,
"name": "key",
"notNull": true,
"primaryKey": true,
"type": "text"
},
"updated_at": {
"autoincrement": false,
"name": "updated_at",
"notNull": false,
"primaryKey": false,
"type": "integer"
},
"value": {
"autoincrement": false,
"name": "value",
"notNull": true,
"primaryKey": false,
"type": "text"
}
},
"compositePrimaryKeys": {},
"foreignKeys": {},
"indexes": {},
"name": "app_state",
"uniqueConstraints": {}
},
"preference": {
"checkConstraints": {},
"columns": {
"created_at": {
"autoincrement": false,
"name": "created_at",
"notNull": false,
"primaryKey": false,
"type": "integer"
},
"key": {
"autoincrement": false,
"name": "key",
"notNull": true,
"primaryKey": false,
"type": "text"
},
"scope": {
"autoincrement": false,
"name": "scope",
"notNull": true,
"primaryKey": false,
"type": "text"
},
"updated_at": {
"autoincrement": false,
"name": "updated_at",
"notNull": false,
"primaryKey": false,
"type": "integer"
},
"value": {
"autoincrement": false,
"name": "value",
"notNull": false,
"primaryKey": false,
"type": "text"
}
},
"compositePrimaryKeys": {},
"foreignKeys": {},
"indexes": {
"scope_name_idx": {
"columns": ["scope", "key"],
"isUnique": false,
"name": "scope_name_idx"
}
},
"name": "preference",
"uniqueConstraints": {}
}
},
"version": "6",
"views": {}
}

View File

@@ -0,0 +1,13 @@
{
"dialect": "sqlite",
"entries": [
{
"breakpoints": true,
"idx": 0,
"tag": "0000_solid_lord_hawal",
"version": "6",
"when": 1754745234572
}
],
"version": "7"
}

View File

@@ -1,6 +1,6 @@
{
"name": "CherryStudio",
"version": "1.7.0-rc.1",
"version": "2.0.0-alpha",
"private": true,
"description": "A powerful AI assistant for producer.",
"main": "./out/main/index.js",
@@ -50,9 +50,10 @@
"generate:icons": "electron-icon-builder --input=./build/logo.png --output=build",
"analyze:renderer": "VISUALIZER_RENDERER=true yarn build",
"analyze:main": "VISUALIZER_MAIN=true yarn build",
"typecheck": "concurrently -n \"node,web\" -c \"cyan,magenta\" \"npm run typecheck:node\" \"npm run typecheck:web\"",
"typecheck": "concurrently -n \"node,web,ui\" -c \"cyan,magenta,green\" \"npm run typecheck:node\" \"npm run typecheck:web\" \"npm run typecheck:ui\"",
"typecheck:node": "tsgo --noEmit -p tsconfig.node.json --composite false",
"typecheck:web": "tsgo --noEmit -p tsconfig.web.json --composite false",
"typecheck:ui": "cd packages/ui && npm run type-check",
"check:i18n": "dotenv -e .env -- tsx scripts/check-i18n.ts",
"sync:i18n": "dotenv -e .env -- tsx scripts/sync-i18n.ts",
"update:i18n": "dotenv -e .env -- tsx scripts/update-i18n.ts",
@@ -69,11 +70,13 @@
"test:e2e": "yarn playwright test",
"test:lint": "oxlint --deny-warnings && eslint . --ext .js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --cache",
"test:scripts": "vitest scripts",
"lint": "oxlint --fix && eslint . --ext .js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --cache && yarn typecheck && yarn check:i18n && yarn format:check",
"lint": "oxlint --fix && eslint . --ext .js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --cache && biome lint --write && biome format --write && yarn typecheck && yarn check:i18n && yarn format:check",
"lint:ox": "oxlint --fix && biome lint --write && biome format --write",
"format": "biome format --write && biome lint --write",
"format:check": "biome format && biome lint",
"prepare": "git config blame.ignoreRevsFile .git-blame-ignore-revs && husky",
"claude": "dotenv -e .env -- claude",
"migrations:generate": "drizzle-kit generate --config ./migrations/sqlite-drizzle.config.ts",
"release:aicore:alpha": "yarn workspace @cherrystudio/ai-core version prerelease --preid alpha --immediate && yarn workspace @cherrystudio/ai-core build && yarn workspace @cherrystudio/ai-core npm publish --tag alpha --access public",
"release:aicore:beta": "yarn workspace @cherrystudio/ai-core version prerelease --preid beta --immediate && yarn workspace @cherrystudio/ai-core build && yarn workspace @cherrystudio/ai-core npm publish --tag beta --access public",
"release:aicore": "yarn workspace @cherrystudio/ai-core version patch --immediate && yarn workspace @cherrystudio/ai-core build && yarn workspace @cherrystudio/ai-core npm publish --access public",
@@ -100,6 +103,7 @@
"selection-hook": "^1.0.12",
"sharp": "^0.34.3",
"socket.io": "^4.8.1",
"stream-json": "^1.9.1",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.1",
"tesseract.js": "patch:tesseract.js@npm%3A6.0.1#~/.yarn/patches/tesseract.js-npm-6.0.1-2562a7e46d.patch",
@@ -141,6 +145,7 @@
"@cherrystudio/embedjs-openai": "^0.1.31",
"@cherrystudio/extension-table-plus": "workspace:^",
"@cherrystudio/openai": "^6.9.0",
"@cherrystudio/ui": "workspace:*",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/modifiers": "^9.0.0",
"@dnd-kit/sortable": "^10.0.0",
@@ -155,7 +160,6 @@
"@eslint/js": "^9.22.0",
"@google/genai": "patch:@google/genai@npm%3A1.0.1#~/.yarn/patches/@google-genai-npm-1.0.1-e26f0f9af7.patch",
"@hello-pangea/dnd": "^18.0.1",
"@kangfenmao/keyv-storage": "^0.1.0",
"@langchain/community": "^1.0.0",
"@langchain/core": "patch:@langchain/core@npm%3A1.0.2#~/.yarn/patches/@langchain-core-npm-1.0.2-183ef83fe4.patch",
"@langchain/openai": "patch:@langchain/openai@npm%3A1.0.0#~/.yarn/patches/@langchain-openai-npm-1.0.0-474d0ad9d4.patch",
@@ -221,6 +225,7 @@
"@types/react-infinite-scroll-component": "^5.0.0",
"@types/react-transition-group": "^4.4.12",
"@types/react-window": "^1",
"@types/stream-json": "^1",
"@types/swagger-jsdoc": "^6",
"@types/swagger-ui-express": "^4.1.8",
"@types/tinycolor2": "^1",

View File

@@ -1,8 +1,7 @@
import { anthropic } from '@ai-sdk/anthropic'
import { google } from '@ai-sdk/google'
import { openai } from '@ai-sdk/openai'
import type { InferToolInput, InferToolOutput } from 'ai'
import { type Tool } from 'ai'
import type { InferToolInput, InferToolOutput, Tool } from 'ai'
import { createOpenRouterOptions, createXaiOptions, mergeProviderOptions } from '../../../options'
import type { ProviderOptionsMap } from '../../../options/types'

857
packages/catalog/PLANS.md Normal file
View File

@@ -0,0 +1,857 @@
# 模型和供应商参数化配置实现方案
## 📋 项目概述
本文档描述了在 `@packages/catalog/` 下实现模型和供应商参数化配置的方案,目标是将现有的硬编码逻辑重构为元数据驱动的配置系统。
## 🎯 目标
### 主要目标
- 将硬编码的模型识别逻辑转换为 JSON 配置驱动
- 解决"同一模型在不同供应商下有差异"的问题
- 提供类型安全的配置系统(使用 Zod
- 支持未来通过配置更新添加新模型
### 痛点解决
- **当前问题**`src/renderer/src/config/models/` 下复杂的正则表达式和硬编码逻辑
- **期望状态**:配置以 JSON 形式存在,代码中使用 Zod Schema 验证
- **可维护性**:新模型发布时只需更新 JSON 配置,无需修改代码
## 🏗️ 架构设计
### 三层分离的元数据架构
```
1. Base Model Catalog (models/*.json)
├─ 模型基础信息ID、能力、模态、限制、价格
└─ 官方/标准配置
2. Provider Catalog (providers/*.json)
├─ 供应商特性端点支持、API 兼容性)
└─ 认证和定价模型
3. Provider Model Overrides (overrides/*.json)
├─ 供应商对特定模型的覆盖
└─ 解决"同一模型不同供应商差异"问题
```
### 简化后的文件结构
```
packages/catalog/
├── src/
│ ├── index.ts # 主导出文件
│ ├── schemas/ # Schema 定义
│ │ ├── index.ts # 统一导出
│ │ ├── model.schema.ts # 模型配置 Schema + Zod
│ │ ├── provider.schema.ts # 供应商配置 Schema + Zod
│ │ └── override.schema.ts # 覆盖配置 Schema + Zod
│ ├── data/ # 配置数据(单文件存储)
│ │ ├── models.json # 所有模型配置
│ │ ├── providers.json # 所有供应商配置
│ │ └── overrides.json # 所有覆盖配置
│ ├── services/ # 核心服务
│ │ ├── CatalogService.ts # 统一的目录服务
│ │ └── ConfigLoader.ts # 配置加载 + 验证
│ ├── utils/ # 工具函数
│ │ ├── migrate.ts # 迁移工具(从旧代码提取配置)
│ │ └── helpers.ts # 辅助函数
│ └── __tests__/ # 测试文件
│ ├── fixtures/ # 测试数据
│ ├── schemas.test.ts # Schema 测试
│ └── catalog.test.ts # 目录服务测试
├── scripts/
│ └── migrate.ts # 迁移脚本 CLI
└── package.json
```
## 📝 Schema 定义
### 1. 模型配置 Schema
```typescript
// packages/catalog/src/schemas/model.schema.ts
import * as z from 'zod'
import { EndpointTypeSchema } from './provider.schema'
// 模态类型
export const ModalitySchema = z.enum(['TEXT', 'VISION', 'AUDIO', 'VIDEO', 'VECTOR'])
// 能力类型
export const ModelCapabilityTypeSchema = z.enum([
'FUNCTION_CALL', // 函数调用
'REASONING', // 推理
'IMAGE_RECOGNITION', // 图像识别
'IMAGE_GENERATION', // 图像生成
'AUDIO_RECOGNITION', // 音频识别
'AUDIO_GENERATION', // 音频生成
'EMBEDDING', // 嵌入向量生成
'RERANK', // 文本重排序
'AUDIO_TRANSCRIPT', // 音频转录
'VIDEO_RECOGNITION', // 视频识别
'VIDEO_GENERATION', // 视频生成
'STRUCTURED_OUTPUT', // 结构化输出
'FILE_INPUT', // 文件输入支持
'WEB_SEARCH', // 内置网络搜索
'CODE_EXECUTION', // 代码执行
'FILE_SEARCH', // 文件搜索
'COMPUTER_USE' // 计算机使用
])
// 推理配置
export const ReasoningConfigSchema = z.object({
supportedEfforts: z.array(z.enum(['low', 'medium', 'high'])),
implementation: z.enum(['OPENAI_O1', 'ANTHROPIC_CLAUDE', 'DEEPSEEK_R1', 'GEMINI_THINKING']),
reasoningMode: z.enum(['ALWAYS_ON', 'ON_DEMAND']),
thinkingControl: z.object({
enabled: z.boolean(),
budget: z.object({
min: z.number().optional(),
max: z.number().optional()
}).optional()
}).optional()
})
// 参数支持配置
export const ParameterSupportSchema = z.object({
temperature: z.object({
supported: z.boolean(),
min: z.number().min(0).max(2).optional(),
max: z.number().min(0).max(2).optional(),
default: z.number().min(0).max(2).optional()
}).optional(),
topP: z.object({
supported: z.boolean(),
min: z.number().min(0).max(1).optional(),
max: z.number().min(0).max(1).optional(),
default: z.number().min(0).max(1).optional()
}).optional(),
topK: z.object({
supported: z.boolean(),
min: z.number().positive().optional(),
max: z.number().positive().optional()
}).optional(),
frequencyPenalty: z.boolean().optional(),
presencePenalty: z.boolean().optional(),
maxTokens: z.boolean().optional(),
stopSequences: z.boolean().optional(),
systemMessage: z.boolean().optional(),
developerRole: z.boolean().optional()
})
// 定价配置
export const ModelPricingSchema = z.object({
input: z.object({
perMillionTokens: z.number(),
currency: z.string().default('USD')
}),
output: z.object({
perMillionTokens: z.number(),
currency: z.string().default('USD')
}),
perImage: z.object({
price: z.number(),
currency: z.string().default('USD')
}).optional(),
perMinute: z.object({
price: z.number(),
currency: z.string().default('USD')
}).optional()
})
// 模型配置 Schema
export const ModelConfigSchema = z.object({
// 基础信息
id: z.string(),
name: z.string().optional(),
ownedBy: z.string().optional(),
description: z.string().optional(),
// 能力(核心)
capabilities: z.array(ModelCapabilityTypeSchema),
// 模态
inputModalities: z.array(ModalitySchema),
outputModalities: z.array(ModalitySchema),
// 限制
contextWindow: z.number(),
maxOutputTokens: z.number(),
maxInputTokens: z.number().optional(),
// 价格
pricing: ModelPricingSchema.optional(),
// 推理配置
reasoning: ReasoningConfigSchema.optional(),
// 参数支持
parameters: ParameterSupportSchema.optional(),
// 端点类型
endpointTypes: z.array(EndpointTypeSchema).optional(),
// 元数据
releaseDate: z.string().optional(),
deprecationDate: z.string().optional(),
replacedBy: z.string().optional()
})
export type ModelConfig = z.infer<typeof ModelConfigSchema>
```
### 2. 供应商配置 Schema简化版
```typescript
// packages/catalog/src/schemas/provider.schema.ts
import * as z from 'zod'
// 端点类型
export const EndpointTypeSchema = z.enum([
'CHAT_COMPLETIONS',
'COMPLETIONS',
'EMBEDDINGS',
'IMAGE_GENERATION',
'AUDIO_SPEECH',
'AUDIO_TRANSCRIPTIONS',
'MESSAGES',
'GENERATE_CONTENT',
'RERANK',
'MODERATIONS'
])
// 认证方式
export const AuthenticationSchema = z.enum([
'API_KEY',
'OAUTH',
'CLOUD_CREDENTIALS'
])
// 定价模型
export const PricingModelSchema = z.enum([
'UNIFIED', // 统一定价 (如 OpenRouter)
'PER_MODEL', // 按模型独立定价 (如 OpenAI 官方)
'TRANSPARENT', // 透明定价 (如 New-API)
])
// 模型路由策略
export const ModelRoutingSchema = z.enum([
'INTELLIGENT', // 智能路由
'DIRECT', // 直接路由
'LOAD_BALANCED', // 负载均衡
])
// API 兼容性配置
export const ApiCompatibilitySchema = z.object({
supportsArrayContent: z.boolean().default(true),
supportsStreamOptions: z.boolean().default(true),
supportsDeveloperRole: z.boolean().default(false),
supportsThinkingControl: z.boolean().default(false),
supportsParallelTools: z.boolean().default(false),
supportsMultimodal: z.boolean().default(false),
maxFileUploadSize: z.number().optional(),
supportedFileTypes: z.array(z.string()).optional()
})
// 供应商能力(简化版 - 使用数组代替多个布尔字段)
export const ProviderCapabilitySchema = z.enum([
'CUSTOM_MODELS', // 支持自定义模型
'MODEL_MAPPING', // 提供模型映射
'FALLBACK_ROUTING', // 降级路由
'AUTO_RETRY', // 自动重试
'REAL_TIME_METRICS', // 实时指标
'USAGE_ANALYTICS', // 使用分析
'STREAMING', // 流式响应
'BATCH_PROCESSING', // 批量处理
'RATE_LIMITING', // 速率限制
])
// 供应商配置 Schema简化版
export const ProviderConfigSchema = z.object({
// 基础信息
id: z.string(),
name: z.string(),
description: z.string().optional(),
// 核心配置
authentication: AuthenticationSchema,
pricingModel: PricingModelSchema,
modelRouting: ModelRoutingSchema,
// 能力(使用数组替代多个布尔字段)
capabilities: z.array(ProviderCapabilitySchema).default([]),
// 功能支持
supportedEndpoints: z.array(EndpointTypeSchema),
apiCompatibility: ApiCompatibilitySchema.optional(),
// 默认配置
defaultApiHost: z.string().optional(),
defaultRateLimit: z.number().optional(),
// 模型匹配
modelIdPatterns: z.array(z.string()).optional(),
aliasModelIds: z.record(z.string()).optional(),
// 元数据
documentation: z.string().url().optional(),
statusPage: z.string().url().optional(),
// 状态
deprecated: z.boolean().default(false)
})
export type ProviderConfig = z.infer<typeof ProviderConfigSchema>
```
### 3. 覆盖配置 Schema
```typescript
// packages/catalog/src/schemas/override.schema.ts
import * as z from 'zod'
import { ModelCapabilityTypeSchema, ModelPricingSchema, ParameterSupportSchema } from './model.schema'
export const ProviderModelOverrideSchema = z.object({
providerId: z.string(),
modelId: z.string(),
// 能力覆盖
capabilities: z.object({
add: z.array(ModelCapabilityTypeSchema).optional(),
remove: z.array(ModelCapabilityTypeSchema).optional()
}).optional(),
// 限制覆盖
limits: z.object({
contextWindow: z.number().optional(),
maxOutputTokens: z.number().optional()
}).optional(),
// 价格覆盖
pricing: ModelPricingSchema.optional(),
// 参数支持覆盖
parameters: ParameterSupportSchema.optional(),
// 禁用模型
disabled: z.boolean().optional(),
// 覆盖原因
reason: z.string().optional()
})
export type ProviderModelOverride = z.infer<typeof ProviderModelOverrideSchema>
```
## 🔧 核心 API 设计
### 统一的目录服务
```typescript
// packages/catalog/src/services/CatalogService.ts
export interface ModelFilters {
capabilities?: ModelCapabilityType[]
inputModalities?: Modality[]
providers?: string[]
minContextWindow?: number
}
export interface ProviderFilter {
capabilities?: ProviderCapability[]
authentication?: AuthenticationSchema
pricingModel?: PricingModelSchema
notDeprecated?: boolean
}
export class CatalogService {
private models: Map<string, ModelConfig>
private providers: Map<string, ProviderConfig>
private overrides: Map<string, ProviderModelOverride[]>
// === 模型查询 ===
/**
* 获取模型配置(应用供应商覆盖)
*/
getModel(modelId: string, providerId?: string): ModelConfig | null
/**
* 检查模型能力
*/
hasCapability(modelId: string, capability: ModelCapabilityType, providerId?: string): boolean
/**
* 获取模型的推理配置
*/
getReasoningConfig(modelId: string, providerId?: string): ReasoningConfig | null
/**
* 获取模型参数范围
*/
getParameterRange(
modelId: string,
parameter: 'temperature' | 'topP' | 'topK',
providerId?: string
): { min: number, max: number, default?: number } | null
/**
* 批量匹配模型
*/
findModels(filters?: ModelFilters): ModelConfig[]
// === 供应商查询 ===
/**
* 获取供应商配置
*/
getProvider(providerId: string): ProviderConfig | null
/**
* 检查供应商能力
*/
hasProviderCapability(providerId: string, capability: ProviderCapability): boolean
/**
* 检查端点支持
*/
supportsEndpoint(providerId: string, endpoint: EndpointType): boolean
/**
* 查找供应商
*/
findProviders(filter?: ProviderFilter): ProviderConfig[]
// === 内部方法 ===
/**
* 应用覆盖配置
*/
private applyOverrides(model: ModelConfig, providerId: string): ModelConfig
}
// 统一导出
export const catalog = new CatalogService()
// 向后兼容的辅助函数
export const isFunctionCallingModel = (model: Model): boolean =>
catalog.hasCapability(model.id, 'FUNCTION_CALL', model.provider)
export const isReasoningModel = (model: Model): boolean =>
catalog.hasCapability(model.id, 'REASONING', model.provider)
export const isVisionModel = (model: Model): boolean =>
catalog.hasCapability(model.id, 'IMAGE_RECOGNITION', model.provider)
```
## 📊 JSON 配置示例
### 模型配置示例
```json
// packages/catalog/src/data/models.json
{
"version": "2025.11.24",
"models": [
{
"id": "claude-3-5-sonnet-20241022",
"name": "Claude 3.5 Sonnet",
"owned_by": "anthropic",
"capabilities": [
"FUNCTION_CALL",
"REASONING",
"IMAGE_RECOGNITION",
"STRUCTURED_OUTPUT",
"FILE_INPUT"
],
"input_modalities": ["TEXT", "VISION"],
"output_modalities": ["TEXT"],
"context_window": 200000,
"max_output_tokens": 8192,
"pricing": {
"input": { "per_million_tokens": 3.0, "currency": "USD" },
"output": { "per_million_tokens": 15.0, "currency": "USD" }
},
"reasoning": {
"type": "anthropic",
"params": {
"type": "enabled",
"budgetTokens": 10000
}
},
"parameters": {
"temperature": {
"supported": true,
"min": 0.0,
"max": 1.0,
"default": 1.0
}
},
"metadata": {}
},
{
"id": "gpt-4-turbo",
"name": "GPT-4 Turbo",
"owned_by": "openai",
"capabilities": [
"FUNCTION_CALL",
"IMAGE_RECOGNITION",
"STRUCTURED_OUTPUT"
],
"input_modalities": ["TEXT", "VISION"],
"output_modalities": ["TEXT"],
"context_window": 128000,
"max_output_tokens": 4096,
"pricing": {
"input": { "per_million_tokens": 10.0, "currency": "USD" },
"output": { "per_million_tokens": 30.0, "currency": "USD" }
},
"metadata": {}
}
]
}
```
### 供应商配置示例
```json
// packages/catalog/src/data/providers.json
{
"version": "2025.11.24",
"providers": [
{
"id": "anthropic",
"name": "Anthropic",
"authentication": "API_KEY",
"pricing_model": "PER_MODEL",
"model_routing": "DIRECT",
"behaviors": {
"supports_custom_models": false,
"provides_model_mapping": false,
"supports_streaming": true,
"has_real_time_metrics": true,
"supports_rate_limiting": true,
"provides_usage_analytics": true,
"requires_api_key_validation": true
},
"supported_endpoints": ["MESSAGES"],
"api_compatibility": {
"supports_stream_options": true,
"supports_parallel_tools": true,
"supports_multimodal": true
},
"default_api_host": "https://api.anthropic.com",
"deprecated": false,
"maintenance_mode": false,
"config_version": "1.0.0",
"special_config": {},
"metadata": {}
},
{
"id": "openrouter",
"name": "OpenRouter",
"authentication": "API_KEY",
"pricing_model": "UNIFIED",
"model_routing": "INTELLIGENT",
"behaviors": {
"supports_custom_models": true,
"provides_model_mapping": true,
"provides_fallback_routing": true,
"has_auto_retry": true,
"supports_streaming": true,
"has_real_time_metrics": true
},
"supported_endpoints": ["CHAT_COMPLETIONS"],
"default_api_host": "https://openrouter.ai/api/v1",
"deprecated": false,
"maintenance_mode": false,
"config_version": "1.0.0",
"special_config": {},
"metadata": {}
}
]
}
```
### 覆盖配置示例
```json
// packages/catalog/src/data/overrides.json
{
"version": "2025.11.24",
"overrides": [
{
"provider_id": "openrouter",
"model_id": "claude-3-5-sonnet-20241022",
"pricing": {
"input": { "per_million_tokens": 4.5, "currency": "USD" },
"output": { "per_million_tokens": 22.5, "currency": "USD" }
},
"capabilities": {
"add": ["WEB_SEARCH"]
},
"reason": "OpenRouter applies markup and adds web search",
"priority": 0
},
{
"provider_id": "openrouter",
"model_id": "gpt-4-turbo",
"limits": {
"context_window": 128000,
"max_output_tokens": 16384
},
"reason": "OpenRouter extends output token limit",
"priority": 0
}
]
}
```
## 🔄 实现计划
### Phase 1: 基础架构 (2-3 days)
**目标**:建立核心架构和类型系统
**任务**
1. **Schema 定义**
- 实现 `model.schema.ts``provider.schema.ts``override.schema.ts`
- 所有 Schema 使用 Zod 验证
- 导出 TypeScript 类型
2. **配置加载器**
```typescript
// packages/catalog/src/services/ConfigLoader.ts
export class ConfigLoader {
loadModels(): ModelConfig[]
loadProviders(): ProviderConfig[]
loadOverrides(): ProviderModelOverride[]
validate(): boolean
}
```
3. **目录服务**
```typescript
// packages/catalog/src/services/CatalogService.ts
export class CatalogService {
// 实现所有查询 API
}
```
**验收标准**
- ✅ 所有 Schema 定义完成,通过 Zod 验证
- ✅ ConfigLoader 可以加载和验证 JSON 文件
- ✅ CatalogService 基础 API 实现
- ✅ 单元测试覆盖核心功能
### Phase 2: 数据迁移 (1-2 days)
**目标**:从现有硬编码逻辑生成 JSON 配置
**任务**
1. **迁移工具**
```typescript
// packages/catalog/src/utils/migrate.ts
export class MigrationTool {
// 从 src/renderer/src/config/models/ 提取模型配置
extractModelConfigs(): ModelConfig[]
// 提取供应商配置
extractProviderConfigs(): ProviderConfig[]
// 写入 JSON 文件
writeConfigs(models: ModelConfig[], providers: ProviderConfig[]): void
// 简单验证
validate(): boolean
}
```
2. **迁移脚本**
```bash
# 运行迁移
yarn catalog:migrate
```
3. **手动审核**
- 检查生成的配置文件
- 补充缺失的价格和限制信息
- 调整不准确的能力定义
**验收标准**
- ✅ 迁移工具能够提取现有配置
- ✅ 生成的配置通过 Schema 验证
- ✅ 手动审核完成,配置准确
### Phase 3: 集成替换 (2-3 days)
**目标**:替换现有硬编码逻辑
**任务**
1. **向后兼容层**
```typescript
// packages/catalog/src/index.ts
export const isFunctionCallingModel = (model: Model): boolean =>
catalog.hasCapability(model.id, 'FUNCTION_CALL', model.provider)
```
2. **逐步替换**
- 替换 `src/renderer/src/config/models/` 中的函数
- 更新所有调用点
- 确保测试通过
3. **集成测试**
- 端到端测试
- 性能测试
- 兼容性测试
**验收标准**
- ✅ 所有现有测试通过
- ✅ 新配置系统与旧系统行为一致
- ✅ 性能不低于原有实现
### 延迟实现 ⏸️
以下功能在初期版本不实现,等待实际需求:
- ⏸️ **在线配置更新**:等到有用户需求再实现
- ⏸️ **复杂缓存机制**:等出现性能问题再优化
- ⏸️ **配置版本控制**:简化为文件级别的版本号
## 🧪 测试策略
### 测试覆盖
1. **Schema 测试**
```typescript
describe('ModelConfig Schema', () => {
it('validates correct config', () => {
expect(() => ModelConfigSchema.parse(validConfig)).not.toThrow()
})
it('rejects invalid config', () => {
expect(() => ModelConfigSchema.parse(invalidConfig)).toThrow()
})
})
```
2. **服务测试**
```typescript
describe('CatalogService', () => {
it('returns model with overrides applied', () => {
const model = catalog.getModel('claude-3-5-sonnet', 'openrouter')
expect(model?.pricing).toEqual(expectedPricing)
})
it('checks capabilities correctly', () => {
expect(catalog.hasCapability('gpt-4', 'FUNCTION_CALL')).toBe(true)
})
})
```
3. **兼容性测试**
```typescript
describe('Backward Compatibility', () => {
it('produces same results as legacy', () => {
expect(isFunctionCallingModel(testModel)).toBe(legacyResult)
})
})
```
## 📖 使用指南
### 基本用法
```typescript
import { catalog } from '@cherrystudio/catalog'
// 检查模型能力
const canCallFunctions = catalog.hasCapability('gpt-4', 'FUNCTION_CALL')
const canReason = catalog.hasCapability('o1-preview', 'REASONING')
// 获取模型配置
const modelConfig = catalog.getModel('claude-3-5-sonnet', 'openrouter')
// 查找模型
const visionModels = catalog.findModels({
capabilities: ['IMAGE_RECOGNITION'],
providers: ['anthropic', 'openai']
})
// 检查供应商能力
const hasMapping = catalog.hasProviderCapability('openrouter', 'MODEL_MAPPING')
```
### 供应商查询
```typescript
// 查找具有特定能力的供应商
const providersWithFallback = catalog.findProviders({
capabilities: ['FALLBACK_ROUTING', 'AUTO_RETRY']
})
// 查找统一定价的供应商
const unifiedPricingProviders = catalog.findProviders({
pricingModel: 'UNIFIED'
})
```
## 📝 维护指南
### 添加新模型
1. 编辑对应的模型配置文件
2. 添加模型信息
3. 运行验证:`yarn catalog:validate`
4. 提交 PR
### 添加新供应商
1. 编辑 `providers.json`
2. 添加供应商配置
3. 如需覆盖,添加到 `overrides.json`
4. 验证并提交
## 🔧 开发工具
### 命令行
```json
{
"scripts": {
"catalog:validate": "tsx scripts/validate.ts",
"catalog:migrate": "tsx scripts/migrate.ts",
"catalog:test": "vitest run",
"catalog:build": "tsdown"
}
}
```
## 📚 迁移对照表
| 旧函数 | 新 API |
|--------|--------|
| `isFunctionCallingModel(model)` | `catalog.hasCapability(model.id, 'FUNCTION_CALL', model.provider)` |
| `isReasoningModel(model)` | `catalog.hasCapability(model.id, 'REASONING', model.provider)` |
| `isVisionModel(model)` | `catalog.hasCapability(model.id, 'IMAGE_RECOGNITION', model.provider)` |
| `getThinkModelType(model)` | `catalog.getReasoningConfig(model.id, model.provider)` |
## 📊 预期成果
### 时间估算
- Phase 1: 2-3 天
- Phase 2: 1-2 天
- Phase 3: 2-3 天
- **总计**: 5-8 天
### 性能目标
- 配置加载时间: < 100ms
- 模型查询时间: < 1ms
- 内存使用: < 50MB
---
这个简化方案专注于核心功能避免过度设计遵循"保持简洁"的原则为未来扩展留有空间

View File

@@ -0,0 +1 @@
# catalog

View File

@@ -0,0 +1,627 @@
{
"openapi": "3.0.3",
"info": {
"title": "Cherry Studio Catalog API",
"description": "REST API for managing AI models and providers catalog",
"version": "1.0.0",
"contact": {
"name": "Cherry Studio Team"
}
},
"servers": [
{
"url": "http://localhost:3000/api",
"description": "Development server"
}
],
"paths": {
"/catalog/models": {
"get": {
"summary": "List models with pagination and filtering",
"parameters": [
{
"name": "page",
"in": "query",
"schema": {
"type": "integer",
"minimum": 1,
"default": 1
}
},
{
"name": "limit",
"in": "query",
"schema": {
"type": "integer",
"minimum": 1,
"maximum": 100,
"default": 20
}
},
{
"name": "search",
"in": "query",
"schema": {
"type": "string"
}
},
{
"name": "capabilities",
"in": "query",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
},
{
"name": "providers",
"in": "query",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
],
"responses": {
"200": {
"description": "Paginated list of models",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PaginatedModels"
}
}
}
}
}
},
"put": {
"summary": "Update models configuration",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ModelsConfig"
}
}
}
},
"responses": {
"200": {
"description": "Models updated successfully"
}
}
}
},
"/catalog/models/{modelId}": {
"get": {
"summary": "Get specific model details",
"parameters": [
{
"name": "modelId",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Model details",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Model"
}
}
}
}
}
},
"put": {
"summary": "Update specific model",
"parameters": [
{
"name": "modelId",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Model"
}
}
}
},
"responses": {
"200": {
"description": "Model updated successfully"
}
}
}
},
"/catalog/providers": {
"get": {
"summary": "List providers with pagination and filtering",
"parameters": [
{
"name": "page",
"in": "query",
"schema": {
"type": "integer",
"minimum": 1,
"default": 1
}
},
{
"name": "limit",
"in": "query",
"schema": {
"type": "integer",
"minimum": 1,
"maximum": 100,
"default": 20
}
},
{
"name": "search",
"in": "query",
"schema": {
"type": "string"
}
},
{
"name": "authentication",
"in": "query",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
],
"responses": {
"200": {
"description": "Paginated list of providers",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PaginatedProviders"
}
}
}
}
}
},
"put": {
"summary": "Update providers configuration",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProvidersConfig"
}
}
}
},
"responses": {
"200": {
"description": "Providers updated successfully"
}
}
}
},
"/catalog/providers/{providerId}": {
"get": {
"summary": "Get specific provider details",
"parameters": [
{
"name": "providerId",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Provider details",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Provider"
}
}
}
}
}
}
},
"/catalog/models/{modelId}/overrides": {
"get": {
"summary": "Get provider-specific overrides for a model",
"parameters": [
{
"name": "modelId",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Provider overrides for the model",
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": {
"$ref": "#/components/schemas/Model"
}
}
}
}
}
}
}
},
"/catalog/models/{modelId}/providers/{providerId}": {
"get": {
"summary": "Get model configuration as seen by specific provider",
"parameters": [
{
"name": "modelId",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "providerId",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Model configuration with provider-specific overrides applied",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Model"
}
}
}
}
}
},
"put": {
"summary": "Update model configuration for specific provider (auto-detects if override is needed)",
"parameters": [
{
"name": "modelId",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "providerId",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Model"
}
}
}
},
"responses": {
"200": {
"description": "Model configuration updated (override created/updated if needed)",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"updated": {
"type": "string",
"enum": ["base_model", "override", "both"]
},
"model": {
"$ref": "#/components/schemas/Model"
}
}
}
}
}
}
}
}
},
"/catalog/stats": {
"get": {
"summary": "Get catalog statistics",
"responses": {
"200": {
"description": "Catalog statistics",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/CatalogStats"
}
}
}
}
}
}
},
"/catalog/validate": {
"post": {
"summary": "Validate catalog configuration",
"responses": {
"200": {
"description": "Validation results",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ValidationResult"
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"Model": {
"type": "object",
"properties": {
"id": { "type": "string" },
"name": { "type": "string" },
"owned_by": { "type": "string" },
"capabilities": {
"type": "array",
"items": { "type": "string" }
},
"input_modalities": {
"type": "array",
"items": { "type": "string" }
},
"output_modalities": {
"type": "array",
"items": { "type": "string" }
},
"context_window": { "type": "integer" },
"max_output_tokens": { "type": "integer" },
"max_input_tokens": { "type": "integer" },
"pricing": {
"$ref": "#/components/schemas/Pricing"
},
"parameters": {
"$ref": "#/components/schemas/Parameters"
},
"endpoint_types": {
"type": "array",
"items": { "type": "string" }
},
"metadata": { "type": "object" }
}
},
"Provider": {
"type": "object",
"properties": {
"id": { "type": "string" },
"name": { "type": "string" },
"description": { "type": "string" },
"authentication": { "type": "string" },
"pricing_model": { "type": "string" },
"model_routing": { "type": "string" },
"behaviors": { "type": "object" },
"supported_endpoints": {
"type": "array",
"items": { "type": "string" }
},
"api_compatibility": { "type": "object" },
"special_config": { "type": "object" },
"documentation": { "type": "string" },
"website": { "type": "string" },
"deprecated": { "type": "boolean" },
"maintenance_mode": { "type": "boolean" },
"config_version": { "type": "string" },
"metadata": { "type": "object" }
}
},
"Override": {
"type": "object",
"properties": {
"provider_id": { "type": "string" },
"model_id": { "type": "string" },
"disabled": { "type": "boolean" },
"reason": { "type": "string" },
"last_updated": { "type": "string" },
"updated_by": { "type": "string" },
"priority": { "type": "integer" },
"limits": {
"type": "object",
"properties": {
"context_window": { "type": "integer" },
"max_output_tokens": { "type": "integer" }
}
},
"pricing": {
"$ref": "#/components/schemas/Pricing"
}
}
},
"Pricing": {
"type": "object",
"properties": {
"input": {
"type": "object",
"properties": {
"per_million_tokens": { "type": "number" },
"currency": { "type": "string" }
}
},
"output": {
"type": "object",
"properties": {
"per_million_tokens": { "type": "number" },
"currency": { "type": "string" }
}
}
}
},
"Parameters": {
"type": "object",
"additionalProperties": true
},
"PaginatedModels": {
"type": "object",
"properties": {
"data": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Model"
}
},
"pagination": {
"$ref": "#/components/schemas/Pagination"
}
}
},
"PaginatedProviders": {
"type": "object",
"properties": {
"data": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Provider"
}
},
"pagination": {
"$ref": "#/components/schemas/Pagination"
}
}
},
"PaginatedOverrides": {
"type": "object",
"properties": {
"data": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Override"
}
},
"pagination": {
"$ref": "#/components/schemas/Pagination"
}
}
},
"Pagination": {
"type": "object",
"properties": {
"page": { "type": "integer" },
"limit": { "type": "integer" },
"total": { "type": "integer" },
"totalPages": { "type": "integer" }
}
},
"ModelsConfig": {
"type": "object",
"properties": {
"version": { "type": "string" },
"models": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Model"
}
}
}
},
"ProvidersConfig": {
"type": "object",
"properties": {
"version": { "type": "string" },
"providers": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Provider"
}
}
}
},
"OverridesConfig": {
"type": "object",
"properties": {
"version": { "type": "string" },
"overrides": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Override"
}
}
}
},
"CatalogStats": {
"type": "object",
"properties": {
"total_models": { "type": "integer" },
"total_providers": { "type": "integer" },
"total_overrides": { "type": "integer" },
"models_by_provider": { "type": "object" },
"overrides_by_provider": { "type": "object" },
"last_updated": { "type": "string" }
}
},
"ValidationResult": {
"type": "object",
"properties": {
"valid": { "type": "boolean" },
"errors": {
"type": "array",
"items": { "type": "string" }
},
"warnings": {
"type": "array",
"items": { "type": "string" }
}
}
}
}
}
}

View File

@@ -0,0 +1,88 @@
{
"timestamp": "2025-11-24T06:41:03.487Z",
"summary": {
"total_providers": 104,
"total_base_models": 241,
"total_overrides": 1164,
"provider_categories": {
"direct": 2,
"cloud": 6,
"proxy": 3,
"self_hosted": 5
},
"models_by_provider": {
"openai": 79,
"anthropic": 20,
"dashscope": 22,
"deepseek": 7,
"gemini": 50,
"mistral": 31,
"xai": 32
},
"overrides_by_provider": {
"bedrock": 152,
"bedrock_converse": 56,
"anyscale": 12,
"azure": 112,
"azure_ai": 45,
"cerebras": 5,
"vertex_ai-chat-models": 5,
"nlp_cloud": 1,
"cloudflare": 4,
"vertex_ai-code-text-models": 1,
"vertex_ai-code-chat-models": 6,
"codestral": 2,
"cohere_chat": 7,
"databricks": 9,
"deepinfra": 67,
"featherless_ai": 2,
"fireworks_ai": 27,
"friendliai": 2,
"openai": 8,
"vertex_ai-language-models": 46,
"vertex_ai-vision-models": 3,
"gradient_ai": 13,
"groq": 27,
"heroku": 4,
"hyperbolic": 16,
"ai21": 9,
"lambda_ai": 20,
"lemonade": 5,
"aleph_alpha": 3,
"meta_llama": 4,
"moonshot": 17,
"morph": 2,
"nscale": 14,
"oci": 13,
"ollama": 21,
"openrouter": 92,
"ovhcloud": 15,
"palm": 2,
"perplexity": 25,
"replicate": 13,
"sagemaker": 3,
"sambanova": 16,
"snowflake": 24,
"together_ai": 36,
"v0": 3,
"vercel_ai_gateway": 85,
"vertex_ai-anthropic_models": 22,
"vertex_ai-mistral_models": 19,
"vertex_ai-deepseek_models": 2,
"vertex_ai": 1,
"vertex_ai-ai21_models": 5,
"vertex_ai-llama_models": 11,
"vertex_ai-minimax_models": 1,
"vertex_ai-moonshot_models": 1,
"vertex_ai-openai_models": 2,
"vertex_ai-qwen_models": 4,
"wandb": 14,
"watsonx": 28
}
},
"files": {
"providers": "providers.json",
"models": "models.json",
"overrides": "overrides.json"
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,54 @@
{
"name": "@cherrystudio/catalog",
"version": "0.0.1-alpha.1",
"description": "All Model Catalog",
"main": "dist/index.js",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"packageManager": "yarn@4.9.1",
"scripts": {
"build": "tsdown",
"dev": "tsc -w",
"clean": "rm -rf dist",
"test": "vitest run",
"test:watch": "vitest"
},
"author": "Cherry Studio",
"license": "MIT",
"files": [
"dist/**/*"
],
"repository": {
"type": "git",
"url": "git+https://github.com/CherryHQ/cherry-studio.git"
},
"bugs": {
"url": "https://github.com/CherryHQ/cherry-studio/issues"
},
"homepage": "https://github.com/CherryHQ/cherry-studio#readme",
"exports": {
".": {
"types": "./dist/index.d.ts",
"react-native": "./dist/index.js",
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"default": "./dist/index.js"
}
},
"devDependencies": {
"@types/json-schema": "^7.0.15",
"tsdown": "^0.16.6",
"typescript": "^5.9.3",
"vitest": "^4.0.13",
"zod": "^4.1.12"
},
"peerDependencies": {
"zod": "^4.1.12"
},
"dependencies": {
"json-schema": "^0.4.0"
},
"workspaces": [
"web"
]
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,39 @@
#!/usr/bin/env tsx
/**
* Migration Script - Phase 2 Implementation
* Usage: npx tsx migrate.ts
*/
import * as path from 'path'
import { MigrationTool } from '../src/utils/migration'
async function main() {
const packageRoot = path.resolve(__dirname, '..')
const sourceDir = packageRoot
const outputDir = path.join(packageRoot, 'data')
console.log('🔧 Cherry Studio Catalog Migration - Phase 2')
console.log('==========================================')
console.log(`📁 Source: ${sourceDir}`)
console.log(`📁 Output: ${outputDir}`)
console.log('')
const tool = new MigrationTool(
path.join(sourceDir, 'provider_endpoints_support.json'),
path.join(sourceDir, 'model_prices_and_context_window.json'),
outputDir
)
try {
await tool.migrate()
console.log('')
console.log('🎉 Migration completed! Check the src/data/ directory for results.')
} catch (error) {
console.error('❌ Migration failed:', error)
process.exit(1)
}
}
main()

View File

@@ -0,0 +1,240 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`Config & Schema > Snapshot Tests > should snapshot complete configuration structure 1`] = `
{
"models": Any<Array>,
"overrides": Any<Array>,
"providers": Any<Array>,
}
`;
exports[`Config & Schema > Snapshot Tests > should snapshot model configurations 1`] = `
[
{
"capabilities": [
"FUNCTION_CALL",
"REASONING",
],
"contextWindow": 128000,
"description": "A test model for unit testing",
"endpointTypes": [
"CHAT_COMPLETIONS",
],
"id": "test-model",
"inputModalities": [
"TEXT",
],
"maxInputTokens": 124000,
"maxOutputTokens": 4096,
"metadata": {
"architecture": "transformer",
"category": "language-model",
"documentation": "https://docs.test.com/models/test-model",
"family": "test-family",
"license": "mit",
"source": "test",
"tags": [
"test",
"fast",
"reliable",
],
"trainingData": "synthetic",
},
"name": "Test Model",
"outputModalities": [
"TEXT",
],
"ownedBy": "TestProvider",
"parameters": {
"maxTokens": true,
"systemMessage": true,
"temperature": {
"default": 1,
"max": 2,
"min": 0,
"supported": true,
},
"topP": {
"default": 1,
"max": 1,
"min": 0,
"supported": true,
},
},
"pricing": {
"input": {
"currency": "USD",
"perMillionTokens": 1,
},
"output": {
"currency": "USD",
"perMillionTokens": 2,
},
},
},
]
`;
exports[`Config & Schema > Snapshot Tests > should snapshot override configurations 1`] = `
[
{
"capabilities": {
"add": [
"FUNCTION_CALL",
],
"remove": [
"REASONING",
],
},
"disabled": false,
"lastUpdated": "2025-11-24T07:08:00Z",
"limits": {
"contextWindow": 256000,
"maxOutputTokens": 8192,
},
"modelId": "test-model",
"pricing": {
"input": {
"currency": "USD",
"perMillionTokens": 0.5,
},
},
"priority": 100,
"providerId": "test-provider",
"reason": "Test override for enhanced capabilities and limits",
"updatedBy": "test-suite",
},
]
`;
exports[`Config & Schema > Snapshot Tests > should snapshot provider configurations 1`] = `
[
{
"apiCompatibility": {
"supportsApiVersion": false,
"supportsArrayContent": true,
"supportsDeveloperRole": false,
"supportsMultimodal": false,
"supportsParallelTools": false,
"supportsServiceTier": false,
"supportsStreamOptions": false,
"supportsThinkingControl": false,
},
"authentication": "API_KEY",
"behaviors": {
"hasAutoRetry": false,
"hasRealTimeMetrics": false,
"providesFallbackRouting": false,
"providesModelMapping": false,
"providesUsageAnalytics": false,
"providesUsageLimits": false,
"requiresApiKeyValidation": true,
"supportsBatchProcessing": false,
"supportsCustomModels": false,
"supportsHealthCheck": false,
"supportsModelFineTuning": false,
"supportsModelVersioning": false,
"supportsRateLimiting": false,
"supportsStreaming": true,
"supportsWebhookEvents": false,
},
"configVersion": "1.0.0",
"deprecated": false,
"description": "A test provider for unit testing",
"documentation": "https://docs.test.com",
"id": "test-provider",
"maintenanceMode": false,
"metadata": {
"category": "ai-provider",
"reliability": "high",
"source": "test",
"supportedLanguages": [
"en",
],
"tags": [
"test",
],
},
"modelRouting": "DIRECT",
"name": "Test Provider",
"pricingModel": "PER_MODEL",
"specialConfig": {},
"supportedEndpoints": [
"CHAT_COMPLETIONS",
],
"website": "https://test.com",
},
]
`;
exports[`Config & Schema > Snapshot Tests > should snapshot validation results 1`] = `
{
"data": {
"capabilities": [
"FUNCTION_CALL",
"REASONING",
],
"contextWindow": 128000,
"description": "A test model for unit testing",
"endpointTypes": [
"CHAT_COMPLETIONS",
],
"id": "test-model",
"inputModalities": [
"TEXT",
],
"maxInputTokens": 124000,
"maxOutputTokens": 4096,
"metadata": {
"architecture": "transformer",
"category": "language-model",
"documentation": "https://docs.test.com/models/test-model",
"family": "test-family",
"license": "mit",
"source": "test",
"tags": [
"test",
"fast",
"reliable",
],
"trainingData": "synthetic",
},
"name": "Test Model",
"outputModalities": [
"TEXT",
],
"ownedBy": "TestProvider",
"parameters": {
"maxTokens": true,
"systemMessage": true,
"temperature": {
"default": 1,
"max": 2,
"min": 0,
"supported": true,
},
"topP": {
"default": 1,
"max": 1,
"min": 0,
"supported": true,
},
},
"pricing": {
"input": {
"currency": "USD",
"perMillionTokens": 1,
},
"output": {
"currency": "USD",
"perMillionTokens": 2,
},
},
},
"success": true,
"warnings": [
"Model has REASONING capability but no reasoning configuration",
"Custom validation warning for snapshot",
],
}
`;

View File

@@ -0,0 +1,381 @@
import * as path from 'path'
import { describe, expect, it } from 'vitest'
import { ConfigLoader } from '../loader/ConfigLoader'
import { SchemaValidator } from '../validator/SchemaValidator'
// Use fixtures directory for test data
const fixturesPath = path.join(__dirname, 'fixtures')
describe('Config & Schema', () => {
describe('ConfigLoader', () => {
it('should load models with complete validation', async () => {
const loader = new ConfigLoader({
basePath: fixturesPath,
validateOnLoad: true,
cacheEnabled: false
})
const models = await loader.loadModels('test-models.json')
expect(models).toBeDefined()
expect(Array.isArray(models)).toBe(true)
expect(models).toHaveLength(1)
const model = models[0]
expect(model).toStrictEqual({
id: 'test-model',
name: 'Test Model',
ownedBy: 'TestProvider',
description: 'A test model for unit testing',
capabilities: ['FUNCTION_CALL', 'REASONING'],
inputModalities: ['TEXT'],
outputModalities: ['TEXT'],
contextWindow: 128000,
maxOutputTokens: 4096,
maxInputTokens: 124000,
pricing: {
input: { perMillionTokens: 1, currency: 'USD' },
output: { perMillionTokens: 2, currency: 'USD' }
},
parameters: {
temperature: { supported: true, min: 0, max: 2, default: 1 },
maxTokens: true,
systemMessage: true,
topP: { supported: true, min: 0, max: 1, default: 1 }
},
endpointTypes: ['CHAT_COMPLETIONS'],
metadata: {
tags: ['test', 'fast', 'reliable'],
category: 'language-model',
source: 'test',
license: 'mit',
documentation: 'https://docs.test.com/models/test-model',
family: 'test-family',
architecture: 'transformer',
trainingData: 'synthetic'
}
})
})
it('should load providers with complete validation', async () => {
const loader = new ConfigLoader({
basePath: fixturesPath,
validateOnLoad: true,
cacheEnabled: false
})
const providers = await loader.loadProviders('test-providers.json')
expect(providers).toBeDefined()
expect(Array.isArray(providers)).toBe(true)
expect(providers).toHaveLength(1)
const provider = providers[0]
expect(provider).toStrictEqual({
id: 'test-provider',
name: 'Test Provider',
description: 'A test provider for unit testing',
authentication: 'API_KEY',
pricingModel: 'PER_MODEL',
modelRouting: 'DIRECT',
behaviors: {
supportsCustomModels: false,
providesModelMapping: false,
supportsModelVersioning: false,
providesFallbackRouting: false,
hasAutoRetry: false,
supportsHealthCheck: false,
hasRealTimeMetrics: false,
providesUsageAnalytics: false,
supportsWebhookEvents: false,
requiresApiKeyValidation: true,
supportsRateLimiting: false,
providesUsageLimits: false,
supportsStreaming: true,
supportsBatchProcessing: false,
supportsModelFineTuning: false
},
supportedEndpoints: ['CHAT_COMPLETIONS'],
apiCompatibility: {
supportsArrayContent: true,
supportsStreamOptions: false,
supportsDeveloperRole: false,
supportsThinkingControl: false,
supportsApiVersion: false,
supportsParallelTools: false,
supportsMultimodal: false,
supportsServiceTier: false
},
specialConfig: {},
documentation: 'https://docs.test.com',
website: 'https://test.com',
deprecated: false,
maintenanceMode: false,
configVersion: '1.0.0',
metadata: {
tags: ['test'],
category: 'ai-provider',
source: 'test',
reliability: 'high',
supportedLanguages: ['en']
}
})
})
it('should load overrides with complete validation', async () => {
const loader = new ConfigLoader({
basePath: fixturesPath,
validateOnLoad: true,
cacheEnabled: false
})
const overrides = await loader.loadOverrides('test-overrides.json')
expect(overrides).toBeDefined()
expect(Array.isArray(overrides)).toBe(true)
expect(overrides).toHaveLength(1)
const override = overrides[0]
expect(override).toMatchObject({
providerId: 'test-provider',
modelId: 'test-model',
disabled: false,
reason: 'Test override for enhanced capabilities and limits',
priority: 100
})
expect(override.capabilities?.add).toContain('FUNCTION_CALL')
expect(override.capabilities?.remove).toContain('REASONING')
expect(override.limits?.contextWindow).toBe(256000)
expect(override.limits?.maxOutputTokens).toBe(8192)
})
it('should load all configs simultaneously', async () => {
const loader = new ConfigLoader({
basePath: fixturesPath,
validateOnLoad: true,
cacheEnabled: false
})
const configs = await loader.loadAllConfigs({
modelsFile: 'test-models.json',
providersFile: 'test-providers.json',
overridesFile: 'test-overrides.json'
})
expect(configs).toHaveProperty('models')
expect(configs).toHaveProperty('providers')
expect(configs).toHaveProperty('overrides')
expect(configs.models).toHaveLength(1)
expect(configs.providers).toHaveLength(1)
expect(configs.overrides).toHaveLength(1)
})
it('should handle missing files gracefully', async () => {
const loader = new ConfigLoader({
basePath: '/nonexistent/path'
})
await expect(loader.loadModels('nonexistent.json')).rejects.toThrow('Failed to load models')
})
})
describe('SchemaValidator', () => {
it('should validate valid model configuration', async () => {
const validator = new SchemaValidator()
const validModel = {
id: 'test-model',
capabilities: ['FUNCTION_CALL', 'REASONING'],
inputModalities: ['TEXT'],
outputModalities: ['TEXT'],
contextWindow: 128000,
maxOutputTokens: 4096,
metadata: {
tags: ['test'],
category: 'language-model',
source: 'test'
}
}
const result = await validator.validateModel(validModel)
expect(result.success).toBe(true)
expect(result.data).toBeDefined()
expect(result.data!.id).toBe('test-model')
})
it('should reject invalid model configuration', async () => {
const validator = new SchemaValidator()
const invalidModel = {
id: 123, // Should be string
capabilities: 'not-array', // Should be array
contextWindow: -1000 // Should be positive
}
const result = await validator.validateModel(invalidModel)
expect(result.success).toBe(false)
expect(result.errors).toBeDefined()
expect(result.errors!.length).toBeGreaterThan(0)
})
it('should provide warnings for model configuration issues', async () => {
const validator = new SchemaValidator()
const modelWithIssues = {
id: 'test-model',
capabilities: [], // Empty capabilities
inputModalities: ['TEXT'],
outputModalities: ['TEXT'],
contextWindow: 200000, // Large context window
maxOutputTokens: 4096,
// Missing pricing and description
metadata: {
tags: ['test'],
category: 'language-model',
source: 'test'
}
}
const result = await validator.validateModel(modelWithIssues)
expect(result.success).toBe(true)
expect(result.warnings).toBeDefined()
expect(result.warnings!.length).toBeGreaterThan(0)
})
it('should accept custom validation warnings', async () => {
const validator = new SchemaValidator()
const model = {
id: 'test-model',
capabilities: ['FUNCTION_CALL'],
inputModalities: ['TEXT'],
outputModalities: ['TEXT'],
contextWindow: 1000,
maxOutputTokens: 500,
metadata: {
tags: ['test'],
category: 'language-model',
source: 'test'
}
}
const result = await validator.validateModel(model, {
includeWarnings: true,
customValidation: () => ['Custom warning message']
})
expect(result.success).toBe(true)
expect(result.warnings).toContain('Custom warning message')
})
})
describe('Integration Tests', () => {
it('should load and validate models end-to-end', async () => {
const loader = new ConfigLoader({
basePath: fixturesPath,
validateOnLoad: true,
cacheEnabled: false
})
const validator = new SchemaValidator()
// Load models
const models = await loader.loadModels('test-models.json')
expect(models.length).toBeGreaterThan(0)
// Validate first model
const validationResult = await validator.validateModel(models[0])
expect(validationResult.success).toBe(true)
expect(validationResult.data).toBeDefined()
expect(validationResult.data!.id).toBe(models[0].id)
})
it('should work with caching enabled', async () => {
const loader = new ConfigLoader({
basePath: fixturesPath,
validateOnLoad: true,
cacheEnabled: true
})
// Test that caching doesn't break basic functionality
const models1 = await loader.loadModels('test-models.json')
expect(models1.length).toBeGreaterThan(0)
expect(models1[0]).toHaveProperty('id', 'test-model')
// Test cache clear functionality
loader.clearCache()
expect(true).toBe(true) // Cache clear should not throw
})
})
describe('Snapshot Tests', () => {
it('should snapshot model configurations', async () => {
const loader = new ConfigLoader({
basePath: fixturesPath,
validateOnLoad: true,
cacheEnabled: false
})
const models = await loader.loadModels('test-models.json')
expect(models).toMatchSnapshot()
})
it('should snapshot provider configurations', async () => {
const loader = new ConfigLoader({
basePath: fixturesPath,
validateOnLoad: true,
cacheEnabled: false
})
const providers = await loader.loadProviders('test-providers.json')
expect(providers).toMatchSnapshot()
})
it('should snapshot override configurations', async () => {
const loader = new ConfigLoader({
basePath: fixturesPath,
validateOnLoad: true,
cacheEnabled: false
})
const overrides = await loader.loadOverrides('test-overrides.json')
expect(overrides).toMatchSnapshot()
})
it('should snapshot complete configuration structure', async () => {
const loader = new ConfigLoader({
basePath: fixturesPath,
validateOnLoad: true,
cacheEnabled: false
})
const configs = await loader.loadAllConfigs({
modelsFile: 'test-models.json',
providersFile: 'test-providers.json',
overridesFile: 'test-overrides.json'
})
expect(configs).toMatchSnapshot({
models: expect.any(Array),
providers: expect.any(Array),
overrides: expect.any(Array)
})
})
it('should snapshot validation results', async () => {
const loader = new ConfigLoader({
basePath: fixturesPath,
validateOnLoad: true,
cacheEnabled: false
})
const validator = new SchemaValidator()
const model = await loader.loadModels('test-models.json')
const validationResult = await validator.validateModel(model[0], {
includeWarnings: true,
customValidation: () => ['Custom validation warning for snapshot']
})
expect(validationResult).toMatchSnapshot()
})
})
})

View File

@@ -0,0 +1,54 @@
{
"version": "1.0.0",
"models": [
{
"id": "test-model",
"name": "Test Model",
"ownedBy": "TestProvider",
"description": "A test model for unit testing",
"capabilities": ["FUNCTION_CALL", "REASONING"],
"inputModalities": ["TEXT"],
"outputModalities": ["TEXT"],
"contextWindow": 128000,
"maxOutputTokens": 4096,
"maxInputTokens": 124000,
"pricing": {
"input": {
"perMillionTokens": 1,
"currency": "USD"
},
"output": {
"perMillionTokens": 2,
"currency": "USD"
}
},
"parameters": {
"temperature": {
"supported": true,
"min": 0,
"max": 2,
"default": 1
},
"maxTokens": true,
"systemMessage": true,
"topP": {
"supported": true,
"min": 0,
"max": 1,
"default": 1
}
},
"endpointTypes": ["CHAT_COMPLETIONS"],
"metadata": {
"tags": ["test", "fast", "reliable"],
"category": "language-model",
"source": "test",
"license": "mit",
"documentation": "https://docs.test.com/models/test-model",
"family": "test-family",
"architecture": "transformer",
"trainingData": "synthetic"
}
}
]
}

View File

@@ -0,0 +1,28 @@
{
"version": "1.0.0",
"overrides": [
{
"providerId": "test-provider",
"modelId": "test-model",
"capabilities": {
"add": ["FUNCTION_CALL"],
"remove": ["REASONING"]
},
"limits": {
"contextWindow": 256000,
"maxOutputTokens": 8192
},
"pricing": {
"input": {
"perMillionTokens": 0.5,
"currency": "USD"
}
},
"disabled": false,
"reason": "Test override for enhanced capabilities and limits",
"lastUpdated": "2025-11-24T07:08:00Z",
"updatedBy": "test-suite",
"priority": 100
}
]
}

View File

@@ -0,0 +1,53 @@
{
"version": "1.0.0",
"providers": [
{
"id": "test-provider",
"name": "Test Provider",
"description": "A test provider for unit testing",
"authentication": "API_KEY",
"pricingModel": "PER_MODEL",
"modelRouting": "DIRECT",
"behaviors": {
"supportsCustomModels": false,
"providesModelMapping": false,
"supportsModelVersioning": false,
"providesFallbackRouting": false,
"hasAutoRetry": false,
"supportsHealthCheck": false,
"hasRealTimeMetrics": false,
"providesUsageAnalytics": false,
"supportsWebhookEvents": false,
"requiresApiKeyValidation": true,
"supportsRateLimiting": false,
"providesUsageLimits": false,
"supportsStreaming": true,
"supportsBatchProcessing": false,
"supportsModelFineTuning": false
},
"supportedEndpoints": ["CHAT_COMPLETIONS"],
"apiCompatibility": {
"supportsArrayContent": true,
"supportsStreamOptions": false,
"supportsDeveloperRole": false,
"supportsThinkingControl": false,
"supportsApiVersion": false,
"supportsParallelTools": false,
"supportsMultimodal": false
},
"specialConfig": {},
"documentation": "https://docs.test.com",
"website": "https://test.com",
"deprecated": false,
"maintenanceMode": false,
"configVersion": "1.0.0",
"metadata": {
"tags": ["test"],
"category": "ai-provider",
"source": "test",
"reliability": "high",
"supportedLanguages": ["en"]
}
}
]
}

View File

@@ -0,0 +1,21 @@
/**
* Cherry Studio Catalog
* Main entry point for the model and provider catalog system
*/
// Export all schemas
export * from './schemas'
// Export core functionality
export type {
ConfigLoadOptions,
ModelConfig,
ProviderConfig,
ProviderModelOverride
} from './loader/ConfigLoader'
export { ConfigLoader } from './loader/ConfigLoader'
export type {
ValidationOptions,
ValidationResult
} from './validator/SchemaValidator'
export { SchemaValidator } from './validator/SchemaValidator'

View File

@@ -0,0 +1,244 @@
/**
* Configuration Loader
* Responsible for loading and parsing JSON configuration files
*/
import * as fs from 'fs/promises'
import * as path from 'path'
import type * as z from 'zod'
import { ModelListSchema, OverrideListSchema, ProviderListSchema } from '../schemas'
import { safeParseJSON } from '../utils/parse-json/parse-json'
import { zod4Schema } from '../utils/schema'
export type ModelConfig = z.infer<typeof ModelListSchema>['models'][0]
export type ProviderConfig = z.infer<typeof ProviderListSchema>['providers'][0]
export type ProviderModelOverride = z.infer<typeof OverrideListSchema>['overrides'][0]
export interface ConfigLoadOptions {
basePath?: string
validateOnLoad?: boolean
cacheEnabled?: boolean
}
export class ConfigLoader {
private cache = new Map<string, any>()
private options: ConfigLoadOptions
constructor(options: ConfigLoadOptions = {}) {
this.options = {
basePath: path.join(__dirname, '../data'),
validateOnLoad: true,
cacheEnabled: true,
...options
}
}
/**
* Load model configurations from JSON file
*/
async loadModels(filename = 'models.json'): Promise<ModelConfig[]> {
const filePath = path.join(this.options.basePath!, filename)
if (this.options.cacheEnabled && this.cache.has(filePath)) {
return this.cache.get(filePath)
}
try {
const rawData = await fs.readFile(filePath, 'utf-8')
let validatedData: any
if (this.options.validateOnLoad) {
const schema = zod4Schema(ModelListSchema)
const parseResult = await safeParseJSON({ text: rawData, schema })
if (!parseResult.success) {
throw new Error(`Validation failed: ${parseResult.error.message}`)
}
validatedData = parseResult.value
} else {
const parseResult = await safeParseJSON({ text: rawData })
if (!parseResult.success) {
throw new Error(`Parse failed: ${parseResult.error.message}`)
}
validatedData = parseResult.value
}
const models = validatedData.models
const version = validatedData.version
if (this.options.cacheEnabled) {
this.cache.set(filePath, { models, version })
}
return models
} catch (error) {
throw new Error(
`Failed to load models from ${filePath}: ${error instanceof Error ? error.message : 'Unknown error'}`
)
}
}
/**
* Load provider configurations from JSON file
*/
async loadProviders(filename = 'providers.json'): Promise<ProviderConfig[]> {
const filePath = path.join(this.options.basePath!, filename)
if (this.options.cacheEnabled && this.cache.has(filePath)) {
return this.cache.get(filePath)
}
try {
const rawData = await fs.readFile(filePath, 'utf-8')
let validatedData: any
if (this.options.validateOnLoad) {
const schema = zod4Schema(ProviderListSchema)
const parseResult = await safeParseJSON({ text: rawData, schema })
if (!parseResult.success) {
throw new Error(`Validation failed: ${parseResult.error.message}`)
}
validatedData = parseResult.value
} else {
const parseResult = await safeParseJSON({ text: rawData })
if (!parseResult.success) {
throw new Error(`Parse failed: ${parseResult.error.message}`)
}
validatedData = parseResult.value
}
const providers = validatedData.providers
const version = validatedData.version
if (this.options.cacheEnabled) {
this.cache.set(filePath, { providers, version })
}
return providers
} catch (error) {
throw new Error(
`Failed to load providers from ${filePath}: ${error instanceof Error ? error.message : 'Unknown error'}`
)
}
}
/**
* Load override configurations from JSON file
*/
async loadOverrides(filename = 'overrides.json'): Promise<ProviderModelOverride[]> {
const filePath = path.join(this.options.basePath!, filename)
if (this.options.cacheEnabled && this.cache.has(filePath)) {
return this.cache.get(filePath)
}
try {
const rawData = await fs.readFile(filePath, 'utf-8')
let validatedData: any
if (this.options.validateOnLoad) {
const schema = zod4Schema(OverrideListSchema)
const parseResult = await safeParseJSON({ text: rawData, schema })
if (!parseResult.success) {
throw new Error(`Validation failed: ${parseResult.error.message}`)
}
validatedData = parseResult.value
} else {
const parseResult = await safeParseJSON({ text: rawData })
if (!parseResult.success) {
throw new Error(`Parse failed: ${parseResult.error.message}`)
}
validatedData = parseResult.value
}
const overrides = validatedData.overrides
const version = validatedData.version
if (this.options.cacheEnabled) {
this.cache.set(filePath, { overrides, version })
}
return overrides
} catch (error) {
throw new Error(
`Failed to load overrides from ${filePath}: ${error instanceof Error ? error.message : 'Unknown error'}`
)
}
}
/**
* Load all configuration files
*/
async loadAllConfigs(options: { modelsFile?: string; providersFile?: string; overridesFile?: string } = {}): Promise<{
models: ModelConfig[]
providers: ProviderConfig[]
overrides: ProviderModelOverride[]
}> {
const [models, providers, overrides] = await Promise.all([
this.loadModels(options.modelsFile),
this.loadProviders(options.providersFile),
this.loadOverrides(options.overridesFile)
])
return { models, providers, overrides }
}
/**
* Clear cache
*/
clearCache(): void {
this.cache.clear()
}
/**
* Check if file exists
*/
private async fileExists(filePath: string): Promise<boolean> {
try {
await fs.access(filePath)
return true
} catch {
return false
}
}
/**
* Get configuration file version
*/
async getConfigVersion(filename: string): Promise<string | null> {
const filePath = path.join(this.options.basePath!, filename)
if (!(await this.fileExists(filePath))) {
return null
}
try {
const rawData = await fs.readFile(filePath, 'utf-8')
const jsonData = JSON.parse(rawData)
return jsonData.version || null
} catch {
return null
}
}
/**
* Get all configuration versions
*/
async getAllConfigVersions(): Promise<{
models: string | null
providers: string | null
overrides: string | null
}> {
const [models, providers, overrides] = await Promise.all([
this.getConfigVersion('models.json'),
this.getConfigVersion('providers.json'),
this.getConfigVersion('overrides.json')
])
return { models, providers, overrides }
}
}

View File

@@ -0,0 +1,69 @@
/**
* Common type definitions for the catalog system
* Shared across model, provider, and override schemas
*/
import * as z from 'zod'
// Common string types for reuse
export const ModelIdSchema = z.string()
export const ProviderIdSchema = z.string()
export const VersionSchema = z.string()
// Currency codes
export const CurrencySchema = z.enum(['USD', 'EUR', 'CNY', 'JPY', 'GBP'])
// Common file size units
export const FileSizeUnitSchema = z.enum(['B', 'KB', 'MB', 'GB'])
// Common status types
export const StatusSchema = z.enum(['active', 'inactive', 'deprecated', 'maintenance'])
// Timestamp schema for date fields
export const TimestampSchema = z.iso.datetime()
// Range helper schemas
export const NumericRangeSchema = z.object({
min: z.number(),
max: z.number()
})
export const StringRangeSchema = z.object({
min: z.string(),
max: z.string()
})
// Price per token schema
export const PricePerTokenSchema = z.object({
perMillionTokens: z.number().nonnegative(),
currency: CurrencySchema.default('USD')
})
// Generic metadata schema
export const MetadataSchema = z.record(z.string(), z.any()).optional()
// Type exports
export type ModelId = z.infer<typeof ModelIdSchema>
export type ProviderId = z.infer<typeof ProviderIdSchema>
export type Version = z.infer<typeof VersionSchema>
export type Currency = z.infer<typeof CurrencySchema>
export type FileSizeUnit = z.infer<typeof FileSizeUnitSchema>
export type Status = z.infer<typeof StatusSchema>
export type Timestamp = z.infer<typeof TimestampSchema>
export type NumericRange = z.infer<typeof NumericRangeSchema>
export type StringRange = z.infer<typeof StringRangeSchema>
export type PricePerToken = z.infer<typeof PricePerTokenSchema>
export type Metadata = z.infer<typeof MetadataSchema>
// Common validation utilities
export const validateRange = (min: number, max: number): boolean => {
return min <= max
}
export const validatePositiveNumber = (value: number): boolean => {
return value >= 0
}
export const validateNonEmptyString = (value: string): boolean => {
return value.trim().length > 0
}

View File

@@ -0,0 +1,49 @@
/**
* Unified export of all catalog schemas and types
* This file provides a single entry point for all schema definitions
*/
// Export all schemas from common types
export * from './common'
// Export model schemas
export * from './model'
// Export provider schemas
export * from './provider'
// Export override schemas
export * from './override'
// Re-export commonly used combined types for convenience
export type {
Modality,
ModelCapabilityType,
ModelConfig,
ModelPricing,
ParameterSupport,
Reasoning
} from './model'
export type {
OverrideResult,
OverrideValidation,
ProviderModelOverride
} from './override'
export type {
Authentication,
EndpointType,
McpSupport,
PricingModel,
ProviderBehaviors,
ProviderConfig
} from './provider'
// Export common types
export type {
Currency,
Metadata,
ModelId,
ProviderId,
Timestamp,
Version
} from './common'

View File

@@ -0,0 +1,254 @@
/**
* Model configuration schema definitions
* Defines the structure for model metadata, capabilities, and configurations
*/
import * as z from 'zod'
import {
CurrencySchema,
MetadataSchema,
ModelIdSchema,
PricePerTokenSchema,
TimestampSchema,
VersionSchema
} from './common'
// Modality types - supported input/output modalities
export const ModalitySchema = z.enum(['TEXT', 'VISION', 'AUDIO', 'VIDEO', 'VECTOR'])
// Model capability types
export const ModelCapabilityTypeSchema = z.enum([
'FUNCTION_CALL', // Function calling
'REASONING', // Reasoning/thinking
'IMAGE_RECOGNITION', // Image recognition
'IMAGE_GENERATION', // Image generation
'AUDIO_RECOGNITION', // Audio recognition
'AUDIO_GENERATION', // Audio generation
'EMBEDDING', // Embedding vector generation
'RERANK', // Text reranking
'AUDIO_TRANSCRIPT', // Audio transcription
'VIDEO_RECOGNITION', // Video recognition
'VIDEO_GENERATION', // Video generation
'STRUCTURED_OUTPUT', // Structured output
'FILE_INPUT', // File input support
'WEB_SEARCH', // Built-in web search
'CODE_EXECUTION', // Code execution
'FILE_SEARCH', // File search
'COMPUTER_USE' // Computer use
])
// Reasoning configuration
export const ReasoningSchema = z.discriminatedUnion('type', [
z.object({
type: z.literal('openai-chat'),
params: z.object({
reasoning_effort: z.enum(['none', 'minimal', 'low', 'medium', 'high']).optional()
})
}),
z.object({
type: z.literal('openai-responses'),
params: z.object({
reasoning: z.object({
effort: z.enum(['none', 'minimal', 'low', 'medium', 'high']).optional(),
summary: z.enum(['auto', 'concise', 'detailed']).optional()
})
})
}),
z.object({
type: z.literal('anthropic'),
params: z.object({
type: z.union([z.literal('enabled'), z.literal('disabled')]),
budgetTokens: z.number().optional()
})
}),
z.object({
type: z.literal('gemini'),
params: z.union([
z
.object({
thinking_config: z.object({
include_thoughts: z.boolean().optional(),
thinking_budget: z.number().optional()
})
})
.optional(),
z
.object({
thinking_level: z.enum(['low', 'medium', 'high']).optional()
})
.optional()
])
}),
z.object({
type: z.literal('openrouter'),
params: z.object({
reasoning: z
.object({
effort: z
.union([z.literal('none'), z.literal('minimal'), z.literal('low'), z.literal('medium'), z.literal('high')])
.optional(),
max_tokens: z.number().optional(),
exclude: z.boolean().optional()
})
.refine((v) => {
v.effort == null || v.max_tokens == null
}, 'One of the following (not both)')
})
}),
z.object({
type: z.literal('qwen'),
params: z.object({
enable_thinking: z.boolean(),
thinking_budget: z.number().optional()
})
}),
z.object({
type: z.literal('doubao'),
params: z.object({
thinking: z.object({
type: z.union([z.literal('enabled'), z.literal('disabled'), z.literal('auto')])
})
})
}),
z.object({
type: z.literal('dashscope'),
params: z.object({
enable_thinking: z.boolean(),
incremental_output: z.boolean().optional()
})
}),
z.object({
type: z.literal('self-hosted'),
params: z.object({
chat_template_kwargs: z.object({
enable_thinking: z.boolean().optional(),
thinking: z.boolean().optional()
})
})
})
])
// Parameter support configuration
export const ParameterSupportSchema = z.object({
temperature: z
.object({
supported: z.boolean(),
min: z.number().min(0).max(2).optional(),
max: z.number().min(0).max(2).optional(),
default: z.number().min(0).max(2).optional()
})
.optional(),
topP: z
.object({
supported: z.boolean(),
min: z.number().min(0).max(1).optional(),
max: z.number().min(0).max(1).optional(),
default: z.number().min(0).max(1).optional()
})
.optional(),
topK: z
.object({
supported: z.boolean(),
min: z.number().positive().optional(),
max: z.number().positive().optional()
})
.optional(),
frequencyPenalty: z.boolean().optional(),
presencePenalty: z.boolean().optional(),
maxTokens: z.boolean().optional(),
stopSequences: z.boolean().optional(),
systemMessage: z.boolean().optional(),
developerRole: z.boolean().optional()
})
// Model pricing configuration
export const ModelPricingSchema = z.object({
input: PricePerTokenSchema,
output: PricePerTokenSchema,
// Image pricing (optional)
per_image: z
.object({
price: z.number(),
currency: CurrencySchema.default('USD'),
unit: z.enum(['image', 'pixel']).optional()
})
.optional(),
// Audio/video pricing (optional)
per_minute: z
.object({
price: z.number(),
currency: CurrencySchema.default('USD')
})
.optional()
})
// Model configuration schema
export const ModelConfigSchema = z.object({
// Basic information
id: ModelIdSchema,
name: z.string().optional(),
owned_by: z.string().optional(),
description: z.string().optional(),
// Capabilities (core)
capabilities: z.array(ModelCapabilityTypeSchema),
// Modalities
input_modalities: z.array(ModalitySchema),
output_modalities: z.array(ModalitySchema),
// Limits
context_window: z.number(),
max_output_tokens: z.number(),
max_input_tokens: z.number().optional(),
// Pricing
pricing: ModelPricingSchema.optional(),
// Reasoning configuration
reasoning: ReasoningSchema.optional(),
// Parameter support
parameters: ParameterSupportSchema.optional(),
// Endpoint types (will reference provider schema)
endpoint_types: z.array(z.string()).optional(),
// Metadata
release_date: TimestampSchema.optional(),
deprecation_date: TimestampSchema.optional(),
replaced_by: ModelIdSchema.optional(),
// Version control
version: VersionSchema.optional(),
compatibility: z
.object({
min_version: VersionSchema.optional(),
max_version: VersionSchema.optional()
})
.optional(),
// Additional metadata
metadata: MetadataSchema
})
// Model list container schema for JSON files
export const ModelListSchema = z.object({
version: VersionSchema,
models: z.array(ModelConfigSchema)
})
// Type exports
export type Modality = z.infer<typeof ModalitySchema>
export type ModelCapabilityType = z.infer<typeof ModelCapabilityTypeSchema>
export type Reasoning = z.infer<typeof ReasoningSchema>
export type ParameterSupport = z.infer<typeof ParameterSupportSchema>
export type ModelPricing = z.infer<typeof ModelPricingSchema>
export type ModelConfig = z.infer<typeof ModelConfigSchema>
export type ModelList = z.infer<typeof ModelListSchema>

View File

@@ -0,0 +1,147 @@
/**
* Provider model override schema definitions
* Defines how providers can override specific model configurations
*/
import * as z from 'zod'
import { MetadataSchema, ModelIdSchema, ProviderIdSchema, VersionSchema } from './common'
import { ModelCapabilityTypeSchema, ModelPricingSchema, ParameterSupportSchema, ReasoningSchema } from './model'
import { EndpointTypeSchema } from './provider'
// Capability override operations
export const CapabilityOverrideSchema = z.object({
add: z.array(ModelCapabilityTypeSchema).optional(), // Add capabilities
remove: z.array(ModelCapabilityTypeSchema).optional(), // Remove capabilities
force: z.array(ModelCapabilityTypeSchema).optional() // Force set capabilities (ignore base config)
})
// Limits override configuration
export const LimitsOverrideSchema = z.object({
context_window: z.number().optional(),
max_output_tokens: z.number().optional(),
max_input_tokens: z.number().optional()
})
// Pricing override configuration
export const PricingOverrideSchema = ModelPricingSchema.partial().optional()
// Endpoint types override
export const EndpointTypesOverrideSchema = z.array(EndpointTypeSchema).optional()
// Reasoning configuration override - allows partial override of reasoning configs
export const ReasoningOverrideSchema = ReasoningSchema.optional()
// Parameter support override
export const ParameterSupportOverrideSchema = ParameterSupportSchema.partial().optional()
// Model metadata override
export const MetadataOverrideSchema = z
.object({
name: z.string().optional(),
description: z.string().optional(),
deprecation_date: z.iso.datetime().optional(),
replaced_by: ModelIdSchema.optional(),
metadata: MetadataSchema
})
.optional()
// Main provider model override schema
export const ProviderModelOverrideSchema = z.object({
// Identification
provider_id: ProviderIdSchema,
model_id: ModelIdSchema,
// Capability overrides
capabilities: CapabilityOverrideSchema.optional(),
// Limits overrides
limits: LimitsOverrideSchema.optional(),
// Pricing overrides
pricing: PricingOverrideSchema,
// Reasoning configuration overrides
reasoning: ReasoningOverrideSchema.optional(),
// Parameter support overrides
parameters: ParameterSupportOverrideSchema.optional(),
// Endpoint type overrides
endpoint_types: EndpointTypesOverrideSchema.optional(),
// Model metadata overrides
metadata: MetadataOverrideSchema.optional(),
// Status overrides
disabled: z.boolean().optional(), // Disable this model for this provider
replace_with: ModelIdSchema.optional(), // Replace with alternative model
// Override tracking
reason: z.string().optional(), // Reason for override
last_updated: z.iso.datetime().optional(),
updated_by: z.string().optional(), // Who made the override
// Override priority (higher number = higher priority)
priority: z.number().default(0),
// Override conditions
conditions: z
.object({
// Apply override only for specific regions
regions: z.array(z.string()).optional(),
// Apply override only for specific user tiers
user_tiers: z.array(z.string()).optional(),
// Apply override only in specific environments
environments: z.array(z.enum(['development', 'staging', 'production'])).optional(),
// Time-based conditions
valid_from: z.iso.datetime().optional(),
valid_until: z.iso.datetime().optional()
})
.optional(),
// Additional override metadata
override_metadata: MetadataSchema.optional()
})
// Override container schema for JSON files
export const OverrideListSchema = z.object({
version: VersionSchema,
overrides: z.array(ProviderModelOverrideSchema)
})
// Override application result schema
export const OverrideResultSchema = z.object({
model_id: ModelIdSchema,
provider_id: ProviderIdSchema,
applied: z.boolean(),
applied_overrides: z.array(z.string()), // List of applied override fields
original_values: z.record(z.string(), z.unknown()), // Original values before override
new_values: z.record(z.string(), z.unknown()), // New values after override
override_reason: z.string().optional(),
applied_at: z.iso.datetime().optional()
})
// Override validation result
export const OverrideValidationSchema = z.object({
valid: z.boolean(),
errors: z.array(z.string()),
warnings: z.array(z.string()),
recommendations: z.array(z.string())
})
// Type exports
export type CapabilityOverride = z.infer<typeof CapabilityOverrideSchema>
export type LimitsOverride = z.infer<typeof LimitsOverrideSchema>
export type PricingOverride = z.infer<typeof PricingOverrideSchema>
export type EndpointTypesOverride = z.infer<typeof EndpointTypesOverrideSchema>
export type ReasoningOverride = z.infer<typeof ReasoningOverrideSchema>
export type ParameterSupportOverride = z.infer<typeof ParameterSupportOverrideSchema>
export type MetadataOverride = z.infer<typeof MetadataOverrideSchema>
export type ProviderModelOverride = z.infer<typeof ProviderModelOverrideSchema>
export type OverrideList = z.infer<typeof OverrideListSchema>
export type OverrideResult = z.infer<typeof OverrideResultSchema>
export type OverrideValidation = z.infer<typeof OverrideValidationSchema>

View File

@@ -0,0 +1,171 @@
/**
* Provider configuration schema definitions
* Defines the structure for AI service provider metadata and capabilities
*/
import * as z from 'zod'
import { MetadataSchema, ProviderIdSchema, VersionSchema } from './common'
// Endpoint types supported by providers
export const EndpointTypeSchema = z.enum([
'CHAT_COMPLETIONS', // /chat/completions
'COMPLETIONS', // /completions
'EMBEDDINGS', // /embeddings
'IMAGE_GENERATION', // /images/generations
'IMAGE_EDIT', // /images/edits
'AUDIO_SPEECH', // /audio/speech (TTS)
'AUDIO_TRANSCRIPTIONS', // /audio/transcriptions (STT)
'MESSAGES', // /messages
'RESPONSES', // /responses
'GENERATE_CONTENT', // :generateContent
'STREAM_GENERATE_CONTENT', // :streamGenerateContent
'RERANK', // /rerank
'MODERATIONS' // /moderations
])
// Authentication methods
export const AuthenticationSchema = z.enum([
'API_KEY', // Standard API Key authentication
'OAUTH', // OAuth 2.0 authentication
'CLOUD_CREDENTIALS' // Cloud service credentials (AWS, GCP, Azure)
])
// Pricing models that affect UI and behavior
export const PricingModelSchema = z.enum([
'UNIFIED', // Unified pricing (like OpenRouter)
'PER_MODEL', // Per-model independent pricing (like OpenAI official)
'TRANSPARENT', // Transparent pricing (like New-API)
'USAGE_BASED', // Dynamic usage-based pricing
'SUBSCRIPTION' // Subscription-based pricing
])
// Model routing strategies affecting performance and reliability
export const ModelRoutingSchema = z.enum([
'INTELLIGENT', // Intelligent routing, auto-select optimal instance
'DIRECT', // Direct routing to specified model
'LOAD_BALANCED', // Load balanced across multiple instances
'GEO_ROUTED', // Geographic location routing
'COST_OPTIMIZED' // Cost-optimized routing
])
// Server-side MCP support configuration
export const McpSupportSchema = z.object({
supported: z.boolean().default(false),
configuration: z
.object({
supports_url_pass_through: z.boolean().default(false),
supported_servers: z.array(z.string()).optional(),
max_concurrent_servers: z.number().optional()
})
.optional()
})
// API compatibility configuration
export const ApiCompatibilitySchema = z.object({
supports_array_content: z.boolean().default(true),
supports_stream_options: z.boolean().default(true),
supports_developer_role: z.boolean().default(false),
supports_service_tier: z.boolean().default(false),
supports_thinking_control: z.boolean().default(false),
supports_api_version: z.boolean().default(false),
supports_parallel_tools: z.boolean().default(false),
supports_multimodal: z.boolean().default(false),
max_file_upload_size: z.number().optional(), // bytes
supported_file_types: z.array(z.string()).optional()
})
// Behavior characteristics configuration - replaces categorization, describes actual behavior
export const ProviderBehaviorsSchema = z.object({
// Model management
supports_custom_models: z.boolean().default(false), // Supports user custom models
provides_model_mapping: z.boolean().default(false), // Provides model name mapping
supports_model_versioning: z.boolean().default(false), // Supports model version control
// Reliability and fault tolerance
provides_fallback_routing: z.boolean().default(false), // Provides fallback routing
has_auto_retry: z.boolean().default(false), // Has automatic retry mechanism
supports_health_check: z.boolean().default(false), // Supports health checks
// Monitoring and metrics
has_real_time_metrics: z.boolean().default(false), // Has real-time metrics
provides_usage_analytics: z.boolean().default(false), // Provides usage analytics
supports_webhook_events: z.boolean().default(false), // Supports webhook events
// Configuration and management
requires_api_key_validation: z.boolean().default(true), // Requires API key validation
supports_rate_limiting: z.boolean().default(false), // Supports rate limiting
provides_usage_limits: z.boolean().default(false), // Provides usage limit configuration
// Advanced features
supports_streaming: z.boolean().default(true), // Supports streaming responses
supports_batch_processing: z.boolean().default(false), // Supports batch processing
supports_model_fine_tuning: z.boolean().default(false) // Provides model fine-tuning
})
// Provider configuration schema
export const ProviderConfigSchema = z.object({
// Basic information
id: ProviderIdSchema,
name: z.string(),
description: z.string().optional(),
// Behavior-related configuration
authentication: AuthenticationSchema,
pricing_model: PricingModelSchema,
model_routing: ModelRoutingSchema,
behaviors: ProviderBehaviorsSchema,
// Feature support
supported_endpoints: z.array(EndpointTypeSchema),
mcp_support: McpSupportSchema.optional(),
api_compatibility: ApiCompatibilitySchema.optional(),
// Default configuration
default_api_host: z.string().optional(),
default_rate_limit: z.number().optional(), // requests per minute
// Model matching assistance
model_id_patterns: z.array(z.string()).optional(),
alias_model_ids: z.record(z.string(), z.string()).optional(), // Model alias mapping
// Special configuration
special_config: MetadataSchema,
// Metadata and links
documentation: z.string().url().optional(),
status_page: z.string().url().optional(),
pricing_page: z.string().url().optional(),
support_email: z.string().email().optional(),
website: z.string().url().optional(),
// Status management
deprecated: z.boolean().default(false),
deprecation_date: z.iso.datetime().optional(),
maintenance_mode: z.boolean().default(false),
// Version and compatibility
min_app_version: VersionSchema.optional(), // Minimum supported app version
max_app_version: VersionSchema.optional(), // Maximum supported app version
config_version: VersionSchema.default('1.0.0'), // Configuration file version
// Additional metadata
metadata: MetadataSchema
})
// Provider list container schema for JSON files
export const ProviderListSchema = z.object({
version: VersionSchema,
providers: z.array(ProviderConfigSchema)
})
// Type exports
export type EndpointType = z.infer<typeof EndpointTypeSchema>
export type Authentication = z.infer<typeof AuthenticationSchema>
export type PricingModel = z.infer<typeof PricingModelSchema>
export type ModelRouting = z.infer<typeof ModelRoutingSchema>
export type McpSupport = z.infer<typeof McpSupportSchema>
export type ApiCompatibility = z.infer<typeof ApiCompatibilitySchema>
export type ProviderBehaviors = z.infer<typeof ProviderBehaviorsSchema>
export type ProviderConfig = z.infer<typeof ProviderConfigSchema>
export type ProviderList = z.infer<typeof ProviderListSchema>

View File

@@ -0,0 +1,2 @@
export { isJSONArray, isJSONObject, isJSONValue } from './is-json'
export type { JSONArray, JSONObject, JSONValue } from './json-value'

View File

@@ -0,0 +1,32 @@
// https://github.com/vercel/ai/blob/4c44a5bea002ef0db0e1b86a1e223cd9f4837d62/packages/provider/src/json-value/is-json.ts
import type { JSONArray, JSONObject, JSONValue } from './json-value'
export function isJSONValue(value: unknown): value is JSONValue {
if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
return true
}
if (Array.isArray(value)) {
return value.every(isJSONValue)
}
if (typeof value === 'object') {
return Object.entries(value).every(
([key, val]) => typeof key === 'string' && (val === undefined || isJSONValue(val))
)
}
return false
}
export function isJSONArray(value: unknown): value is JSONArray {
return Array.isArray(value) && value.every(isJSONValue)
}
export function isJSONObject(value: unknown): value is JSONObject {
return (
value != null &&
typeof value === 'object' &&
Object.entries(value).every(([key, val]) => typeof key === 'string' && (val === undefined || isJSONValue(val)))
)
}

View File

@@ -0,0 +1,13 @@
// https://github.com/vercel/ai/blob/4c44a5bea002ef0db0e1b86a1e223cd9f4837d62/packages/provider/src/json-value/json-value.ts
/**
A JSON value can be a string, number, boolean, object, array, or null.
JSON values can be serialized and deserialized by the JSON.stringify and JSON.parse methods.
*/
export type JSONValue = null | string | number | boolean | JSONObject | JSONArray
export type JSONObject = {
[key: string]: JSONValue | undefined
}
export type JSONArray = JSONValue[]

View File

@@ -0,0 +1,543 @@
/**
* Migration Tool - Phase 2 Implementation
* Migrates existing JSON data to new schema-based catalog system
*/
import * as fs from 'fs/promises'
import * as path from 'path'
interface ProviderEndpointsData {
providers: Record<
string,
{
display_name: string
endpoints: Record<string, boolean>
url: string
}
>
}
interface ModelPricesData {
[modelId: string]: {
litellm_provider: string
mode: string
input_cost_per_token?: number
output_cost_per_token?: number
input_cost_per_pixel?: number
output_cost_per_pixel?: number
output_cost_per_image?: number
max_input_tokens?: number
max_output_tokens?: number
max_tokens?: number
supports_function_calling?: boolean
supports_vision?: boolean
supports_parallel_function_calling?: boolean
supports_response_schema?: boolean
supports_tool_choice?: boolean
supports_system_messages?: boolean
supports_assistant_prefill?: boolean
supports_pdf_input?: boolean
supports_prompt_caching?: boolean
cache_creation_input_token_cost?: number
cache_read_input_token_cost?: number
metadata?: {
notes?: string
}
source?: string
supported_endpoints?: string[]
deprecation_date?: string
}
}
interface ModelConfig {
id: string
name?: string
owned_by?: string
description?: string
capabilities: string[]
input_modalities: string[]
output_modalities: string[]
context_window: number
max_output_tokens: number
max_input_tokens?: number
pricing?: {
input: { per_million_tokens: number; currency: string }
output: { per_million_tokens: number; currency: string }
}
parameters?: Record<string, any>
endpoint_types?: string[]
metadata?: Record<string, any>
}
interface ProviderConfig {
id: string
name: string
description?: string
authentication: string
supported_endpoints: string[]
api_compatibility?: Record<string, boolean>
special_config?: Record<string, any>
documentation?: string
website?: string
deprecated: boolean
maintenance_mode: boolean
config_version: string
metadata?: Record<string, any>
}
interface OverrideConfig {
provider_id: string
model_id: string
capabilities?: {
add?: string[]
remove?: string[]
force?: string[]
}
limits?: {
context_window?: number
max_output_tokens?: number
max_input_tokens?: number
}
pricing?: {
input: { per_million_tokens: number; currency: string }
output: { per_million_tokens: number; currency: string }
}
disabled?: boolean
reason?: string
last_updated?: string
updated_by?: string
priority?: number
}
export class MigrationTool {
private providerEndpointsData: ProviderEndpointsData
private modelPricesData: ModelPricesData
constructor(
private providerEndpointsPath: string,
private modelPricesPath: string,
private outputDir: string
) {
// Initialize with empty objects to satisfy TypeScript
this.providerEndpointsData = { providers: {} }
this.modelPricesData = {}
}
async loadData(): Promise<void> {
console.log('📖 Loading existing data...')
const providerEndpointsContent = await fs.readFile(this.providerEndpointsPath, 'utf-8')
this.providerEndpointsData = JSON.parse(providerEndpointsContent)
const modelPricesContent = await fs.readFile(this.modelPricesPath, 'utf-8')
this.modelPricesData = JSON.parse(modelPricesContent)
console.log(`✅ Loaded ${Object.keys(this.providerEndpointsData.providers).length} providers`)
console.log(`✅ Loaded ${Object.keys(this.modelPricesData).length} model configurations`)
}
/**
* Extract base model identifier from provider-specific model ID
*/
private extractBaseModelId(providerModelId: string): string {
// Remove provider prefixes
const prefixes = [
'azure/',
'bedrock/',
'openrouter/',
'vertex_ai/',
'sagemaker/',
'watsonx/',
'litellm_proxy/',
'custom/',
'aiml/',
'together_ai/',
'deepinfra/',
'hyperbolic/',
'fireworks_ai/',
'replicate/',
'novita/',
'anyscale/',
'runpod/',
'triton/',
'vllm/',
'ollama/',
'lm_studio/'
]
let baseId = providerModelId
for (const prefix of prefixes) {
if (baseId.startsWith(prefix)) {
baseId = baseId.substring(prefix.length)
break
}
}
// Handle AWS Bedrock specific naming
if (baseId.includes(':')) {
baseId = baseId.split(':')[0]
}
// Handle version suffixes
baseId = baseId.replace(/\/v\d+$/, '').replace(/:v\d+$/, '')
return baseId
}
/**
* Determine if a model is a base model or provider-specific override
*/
private isBaseModel(modelId: string, provider: string): boolean {
const baseId = this.extractBaseModelId(modelId)
// Official provider models are base models
const officialProviders = [
'anthropic',
'openai',
'gemini',
'deepseek',
'dashscope',
'volceengine',
'minimax',
'moonshotai',
'zai',
'meta',
'mistral',
'cohere',
'xai'
]
if (officialProviders.includes(provider)) {
return modelId === baseId || modelId.startsWith(provider + '/')
}
// Third-party providers selling access to official models are overrides
return false
}
/**
* Convert endpoint support to provider capabilities
*/
private privateConvertEndpointsToCapabilities(endpoints: Record<string, boolean>): string[] {
const endpointCapabilityMap: Record<string, string> = {
chat_completions: 'CHAT_COMPLETIONS',
messages: 'MESSAGES',
responses: 'RESPONSES',
completions: 'COMPLETIONS',
embeddings: 'EMBEDDINGS',
image_generations: 'IMAGE_GENERATION',
image_edit: 'IMAGE_EDIT',
audio_speech: 'AUDIO_GENERATION',
audio_transcriptions: 'AUDIO_TRANSCRIPT',
rerank: 'RERANK',
moderations: 'MODERATIONS',
ocr: 'OCR',
search: 'WEB_SEARCH'
}
const capabilities: string[] = []
for (const [endpoint, supported] of Object.entries(endpoints)) {
if (supported && endpointCapabilityMap[endpoint]) {
capabilities.push(endpointCapabilityMap[endpoint])
}
}
return capabilities
}
/**
* Generate provider configurations
*/
private generateProviderConfigs(): ProviderConfig[] {
const providers: ProviderConfig[] = []
for (const [providerId, providerData] of Object.entries(this.providerEndpointsData.providers)) {
const supported_endpoints = this.privateConvertEndpointsToCapabilities(providerData.endpoints)
const provider: ProviderConfig = {
id: providerId,
name: providerData.display_name,
description: `Provider: ${providerData.display_name}`,
authentication: 'API_KEY',
supported_endpoints,
api_compatibility: {
supports_array_content: providerData.endpoints.chat_completions || false,
supports_stream_options: providerData.endpoints.chat_completions || false,
supports_developer_role: providerId === 'openai',
supports_service_tier: providerId === 'openai',
supports_thinking_control: false,
supports_api_version: providerId === 'openai',
supports_parallel_tools: providerData.endpoints.chat_completions || false,
supports_multimodal: providerData.endpoints.chat_completions || false
},
special_config: {},
documentation: providerData.url,
website: providerData.url,
deprecated: false,
maintenance_mode: false,
config_version: '1.0.0'
}
providers.push(provider)
}
return providers
}
/**
* Generate base model configurations
*/
private generateBaseModels(): ModelConfig[] {
const baseModels = new Map<string, ModelConfig>()
for (const [modelId, modelData] of Object.entries(this.modelPricesData)) {
if (modelData.mode !== 'chat') continue // Skip non-chat models for now
const baseId = this.extractBaseModelId(modelId)
const isBase = this.isBaseModel(modelId, modelData.litellm_provider)
if (!isBase) continue // Only process base models
// Extract capabilities from model data
const capabilities: string[] = []
if (modelData.supports_function_calling) capabilities.push('FUNCTION_CALL')
if (modelData.supports_vision) capabilities.push('IMAGE_RECOGNITION')
if (modelData.supports_response_schema) capabilities.push('STRUCTURED_OUTPUT')
if (modelData.supports_pdf_input) capabilities.push('FILE_INPUT')
if (modelData.supports_tool_choice) capabilities.push('FUNCTION_CALL')
// Determine modalities
const input_modalities = ['TEXT']
const output_modalities = ['TEXT']
if (modelData.supports_vision) {
input_modalities.push('VISION')
}
// Convert pricing
let pricing
if (modelData.input_cost_per_token && modelData.output_cost_per_token) {
pricing = {
input: {
per_million_tokens: Math.round(modelData.input_cost_per_token * 1000000 * 1000) / 1000,
currency: 'USD'
},
output: {
per_million_tokens: Math.round(modelData.output_cost_per_token * 1000000 * 1000) / 1000,
currency: 'USD'
}
}
}
const baseModel: ModelConfig = {
id: baseId,
name: baseId,
owned_by: modelData.litellm_provider,
capabilities,
input_modalities,
output_modalities,
context_window: modelData.max_input_tokens || 4096,
max_output_tokens: modelData.max_output_tokens || modelData.max_tokens || 2048,
max_input_tokens: modelData.max_input_tokens,
pricing,
parameters: {
temperature: { supported: true, min: 0, max: 1, default: 1 },
max_tokens: true,
system_message: modelData.supports_system_messages || false,
top_p: { supported: false }
},
endpoint_types: ['CHAT_COMPLETIONS'],
metadata: {
source: 'migration',
original_provider: modelData.litellm_provider,
supports_caching: !!modelData.supports_prompt_caching
}
}
baseModels.set(baseId, baseModel)
}
return Array.from(baseModels.values())
}
/**
* Generate override configurations
*/
private generateOverrides(): OverrideConfig[] {
const overrides: OverrideConfig[] = []
for (const [modelId, modelData] of Object.entries(this.modelPricesData)) {
if (modelData.mode !== 'chat') continue
const baseId = this.extractBaseModelId(modelId)
const isBase = this.isBaseModel(modelId, modelData.litellm_provider)
if (isBase) continue // Only generate overrides for non-base models
const override: OverrideConfig = {
provider_id: modelData.litellm_provider,
model_id: baseId,
disabled: false,
reason: `Provider-specific implementation of ${baseId}`,
last_updated: new Date().toISOString().split('T')[0],
updated_by: 'migration-tool',
priority: 100
}
// Add capability differences
const capabilities = modelData.supports_function_calling ? ['FUNCTION_CALL'] : []
if (modelData.supports_vision) capabilities.push('IMAGE_RECOGNITION')
if (capabilities.length > 0) {
override.capabilities = { add: capabilities }
}
// Add limit differences
const limits: any = {}
if (modelData.max_input_tokens && modelData.max_input_tokens !== 128000) {
limits.context_window = modelData.max_input_tokens
}
if (modelData.max_output_tokens && modelData.max_output_tokens !== 4096) {
limits.max_output_tokens = modelData.max_output_tokens
}
if (Object.keys(limits).length > 0) {
override.limits = limits
}
// Add pricing differences
if (modelData.input_cost_per_token && modelData.output_cost_per_token) {
override.pricing = {
input: {
per_million_tokens: Math.round(modelData.input_cost_per_token * 1000000 * 1000) / 1000,
currency: 'USD'
},
output: {
per_million_tokens: Math.round(modelData.output_cost_per_token * 1000000 * 1000) / 1000,
currency: 'USD'
}
}
}
overrides.push(override)
}
return overrides
}
/**
* Execute the full migration
*/
async migrate(): Promise<void> {
console.log('🚀 Starting Phase 2 Migration...')
await this.loadData()
// Create output directory
await fs.mkdir(this.outputDir, { recursive: true })
// Generate configurations
console.log('📦 Generating provider configurations...')
const providers = this.generateProviderConfigs()
console.log('📦 Generating base model configurations...')
const models = this.generateBaseModels()
console.log('📦 Generating override configurations...')
const overrides = this.generateOverrides()
// Write single file for all providers
console.log('💾 Writing providers.json...')
await this.writeJsonFile('providers.json', {
version: '2025.11.24',
providers
})
// Write single file for all models
console.log('💾 Writing models.json...')
await this.writeJsonFile('models.json', {
version: '2025.11.24',
models
})
// Write single file for all overrides
console.log('💾 Writing overrides.json...')
await this.writeJsonFile('overrides.json', {
version: '2025.11.24',
overrides
})
// Generate migration report
const providersByType = {
direct: providers.filter((p) => ['anthropic', 'openai', 'google'].includes(p.id)).length,
cloud: providers.filter((p) => ['azure', 'bedrock', 'vertex_ai'].some((c) => p.id.includes(c))).length,
proxy: providers.filter((p) => ['openrouter', 'litellm_proxy', 'together_ai'].some((c) => p.id.includes(c)))
.length,
self_hosted: providers.filter((p) => ['ollama', 'lm_studio', 'vllm'].some((c) => p.id.includes(c))).length
}
const modelsByProvider = models.reduce(
(acc, model) => {
const provider = model.owned_by || 'unknown'
acc[provider] = (acc[provider] || 0) + 1
return acc
},
{} as Record<string, number>
)
const overridesByProvider = overrides.reduce(
(acc, override) => {
acc[override.provider_id] = (acc[override.provider_id] || 0) + 1
return acc
},
{} as Record<string, number>
)
const report = {
timestamp: new Date().toISOString(),
summary: {
total_providers: providers.length,
total_base_models: models.length,
total_overrides: overrides.length,
provider_categories: providersByType,
models_by_provider: modelsByProvider,
overrides_by_provider: overridesByProvider
},
files: {
providers: 'providers.json',
models: 'models.json',
overrides: 'overrides.json'
}
}
await this.writeJsonFile('migration-report.json', report)
console.log('\n✅ Migration completed successfully!')
console.log(`📊 Migration Summary:`)
console.log(
` Providers: ${providers.length} (${providersByType.direct} direct, ${providersByType.cloud} cloud, ${providersByType.proxy} proxy, ${providersByType.self_hosted} self-hosted)`
)
console.log(` Base Models: ${models.length}`)
console.log(` Overrides: ${overrides.length}`)
console.log(`\n📁 Output Files:`)
console.log(` ${this.outputDir}/providers.json`)
console.log(` ${this.outputDir}/models.json`)
console.log(` ${this.outputDir}/overrides.json`)
console.log(` ${this.outputDir}/migration-report.json`)
}
private async writeJsonFile(filename: string, data: any): Promise<void> {
const filePath = path.join(this.outputDir, filename)
await fs.writeFile(filePath, JSON.stringify(data, null, 2), 'utf-8')
}
}
// CLI execution
if (require.main === module) {
const tool = new MigrationTool(
'./provider_endpoints_support.json',
'./model_prices_and_context_window.json',
'./migrated-data'
)
tool.migrate().catch(console.error)
}

View File

@@ -0,0 +1,88 @@
// https://github.com/vercel/ai/blob/6306603220f9f023fcdbeb9768d1c3fc2ca6bc80/packages/provider-utils/src/parse-json.ts
import type { JSONValue } from '../json-value'
import type { Schema } from '../schema'
import { safeValidateTypes, validateTypes } from '../validate-type'
import { secureJsonParse } from './secure-json-parse'
/**
* Parses a JSON string into an unknown object.
*
* @param text - The JSON string to parse.
* @returns {JSONValue} - The parsed JSON object.
*/
export async function parseJSON(options: { text: string; schema?: undefined }): Promise<JSONValue>
/**
* Parses a JSON string into a strongly-typed object using the provided schema.
*
* @template T - The type of the object to parse the JSON into.
* @param {string} text - The JSON string to parse.
* @param {Validator<T>} schema - The schema to use for parsing the JSON.
* @returns {Promise<T>} - The parsed object.
*/
export async function parseJSON<T>(options: { text: string; schema: Schema<T> }): Promise<T>
export async function parseJSON<T>({ text, schema }: { text: string; schema?: Schema<T> }): Promise<T> {
const value = secureJsonParse(text)
if (schema == null) {
return value
}
return validateTypes<T>({ value, schema })
}
export type ParseResult<T> =
| { success: true; value: T; rawValue: unknown }
| {
success: false
error: Error
rawValue: unknown
}
/**
* Safely parses a JSON string and returns the result as an object of type `unknown`.
*
* @param text - The JSON string to parse.
* @returns {Promise<object>} Either an object with `success: true` and the parsed data, or an object with `success: false` and the error that occurred.
*/
export async function safeParseJSON(options: { text: string; schema?: undefined }): Promise<ParseResult<JSONValue>>
/**
* Safely parses a JSON string into a strongly-typed object, using a provided schema to validate the object.
*
* @template T - The type of the object to parse the JSON into.
* @param {string} text - The JSON string to parse.
* @param {Validator<T>} schema - The schema to use for parsing the JSON.
* @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.
*/
export async function safeParseJSON<T>(options: { text: string; schema: Schema<T> }): Promise<ParseResult<T>>
export async function safeParseJSON<T>({
text,
schema
}: {
text: string
schema?: Schema<T>
}): Promise<ParseResult<T>> {
try {
const value = secureJsonParse(text)
if (schema == null) {
return { success: true, value: value as T, rawValue: value }
}
return await safeValidateTypes<T>({ value, schema })
} catch (error) {
return {
success: false,
error: error instanceof Error ? error : new Error('Unknown parsing error'),
rawValue: undefined
}
}
}
export function isParsableJson(input: string): boolean {
try {
secureJsonParse(input)
return true
} catch {
return false
}
}

View File

@@ -0,0 +1,90 @@
// https://github.com/vercel/ai/blob/32d8dbbebdb7831467c702094cc903cf93ee15ef/packages/provider-utils/src/secure-json-parse.ts
// Licensed under BSD-3-Clause (this file only)
// Code adapted from https://github.com/fastify/secure-json-parse/blob/783fcb1b5434709466759847cec974381939673a/index.js
//
// Copyright (c) Vercel, Inc. (https://vercel.com)
// Copyright (c) 2019 The Fastify Team
// Copyright (c) 2019, Sideway Inc, and project contributors
// All rights reserved.
//
// The complete list of contributors can be found at:
// - https://github.com/hapijs/bourne/graphs/contributors
// - https://github.com/fastify/secure-json-parse/graphs/contributors
// - https://github.com/vercel/ai/commits/main/packages/provider-utils/src/secure-parse-json.ts
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
const suspectProtoRx = /"__proto__"\s*:/
const suspectConstructorRx = /"constructor"\s*:/
function _parse(text: string) {
// Parse normally
const obj = JSON.parse(text)
// Ignore null and non-objects
if (obj === null || typeof obj !== 'object') {
return obj
}
if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
return obj
}
// Scan result for proto keys
return filter(obj)
}
function filter(obj: any) {
let next = [obj]
while (next.length) {
const nodes = next
next = []
for (const node of nodes) {
if (Object.prototype.hasOwnProperty.call(node, '__proto__')) {
throw new SyntaxError('Object contains forbidden prototype property')
}
if (
Object.prototype.hasOwnProperty.call(node, 'constructor') &&
Object.prototype.hasOwnProperty.call(node.constructor, 'prototype')
) {
throw new SyntaxError('Object contains forbidden prototype property')
}
for (const key in node) {
const value = node[key]
if (value && typeof value === 'object') {
next.push(value)
}
}
}
}
return obj
}
export function secureJsonParse(text: string) {
const { stackTraceLimit } = Error
try {
// Performance optimization, see https://github.com/fastify/secure-json-parse/pull/90
Error.stackTraceLimit = 0
} catch (e) {
// Fallback in case Error is immutable (v8 readonly)
return _parse(text)
}
try {
return _parse(text)
} finally {
Error.stackTraceLimit = stackTraceLimit
}
}

View File

@@ -0,0 +1,92 @@
// https://github.com/vercel/ai/blob/6306603220f9f023fcdbeb9768d1c3fc2ca6bc80/packages/provider-utils/src/schema.ts
import type { JSONSchema7 } from 'json-schema'
import * as z4 from 'zod/v4'
export type ValidationResult<OBJECT> = { success: true; value: OBJECT } | { success: false; error: Error }
const schemaSymbol = Symbol.for('schema')
export type Schema<OBJECT = unknown> = {
/**
* Used to mark schemas so we can support both Zod and custom schemas.
*/
[schemaSymbol]: true
/**
* Schema type for inference.
*/
_type: OBJECT
/**
* Optional. Validates that the structure of a value matches this schema,
* and returns a typed version of the value if it does.
*/
readonly validate?: (value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>
/**
* The JSON Schema for the schema.
*/
readonly jsonSchema: JSONSchema7 | PromiseLike<JSONSchema7>
}
export function asSchema<OBJECT>(schema: Schema<OBJECT> | undefined): Schema<OBJECT> {
return schema == null
? jsonSchema({
properties: {},
additionalProperties: false
})
: schema
}
export function jsonSchema<OBJECT = unknown>(
jsonSchema: JSONSchema7 | PromiseLike<JSONSchema7> | (() => JSONSchema7 | PromiseLike<JSONSchema7>),
{
validate
}: {
validate?: (value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>
} = {}
): Schema<OBJECT> {
return {
[schemaSymbol]: true,
_type: undefined as OBJECT, // should never be used directly
get jsonSchema() {
if (typeof jsonSchema === 'function') {
jsonSchema = jsonSchema() // cache the function results
}
return jsonSchema
},
validate
}
}
export function zod4Schema<OBJECT>(
zodSchema: z4.core.$ZodType<OBJECT, any>,
options?: {
/**
* Enables support for references in the schema.
* This is required for recursive schemas, e.g. with `z.lazy`.
* However, not all language models and providers support such references.
* Defaults to `false`.
*/
useReferences?: boolean
}
): Schema<OBJECT> {
// default to no references (to support openapi conversion for google)
const useReferences = options?.useReferences ?? false
return jsonSchema(
// defer json schema creation to avoid unnecessary computation when only validation is needed
() =>
z4.toJSONSchema(zodSchema, {
target: 'draft-7',
io: 'output',
reused: useReferences ? 'ref' : 'inline'
}) as JSONSchema7,
{
validate: async (value) => {
const result = await z4.safeParseAsync(zodSchema, value)
return result.success ? { success: true, value: result.data } : { success: false, error: result.error }
}
}
)
}

View File

@@ -0,0 +1,75 @@
// https://github.com/vercel/ai/blob/6306603220f9f023fcdbeb9768d1c3fc2ca6bc80/packages/provider-utils/src/validate-types.ts
import { asSchema, type Schema } from './schema'
/**
* Validates the types of an unknown object using a schema and
* return a strongly-typed object.
*
* @template T - The type of the object to validate.
* @param {string} options.value - The object to validate.
* @param {Validator<T>} options.schema - The schema to use for validating the JSON.
* @returns {Promise<T>} - The typed object.
*/
export async function validateTypes<OBJECT>({
value,
schema
}: {
value: unknown
schema: Schema<OBJECT>
}): Promise<OBJECT> {
const result = await safeValidateTypes({ value, schema })
if (!result.success) {
throw Error(`Validation failed: ${result.error.message}`)
}
return result.value
}
/**
* Safely validates the types of an unknown object using a schema and
* return a strongly-typed object.
*
* @template T - The type of the object to validate.
* @param {string} options.value - The JSON object to validate.
* @param {Validator<T>} options.schema - The schema to use for validating the JSON.
* @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.
*/
export async function safeValidateTypes<OBJECT>({ value, schema }: { value: unknown; schema: Schema<OBJECT> }): Promise<
| {
success: true
value: OBJECT
rawValue: unknown
}
| {
success: false
error: Error
rawValue: unknown
}
> {
const actualSchema = asSchema(schema)
try {
if (actualSchema.validate == null) {
return { success: true, value: value as OBJECT, rawValue: value }
}
const result = await actualSchema.validate(value)
if (result.success) {
return { success: true, value: result.value, rawValue: value }
}
return {
success: false,
error: Error(`Validation failed: ${result.error.message}`),
rawValue: value
}
} catch (error) {
return {
success: false,
error: error instanceof Error ? error : new Error('Unknown validation error'),
rawValue: value
}
}
}

View File

@@ -0,0 +1,299 @@
/**
* Schema Validator
* Provides validation functionality for all configuration schemas
*/
import * as z from 'zod'
import { ModelConfigSchema, OverrideListSchema, ProviderConfigSchema } from '../schemas'
import { zod4Schema } from '../utils/schema'
import { safeValidateTypes } from '../utils/validate-type'
export type ModelConfig = z.infer<typeof ModelConfigSchema>
export type ProviderConfig = z.infer<typeof ProviderConfigSchema>
export type OverrideConfig = z.infer<typeof OverrideListSchema>
export interface ValidationResult<T = any> {
success: boolean
data?: T
errors?: z.ZodIssue['path'] extends (string | number)[] ? z.ZodIssue : z.ZodIssue[]
warnings?: string[]
}
export interface ValidationOptions {
strict?: boolean
includeWarnings?: boolean
customValidation?: (data: any) => string[]
}
export class SchemaValidator {
/**
* Validate model configuration
*/
async validateModel(config: any, options: ValidationOptions = {}): Promise<ValidationResult<ModelConfig>> {
const { includeWarnings = true, customValidation } = options
const schema = zod4Schema(ModelConfigSchema)
const validation = await safeValidateTypes({ value: config, schema })
if (!validation.success) {
return {
success: false,
errors: [{ code: 'custom' as const, message: validation.error.message, path: [] }]
}
}
const model = validation.value
const warnings: string[] = []
// Basic warnings
if (includeWarnings) {
if (!model.pricing) {
warnings.push('No pricing information provided')
}
if (!model.description) {
warnings.push('No model description provided')
}
if (model.capabilities?.includes('REASONING') && !model.reasoning) {
warnings.push('Model has REASONING capability but no reasoning configuration')
}
if (model.contextWindow && model.contextWindow > 128000) {
warnings.push('Large context window may impact performance')
}
if (model.capabilities?.length === 0) {
warnings.push('No capabilities specified for model')
}
}
// Custom validation warnings
if (includeWarnings && customValidation) {
warnings.push(...customValidation(config))
}
return {
success: true,
data: model,
warnings: warnings.length > 0 ? warnings : undefined
}
}
/**
* Validate provider configuration
*/
validateProvider(config: any, options: ValidationOptions = {}): ValidationResult<ProviderConfig> {
const { includeWarnings = true, customValidation } = options
try {
const result = ProviderConfigSchema.parse(config)
const warnings: string[] = []
if (includeWarnings && customValidation) {
warnings.push(...customValidation(config))
}
if (includeWarnings) {
if (!config.behaviors.requiresApiKeyValidation) {
warnings.push('Provider does not require API key validation - ensure this is intentional')
}
if (config.endpoints.length === 0) {
warnings.push('No endpoints defined for provider')
}
if (config.pricingModel === 'UNIFIED' && !config.behaviors.providesModelMapping) {
warnings.push('Unified pricing model without model mapping may cause confusion')
}
}
return {
success: true,
data: result,
warnings: warnings.length > 0 ? warnings : undefined
}
} catch (error) {
if (error instanceof z.ZodError) {
return {
success: false,
errors: error.issues
}
}
return {
success: false,
errors: [{ code: 'custom' as const, message: 'Unknown validation error', path: [] }]
}
}
}
/**
* Validate override configuration
*/
validateOverride(config: any, options: ValidationOptions = {}): ValidationResult<OverrideConfig> {
const { includeWarnings = true, customValidation } = options
try {
const result = OverrideListSchema.parse(config)
const warnings: string[] = []
if (includeWarnings && customValidation) {
warnings.push(...customValidation(config))
}
if (includeWarnings) {
if (result.overrides.some((override) => !override.reason)) {
warnings.push('Some overrides lack reason documentation')
}
if (result.overrides.some((override) => override.priority > 1000)) {
warnings.push('Very high priority values may indicate configuration issues')
}
// Check for potential conflicts
const modelProviderPairs = result.overrides.map((o) => `${o.modelId}:${o.providerId}`)
const duplicates = modelProviderPairs.filter((pair, index) => modelProviderPairs.indexOf(pair) !== index)
if (duplicates.length > 0) {
warnings.push(`Duplicate override entries detected: ${duplicates.join(', ')}`)
}
}
return {
success: true,
data: result,
warnings: warnings.length > 0 ? warnings : undefined
}
} catch (error) {
if (error instanceof z.ZodError) {
return {
success: false,
errors: error.issues
}
}
return {
success: false,
errors: [{ code: 'custom' as const, message: 'Unknown validation error', path: [] }]
}
}
}
/**
* Validate array of configurations
*/
async validateModelArray(
configs: any[],
options: ValidationOptions = {}
): Promise<{
valid: ModelConfig[]
invalid: { config: any; errors: z.ZodIssue['path'] extends (string | number)[] ? z.ZodIssue : z.ZodIssue[] }[]
warnings: string[]
}> {
const valid: ModelConfig[] = []
const invalid: {
config: any
errors: z.ZodIssue['path'] extends (string | number)[] ? z.ZodIssue : z.ZodIssue[]
}[] = []
const allWarnings: string[] = []
configs.forEach(async (config, index) => {
const result = await this.validateModel(config, options)
if (result.success) {
valid.push(result.data!)
if (result.warnings) {
allWarnings.push(...result.warnings.map((w) => `Model ${index}: ${w}`))
}
} else {
invalid.push({ config, errors: result.errors! })
}
})
return { valid, invalid, warnings: allWarnings }
}
/**
* Validate provider array
*/
validateProviderArray(
configs: any[],
options: ValidationOptions = {}
): {
valid: ProviderConfig[]
invalid: { config: any; errors: z.ZodIssue['path'] extends (string | number)[] ? z.ZodIssue : z.ZodIssue[] }[]
warnings: string[]
} {
const valid: ProviderConfig[] = []
const invalid: {
config: any
errors: z.ZodIssue['path'] extends (string | number)[] ? z.ZodIssue : z.ZodIssue[]
}[] = []
const allWarnings: string[] = []
configs.forEach((config, index) => {
const result = this.validateProvider(config, options)
if (result.success) {
valid.push(result.data!)
if (result.warnings) {
allWarnings.push(...result.warnings.map((w) => `Provider ${index}: ${w}`))
}
} else {
invalid.push({ config, errors: result.errors! })
}
})
return { valid, invalid, warnings: allWarnings }
}
/**
* Format validation errors for display
*/
formatErrors(errors: z.ZodIssue['path'] extends (string | number)[] ? z.ZodIssue : z.ZodIssue[]): string[] {
return errors.map((error) => {
const path = error.path.length > 0 ? `${error.path.join('.')}: ` : ''
return `${path}${error.message}`
})
}
/**
* Generate validation summary
*/
generateSummary(results: {
models: {
valid: ModelConfig[]
invalid: { config: any; errors: z.ZodIssue['path'] extends (string | number)[] ? z.ZodIssue : z.ZodIssue[] }[]
warnings: string[]
}
providers: {
valid: ProviderConfig[]
invalid: { config: any; errors: z.ZodIssue['path'] extends (string | number)[] ? z.ZodIssue : z.ZodIssue[] }[]
warnings: string[]
}
overrides: ValidationResult<OverrideConfig>
}): {
totalModels: number
validModels: number
totalProviders: number
validProviders: number
overridesValid: boolean
allWarnings: string[]
} {
const { models, providers, overrides } = results
return {
totalModels: models.valid.length + models.invalid.length,
validModels: models.valid.length,
totalProviders: providers.valid.length + providers.invalid.length,
validProviders: providers.valid.length,
overridesValid: overrides.success || false,
allWarnings: [...models.warnings, ...providers.warnings, ...(overrides.warnings || [])]
}
}
}

View File

@@ -0,0 +1,21 @@
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"declaration": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "bundler",
"noEmitOnError": false,
"outDir": "./dist",
"resolveJsonModule": true,
"rootDir": "./src",
"skipLibCheck": true,
"strict": true,
"target": "ES2020"
},
"exclude": ["node_modules", "dist"],
"include": ["src/**/*", "scripts"]
}

View File

@@ -0,0 +1,12 @@
import { defineConfig } from 'tsdown'
export default defineConfig({
entry: {
index: 'src/index.ts'
},
outDir: 'dist',
format: ['esm', 'cjs'],
clean: true,
dts: true,
tsconfig: 'tsconfig.json'
})

View File

41
packages/catalog/web/.gitignore vendored Normal file
View File

@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

View File

@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.

View File

@@ -0,0 +1,285 @@
import { promises as fs } from 'fs'
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import path from 'path'
import { z } from 'zod'
import type { Model, ProviderModelOverride, OverridesDataFile } from '@/lib/catalog-types'
import {
ModelSchema,
ModelsDataFileSchema,
ProvidersDataFileSchema,
OverridesDataFileSchema
} from '@/lib/catalog-types'
import { safeParseWithValidation, validateString, ValidationError, createErrorResponse } from '@/lib/validation'
const DATA_DIR = path.join(process.cwd(), '../data')
// Type-safe helper function to apply overrides to base model
function applyOverrides(baseModel: Model, override: ProviderModelOverride | null): Model {
if (!override) return baseModel
return {
...baseModel,
...(override.limits && {
context_window: override.limits.context_window ?? baseModel.context_window,
max_output_tokens: override.limits.max_output_tokens ?? baseModel.max_output_tokens
}),
...(override.pricing && { pricing: override.pricing })
}
}
// Type-safe helper function to detect model modifications
function detectModifications(
baseModel: Model,
updatedModel: Partial<Model>
): {
pricing: Model['pricing'] | undefined
limits:
| {
context_window?: number
max_output_tokens?: number
}
| undefined
} | null {
const modifications: {
pricing: Model['pricing'] | undefined
limits:
| {
context_window?: number
max_output_tokens?: number
}
| undefined
} = {
pricing: undefined,
limits: undefined
}
// Check for differences in pricing
if (JSON.stringify(baseModel.pricing) !== JSON.stringify(updatedModel.pricing)) {
modifications.pricing = updatedModel.pricing
}
// Check for differences in limits
if (
baseModel.context_window !== updatedModel.context_window ||
baseModel.max_output_tokens !== updatedModel.max_output_tokens
) {
modifications.limits = {}
if (baseModel.context_window !== updatedModel.context_window) {
modifications.limits.context_window = updatedModel.context_window
}
if (baseModel.max_output_tokens !== updatedModel.max_output_tokens) {
modifications.limits.max_output_tokens = updatedModel.max_output_tokens
}
}
return modifications.pricing || modifications.limits ? modifications : null
}
export async function GET(request: NextRequest, { params }: { params: { modelId: string; providerId: string } }) {
try {
const { modelId, providerId } = params
// Validate parameters
const validModelId = validateString(modelId, 'modelId')
const validProviderId = validateString(providerId, 'providerId')
// Read and validate all data files
const [modelsDataRaw, providersDataRaw, overridesDataRaw] = await Promise.all([
fs.readFile(path.join(DATA_DIR, 'models.json'), 'utf-8'),
fs.readFile(path.join(DATA_DIR, 'providers.json'), 'utf-8'),
fs.readFile(path.join(DATA_DIR, 'overrides.json'), 'utf-8')
])
const modelsData = await safeParseWithValidation(
modelsDataRaw,
ModelsDataFileSchema,
'Invalid models data format in file'
)
const providersData = await safeParseWithValidation(
providersDataRaw,
ProvidersDataFileSchema,
'Invalid providers data format in file'
)
const overridesData = await safeParseWithValidation(
overridesDataRaw,
OverridesDataFileSchema,
'Invalid overrides data format in file'
)
// Find base model
const baseModel = modelsData.models.find((m) => m.id === validModelId)
if (!baseModel) {
return NextResponse.json(createErrorResponse('Model not found', 404), { status: 404 })
}
// Find provider override for this model
const override = overridesData.overrides.find(
(o) => o.model_id === validModelId && o.provider_id === validProviderId
)
// Apply override if exists
const finalModel = applyOverrides(baseModel, override || null)
return NextResponse.json(ModelSchema.parse(finalModel))
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation error:', error.message, error.details)
return NextResponse.json(createErrorResponse(error.message, 400, error.details), { status: 400 })
}
console.error('Error fetching provider model:', error)
return NextResponse.json(
createErrorResponse(
'Failed to fetch model configuration',
500,
error instanceof Error ? error.message : 'Unknown error'
),
{ status: 500 }
)
}
}
// Response schema for provider model updates
const ProviderModelUpdateResponseSchema = z.object({
updated: z.enum(['base_model', 'override', 'override_updated', 'override_removed']),
model: ModelSchema
})
export async function PUT(request: NextRequest, { params }: { params: { modelId: string; providerId: string } }) {
try {
const { modelId, providerId } = params
// Validate parameters
const validModelId = validateString(modelId, 'modelId')
const validProviderId = validateString(providerId, 'providerId')
// Validate request body
const requestBody = await request.json()
const updatedModel = await safeParseWithValidation(
JSON.stringify(requestBody),
ModelSchema.partial(),
'Invalid model data in request body'
)
// Read and validate current data
const [modelsDataRaw, providersDataRaw, overridesDataRaw] = await Promise.all([
fs.readFile(path.join(DATA_DIR, 'models.json'), 'utf-8'),
fs.readFile(path.join(DATA_DIR, 'providers.json'), 'utf-8'),
fs.readFile(path.join(DATA_DIR, 'overrides.json'), 'utf-8')
])
const modelsData = await safeParseWithValidation(
modelsDataRaw,
ModelsDataFileSchema,
'Invalid models data format in file'
)
const providersData = await safeParseWithValidation(
providersDataRaw,
ProvidersDataFileSchema,
'Invalid providers data format in file'
)
const overridesData = await safeParseWithValidation(
overridesDataRaw,
OverridesDataFileSchema,
'Invalid overrides data format in file'
)
// Find base model and existing override
const baseModelIndex = modelsData.models.findIndex((m) => m.id === validModelId)
const existingOverrideIndex = overridesData.overrides.findIndex(
(o) => o.model_id === validModelId && o.provider_id === validProviderId
)
if (baseModelIndex === -1) {
return NextResponse.json(createErrorResponse('Base model not found', 404), { status: 404 })
}
const baseModel = modelsData.models[baseModelIndex]
// Detect what needs to be overridden
const modifications = detectModifications(baseModel, updatedModel)
let updated: 'base_model' | 'override' | 'override_updated' | 'override_removed' = 'base_model'
let overrideCreated = false
if (modifications) {
// Create or update override
const override: ProviderModelOverride = {
provider_id: validProviderId,
model_id: validModelId,
disabled: false,
reason: 'Manual configuration update',
last_updated: new Date().toISOString().split('T')[0],
updated_by: 'web-interface',
priority: 100,
...modifications
}
const updatedOverrides = [...overridesData.overrides]
if (existingOverrideIndex >= 0) {
updatedOverrides[existingOverrideIndex] = {
...updatedOverrides[existingOverrideIndex],
...override,
last_updated: new Date().toISOString().split('T')[0]
}
} else {
updatedOverrides.push(override)
overrideCreated = true
}
const updatedOverridesData: OverridesDataFile = {
...overridesData,
overrides: updatedOverrides
}
updated = overrideCreated ? 'override' : 'override_updated'
// Save changes to overrides file
await fs.writeFile(path.join(DATA_DIR, 'overrides.json'), JSON.stringify(updatedOverridesData, null, 2), 'utf-8')
} else if (existingOverrideIndex >= 0) {
// Remove override if no differences exist
const updatedOverrides = overridesData.overrides.filter((_, index) => index !== existingOverrideIndex)
const updatedOverridesData: OverridesDataFile = {
...overridesData,
overrides: updatedOverrides
}
updated = 'override_removed'
// Save changes to overrides file
await fs.writeFile(path.join(DATA_DIR, 'overrides.json'), JSON.stringify(updatedOverridesData, null, 2), 'utf-8')
}
// Return the final model configuration
const finalOverride = overridesData.overrides.find(
(o) => o.model_id === validModelId && o.provider_id === validProviderId
)
const finalModel = applyOverrides(baseModel, finalOverride || null)
const response = ProviderModelUpdateResponseSchema.parse({
updated,
model: finalModel
})
return NextResponse.json(response)
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation error:', error.message, error.details)
return NextResponse.json(createErrorResponse(error.message, 400, error.details), { status: 400 })
}
console.error('Error updating provider model:', error)
return NextResponse.json(
createErrorResponse(
'Failed to update model configuration',
500,
error instanceof Error ? error.message : 'Unknown error'
),
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,113 @@
import { promises as fs } from 'fs'
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import path from 'path'
import type { ModelsDataFile } from '@/lib/catalog-types'
import { ModelSchema, ModelsDataFileSchema, ModelUpdateResponseSchema } from '@/lib/catalog-types'
import { createErrorResponse, safeParseWithValidation, ValidationError } from '@/lib/validation'
const DATA_DIR = path.join(process.cwd(), '../data')
export async function GET(request: NextRequest, { params }: { params: { modelId: string } }) {
try {
const { modelId } = params
// Read and validate models data using Zod
const modelsDataPath = path.join(DATA_DIR, 'models.json')
const modelsDataRaw = await fs.readFile(modelsDataPath, 'utf-8')
const modelsData = await safeParseWithValidation(
modelsDataRaw,
ModelsDataFileSchema,
'Invalid models data format in file'
)
// Find the model with type safety
const model = modelsData.models.find((m) => m.id === modelId)
if (!model) {
return NextResponse.json(createErrorResponse('Model not found', 404), { status: 404 })
}
return NextResponse.json(model)
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation error:', error.message, error.details)
return NextResponse.json(createErrorResponse(error.message, 400, error.details), { status: 400 })
}
console.error('Error fetching model:', error)
return NextResponse.json(
createErrorResponse('Failed to fetch model', 500, error instanceof Error ? error.message : 'Unknown error'),
{ status: 500 }
)
}
}
export async function PUT(request: NextRequest, { params }: { params: { modelId: string } }) {
try {
const { modelId } = params
// Read and validate request body using Zod
const requestBody = await request.json()
const updatedModel = await safeParseWithValidation(
JSON.stringify(requestBody),
ModelSchema,
'Invalid model data in request body'
)
// Validate that the model ID matches
if (updatedModel.id !== modelId) {
return NextResponse.json(createErrorResponse('Model ID in request body must match URL parameter', 400), {
status: 400
})
}
// Read current models data using Zod
const modelsDataPath = path.join(DATA_DIR, 'models.json')
const modelsDataRaw = await fs.readFile(modelsDataPath, 'utf-8')
const modelsData = await safeParseWithValidation(
modelsDataRaw,
ModelsDataFileSchema,
'Invalid models data format in file'
)
// Find and update the model
const modelIndex = modelsData.models.findIndex((m) => m.id === modelId)
if (modelIndex === -1) {
return NextResponse.json(createErrorResponse('Model not found', 404), { status: 404 })
}
// Create updated models array (immutability)
const updatedModels = [
...modelsData.models.slice(0, modelIndex),
updatedModel,
...modelsData.models.slice(modelIndex + 1)
]
const updatedModelsData: ModelsDataFile = {
...modelsData,
models: updatedModels
}
// Write back to file
await fs.writeFile(modelsDataPath, JSON.stringify(updatedModelsData, null, 2), 'utf-8')
const response = ModelUpdateResponseSchema.parse({
success: true,
model: updatedModel
})
return NextResponse.json(response)
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation error:', error.message, error.details)
return NextResponse.json(createErrorResponse(error.message, 400, error.details), { status: 400 })
}
console.error('Error updating model:', error)
return NextResponse.json(
createErrorResponse('Failed to update model', 500, error instanceof Error ? error.message : 'Unknown error'),
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,156 @@
import { promises as fs } from 'fs'
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import path from 'path'
import type { Model } from '@/lib/catalog-types'
import {
ModelSchema,
ModelsDataFileSchema
} from '@/lib/catalog-types'
import {
createErrorResponse,
safeParseWithValidation,
validatePaginatedResponse,
validateQueryParams,
ValidationError
} from '@/lib/validation'
const DATA_DIR = path.join(process.cwd(), '../data')
function filterModels(
models: readonly Model[],
search?: string,
capabilities?: string[],
providers?: string[]
): Model[] {
let filtered = [...models]
if (search) {
const searchLower = search.toLowerCase()
filtered = filtered.filter(
(model) =>
model.id.toLowerCase().includes(searchLower) ||
model.name?.toLowerCase().includes(searchLower) ||
model.owned_by?.toLowerCase().includes(searchLower)
)
}
if (capabilities && capabilities.length > 0) {
filtered = filtered.filter((model) => capabilities.some((cap) => model.capabilities.includes(cap)))
}
if (providers && providers.length > 0) {
filtered = filtered.filter((model) => model.owned_by && providers.includes(model.owned_by))
}
return filtered
}
function paginateItems<T>(
items: readonly T[],
page: number,
limit: number
): {
items: T[]
pagination: {
page: number
limit: number
total: number
totalPages: number
hasNext: boolean
hasPrev: boolean
}
} {
const total = items.length
const totalPages = Math.ceil(total / limit)
const offset = (page - 1) * limit
const paginatedItems = items.slice(offset, offset + limit)
return {
items: paginatedItems,
pagination: {
page,
limit,
total,
totalPages,
hasNext: page < totalPages,
hasPrev: page > 1
}
}
}
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
// Validate query parameters using Zod
const validatedParams = validateQueryParams(searchParams)
// Read and validate models data using Zod
const modelsDataPath = path.join(DATA_DIR, 'models.json')
const modelsDataRaw = await fs.readFile(modelsDataPath, 'utf-8')
const modelsData = await safeParseWithValidation(
modelsDataRaw,
ModelsDataFileSchema,
'Invalid models data format in file'
)
// Filter models with type safety
const filteredModels = filterModels(
modelsData.models,
validatedParams.search,
validatedParams.capabilities,
validatedParams.providers
)
// Paginate results
const { items, pagination } = paginateItems(filteredModels, validatedParams.page, validatedParams.limit)
// Create paginated response using Zod schema
const response = validatePaginatedResponse({ data: items, pagination }, ModelSchema)
return NextResponse.json(response)
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation error:', error.message, error.details)
return NextResponse.json(createErrorResponse(error.message, 400, error.details), { status: 400 })
}
console.error('Error fetching models:', error)
return NextResponse.json(
createErrorResponse('Failed to fetch models', 500, error instanceof Error ? error.message : 'Unknown error'),
{ status: 500 }
)
}
}
export async function PUT(request: NextRequest) {
try {
const body = await request.json()
// Validate the data structure using Zod
const validatedData = await safeParseWithValidation(
JSON.stringify(body),
ModelsDataFileSchema,
'Invalid models data format in request body'
)
// Write validated data back to file
const modelsDataPath = path.join(DATA_DIR, 'models.json')
await fs.writeFile(modelsDataPath, JSON.stringify(validatedData, null, 2), 'utf-8')
return NextResponse.json({ success: true })
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation error:', error.message, error.details)
return NextResponse.json(createErrorResponse(error.message, 400, error.details), { status: 400 })
}
console.error('Error updating models:', error)
return NextResponse.json(
createErrorResponse('Failed to update models', 500, error instanceof Error ? error.message : 'Unknown error'),
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,113 @@
import { promises as fs } from 'fs'
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import path from 'path'
import type { ProvidersDataFile } from '@/lib/catalog-types'
import { ProviderSchema, ProvidersDataFileSchema, ProviderUpdateResponseSchema } from '@/lib/catalog-types'
import { createErrorResponse, safeParseWithValidation, ValidationError } from '@/lib/validation'
const DATA_DIR = path.join(process.cwd(), '../data')
export async function GET(request: NextRequest, { params }: { params: { providerId: string } }) {
try {
const { providerId } = params
// Read and validate providers data using Zod
const providersDataPath = path.join(DATA_DIR, 'providers.json')
const providersDataRaw = await fs.readFile(providersDataPath, 'utf-8')
const providersData = await safeParseWithValidation(
providersDataRaw,
ProvidersDataFileSchema,
'Invalid providers data format in file'
)
// Find the provider with type safety
const provider = providersData.providers.find((p) => p.id === providerId)
if (!provider) {
return NextResponse.json(createErrorResponse('Provider not found', 404), { status: 404 })
}
return NextResponse.json(provider)
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation error:', error.message, error.details)
return NextResponse.json(createErrorResponse(error.message, 400, error.details), { status: 400 })
}
console.error('Error fetching provider:', error)
return NextResponse.json(
createErrorResponse('Failed to fetch provider', 500, error instanceof Error ? error.message : 'Unknown error'),
{ status: 500 }
)
}
}
export async function PUT(request: NextRequest, { params }: { params: { providerId: string } }) {
try {
const { providerId } = params
// Read and validate request body using Zod
const requestBody = await request.json()
const updatedProvider = await safeParseWithValidation(
JSON.stringify(requestBody),
ProviderSchema,
'Invalid provider data in request body'
)
// Validate that the provider ID matches
if (updatedProvider.id !== providerId) {
return NextResponse.json(createErrorResponse('Provider ID in request body must match URL parameter', 400), {
status: 400
})
}
// Read current providers data using Zod
const providersDataPath = path.join(DATA_DIR, 'providers.json')
const providersDataRaw = await fs.readFile(providersDataPath, 'utf-8')
const providersData = await safeParseWithValidation(
providersDataRaw,
ProvidersDataFileSchema,
'Invalid providers data format in file'
)
// Find and update the provider
const providerIndex = providersData.providers.findIndex((p) => p.id === providerId)
if (providerIndex === -1) {
return NextResponse.json(createErrorResponse('Provider not found', 404), { status: 404 })
}
// Create updated providers array (immutability)
const updatedProviders = [
...providersData.providers.slice(0, providerIndex),
updatedProvider,
...providersData.providers.slice(providerIndex + 1)
]
const updatedProvidersData: ProvidersDataFile = {
...providersData,
providers: updatedProviders
}
// Write back to file
await fs.writeFile(providersDataPath, JSON.stringify(updatedProvidersData, null, 2), 'utf-8')
const response = ProviderUpdateResponseSchema.parse({
success: true,
provider: updatedProvider
})
return NextResponse.json(response)
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation error:', error.message, error.details)
return NextResponse.json(createErrorResponse(error.message, 400, error.details), { status: 400 })
}
console.error('Error updating provider:', error)
return NextResponse.json(
createErrorResponse('Failed to update provider', 500, error instanceof Error ? error.message : 'Unknown error'),
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,146 @@
import { promises as fs } from 'fs'
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import path from 'path'
import type { Provider } from '@/lib/catalog-types'
import {
ProviderSchema,
ProvidersDataFileSchema
} from '@/lib/catalog-types'
import {
createErrorResponse,
safeParseWithValidation,
validatePaginatedResponse,
validateQueryParams,
ValidationError
} from '@/lib/validation'
const DATA_DIR = path.join(process.cwd(), '../data')
function filterProviders(providers: readonly Provider[], search?: string, authentication?: string[]): Provider[] {
let filtered = [...providers]
if (search) {
const searchLower = search.toLowerCase()
filtered = filtered.filter(
(provider) =>
provider.id.toLowerCase().includes(searchLower) ||
provider.name.toLowerCase().includes(searchLower) ||
provider.description?.toLowerCase().includes(searchLower)
)
}
if (authentication && authentication.length > 0) {
filtered = filtered.filter((provider) => authentication.includes(provider.authentication))
}
return filtered
}
function paginateItems<T>(
items: readonly T[],
page: number,
limit: number
): {
items: T[]
pagination: {
page: number
limit: number
total: number
totalPages: number
hasNext: boolean
hasPrev: boolean
}
} {
const total = items.length
const totalPages = Math.ceil(total / limit)
const offset = (page - 1) * limit
const paginatedItems = items.slice(offset, offset + limit)
return {
items: paginatedItems,
pagination: {
page,
limit,
total,
totalPages,
hasNext: page < totalPages,
hasPrev: page > 1
}
}
}
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
// Validate query parameters using Zod
const validatedParams = validateQueryParams(searchParams)
// Read and validate providers data using Zod
const providersDataPath = path.join(DATA_DIR, 'providers.json')
const providersDataRaw = await fs.readFile(providersDataPath, 'utf-8')
const providersData = await safeParseWithValidation(
providersDataRaw,
ProvidersDataFileSchema,
'Invalid providers data format in file'
)
// Filter providers with type safety
const filteredProviders = filterProviders(
providersData.providers,
validatedParams.search,
validatedParams.authentication
)
// Paginate results
const { items, pagination } = paginateItems(filteredProviders, validatedParams.page, validatedParams.limit)
// Create paginated response using Zod schema
const response = validatePaginatedResponse({ data: items, pagination }, ProviderSchema)
return NextResponse.json(response)
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation error:', error.message, error.details)
return NextResponse.json(createErrorResponse(error.message, 400, error.details), { status: 400 })
}
console.error('Error fetching providers:', error)
return NextResponse.json(
createErrorResponse('Failed to fetch providers', 500, error instanceof Error ? error.message : 'Unknown error'),
{ status: 500 }
)
}
}
export async function PUT(request: NextRequest) {
try {
const body = await request.json()
// Validate the data structure using Zod
const validatedData = await safeParseWithValidation(
JSON.stringify(body),
ProvidersDataFileSchema,
'Invalid providers data format in request body'
)
// Write validated data back to file
const providersDataPath = path.join(DATA_DIR, 'providers.json')
await fs.writeFile(providersDataPath, JSON.stringify(validatedData, null, 2), 'utf-8')
return NextResponse.json({ success: true })
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation error:', error.message, error.details)
return NextResponse.json(createErrorResponse(error.message, 400, error.details), { status: 400 })
}
console.error('Error updating providers:', error)
return NextResponse.json(
createErrorResponse('Failed to update providers', 500, error instanceof Error ? error.message : 'Unknown error'),
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,70 @@
import { promises as fs } from 'fs'
import { NextResponse } from 'next/server'
import path from 'path'
import { z } from 'zod'
// Define schema for stats response
const StatsResponseSchema = z.object({
total_models: z.number(),
total_providers: z.number(),
total_overrides: z.number(),
last_updated: z.string().optional(),
migration_status: z.enum(['completed', 'in_progress', 'failed']).optional()
})
const DATA_DIR = path.join(process.cwd(), '../data')
// Define schema for migration report
const MigrationReportSchema = z.object({
summary: z.object({
total_base_models: z.number(),
total_providers: z.number(),
total_overrides: z.number()
})
})
const ModelsDataSchema = z.object({
version: z.string(),
models: z.array(z.any())
})
export async function GET() {
try {
// Read migration report for stats with Zod validation
const reportData = await fs.readFile(path.join(DATA_DIR, 'migration-report.json'), 'utf-8')
const report = MigrationReportSchema.parse(JSON.parse(reportData))
// Read actual data for last updated timestamp with Zod validation
const modelsData = await fs.readFile(path.join(DATA_DIR, 'models.json'), 'utf-8')
const models = ModelsDataSchema.parse(JSON.parse(modelsData))
const stats = {
total_models: report.summary.total_base_models,
total_providers: report.summary.total_providers,
total_overrides: report.summary.total_overrides,
last_updated: new Date().toISOString(),
version: models.version
}
// Validate response with Zod schema
const validatedStats = StatsResponseSchema.parse(stats)
return NextResponse.json(validatedStats)
} catch (error) {
console.error('Error fetching stats:', error)
// Try to provide a minimal fallback response
const fallbackStats = {
total_models: 0,
total_providers: 0,
total_overrides: 0
}
try {
const validatedFallback = StatsResponseSchema.parse(fallbackStats)
return NextResponse.json(validatedFallback)
} catch {
return NextResponse.json({ error: 'Failed to fetch stats' }, { status: 500 })
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View File

@@ -0,0 +1,26 @@
@import 'tailwindcss';
:root {
--background: #ffffff;
--foreground: #171717;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
}

View File

@@ -0,0 +1,31 @@
import './globals.css'
import type { Metadata } from 'next'
import { Geist, Geist_Mono } from 'next/font/google'
const geistSans = Geist({
variable: '--font-geist-sans',
subsets: ['latin']
})
const geistMono = Geist_Mono({
variable: '--font-geist-mono',
subsets: ['latin']
})
export const metadata: Metadata = {
title: 'Create Next App',
description: 'Generated by create next app'
}
export default function RootLayout({
children
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang="en">
<body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>{children}</body>
</html>
)
}

View File

@@ -0,0 +1,348 @@
'use client'
import { useState } from 'react'
import { Navigation } from '@/components/navigation'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Separator } from '@/components/ui/separator'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Textarea } from '@/components/ui/textarea'
// Import SWR hooks and utilities
import { getErrorMessage, useDebounce, useModels, useUpdateModel } from '@/lib/api-client'
import type { CapabilityType, Model } from '@/lib/catalog-types'
// Type-safe capabilities list
const CAPABILITIES: readonly CapabilityType[] = [
'FUNCTION_CALL',
'REASONING',
'IMAGE_RECOGNITION',
'IMAGE_GENERATION',
'AUDIO_RECOGNITION',
'AUDIO_GENERATION',
'EMBEDDING',
'RERANK',
'AUDIO_TRANSCRIPT',
'VIDEO_RECOGNITION',
'VIDEO_GENERATION',
'STRUCTURED_OUTPUT',
'FILE_INPUT',
'WEB_SEARCH',
'CODE_EXECUTION',
'FILE_SEARCH',
'COMPUTER_USE'
] as const
// Simple Pagination Component
function SimplePagination({
currentPage,
totalPages,
onPageChange
}: {
currentPage: number
totalPages: number
onPageChange: (page: number) => void
}) {
const pages = Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
if (totalPages <= 5) return i + 1
if (currentPage <= 3) return i + 1
if (currentPage >= totalPages - 2) return totalPages - 4 + i
return currentPage - 2 + i
})
return (
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={() => onPageChange(currentPage - 1)} disabled={currentPage <= 1}>
Previous
</Button>
{pages.map((page) => (
<Button
key={page}
variant={currentPage === page ? 'default' : 'outline'}
size="sm"
onClick={() => onPageChange(page)}>
{page}
</Button>
))}
<Button
variant="outline"
size="sm"
onClick={() => onPageChange(currentPage + 1)}
disabled={currentPage >= totalPages}>
Next
</Button>
</div>
)
}
export default function CatalogReview() {
// Form state
const [search, setSearch] = useState('')
const [selectedCapabilities, setSelectedCapabilities] = useState<string[]>([])
const [selectedProviders, setSelectedProviders] = useState<string[]>([])
const [currentPage, setCurrentPage] = useState(1)
const [editingModel, setEditingModel] = useState<Model | null>(null)
const [jsonContent, setJsonContent] = useState('')
// Debounce search to avoid excessive API calls
const debouncedSearch = useDebounce(search, 300)
// SWR hook for fetching models
const {
data: modelsData,
error,
isLoading
} = useModels({
page: currentPage,
limit: 20,
search: debouncedSearch,
capabilities: selectedCapabilities.length > 0 ? selectedCapabilities : undefined,
providers: selectedProviders.length > 0 ? selectedProviders : undefined
})
// SWR mutation for updating models
const { trigger: updateModel, isMutating: isUpdating } = useUpdateModel()
// Extract data from SWR response
const models = modelsData?.data || []
const pagination = modelsData?.pagination || {
page: 1,
limit: 20,
total: 0,
totalPages: 0,
hasNext: false,
hasPrev: false
}
const handleEdit = (model: Model) => {
setEditingModel(model)
setJsonContent(JSON.stringify(model, null, 2))
}
const handleSave = async () => {
if (!editingModel) return
try {
// Validate JSON before sending
const updatedModel = JSON.parse(jsonContent) as unknown
// Basic validation - the API will do thorough validation
if (!updatedModel || typeof updatedModel !== 'object') {
throw new Error('Invalid JSON format')
}
// Use SWR mutation for optimistic update
await updateModel({
id: editingModel.id,
data: updatedModel as Partial<Model>
})
// Close dialog and reset form
setEditingModel(null)
setJsonContent('')
} catch (error) {
console.error('Error saving model:', error)
// Error will be handled by SWR and displayed in UI
}
}
// Type-safe function to extract unique providers
const getUniqueProviders = (): string[] => {
return [
...new Set(models.map((model) => model.owned_by).filter((provider): provider is string => Boolean(provider)))
]
}
return (
<div className="container mx-auto p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold">Catalog Review</h1>
<p className="text-muted-foreground">Review and validate model configurations after migration</p>
</div>
<Navigation />
</div>
<Card>
<CardHeader>
<CardTitle>Filters</CardTitle>
<CardDescription>Filter models to review specific configurations</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex gap-4">
<Input
placeholder="Search models..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="max-w-sm"
/>
</div>
<div>
<label className="text-sm font-medium mb-2 block">Capabilities</label>
<div className="flex flex-wrap gap-2">
{CAPABILITIES.map((capability) => (
<Badge
key={capability}
variant={selectedCapabilities.includes(capability) ? 'default' : 'outline'}
className="cursor-pointer"
onClick={() => {
setSelectedCapabilities((prev) =>
prev.includes(capability) ? prev.filter((c) => c !== capability) : [...prev, capability]
)
}}>
{capability.replace('_', ' ')}
</Badge>
))}
</div>
</div>
<div>
<label className="text-sm font-medium mb-2 block">Providers</label>
<div className="flex flex-wrap gap-2">
{getUniqueProviders().map((provider) => (
<Badge
key={provider}
variant={selectedProviders.includes(provider) ? 'default' : 'outline'}
className="cursor-pointer"
onClick={() => {
setSelectedProviders((prev) =>
prev.includes(provider) ? prev.filter((p) => p !== provider) : [...prev, provider]
)
}}>
{provider}
</Badge>
))}
</div>
</div>
</CardContent>
</Card>
{/* Error Display */}
{error && (
<Alert variant="destructive">
<AlertDescription>{getErrorMessage(error)}</AlertDescription>
</Alert>
)}
<Card>
<CardHeader>
<CardTitle>Models ({pagination.total})</CardTitle>
<CardDescription>Review migrated model configurations</CardDescription>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="text-center py-8">
<div className="animate-pulse">Loading models...</div>
</div>
) : (
<>
<Table>
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>Name</TableHead>
<TableHead>Provider</TableHead>
<TableHead>Capabilities</TableHead>
<TableHead>Context Window</TableHead>
<TableHead>Modalities</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{models.map((model) => (
<TableRow key={model.id}>
<TableCell className="font-mono text-sm">{model.id}</TableCell>
<TableCell>{model.name || model.id}</TableCell>
<TableCell>
<Badge variant="outline">{model.owned_by}</Badge>
</TableCell>
<TableCell>
<div className="flex flex-wrap gap-1 max-w-xs">
{model.capabilities.slice(0, 3).map((cap) => (
<Badge key={cap} variant="secondary" className="text-xs">
{cap.replace('_', ' ')}
</Badge>
))}
{model.capabilities.length > 3 && (
<Badge variant="secondary" className="text-xs">
+{model.capabilities.length - 3}
</Badge>
)}
</div>
</TableCell>
<TableCell>{model.context_window.toLocaleString()}</TableCell>
<TableCell>
<div className="text-sm">
<div>In: {model.input_modalities?.join(', ')}</div>
<div>Out: {model.output_modalities?.join(', ')}</div>
</div>
</TableCell>
<TableCell>
<Dialog>
<DialogTrigger asChild>
<Button variant="outline" size="sm" onClick={() => handleEdit(model)}>
Edit
</Button>
</DialogTrigger>
<DialogContent className="max-w-4xl max-h-[80vh] overflow-auto">
<DialogHeader>
<DialogTitle>Edit Model Configuration</DialogTitle>
<DialogDescription>
Modify the JSON configuration for {model.name || model.id}
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<Textarea
value={jsonContent}
onChange={(e) => setJsonContent(e.target.value)}
className="min-h-[400px] font-mono text-sm"
/>
<div className="flex gap-2 justify-end">
<Button variant="outline" onClick={() => setEditingModel(null)}>
Cancel
</Button>
<Button onClick={handleSave} disabled={isUpdating}>
{isUpdating ? 'Saving...' : 'Save Changes'}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<Separator className="my-4" />
<div className="flex items-center justify-between">
<div className="text-sm text-muted-foreground">
Showing {(pagination.page - 1) * pagination.limit + 1} to{' '}
{Math.min(pagination.page * pagination.limit, pagination.total)} of {pagination.total} models
</div>
<SimplePagination
currentPage={pagination.page}
totalPages={pagination.totalPages}
onPageChange={setCurrentPage}
/>
</div>
</>
)}
</CardContent>
</Card>
</div>
)
}

View File

@@ -0,0 +1,323 @@
'use client'
import { useState } from 'react'
import { Navigation } from '@/components/navigation'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Separator } from '@/components/ui/separator'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Textarea } from '@/components/ui/textarea'
// Import SWR hooks and utilities
import { getErrorMessage, useDebounce, useProviders, useUpdateProvider } from '@/lib/api-client'
import type { Provider } from '@/lib/catalog-types'
// Simple Pagination Component
function SimplePagination({
currentPage,
totalPages,
onPageChange
}: {
currentPage: number
totalPages: number
onPageChange: (page: number) => void
}) {
const pages = Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
if (totalPages <= 5) return i + 1
if (currentPage <= 3) return i + 1
if (currentPage >= totalPages - 2) return totalPages - 4 + i
return currentPage - 2 + i
})
return (
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={() => onPageChange(currentPage - 1)} disabled={currentPage <= 1}>
Previous
</Button>
{pages.map((page) => (
<Button
key={page}
variant={currentPage === page ? 'default' : 'outline'}
size="sm"
onClick={() => onPageChange(page)}>
{page}
</Button>
))}
<Button
variant="outline"
size="sm"
onClick={() => onPageChange(currentPage + 1)}
disabled={currentPage >= totalPages}>
Next
</Button>
</div>
)
}
export default function ProvidersPage() {
// Form state
const [search, setSearch] = useState('')
const [currentPage, setCurrentPage] = useState(1)
const [editingProvider, setEditingProvider] = useState<Provider | null>(null)
const [jsonContent, setJsonContent] = useState('')
// Debounce search to avoid excessive API calls
const debouncedSearch = useDebounce(search, 300)
// SWR hook for fetching providers
const {
data: providersData,
error,
isLoading,
mutate: refetchProviders
} = useProviders({
page: currentPage,
limit: 20,
search: debouncedSearch
})
// SWR mutation for updating providers
const { trigger: updateProvider, isMutating: isUpdating } = useUpdateProvider()
// Extract data from SWR response
const providers = providersData?.data || []
const pagination = providersData?.pagination || {
page: 1,
limit: 20,
total: 0,
totalPages: 0,
hasNext: false,
hasPrev: false
}
const handleEdit = (provider: Provider) => {
setEditingProvider(provider)
setJsonContent(JSON.stringify(provider, null, 2))
}
const handleSave = async () => {
if (!editingProvider) return
try {
// Validate JSON before sending
const updatedProvider = JSON.parse(jsonContent) as unknown
// Basic validation - the API will do thorough validation
if (!updatedProvider || typeof updatedProvider !== 'object') {
throw new Error('Invalid JSON format')
}
// Use SWR mutation for optimistic update
await updateProvider({
id: editingProvider.id,
data: updatedProvider as Partial<Provider>
})
// Close dialog and reset form
setEditingProvider(null)
setJsonContent('')
} catch (error) {
console.error('Error saving provider:', error)
// Error will be handled by SWR and displayed in UI
}
}
// Type-safe function to extract provider capabilities
const getCapabilities = (behaviors: Record<string, unknown>): string[] => {
return Object.entries(behaviors)
.filter(([_, value]) => value === true)
.map(([key, _]) => key.replace(/_/g, ' ').replace(/\b\w/g, (letter) => letter.toUpperCase()))
}
return (
<div className="container mx-auto p-6 space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold">Provider Management</h1>
<p className="text-muted-foreground">Review and validate provider configurations</p>
</div>
<Navigation />
</div>
<Card>
<CardHeader>
<CardTitle>Filters</CardTitle>
<CardDescription>Filter providers to review specific configurations</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex gap-4">
<Input
placeholder="Search providers..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="max-w-sm"
/>
</div>
</CardContent>
</Card>
{/* Error Display */}
{error && (
<Alert variant="destructive">
<AlertDescription>{getErrorMessage(error)}</AlertDescription>
</Alert>
)}
<Card>
<CardHeader>
<CardTitle>Providers ({pagination.total})</CardTitle>
<CardDescription>Review provider configurations and capabilities</CardDescription>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="text-center py-8">
<div className="animate-pulse">Loading providers...</div>
</div>
) : (
<>
<Table>
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>Name</TableHead>
<TableHead>Authentication</TableHead>
<TableHead>Pricing Model</TableHead>
<TableHead>Endpoints</TableHead>
<TableHead>Capabilities</TableHead>
<TableHead>Status</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{providers.map((provider) => (
<TableRow key={provider.id}>
<TableCell className="font-mono text-sm">{provider.id}</TableCell>
<TableCell>
<div>
<div className="font-medium">{provider.name}</div>
{provider.description && (
<div className="text-sm text-muted-foreground">{provider.description}</div>
)}
</div>
</TableCell>
<TableCell>
<Badge variant="outline">{provider.authentication}</Badge>
</TableCell>
<TableCell>
<Badge variant="secondary">{provider.pricing_model}</Badge>
</TableCell>
<TableCell>
<div className="flex flex-wrap gap-1 max-w-xs">
{provider.supported_endpoints.slice(0, 2).map((endpoint) => (
<Badge key={endpoint} variant="outline" className="text-xs">
{endpoint}
</Badge>
))}
{provider.supported_endpoints.length > 2 && (
<Badge variant="outline" className="text-xs">
+{provider.supported_endpoints.length - 2}
</Badge>
)}
</div>
</TableCell>
<TableCell>
<div className="flex flex-wrap gap-1 max-w-xs">
{getCapabilities(provider.behaviors)
.slice(0, 2)
.map((capability) => (
<Badge key={capability} variant="secondary" className="text-xs">
{capability}
</Badge>
))}
{getCapabilities(provider.behaviors).length > 2 && (
<Badge variant="secondary" className="text-xs">
+{getCapabilities(provider.behaviors).length - 2}
</Badge>
)}
</div>
</TableCell>
<TableCell>
<div className="space-y-1">
{provider.deprecated && (
<Badge variant="destructive" className="text-xs">
Deprecated
</Badge>
)}
{provider.maintenance_mode && (
<Badge variant="outline" className="text-xs">
Maintenance
</Badge>
)}
{!provider.deprecated && !provider.maintenance_mode && (
<Badge variant="default" className="text-xs">
Active
</Badge>
)}
</div>
</TableCell>
<TableCell>
<Dialog>
<DialogTrigger asChild>
<Button variant="outline" size="sm" onClick={() => handleEdit(provider)}>
Edit
</Button>
</DialogTrigger>
<DialogContent className="max-w-4xl max-h-[80vh] overflow-auto">
<DialogHeader>
<DialogTitle>Edit Provider Configuration</DialogTitle>
<DialogDescription>Modify the JSON configuration for {provider.name}</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<Textarea
value={jsonContent}
onChange={(e) => setJsonContent(e.target.value)}
className="min-h-[400px] font-mono text-sm"
/>
<div className="flex gap-2 justify-end">
<Button variant="outline" onClick={() => setEditingProvider(null)}>
Cancel
</Button>
<Button onClick={handleSave} disabled={isUpdating}>
{isUpdating ? 'Saving...' : 'Save Changes'}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<Separator className="my-4" />
<div className="flex items-center justify-between">
<div className="text-sm text-muted-foreground">
Showing {(pagination.page - 1) * pagination.limit + 1} to{' '}
{Math.min(pagination.page * pagination.limit, pagination.total)} of {pagination.total} providers
</div>
<SimplePagination
currentPage={pagination.page}
totalPages={pagination.totalPages}
onPageChange={setCurrentPage}
/>
</div>
</>
)}
</CardContent>
</Card>
</div>
)
}

View File

@@ -0,0 +1,20 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "tailwind.config.ts",
"css": "app/globals.css",
"baseColor": "slate",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
}
}

View File

@@ -0,0 +1,32 @@
'use client'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { cn } from '@/lib/utils'
const navigation = [
{ name: 'Models', href: '/' },
{ name: 'Providers', href: '/providers' },
{ name: 'Overrides', href: '/overrides' }
]
export function Navigation() {
const pathname = usePathname()
return (
<nav className="flex space-x-8">
{navigation.map((item) => (
<Link
key={item.name}
href={item.href}
className={cn(
'text-sm font-medium transition-colors hover:text-primary',
pathname === item.href ? 'text-foreground' : 'text-muted-foreground'
)}>
{item.name}
</Link>
))}
</nav>
)
}

View File

@@ -0,0 +1,59 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
))
Alert.displayName = "Alert"
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
))
AlertTitle.displayName = "AlertTitle"
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
))
AlertDescription.displayName = "AlertDescription"
export { Alert, AlertTitle, AlertDescription }

View File

@@ -0,0 +1,29 @@
import { cva, type VariantProps } from 'class-variance-authority'
import * as React from 'react'
import { cn } from '@/lib/utils'
const badgeVariants = cva(
'inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
{
variants: {
variant: {
default: 'border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80',
secondary: 'border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80',
destructive: 'border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80',
outline: 'text-foreground'
}
},
defaultVariants: {
variant: 'default'
}
}
)
export interface BadgeProps extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return <div className={cn(badgeVariants({ variant }), className)} {...props} />
}
export { Badge, badgeVariants }

View File

@@ -0,0 +1,52 @@
import { Slot } from '@radix-ui/react-slot'
import { cva, type VariantProps } from 'class-variance-authority'
import * as React from 'react'
import { cn } from '@/lib/utils'
const buttonVariants = cva(
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground shadow hover:bg-primary/90',
destructive: 'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90',
outline: 'border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground',
secondary: 'bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80',
ghost: 'hover:bg-accent hover:text-accent-foreground',
link: 'text-primary underline-offset-4 hover:underline'
},
size: {
default: 'h-9 px-4 py-2',
sm: 'h-8 rounded-md px-3 text-xs',
lg: 'h-10 rounded-md px-8',
icon: 'h-9 w-9'
}
},
defaultVariants: {
variant: 'default',
size: 'default'
}
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = ({
ref,
className,
variant,
size,
asChild = false,
...props
}: ButtonProps & { ref?: React.RefObject<HTMLButtonElement | null> }) => {
const Comp = asChild ? Slot : 'button'
return <Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />
}
Button.displayName = 'Button'
export { Button, buttonVariants }

View File

@@ -0,0 +1,59 @@
import * as React from 'react'
import { cn } from '@/lib/utils'
const Card = ({
ref,
className,
...props
}: React.HTMLAttributes<HTMLDivElement> & { ref?: React.RefObject<HTMLDivElement | null> }) => (
<div ref={ref} className={cn('rounded-xl border bg-card text-card-foreground shadow', className)} {...props} />
)
Card.displayName = 'Card'
const CardHeader = ({
ref,
className,
...props
}: React.HTMLAttributes<HTMLDivElement> & { ref?: React.RefObject<HTMLDivElement | null> }) => (
<div ref={ref} className={cn('flex flex-col space-y-1.5 p-6', className)} {...props} />
)
CardHeader.displayName = 'CardHeader'
const CardTitle = ({
ref,
className,
...props
}: React.HTMLAttributes<HTMLDivElement> & { ref?: React.RefObject<HTMLDivElement | null> }) => (
<div ref={ref} className={cn('font-semibold leading-none tracking-tight', className)} {...props} />
)
CardTitle.displayName = 'CardTitle'
const CardDescription = ({
ref,
className,
...props
}: React.HTMLAttributes<HTMLDivElement> & { ref?: React.RefObject<HTMLDivElement | null> }) => (
<div ref={ref} className={cn('text-sm text-muted-foreground', className)} {...props} />
)
CardDescription.displayName = 'CardDescription'
const CardContent = ({
ref,
className,
...props
}: React.HTMLAttributes<HTMLDivElement> & { ref?: React.RefObject<HTMLDivElement | null> }) => (
<div ref={ref} className={cn('p-6 pt-0', className)} {...props} />
)
CardContent.displayName = 'CardContent'
const CardFooter = ({
ref,
className,
...props
}: React.HTMLAttributes<HTMLDivElement> & { ref?: React.RefObject<HTMLDivElement | null> }) => (
<div ref={ref} className={cn('flex items-center p-6 pt-0', className)} {...props} />
)
CardFooter.displayName = 'CardFooter'
export { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle }

View File

@@ -0,0 +1,107 @@
'use client'
import * as DialogPrimitive from '@radix-ui/react-dialog'
import { Cross2Icon } from '@radix-ui/react-icons'
import * as React from 'react'
import { cn } from '@/lib/utils'
const Dialog = DialogPrimitive.Root
const DialogTrigger = DialogPrimitive.Trigger
const DialogPortal = DialogPrimitive.Portal
const DialogClose = DialogPrimitive.Close
const DialogOverlay = ({
ref,
className,
...props
}: React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay> & {
ref?: React.RefObject<React.ElementRef<typeof DialogPrimitive.Overlay> | null>
}) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className
)}
{...props}
/>
)
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = ({
ref,
className,
children,
...props
}: React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & {
ref?: React.RefObject<React.ElementRef<typeof DialogPrimitive.Content> | null>
}) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
className
)}
{...props}>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<Cross2Icon className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
)
DialogContent.displayName = DialogPrimitive.Content.displayName
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn('flex flex-col space-y-1.5 text-center sm:text-left', className)} {...props} />
)
DialogHeader.displayName = 'DialogHeader'
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn('flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2', className)} {...props} />
)
DialogFooter.displayName = 'DialogFooter'
const DialogTitle = ({
ref,
className,
...props
}: React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title> & {
ref?: React.RefObject<React.ElementRef<typeof DialogPrimitive.Title> | null>
}) => (
<DialogPrimitive.Title
ref={ref}
className={cn('text-lg font-semibold leading-none tracking-tight', className)}
{...props}
/>
)
DialogTitle.displayName = DialogPrimitive.Title.displayName
const DialogDescription = ({
ref,
className,
...props
}: React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description> & {
ref?: React.RefObject<React.ElementRef<typeof DialogPrimitive.Description> | null>
}) => <DialogPrimitive.Description ref={ref} className={cn('text-sm text-muted-foreground', className)} {...props} />
DialogDescription.displayName = DialogPrimitive.Description.displayName
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger
}

View File

@@ -0,0 +1,25 @@
import * as React from 'react'
import { cn } from '@/lib/utils'
const Input = ({
ref,
className,
type,
...props
}: React.ComponentProps<'input'> & { ref?: React.RefObject<HTMLInputElement | null> }) => {
return (
<input
type={type}
className={cn(
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
className
)}
ref={ref}
{...props}
/>
)
}
Input.displayName = 'Input'
export { Input }

View File

@@ -0,0 +1,88 @@
import { ChevronLeftIcon, ChevronRightIcon, DotsHorizontalIcon } from '@radix-ui/react-icons'
import * as React from 'react'
import type { ButtonProps } from '@/components/ui/button'
import { buttonVariants } from '@/components/ui/button'
import { cn } from '@/lib/utils'
const Pagination = ({ className, ...props }: React.ComponentProps<'nav'>) => (
<nav
role="navigation"
aria-label="pagination"
className={cn('mx-auto flex w-full justify-center', className)}
{...props}
/>
)
Pagination.displayName = 'Pagination'
const PaginationContent = ({
ref,
className,
...props
}: React.ComponentProps<'ul'> & { ref?: React.RefObject<HTMLUListElement | null> }) => (
<ul ref={ref} className={cn('flex flex-row items-center gap-1', className)} {...props} />
)
PaginationContent.displayName = 'PaginationContent'
const PaginationItem = ({
ref,
className,
...props
}: React.ComponentProps<'li'> & { ref?: React.RefObject<HTMLLIElement | null> }) => (
<li ref={ref} className={cn('', className)} {...props} />
)
PaginationItem.displayName = 'PaginationItem'
type PaginationLinkProps = {
isActive?: boolean
} & Pick<ButtonProps, 'size'> &
React.ComponentProps<'a'>
const PaginationLink = ({ className, isActive, size = 'icon', ...props }: PaginationLinkProps) => (
<a
aria-current={isActive ? 'page' : undefined}
className={cn(
buttonVariants({
variant: isActive ? 'outline' : 'ghost',
size
}),
className
)}
{...props}
/>
)
PaginationLink.displayName = 'PaginationLink'
const PaginationPrevious = ({ className, ...props }: React.ComponentProps<typeof PaginationLink>) => (
<PaginationLink aria-label="Go to previous page" size="default" className={cn('gap-1 pl-2.5', className)} {...props}>
<ChevronLeftIcon className="h-4 w-4" />
<span>Previous</span>
</PaginationLink>
)
PaginationPrevious.displayName = 'PaginationPrevious'
const PaginationNext = ({ className, ...props }: React.ComponentProps<typeof PaginationLink>) => (
<PaginationLink aria-label="Go to next page" size="default" className={cn('gap-1 pr-2.5', className)} {...props}>
<span>Next</span>
<ChevronRightIcon className="h-4 w-4" />
</PaginationLink>
)
PaginationNext.displayName = 'PaginationNext'
const PaginationEllipsis = ({ className, ...props }: React.ComponentProps<'span'>) => (
<span aria-hidden className={cn('flex h-9 w-9 items-center justify-center', className)} {...props}>
<DotsHorizontalIcon className="h-4 w-4" />
<span className="sr-only">More pages</span>
</span>
)
PaginationEllipsis.displayName = 'PaginationEllipsis'
export {
Pagination,
PaginationContent,
PaginationEllipsis,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious
}

View File

@@ -0,0 +1,27 @@
'use client'
import * as SeparatorPrimitive from '@radix-ui/react-separator'
import * as React from 'react'
import { cn } from '@/lib/utils'
const Separator = ({
ref,
className,
orientation = 'horizontal',
decorative = true,
...props
}: React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root> & {
ref?: React.RefObject<React.ElementRef<typeof SeparatorPrimitive.Root> | null>
}) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn('shrink-0 bg-border', orientation === 'horizontal' ? 'h-[1px] w-full' : 'h-full w-[1px]', className)}
{...props}
/>
)
Separator.displayName = SeparatorPrimitive.Root.displayName
export { Separator }

View File

@@ -0,0 +1,94 @@
import * as React from 'react'
import { cn } from '@/lib/utils'
const Table = ({
ref,
className,
...props
}: React.HTMLAttributes<HTMLTableElement> & { ref?: React.RefObject<HTMLTableElement | null> }) => (
<div className="relative w-full overflow-auto">
<table ref={ref} className={cn('w-full caption-bottom text-sm', className)} {...props} />
</div>
)
Table.displayName = 'Table'
const TableHeader = ({
ref,
className,
...props
}: React.HTMLAttributes<HTMLTableSectionElement> & { ref?: React.RefObject<HTMLTableSectionElement | null> }) => (
<thead ref={ref} className={cn('[&_tr]:border-b', className)} {...props} />
)
TableHeader.displayName = 'TableHeader'
const TableBody = ({
ref,
className,
...props
}: React.HTMLAttributes<HTMLTableSectionElement> & { ref?: React.RefObject<HTMLTableSectionElement | null> }) => (
<tbody ref={ref} className={cn('[&_tr:last-child]:border-0', className)} {...props} />
)
TableBody.displayName = 'TableBody'
const TableFooter = ({
ref,
className,
...props
}: React.HTMLAttributes<HTMLTableSectionElement> & { ref?: React.RefObject<HTMLTableSectionElement | null> }) => (
<tfoot ref={ref} className={cn('border-t bg-muted/50 font-medium [&>tr]:last:border-b-0', className)} {...props} />
)
TableFooter.displayName = 'TableFooter'
const TableRow = ({
ref,
className,
...props
}: React.HTMLAttributes<HTMLTableRowElement> & { ref?: React.RefObject<HTMLTableRowElement | null> }) => (
<tr
ref={ref}
className={cn('border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted', className)}
{...props}
/>
)
TableRow.displayName = 'TableRow'
const TableHead = ({
ref,
className,
...props
}: React.ThHTMLAttributes<HTMLTableCellElement> & { ref?: React.RefObject<HTMLTableCellElement | null> }) => (
<th
ref={ref}
className={cn(
'h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]',
className
)}
{...props}
/>
)
TableHead.displayName = 'TableHead'
const TableCell = ({
ref,
className,
...props
}: React.TdHTMLAttributes<HTMLTableCellElement> & { ref?: React.RefObject<HTMLTableCellElement | null> }) => (
<td
ref={ref}
className={cn('p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]', className)}
{...props}
/>
)
TableCell.displayName = 'TableCell'
const TableCaption = ({
ref,
className,
...props
}: React.HTMLAttributes<HTMLTableCaptionElement> & { ref?: React.RefObject<HTMLTableCaptionElement | null> }) => (
<caption ref={ref} className={cn('mt-4 text-sm text-muted-foreground', className)} {...props} />
)
TableCaption.displayName = 'TableCaption'
export { Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow }

View File

@@ -0,0 +1,23 @@
import * as React from 'react'
import { cn } from '@/lib/utils'
const Textarea = ({
ref,
className,
...props
}: React.ComponentProps<'textarea'> & { ref?: React.RefObject<HTMLTextAreaElement | null> }) => {
return (
<textarea
className={cn(
'flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
className
)}
ref={ref}
{...props}
/>
)
}
Textarea.displayName = 'Textarea'
export { Textarea }

View File

@@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from 'eslint/config'
import nextVitals from 'eslint-config-next/core-web-vitals'
import nextTs from 'eslint-config-next/typescript'
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
'.next/**',
'out/**',
'build/**',
'next-env.d.ts'
])
])
export default eslintConfig

View File

@@ -0,0 +1,299 @@
/**
* API Client with SWR integration for catalog management
*
* This file provides:
* - Custom SWR fetchers with Zod validation
* - Mutations for CRUD operations with optimistic updates
* - Error handling utilities
* - Type-safe API interactions
*/
import { useEffect, useState } from 'react'
import type { SWRConfiguration, SWRResponse } from 'swr'
import useSWR from 'swr'
import useSWRMutation from 'swr/mutation'
import type { z } from 'zod'
// Import catalog types and schemas
import type { Model, PaginatedResponse, Provider } from './catalog-types'
import {
ModelSchema,
ModelUpdateResponseSchema,
PaginatedResponseSchema,
ProviderSchema,
ProviderUpdateResponseSchema
} from './catalog-types'
// API base configuration
const API_BASE = '/api/catalog'
// Extended error interface for better error handling
export interface ExtendedApiError {
error: string
status?: number
info?: unknown
}
// Generic API fetcher with Zod validation
async function apiFetcher<T extends z.ZodType>(url: string, schema: T, options?: RequestInit): Promise<z.infer<T>> {
const response = await fetch(url, {
headers: {
'Content-Type': 'application/json',
...options?.headers
},
...options
})
if (!response.ok) {
const errorData = response.headers.get('content-type')?.includes('application/json')
? await response.json()
: { error: response.statusText }
const error: ExtendedApiError = {
error: errorData.error || `HTTP ${response.status}`,
status: response.status,
info: errorData
}
throw error
}
const data = await response.json()
return schema.parse(data)
}
// API Client class for organized endpoint management
export class ApiClient {
// Models endpoints
static models = {
// Get models with pagination and filtering
list: (
params: { page?: number; limit?: number; search?: string; capabilities?: string[]; providers?: string[] } = {}
) => {
const searchParams = new URLSearchParams()
if (params.page) searchParams.set('page', params.page.toString())
if (params.limit) searchParams.set('limit', params.limit.toString())
if (params.search) searchParams.set('search', params.search)
if (params.capabilities?.length) searchParams.set('capabilities', params.capabilities.join(','))
if (params.providers?.length) searchParams.set('providers', params.providers.join(','))
return `${API_BASE}/models?${searchParams.toString()}`
},
// Update a model
update: (id: string, data: Partial<Model>) => ({
url: `${API_BASE}/models/${id}`,
method: 'PUT',
body: data
}),
// Delete a model (if implemented)
delete: (id: string) => ({
url: `${API_BASE}/models/${id}`,
method: 'DELETE'
})
}
// Providers endpoints
static providers = {
// Get providers with pagination and filtering
list: (params: { page?: number; limit?: number; search?: string } = {}) => {
const searchParams = new URLSearchParams()
if (params.page) searchParams.set('page', params.page.toString())
if (params.limit) searchParams.set('limit', params.limit.toString())
if (params.search) searchParams.set('search', params.search)
return `${API_BASE}/providers?${searchParams.toString()}`
},
// Update a provider
update: (id: string, data: Partial<Provider>) => ({
url: `${API_BASE}/providers/${id}`,
method: 'PUT',
body: data
}),
// Delete a provider (if implemented)
delete: (id: string) => ({
url: `${API_BASE}/providers/${id}`,
method: 'DELETE'
})
}
}
// SWR Hooks for Models
export function useModels(
params: {
page?: number
limit?: number
search?: string
capabilities?: string[]
providers?: string[]
} = {},
config?: SWRConfiguration<PaginatedResponse<Model>, ExtendedApiError>
): SWRResponse<PaginatedResponse<Model>, ExtendedApiError> {
const url = ApiClient.models.list(params)
return useSWR<PaginatedResponse<Model>, ExtendedApiError>(
url,
(url) => apiFetcher(url, PaginatedResponseSchema(ModelSchema)),
{
revalidateOnFocus: true,
revalidateOnReconnect: true,
dedupingInterval: 5000,
errorRetryCount: 3,
errorRetryInterval: 1000,
...config
}
)
}
// SWR Hooks for Providers
export function useProviders(
params: {
page?: number
limit?: number
search?: string
} = {},
config?: SWRConfiguration<PaginatedResponse<Provider>, ExtendedApiError>
): SWRResponse<PaginatedResponse<Provider>, ExtendedApiError> {
const url = ApiClient.providers.list(params)
return useSWR<PaginatedResponse<Provider>, ExtendedApiError>(
url,
(url) => apiFetcher(url, PaginatedResponseSchema(ProviderSchema)),
{
revalidateOnFocus: true,
revalidateOnReconnect: true,
dedupingInterval: 5000,
errorRetryCount: 3,
errorRetryInterval: 1000,
...config
}
)
}
// Mutation for updating models
export function useUpdateModel() {
return useSWRMutation(
'/api/catalog/models',
async (url: string, { arg }: { arg: { id: string; data: Partial<Model> } }) => {
const response = await fetch(`${url}/${arg.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(arg.data)
})
if (!response.ok) {
const errorData = await response.json()
const error: ExtendedApiError = {
error: errorData.error || 'Failed to update model',
status: response.status,
info: errorData
}
throw error
}
const data = await response.json()
return ModelUpdateResponseSchema.parse(data)
}
)
}
// Mutation for updating providers
export function useUpdateProvider() {
return useSWRMutation(
'/api/catalog/providers',
async (url: string, { arg }: { arg: { id: string; data: Partial<Provider> } }) => {
const response = await fetch(`${url}/${arg.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(arg.data)
})
if (!response.ok) {
const errorData = await response.json()
const error: ExtendedApiError = {
error: errorData.error || 'Failed to update provider',
status: response.status,
info: errorData
}
throw error
}
const data = await response.json()
return ProviderUpdateResponseSchema.parse(data)
}
)
}
// Utility function for global error handling
export function handleApiError(error: unknown): ExtendedApiError {
if (error && typeof error === 'object' && 'error' in error) {
return error as ExtendedApiError
}
return {
error: error instanceof Error ? error.message : 'Unknown error occurred'
}
}
// Utility function to get user-friendly error messages
export function getErrorMessage(error: unknown): string {
const apiError = handleApiError(error)
// Map common error codes to user-friendly messages
switch (apiError.status) {
case 400:
return 'Invalid request. Please check your input and try again.'
case 401:
return 'Authentication required. Please log in and try again.'
case 403:
return 'You do not have permission to perform this action.'
case 404:
return 'The requested resource was not found.'
case 429:
return 'Too many requests. Please wait a moment and try again.'
case 500:
return 'Server error. Please try again later.'
default:
return apiError.error || 'An unexpected error occurred.'
}
}
// Custom hook for debounced search
export function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState(value)
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value)
}, delay)
return () => {
clearTimeout(handler)
}
}, [value, delay])
return debouncedValue
}
// Export all types for use in components
export type { SWRResponse }
// Re-export SWR types for convenience
export type { SWRConfiguration } from 'swr'
// Legacy API Error class for backward compatibility
export class ApiError extends Error {
constructor(
message: string,
public status: number,
public details?: unknown
) {
super(message)
this.name = 'ApiError'
}
}

View File

@@ -0,0 +1,86 @@
/**
* Type definitions for catalog management system
* Now using Zod inferred types for complete type safety
*
* This file serves as the main export point for all types and schemas.
* Types are now inferred from Zod schemas to ensure compile-time and runtime consistency.
*/
// Import all types from Zod validation schemas
export type {
// Response and error types
ApiError,
AuthenticationType,
// Utility enum types
CapabilityType,
EndpointType,
ModalityType,
// Core data types (inferred from Zod schemas)
Model,
ModelListRequest,
ModelsDataFile,
ModelUpdateResponse,
OverridesDataFile,
PaginatedResponse,
// Pagination and response types
PaginationInfo,
Provider,
ProviderListRequest,
ProviderModelOverride,
ProvidersDataFile,
ProviderUpdateResponse,
SuccessResponse
} from './validation'
// Import Zod schemas for direct use if needed
export {
ApiErrorSchema,
AuthenticationTypeSchema,
// Utility schemas
CapabilityTypeSchema,
EndpointTypeSchema,
ModalityTypeSchema,
ModelListRequestSchema,
// Core schemas
ModelSchema,
ModelsDataFileSchema,
ModelUpdateResponseSchema,
OverridesDataFileSchema,
PaginatedResponseSchema,
ProviderModelOverrideSchema,
// Response schemas
PaginationInfoSchema,
ProviderListRequestSchema,
ProviderSchema,
ProvidersDataFileSchema,
ProviderUpdateResponseSchema,
QueryParamsSchema,
SuccessResponseSchema
} from './validation'
// Import validation utilities for easy access
export {
createErrorResponse,
formatZodError,
// Type guard functions (powered by Zod)
isModel,
isModelsDataFile,
isProvider,
isProvidersDataFile,
safeParseWithValidation,
safeTypeCast,
validatePaginatedResponse,
validateQueryParams,
validateString,
// Validation functions
ValidationError
} from './validation'
// Legacy convenience types (for backward compatibility)
// These are now re-exports of the Zod-inferred types above
export type {
// Re-export core types with legacy names for compatibility
Model as CatalogModel,
Provider as CatalogProvider,
PaginatedResponse as CatalogResponse
} from './validation'

View File

@@ -0,0 +1,6 @@
import { type ClassValue, clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

View File

@@ -0,0 +1,431 @@
/**
* Zod v4 schemas for comprehensive runtime type validation
* Replaces manual validation with strict type-safe schemas
*/
//TODO: 从catalog导入
import * as z from 'zod'
// Base parameter schemas
const ParameterRangeSchema = z.object({
supported: z.literal(true),
min: z.number().positive(),
max: z.number().positive(),
default: z.number().positive()
})
const ParameterBooleanSchema = z.object({
supported: z.boolean()
})
const ParameterUnsupportedSchema = z.object({
supported: z.literal(false)
})
const ParameterValueSchema = z.union([ParameterRangeSchema, ParameterBooleanSchema, ParameterUnsupportedSchema])
// Model parameters schema
const ModelParametersSchema = z
.object({
temperature: ParameterValueSchema.optional(),
max_tokens: z.union([
z.boolean(), // Simple boolean support indicator
z.object({
supported: z.literal(true),
default: z.number().positive().optional()
})
]).optional(),
system_message: z.boolean().optional(), // Simple boolean support indicator
top_p: z.union([ParameterValueSchema, ParameterUnsupportedSchema]).optional()
})
.loose() // Allow additional parameter types
// Pricing schema
const PricingInfoSchema = z.object({
input: z.object({
per_million_tokens: z.number().nonnegative(),
currency: z.string().length(3) // ISO 4217 currency codes
}),
output: z.object({
per_million_tokens: z.number().nonnegative(),
currency: z.string().length(3)
})
})
// Model metadata schema
const ModelMetadataSchema = z
.object({
source: z.string().optional(),
original_provider: z.string().optional(),
supports_caching: z.boolean().optional()
})
.loose() // Allow additional metadata
// Complete Model schema
export const ModelSchema = z.object({
id: z.string().min(1),
name: z.string().optional(),
owned_by: z.string().optional(),
capabilities: z.array(z.string()),
input_modalities: z.array(z.string()),
output_modalities: z.array(z.string()),
context_window: z.number().positive(),
max_output_tokens: z.number().positive(),
max_input_tokens: z.number().positive().optional(),
pricing: PricingInfoSchema.optional(),
parameters: ModelParametersSchema.optional(),
endpoint_types: z.array(z.string()).optional(),
metadata: ModelMetadataSchema.optional()
})
// Provider behaviors schema
const ProviderBehaviorsSchema = z
.object({
supports_custom_models: z.boolean(),
provides_model_mapping: z.boolean(),
supports_model_versioning: z.boolean(),
provides_fallback_routing: z.boolean(),
has_auto_retry: z.boolean(),
supports_health_check: z.boolean(),
has_real_time_metrics: z.boolean(),
provides_usage_analytics: z.boolean(),
supports_webhook_events: z.boolean(),
requires_api_key_validation: z.boolean(),
supports_rate_limiting: z.boolean(),
provides_usage_limits: z.boolean(),
supports_streaming: z.boolean(),
supports_batch_processing: z.boolean(),
supports_model_fine_tuning: z.boolean()
})
.loose() // Allow extensions
// API compatibility schema
const ApiCompatibilitySchema = z
.object({
supports_array_content: z.boolean().optional(),
supports_stream_options: z.boolean().optional(),
supports_developer_role: z.boolean().optional(),
supports_service_tier: z.boolean().optional(),
supports_thinking_control: z.boolean().optional(),
supports_api_version: z.boolean().optional(),
supports_parallel_tools: z.boolean().optional(),
supports_multimodal: z.boolean().optional()
})
.loose()
// Special configuration schema (flexible)
const SpecialConfigSchema = z.record(z.string(), z.unknown())
// Provider metadata schema
const ProviderMetadataSchema = z
.object({
source: z.string().optional(),
tags: z.array(z.string()).optional(),
reliability: z.enum(['low', 'medium', 'high']).optional()
})
.loose()
// Complete Provider schema
export const ProviderSchema = z.object({
id: z.string().min(1),
name: z.string().min(1),
description: z.string().optional(),
authentication: z.string().min(1),
pricing_model: z.string().min(1),
model_routing: z.string().min(1),
behaviors: ProviderBehaviorsSchema,
supported_endpoints: z.array(z.string()),
api_compatibility: ApiCompatibilitySchema.optional(),
default_api_host: z.url().optional(),
default_rate_limit: z.number().positive().optional(),
model_id_patterns: z.array(z.string()).optional(),
alias_model_ids: z.record(z.string(), z.string()).optional(),
documentation: z.string().url().optional(),
website: z.string().url().optional(),
deprecated: z.boolean(),
maintenance_mode: z.boolean(),
config_version: z.string().min(1),
special_config: SpecialConfigSchema.optional(),
metadata: ProviderMetadataSchema.optional()
})
// Data file schemas
export const ModelsDataFileSchema = z.object({
version: z.string().min(1),
models: z.array(ModelSchema)
})
export const ProvidersDataFileSchema = z.object({
version: z.string().min(1),
providers: z.array(ProviderSchema)
})
// Override schemas
const OverrideLimitsSchema = z.object({
context_window: z.number().positive().optional(),
max_output_tokens: z.number().positive().optional()
})
export const ProviderModelOverrideSchema = z.object({
provider_id: z.string().min(1),
model_id: z.string().min(1),
disabled: z.boolean().default(false),
reason: z.string().optional(),
last_updated: z.string().optional(),
updated_by: z.string().optional(),
priority: z.number().default(100),
limits: OverrideLimitsSchema.optional(),
pricing: PricingInfoSchema.optional()
})
export const OverridesDataFileSchema = z.object({
version: z.string().min(1),
overrides: z.array(ProviderModelOverrideSchema)
})
// Pagination schemas
export const PaginationInfoSchema = z.object({
page: z.number().positive(),
limit: z.number().positive().max(100),
total: z.number().nonnegative(),
totalPages: z.number().nonnegative(),
hasNext: z.boolean(),
hasPrev: z.boolean()
})
export const PaginatedResponseSchema = <T extends z.ZodType>(itemSchema: T) =>
z.object({
data: z.array(itemSchema),
pagination: PaginationInfoSchema
})
// Query parameter schemas
export const QueryParamsSchema = z.object({
page: z.coerce.number().positive().default(1),
limit: z.coerce.number().positive().max(100).default(20),
search: z.string().trim().optional(),
capabilities: z.array(z.string()).optional(),
providers: z.array(z.string()).optional(),
authentication: z.array(z.string()).optional()
})
// Request schemas for API endpoints
export const ModelListRequestSchema = QueryParamsSchema.extend({
capabilities: z.array(z.string()).optional(),
providers: z.array(z.string()).optional()
})
export const ProviderListRequestSchema = QueryParamsSchema.extend({
authentication: z.array(z.string()).optional()
})
// Response schemas
export const ApiErrorSchema = z.object({
error: z.string(),
details: z.unknown().optional()
})
export const SuccessResponseSchema = z.object({
success: z.literal(true)
})
export const ModelUpdateResponseSchema = SuccessResponseSchema.extend({
model: ModelSchema
})
export const ProviderUpdateResponseSchema = SuccessResponseSchema.extend({
provider: ProviderSchema
})
// Utility types for strict typing
export const CapabilityTypeSchema = z.enum([
'FUNCTION_CALL',
'REASONING',
'IMAGE_RECOGNITION',
'IMAGE_GENERATION',
'AUDIO_RECOGNITION',
'AUDIO_GENERATION',
'EMBEDDING',
'RERANK',
'AUDIO_TRANSCRIPT',
'VIDEO_RECOGNITION',
'VIDEO_GENERATION',
'STRUCTURED_OUTPUT',
'FILE_INPUT',
'WEB_SEARCH',
'CODE_EXECUTION',
'FILE_SEARCH',
'COMPUTER_USE'
])
export const ModalityTypeSchema = z.enum(['TEXT', 'VISION', 'AUDIO', 'VIDEO'])
export const AuthenticationTypeSchema = z.enum(['API_KEY', 'OAUTH', 'NONE', 'CUSTOM'])
export const EndpointTypeSchema = z.enum(['CHAT_COMPLETIONS', 'MESSAGES', 'RESPONSES', 'EMBEDDINGS', 'RERANK'])
// Validation utilities using Zod
// Custom error class for Zod validation errors
export class ValidationError extends Error {
constructor(
message: string,
public details?: unknown,
public zodError?: z.ZodError
) {
super(message)
this.name = 'ValidationError'
}
}
// String validation function
export function validateString(value: string, fieldName: string): string {
if (typeof value !== 'string' || value.trim().length === 0) {
throw new ValidationError(`${fieldName} must be a non-empty string`)
}
return value.trim()
}
// Safe JSON parsing with Zod validation
export async function safeParseWithValidation<T>(
jsonString: string,
schema: z.ZodType<T>,
errorMessage: string
): Promise<T> {
try {
const parsed = JSON.parse(jsonString)
const result = schema.safeParse(parsed)
if (!result.success) {
throw new ValidationError(`${errorMessage}: ${result.error.message}`, result.error.issues, result.error)
}
return result.data
} catch (error) {
if (error instanceof SyntaxError) {
throw new ValidationError('Invalid JSON format', { originalError: error.message })
}
if (error instanceof ValidationError) {
throw error
}
throw new ValidationError(
`Unexpected error during validation: ${error instanceof Error ? error.message : 'Unknown error'}`
)
}
}
// Validate API response structure using Zod
export function validatePaginatedResponse<T>(
data: unknown,
itemSchema: z.ZodType<T>
): z.infer<ReturnType<typeof PaginatedResponseSchema<typeof itemSchema>>> {
const schema = PaginatedResponseSchema(itemSchema)
const result = schema.safeParse(data)
if (!result.success) {
throw new ValidationError(`Invalid response format: ${result.error.message}`, result.error.issues, result.error)
}
return result.data
}
// Validate and sanitize query parameters using Zod
export function validateQueryParams(params: URLSearchParams): z.infer<typeof QueryParamsSchema> {
const queryParams: Record<string, string | string[]> = {}
// Handle all parameters - Array.from() for compatibility
Array.from(params.entries()).forEach(([key, value]) => {
if (['capabilities', 'providers', 'authentication'].includes(key)) {
if (!queryParams[key]) {
queryParams[key] = []
}
;(queryParams[key] as string[]).push(value)
} else {
queryParams[key] = value
}
})
const result = QueryParamsSchema.safeParse(queryParams)
if (!result.success) {
throw new ValidationError(`Invalid query parameters: ${result.error.message}`, result.error.issues, result.error)
}
return result.data
}
// Type-safe error response creation
export function createErrorResponse(
message: string,
status: number = 500,
details?: unknown
): z.infer<typeof ApiErrorSchema> {
const error: z.infer<typeof ApiErrorSchema> = { error: message }
if (details !== undefined) {
;(error as any).details = details
}
return error
}
// Safe type casting utility using Zod
export function safeTypeCast<T>(value: unknown, schema: z.ZodType<T>, typeName?: string): T {
const result = schema.safeParse(value)
if (!result.success) {
throw new ValidationError(
`Expected ${typeName || schema.description || 'valid type'}, but validation failed: ${result.error.message}`,
result.error.issues,
result.error
)
}
return result.data
}
// Utility function to extract validation error details
export function formatZodError(error: z.ZodError): string {
return error.issues
.map((issue) => {
const path = issue.path.join('.')
return `${path ? `${path}: ` : ''}${issue.message}`
})
.join('; ')
}
// Export inferred types
export type Model = z.infer<typeof ModelSchema>
export type Provider = z.infer<typeof ProviderSchema>
export type ProviderModelOverride = z.infer<typeof ProviderModelOverrideSchema>
export type ModelsDataFile = z.infer<typeof ModelsDataFileSchema>
export type ProvidersDataFile = z.infer<typeof ProvidersDataFileSchema>
export type OverridesDataFile = z.infer<typeof OverridesDataFileSchema>
export type PaginationInfo = z.infer<typeof PaginationInfoSchema>
export type PaginatedResponse<T> = z.infer<ReturnType<typeof PaginatedResponseSchema<z.ZodType<T>>>>
export type ModelListRequest = z.infer<typeof ModelListRequestSchema>
export type ProviderListRequest = z.infer<typeof ProviderListRequestSchema>
export type ApiError = z.infer<typeof ApiErrorSchema>
export type SuccessResponse = z.infer<typeof SuccessResponseSchema>
export type ModelUpdateResponse = z.infer<typeof ModelUpdateResponseSchema>
export type ProviderUpdateResponse = z.infer<typeof ProviderUpdateResponseSchema>
// Export enum types for convenience
export type CapabilityType = z.infer<typeof CapabilityTypeSchema>
export type ModalityType = z.infer<typeof ModalityTypeSchema>
export type AuthenticationType = z.infer<typeof AuthenticationTypeSchema>
export type EndpointType = z.infer<typeof EndpointTypeSchema>
// Legacy compatibility type guards (now using Zod internally)
export function isModel(obj: unknown): obj is Model {
return ModelSchema.safeParse(obj).success
}
export function isProvider(obj: unknown): obj is Provider {
return ProviderSchema.safeParse(obj).success
}
export function isModelsDataFile(obj: unknown): obj is ModelsDataFile {
return ModelsDataFileSchema.safeParse(obj).success
}
export function isProvidersDataFile(obj: unknown): obj is ProvidersDataFile {
return ProvidersDataFileSchema.safeParse(obj).success
}

View File

@@ -0,0 +1,40 @@
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
// Configure static file serving from external directory
async rewrites() {
return [
// Proxy API requests to the catalog API
{
source: '/api/catalog/:path*',
destination: 'http://localhost:3001/api/catalog/:path*'
}
]
},
// Add custom headers for static files
async headers() {
return [
{
source: '/data/:path*',
headers: [
{
key: 'Cache-Control',
value: 'public, max-age=3600, must-revalidate'
},
{
key: 'Access-Control-Allow-Origin',
value: '*'
}
]
}
]
},
// Configure serving static files from outside public directory
outputFileTracingExcludes: {
'*': ['./**/__tests__/**/*']
},
// Basic Turbopack configuration to silence warning
turbopack: {}
}
export default nextConfig

View File

@@ -0,0 +1,32 @@
{
"name": "@cherrystudio/catalog-web",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint"
},
"dependencies": {
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-icons": "^1.3.2",
"@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4",
"next": "16.0.6",
"react": "19.2.0",
"react-dom": "19.2.0",
"swr": "^2.3.7",
"zod": "^4.0.0"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "16.0.6",
"tailwindcss": "^4",
"typescript": "^5"
}
}

View File

@@ -0,0 +1,7 @@
const config = {
plugins: {
'@tailwindcss/postcss': {}
}
}
export default config

View File

@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts", "**/*.mts"],
"exclude": ["node_modules"]
}

View File

@@ -2,7 +2,7 @@ export enum IpcChannel {
App_GetCacheSize = 'app:get-cache-size',
App_ClearCache = 'app:clear-cache',
App_SetLaunchOnBoot = 'app:set-launch-on-boot',
App_SetLanguage = 'app:set-language',
// App_SetLanguage = 'app:set-language',
App_SetEnableSpellCheck = 'app:set-enable-spell-check',
App_SetSpellCheckLanguages = 'app:set-spell-check-languages',
App_CheckForUpdate = 'app:check-for-update',
@@ -14,7 +14,7 @@ export enum IpcChannel {
App_SetLaunchToTray = 'app:set-launch-to-tray',
App_SetTray = 'app:set-tray',
App_SetTrayOnClose = 'app:set-tray-on-close',
App_SetTheme = 'app:set-theme',
// App_SetTheme = 'app:set-theme',
App_SetAutoUpdate = 'app:set-auto-update',
App_SetTestPlan = 'app:set-test-plan',
App_SetTestChannel = 'app:set-test-channel',
@@ -47,7 +47,7 @@ export enum IpcChannel {
App_MacRequestProcessTrust = 'app:mac-request-process-trust',
App_QuoteToMain = 'app:quote-to-main',
App_SetDisableHardwareAcceleration = 'app:set-disable-hardware-acceleration',
// App_SetDisableHardwareAcceleration = 'app:set-disable-hardware-acceleration',
Notification_Send = 'notification:send',
Notification_OnClick = 'notification:on-click',
@@ -227,6 +227,22 @@ export enum IpcChannel {
Backup_DeleteS3File = 'backup:deleteS3File',
Backup_CheckS3Connection = 'backup:checkS3Connection',
// data migration
DataMigrate_CheckNeeded = 'data-migrate:check-needed',
DataMigrate_GetProgress = 'data-migrate:get-progress',
DataMigrate_Cancel = 'data-migrate:cancel',
DataMigrate_RequireBackup = 'data-migrate:require-backup',
DataMigrate_BackupCompleted = 'data-migrate:backup-completed',
DataMigrate_ShowBackupDialog = 'data-migrate:show-backup-dialog',
DataMigrate_StartFlow = 'data-migrate:start-flow',
DataMigrate_ProceedToBackup = 'data-migrate:proceed-to-backup',
DataMigrate_StartMigration = 'data-migrate:start-migration',
DataMigrate_RetryMigration = 'data-migrate:retry-migration',
DataMigrate_RestartApp = 'data-migrate:restart-app',
DataMigrate_CloseWindow = 'data-migrate:close-window',
DataMigrate_SendReduxData = 'data-migrate:send-redux-data',
DataMigrate_GetReduxData = 'data-migrate:get-redux-data',
// zip
Zip_Compress = 'zip:compress',
Zip_Decompress = 'zip:decompress',
@@ -242,7 +258,8 @@ export enum IpcChannel {
// events
BackupProgress = 'backup-progress',
ThemeUpdated = 'theme:updated',
DataMigrateProgress = 'data-migrate-progress',
NativeThemeUpdated = 'native-theme:updated',
RestoreProgress = 'restore-progress',
UpdateError = 'update-error',
UpdateAvailable = 'update-available',
@@ -281,12 +298,6 @@ export enum IpcChannel {
Selection_ToolbarVisibilityChange = 'selection:toolbar-visibility-change',
Selection_ToolbarDetermineSize = 'selection:toolbar-determine-size',
Selection_WriteToClipboard = 'selection:write-to-clipboard',
Selection_SetEnabled = 'selection:set-enabled',
Selection_SetTriggerMode = 'selection:set-trigger-mode',
Selection_SetFilterMode = 'selection:set-filter-mode',
Selection_SetFilterList = 'selection:set-filter-list',
Selection_SetFollowToolbar = 'selection:set-follow-toolbar',
Selection_SetRemeberWinSize = 'selection:set-remeber-win-size',
Selection_ActionWindowClose = 'selection:action-window-close',
Selection_ActionWindowMinimize = 'selection:action-window-minimize',
Selection_ActionWindowPin = 'selection:action-window-pin',
@@ -305,6 +316,27 @@ export enum IpcChannel {
Memory_DeleteAllMemoriesForUser = 'memory:delete-all-memories-for-user',
Memory_GetUsersList = 'memory:get-users-list',
// Data: Preference
Preference_Get = 'preference:get',
Preference_Set = 'preference:set',
Preference_GetMultiple = 'preference:get-multiple',
Preference_SetMultiple = 'preference:set-multiple',
Preference_GetAll = 'preference:get-all',
Preference_Subscribe = 'preference:subscribe',
Preference_Changed = 'preference:changed',
// Data: Cache
Cache_Sync = 'cache:sync',
Cache_SyncBatch = 'cache:sync-batch',
// Data: API Channels
DataApi_Request = 'data-api:request',
DataApi_Batch = 'data-api:batch',
DataApi_Transaction = 'data-api:transaction',
DataApi_Subscribe = 'data-api:subscribe',
DataApi_Unsubscribe = 'data-api:unsubscribe',
DataApi_Stream = 'data-api:stream',
// TRACE
TRACE_SAVE_DATA = 'trace:saveData',
TRACE_GET_DATA = 'trace:getData',

View File

@@ -202,11 +202,11 @@ export enum UpdateConfigUrl {
GITCODE = 'https://raw.gitcode.com/CherryHQ/cherry-studio/raw/x-files%2Fapp-upgrade-config/app-upgrade-config.json'
}
export enum UpgradeChannel {
LATEST = 'latest', // 最新稳定版本
RC = 'rc', // 公测版本
BETA = 'beta' // 预览版本
}
// export enum UpgradeChannel {
// LATEST = 'latest', // 最新稳定版本
// RC = 'rc', // 公测版本
// BETA = 'beta' // 预览版本
// }
export enum UpdateMirror {
GITHUB = 'github',

View File

@@ -0,0 +1,106 @@
# Cherry Studio Shared Data
This directory contains shared type definitions and schemas for the Cherry Studio data management systems. These files provide type safety and consistency across the entire application.
## 📁 Directory Structure
```
packages/shared/data/
├── api/ # Data API type system
│ ├── index.ts # Barrel exports for clean imports
│ ├── apiSchemas.ts # API endpoint definitions and mappings
│ ├── apiTypes.ts # Core request/response infrastructure types
│ ├── apiModels.ts # Business entity types and DTOs
│ ├── apiPaths.ts # API path definitions and utilities
│ └── errorCodes.ts # Standardized error handling
├── cache/ # Cache system type definitions
│ ├── cacheTypes.ts # Core cache infrastructure types
│ ├── cacheSchemas.ts # Cache key schemas and type mappings
│ └── cacheValueTypes.ts # Cache value type definitions
├── preference/ # Preference system type definitions
│ ├── preferenceTypes.ts # Core preference system types
│ └── preferenceSchemas.ts # Preference schemas and default values
└── README.md # This file
```
## 🏗️ System Overview
This directory provides type definitions for three main data management systems:
### API System (`api/`)
- **Purpose**: Type-safe IPC communication between Main and Renderer processes
- **Features**: RESTful patterns, error handling, business entity definitions
- **Usage**: Ensures type safety for all data API operations
### Cache System (`cache/`)
- **Purpose**: Type definitions for three-layer caching architecture
- **Features**: Memory/shared/persist cache schemas, TTL support, hook integration
- **Usage**: Type-safe caching operations across the application
### Preference System (`preference/`)
- **Purpose**: User configuration and settings management
- **Features**: 158 configuration items, default values, nested key support
- **Usage**: Type-safe preference access and synchronization
## 📋 File Categories
**Framework Infrastructure** - These are TypeScript type definitions that:
- ✅ Exist only at compile time
- ✅ Provide type safety and IntelliSense support
- ✅ Define contracts between application layers
- ✅ Enable static analysis and error detection
## 📖 Usage Examples
### API Types
```typescript
// Import API types
import type { DataRequest, DataResponse, ApiSchemas } from '@shared/data/api'
```
### Cache Types
```typescript
// Import cache types
import type { UseCacheKey, UseSharedCacheKey } from '@shared/data/cache'
```
### Preference Types
```typescript
// Import preference types
import type { PreferenceKeyType, PreferenceDefaultScopeType } from '@shared/data/preference'
```
## 🔧 Development Guidelines
### Adding Cache Types
1. Add cache key to `cache/cacheSchemas.ts`
2. Define value type in `cache/cacheValueTypes.ts`
3. Update type mappings for type safety
### Adding Preference Types
1. Add preference key to `preference/preferenceSchemas.ts`
2. Define default value and type
3. Preference system automatically picks up new keys
### Adding API Types
1. Define business entities in `api/apiModels.ts`
2. Add endpoint definitions to `api/apiSchemas.ts`
3. Export types from `api/index.ts`
### Best Practices
- Use `import type` for type-only imports
- Follow existing naming conventions
- Document complex types with JSDoc
- Maintain type safety across all imports
## 🔗 Related Implementation
### Main Process Services
- `src/main/data/CacheService.ts` - Main process cache management
- `src/main/data/PreferenceService.ts` - Preference management service
- `src/main/data/DataApiService.ts` - Data API coordination service
### Renderer Process Services
- `src/renderer/src/data/CacheService.ts` - Renderer cache service
- `src/renderer/src/data/PreferenceService.ts` - Renderer preference service
- `src/renderer/src/data/DataApiService.ts` - Renderer API client

View File

@@ -0,0 +1,107 @@
/**
* Generic test model definitions
* Contains flexible types for comprehensive API testing
*/
/**
* Generic test item entity - flexible structure for testing various scenarios
*/
export interface TestItem {
/** Unique identifier */
id: string
/** Item title */
title: string
/** Optional description */
description?: string
/** Type category */
type: string
/** Current status */
status: string
/** Priority level */
priority: string
/** Associated tags */
tags: string[]
/** Creation timestamp */
createdAt: string
/** Last update timestamp */
updatedAt: string
/** Additional metadata */
metadata: Record<string, any>
}
/**
* Data Transfer Objects (DTOs) for test operations
*/
/**
* DTO for creating a new test item
*/
export interface CreateTestItemDto {
/** Item title */
title: string
/** Optional description */
description?: string
/** Type category */
type?: string
/** Current status */
status?: string
/** Priority level */
priority?: string
/** Associated tags */
tags?: string[]
/** Additional metadata */
metadata?: Record<string, any>
}
/**
* DTO for updating an existing test item
*/
export interface UpdateTestItemDto {
/** Updated title */
title?: string
/** Updated description */
description?: string
/** Updated type */
type?: string
/** Updated status */
status?: string
/** Updated priority */
priority?: string
/** Updated tags */
tags?: string[]
/** Updated metadata */
metadata?: Record<string, any>
}
/**
* Bulk operation types for batch processing
*/
/**
* Request for bulk operations on multiple items
*/
export interface BulkOperationRequest<TData = any> {
/** Type of bulk operation to perform */
operation: 'create' | 'update' | 'delete' | 'archive' | 'restore'
/** Array of data items to process */
data: TData[]
}
/**
* Response from a bulk operation
*/
export interface BulkOperationResponse {
/** Number of successfully processed items */
successful: number
/** Number of items that failed processing */
failed: number
/** Array of errors that occurred during processing */
errors: Array<{
/** Index of the item that failed */
index: number
/** Error message */
error: string
/** Optional additional error data */
data?: any
}>
}

View File

@@ -0,0 +1,60 @@
import type { ApiSchemas } from './apiSchemas'
/**
* Template literal type utilities for converting parameterized paths to concrete paths
* This enables type-safe API calls with actual paths like '/test/items/123' instead of '/test/items/:id'
*/
/**
* Convert parameterized path templates to concrete path types
* @example '/test/items/:id' -> '/test/items/${string}'
* @example '/topics/:id/messages' -> '/topics/${string}/messages'
*/
export type ResolvedPath<T extends string> = T extends `${infer Prefix}/:${string}/${infer Suffix}`
? `${Prefix}/${string}/${ResolvedPath<Suffix>}`
: T extends `${infer Prefix}/:${string}`
? `${Prefix}/${string}`
: T
/**
* Generate all possible concrete paths from ApiSchemas
* This creates a union type of all valid API paths
*/
export type ConcreteApiPaths = {
[K in keyof ApiSchemas]: ResolvedPath<K & string>
}[keyof ApiSchemas]
/**
* Reverse lookup: from concrete path back to original template path
* Used to determine which ApiSchema entry matches a concrete path
*/
export type MatchApiPath<Path extends string> = {
[K in keyof ApiSchemas]: Path extends ResolvedPath<K & string> ? K : never
}[keyof ApiSchemas]
/**
* Extract query parameters type for a given concrete path
*/
export type QueryParamsForPath<Path extends string> = MatchApiPath<Path> extends keyof ApiSchemas
? ApiSchemas[MatchApiPath<Path>] extends { GET: { query?: infer Q } }
? Q
: Record<string, any>
: Record<string, any>
/**
* Extract request body type for a given concrete path and HTTP method
*/
export type BodyForPath<Path extends string, Method extends string> = MatchApiPath<Path> extends keyof ApiSchemas
? ApiSchemas[MatchApiPath<Path>] extends { [M in Method]: { body: infer B } }
? B
: any
: any
/**
* Extract response type for a given concrete path and HTTP method
*/
export type ResponseForPath<Path extends string, Method extends string> = MatchApiPath<Path> extends keyof ApiSchemas
? ApiSchemas[MatchApiPath<Path>] extends { [M in Method]: { response: infer R } }
? R
: any
: any

View File

@@ -0,0 +1,487 @@
// NOTE: Types are defined inline in the schema for simplicity
// If needed, specific types can be imported from './apiModels'
import type { BodyForPath, ConcreteApiPaths, QueryParamsForPath, ResponseForPath } from './apiPaths'
import type { HttpMethod, PaginatedResponse, PaginationParams } from './apiTypes'
// Re-export for external use
export type { ConcreteApiPaths } from './apiPaths'
/**
* Complete API Schema definitions for Test API
*
* Each path defines the supported HTTP methods with their:
* - Request parameters (params, query, body)
* - Response types
* - Type safety guarantees
*
* This schema serves as the contract between renderer and main processes,
* enabling full TypeScript type checking across IPC boundaries.
*/
export interface ApiSchemas {
/**
* Test items collection endpoint
* @example GET /test/items?page=1&limit=10&search=hello
* @example POST /test/items { "title": "New Test Item" }
*/
'/test/items': {
/** List all test items with optional filtering and pagination */
GET: {
query?: PaginationParams & {
/** Search items by title or description */
search?: string
/** Filter by item type */
type?: string
/** Filter by status */
status?: string
}
response: PaginatedResponse<any>
}
/** Create a new test item */
POST: {
body: {
title: string
description?: string
type?: string
status?: string
priority?: string
tags?: string[]
metadata?: Record<string, any>
}
response: any
}
}
/**
* Individual test item endpoint
* @example GET /test/items/123
* @example PUT /test/items/123 { "title": "Updated Title" }
* @example DELETE /test/items/123
*/
'/test/items/:id': {
/** Get a specific test item by ID */
GET: {
params: { id: string }
response: any
}
/** Update a specific test item */
PUT: {
params: { id: string }
body: {
title?: string
description?: string
type?: string
status?: string
priority?: string
tags?: string[]
metadata?: Record<string, any>
}
response: any
}
/** Delete a specific test item */
DELETE: {
params: { id: string }
response: void
}
}
/**
* Test search endpoint
* @example GET /test/search?query=hello&page=1&limit=20
*/
'/test/search': {
/** Search test items */
GET: {
query: {
/** Search query string */
query: string
/** Page number for pagination */
page?: number
/** Number of results per page */
limit?: number
/** Additional filters */
type?: string
status?: string
}
response: PaginatedResponse<any>
}
}
/**
* Test statistics endpoint
* @example GET /test/stats
*/
'/test/stats': {
/** Get comprehensive test statistics */
GET: {
response: {
/** Total number of items */
total: number
/** Item count grouped by type */
byType: Record<string, number>
/** Item count grouped by status */
byStatus: Record<string, number>
/** Item count grouped by priority */
byPriority: Record<string, number>
/** Recent activity timeline */
recentActivity: Array<{
/** Date of activity */
date: string
/** Number of items on that date */
count: number
}>
}
}
}
/**
* Test bulk operations endpoint
* @example POST /test/bulk { "operation": "create", "data": [...] }
*/
'/test/bulk': {
/** Perform bulk operations on test items */
POST: {
body: {
/** Operation type */
operation: 'create' | 'update' | 'delete'
/** Array of data items to process */
data: any[]
}
response: {
successful: number
failed: number
errors: string[]
}
}
}
/**
* Test error simulation endpoint
* @example POST /test/error { "errorType": "timeout" }
*/
'/test/error': {
/** Simulate various error scenarios for testing */
POST: {
body: {
/** Type of error to simulate */
errorType:
| 'timeout'
| 'network'
| 'server'
| 'notfound'
| 'validation'
| 'unauthorized'
| 'ratelimit'
| 'generic'
}
response: never
}
}
/**
* Test slow response endpoint
* @example POST /test/slow { "delay": 2000 }
*/
'/test/slow': {
/** Test slow response for performance testing */
POST: {
body: {
/** Delay in milliseconds */
delay: number
}
response: {
message: string
delay: number
timestamp: string
}
}
}
/**
* Test data reset endpoint
* @example POST /test/reset
*/
'/test/reset': {
/** Reset all test data to initial state */
POST: {
response: {
message: string
timestamp: string
}
}
}
/**
* Test config endpoint
* @example GET /test/config
* @example PUT /test/config { "setting": "value" }
*/
'/test/config': {
/** Get test configuration */
GET: {
response: Record<string, any>
}
/** Update test configuration */
PUT: {
body: Record<string, any>
response: Record<string, any>
}
}
/**
* Test status endpoint
* @example GET /test/status
*/
'/test/status': {
/** Get system test status */
GET: {
response: {
status: string
timestamp: string
version: string
uptime: number
environment: string
}
}
}
/**
* Test performance endpoint
* @example GET /test/performance
*/
'/test/performance': {
/** Get performance metrics */
GET: {
response: {
requestsPerSecond: number
averageLatency: number
memoryUsage: number
cpuUsage: number
uptime: number
}
}
}
/**
* Batch execution of multiple requests
* @example POST /batch { "requests": [...], "parallel": true }
*/
'/batch': {
/** Execute multiple API requests in a single call */
POST: {
body: {
/** Array of requests to execute */
requests: Array<{
/** HTTP method for the request */
method: HttpMethod
/** API path for the request */
path: string
/** URL parameters */
params?: any
/** Request body */
body?: any
}>
/** Execute requests in parallel vs sequential */
parallel?: boolean
}
response: {
/** Results array matching input order */
results: Array<{
/** HTTP status code */
status: number
/** Response data if successful */
data?: any
/** Error information if failed */
error?: any
}>
/** Batch execution metadata */
metadata: {
/** Total execution duration in ms */
duration: number
/** Number of successful requests */
successCount: number
/** Number of failed requests */
errorCount: number
}
}
}
}
/**
* Atomic transaction of multiple operations
* @example POST /transaction { "operations": [...], "options": { "rollbackOnError": true } }
*/
'/transaction': {
/** Execute multiple operations in a database transaction */
POST: {
body: {
/** Array of operations to execute atomically */
operations: Array<{
/** HTTP method for the operation */
method: HttpMethod
/** API path for the operation */
path: string
/** URL parameters */
params?: any
/** Request body */
body?: any
}>
/** Transaction configuration options */
options?: {
/** Database isolation level */
isolation?: 'read-uncommitted' | 'read-committed' | 'repeatable-read' | 'serializable'
/** Rollback all operations on any error */
rollbackOnError?: boolean
/** Transaction timeout in milliseconds */
timeout?: number
}
}
response: Array<{
/** HTTP status code */
status: number
/** Response data if successful */
data?: any
/** Error information if failed */
error?: any
}>
}
}
}
/**
* Simplified type extraction helpers
*/
export type ApiPaths = keyof ApiSchemas
export type ApiMethods<TPath extends ApiPaths> = keyof ApiSchemas[TPath] & HttpMethod
export type ApiResponse<TPath extends ApiPaths, TMethod extends string> = TPath extends keyof ApiSchemas
? TMethod extends keyof ApiSchemas[TPath]
? ApiSchemas[TPath][TMethod] extends { response: infer R }
? R
: never
: never
: never
export type ApiParams<TPath extends ApiPaths, TMethod extends string> = TPath extends keyof ApiSchemas
? TMethod extends keyof ApiSchemas[TPath]
? ApiSchemas[TPath][TMethod] extends { params: infer P }
? P
: never
: never
: never
export type ApiQuery<TPath extends ApiPaths, TMethod extends string> = TPath extends keyof ApiSchemas
? TMethod extends keyof ApiSchemas[TPath]
? ApiSchemas[TPath][TMethod] extends { query: infer Q }
? Q
: never
: never
: never
export type ApiBody<TPath extends ApiPaths, TMethod extends string> = TPath extends keyof ApiSchemas
? TMethod extends keyof ApiSchemas[TPath]
? ApiSchemas[TPath][TMethod] extends { body: infer B }
? B
: never
: never
: never
/**
* Type-safe API client interface using concrete paths
* Accepts actual paths like '/test/items/123' instead of '/test/items/:id'
* Automatically infers query, body, and response types from ApiSchemas
*/
export interface ApiClient {
get<TPath extends ConcreteApiPaths>(
path: TPath,
options?: {
query?: QueryParamsForPath<TPath>
headers?: Record<string, string>
}
): Promise<ResponseForPath<TPath, 'GET'>>
post<TPath extends ConcreteApiPaths>(
path: TPath,
options: {
body?: BodyForPath<TPath, 'POST'>
query?: Record<string, any>
headers?: Record<string, string>
}
): Promise<ResponseForPath<TPath, 'POST'>>
put<TPath extends ConcreteApiPaths>(
path: TPath,
options: {
body: BodyForPath<TPath, 'PUT'>
query?: Record<string, any>
headers?: Record<string, string>
}
): Promise<ResponseForPath<TPath, 'PUT'>>
delete<TPath extends ConcreteApiPaths>(
path: TPath,
options?: {
query?: Record<string, any>
headers?: Record<string, string>
}
): Promise<ResponseForPath<TPath, 'DELETE'>>
patch<TPath extends ConcreteApiPaths>(
path: TPath,
options: {
body?: BodyForPath<TPath, 'PATCH'>
query?: Record<string, any>
headers?: Record<string, string>
}
): Promise<ResponseForPath<TPath, 'PATCH'>>
}
/**
* Helper types to determine if parameters are required based on schema
*/
type HasRequiredQuery<Path extends ApiPaths, Method extends ApiMethods<Path>> = Path extends keyof ApiSchemas
? Method extends keyof ApiSchemas[Path]
? ApiSchemas[Path][Method] extends { query: any }
? true
: false
: false
: false
type HasRequiredBody<Path extends ApiPaths, Method extends ApiMethods<Path>> = Path extends keyof ApiSchemas
? Method extends keyof ApiSchemas[Path]
? ApiSchemas[Path][Method] extends { body: any }
? true
: false
: false
: false
type HasRequiredParams<Path extends ApiPaths, Method extends ApiMethods<Path>> = Path extends keyof ApiSchemas
? Method extends keyof ApiSchemas[Path]
? ApiSchemas[Path][Method] extends { params: any }
? true
: false
: false
: false
/**
* Handler function for a specific API endpoint
* Provides type-safe parameter extraction based on ApiSchemas
* Parameters are required or optional based on the schema definition
*/
export type ApiHandler<Path extends ApiPaths, Method extends ApiMethods<Path>> = (
params: (HasRequiredParams<Path, Method> extends true
? { params: ApiParams<Path, Method> }
: { params?: ApiParams<Path, Method> }) &
(HasRequiredQuery<Path, Method> extends true
? { query: ApiQuery<Path, Method> }
: { query?: ApiQuery<Path, Method> }) &
(HasRequiredBody<Path, Method> extends true ? { body: ApiBody<Path, Method> } : { body?: ApiBody<Path, Method> })
) => Promise<ApiResponse<Path, Method>>
/**
* Complete API implementation that must match ApiSchemas structure
* TypeScript will error if any endpoint is missing - this ensures exhaustive coverage
*/
export type ApiImplementation = {
[Path in ApiPaths]: {
[Method in ApiMethods<Path>]: ApiHandler<Path, Method>
}
}

View File

@@ -0,0 +1,289 @@
/**
* Core types for the Data API system
* Provides type definitions for request/response handling across renderer-main IPC communication
*/
/**
* Standard HTTP methods supported by the Data API
*/
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
/**
* Request object structure for Data API calls
*/
export interface DataRequest<T = any> {
/** Unique request identifier for tracking and correlation */
id: string
/** HTTP method for the request */
method: HttpMethod
/** API path (e.g., '/topics', '/topics/123') */
path: string
/** URL parameters for the request */
params?: Record<string, any>
/** Request body data */
body?: T
/** Request headers */
headers?: Record<string, string>
/** Additional metadata for request processing */
metadata?: {
/** Request timestamp */
timestamp: number
/** OpenTelemetry span context for tracing */
spanContext?: any
/** Cache options for this specific request */
cache?: CacheOptions
}
}
/**
* Response object structure for Data API calls
*/
export interface DataResponse<T = any> {
/** Request ID that this response corresponds to */
id: string
/** HTTP status code */
status: number
/** Response data if successful */
data?: T
/** Error information if request failed */
error?: DataApiError
/** Response metadata */
metadata?: {
/** Request processing duration in milliseconds */
duration: number
/** Whether response was served from cache */
cached?: boolean
/** Cache TTL if applicable */
cacheTtl?: number
/** Response timestamp */
timestamp: number
}
}
/**
* Standardized error structure for Data API
*/
export interface DataApiError {
/** Error code for programmatic handling */
code: string
/** Human-readable error message */
message: string
/** HTTP status code */
status: number
/** Additional error details */
details?: any
/** Error stack trace (development mode only) */
stack?: string
}
/**
* Standard error codes for Data API
*/
export enum ErrorCode {
// Client errors (4xx)
BAD_REQUEST = 'BAD_REQUEST',
UNAUTHORIZED = 'UNAUTHORIZED',
FORBIDDEN = 'FORBIDDEN',
NOT_FOUND = 'NOT_FOUND',
METHOD_NOT_ALLOWED = 'METHOD_NOT_ALLOWED',
VALIDATION_ERROR = 'VALIDATION_ERROR',
RATE_LIMIT_EXCEEDED = 'RATE_LIMIT_EXCEEDED',
// Server errors (5xx)
INTERNAL_SERVER_ERROR = 'INTERNAL_SERVER_ERROR',
DATABASE_ERROR = 'DATABASE_ERROR',
SERVICE_UNAVAILABLE = 'SERVICE_UNAVAILABLE',
// Custom application errors
MIGRATION_ERROR = 'MIGRATION_ERROR',
PERMISSION_DENIED = 'PERMISSION_DENIED',
RESOURCE_LOCKED = 'RESOURCE_LOCKED',
CONCURRENT_MODIFICATION = 'CONCURRENT_MODIFICATION'
}
/**
* Cache configuration options
*/
export interface CacheOptions {
/** Cache TTL in seconds */
ttl?: number
/** Return stale data while revalidating in background */
staleWhileRevalidate?: boolean
/** Custom cache key override */
cacheKey?: string
/** Operations that should invalidate this cache entry */
invalidateOn?: string[]
/** Whether to bypass cache entirely */
noCache?: boolean
}
/**
* Transaction request wrapper for atomic operations
*/
export interface TransactionRequest {
/** List of operations to execute in transaction */
operations: DataRequest[]
/** Transaction options */
options?: {
/** Database isolation level */
isolation?: 'read-uncommitted' | 'read-committed' | 'repeatable-read' | 'serializable'
/** Whether to rollback entire transaction on any error */
rollbackOnError?: boolean
/** Transaction timeout in milliseconds */
timeout?: number
}
}
/**
* Batch request for multiple operations
*/
export interface BatchRequest {
/** List of requests to execute */
requests: DataRequest[]
/** Whether to execute requests in parallel */
parallel?: boolean
/** Stop on first error */
stopOnError?: boolean
}
/**
* Batch response containing results for all requests
*/
export interface BatchResponse {
/** Individual response for each request */
results: DataResponse[]
/** Overall batch execution metadata */
metadata: {
/** Total execution time */
duration: number
/** Number of successful operations */
successCount: number
/** Number of failed operations */
errorCount: number
}
}
/**
* Pagination parameters for list operations
*/
export interface PaginationParams {
/** Page number (1-based) */
page?: number
/** Items per page */
limit?: number
/** Cursor for cursor-based pagination */
cursor?: string
/** Sort field and direction */
sort?: {
field: string
order: 'asc' | 'desc'
}
}
/**
* Paginated response wrapper
*/
export interface PaginatedResponse<T> {
/** Items for current page */
items: T[]
/** Total number of items */
total: number
/** Current page number */
page: number
/** Total number of pages */
pageCount: number
/** Whether there are more pages */
hasNext: boolean
/** Whether there are previous pages */
hasPrev: boolean
/** Next cursor for cursor-based pagination */
nextCursor?: string
/** Previous cursor for cursor-based pagination */
prevCursor?: string
}
/**
* Subscription options for real-time data updates
*/
export interface SubscriptionOptions {
/** Path pattern to subscribe to */
path: string
/** Filters to apply to subscription */
filters?: Record<string, any>
/** Whether to receive initial data */
includeInitial?: boolean
/** Custom subscription metadata */
metadata?: Record<string, any>
}
/**
* Subscription callback function
*/
export type SubscriptionCallback<T = any> = (data: T, event: SubscriptionEvent) => void
/**
* Subscription event types
*/
export enum SubscriptionEvent {
CREATED = 'created',
UPDATED = 'updated',
DELETED = 'deleted',
INITIAL = 'initial',
ERROR = 'error'
}
/**
* Middleware interface
*/
export interface Middleware {
/** Middleware name */
name: string
/** Execution priority (lower = earlier) */
priority?: number
/** Middleware execution function */
execute(req: DataRequest, res: DataResponse, next: () => Promise<void>): Promise<void>
}
/**
* Request context passed through middleware chain
*/
export interface RequestContext {
/** Original request */
request: DataRequest
/** Response being built */
response: DataResponse
/** Path that matched this request */
path?: string
/** HTTP method */
method?: HttpMethod
/** Authenticated user (if any) */
user?: any
/** Additional context data */
data: Map<string, any>
}
/**
* Base options for service operations
*/
export interface ServiceOptions {
/** Database transaction to use */
transaction?: any
/** User context for authorization */
user?: any
/** Additional service-specific options */
metadata?: Record<string, any>
}
/**
* Standard service response wrapper
*/
export interface ServiceResult<T = any> {
/** Whether operation was successful */
success: boolean
/** Result data if successful */
data?: T
/** Error information if failed */
error?: DataApiError
/** Additional metadata */
metadata?: Record<string, any>
}

View File

@@ -0,0 +1,194 @@
/**
* Centralized error code definitions for the Data API system
* Provides consistent error handling across renderer and main processes
*/
import type { DataApiError } from './apiTypes'
import { ErrorCode } from './apiTypes'
// Re-export ErrorCode for convenience
export { ErrorCode } from './apiTypes'
/**
* Error code to HTTP status mapping
*/
export const ERROR_STATUS_MAP: Record<ErrorCode, number> = {
// Client errors (4xx)
[ErrorCode.BAD_REQUEST]: 400,
[ErrorCode.UNAUTHORIZED]: 401,
[ErrorCode.FORBIDDEN]: 403,
[ErrorCode.NOT_FOUND]: 404,
[ErrorCode.METHOD_NOT_ALLOWED]: 405,
[ErrorCode.VALIDATION_ERROR]: 422,
[ErrorCode.RATE_LIMIT_EXCEEDED]: 429,
// Server errors (5xx)
[ErrorCode.INTERNAL_SERVER_ERROR]: 500,
[ErrorCode.DATABASE_ERROR]: 500,
[ErrorCode.SERVICE_UNAVAILABLE]: 503,
// Custom application errors (5xx)
[ErrorCode.MIGRATION_ERROR]: 500,
[ErrorCode.PERMISSION_DENIED]: 403,
[ErrorCode.RESOURCE_LOCKED]: 423,
[ErrorCode.CONCURRENT_MODIFICATION]: 409
}
/**
* Default error messages for each error code
*/
export const ERROR_MESSAGES: Record<ErrorCode, string> = {
[ErrorCode.BAD_REQUEST]: 'Bad request: Invalid request format or parameters',
[ErrorCode.UNAUTHORIZED]: 'Unauthorized: Authentication required',
[ErrorCode.FORBIDDEN]: 'Forbidden: Insufficient permissions',
[ErrorCode.NOT_FOUND]: 'Not found: Requested resource does not exist',
[ErrorCode.METHOD_NOT_ALLOWED]: 'Method not allowed: HTTP method not supported for this endpoint',
[ErrorCode.VALIDATION_ERROR]: 'Validation error: Request data does not meet requirements',
[ErrorCode.RATE_LIMIT_EXCEEDED]: 'Rate limit exceeded: Too many requests',
[ErrorCode.INTERNAL_SERVER_ERROR]: 'Internal server error: An unexpected error occurred',
[ErrorCode.DATABASE_ERROR]: 'Database error: Failed to access or modify data',
[ErrorCode.SERVICE_UNAVAILABLE]: 'Service unavailable: The service is temporarily unavailable',
[ErrorCode.MIGRATION_ERROR]: 'Migration error: Failed to migrate data',
[ErrorCode.PERMISSION_DENIED]: 'Permission denied: Operation not allowed for current user',
[ErrorCode.RESOURCE_LOCKED]: 'Resource locked: Resource is currently locked by another operation',
[ErrorCode.CONCURRENT_MODIFICATION]: 'Concurrent modification: Resource was modified by another user'
}
/**
* Utility class for creating standardized Data API errors
*/
export class DataApiErrorFactory {
/**
* Create a DataApiError with standard properties
*/
static create(code: ErrorCode, customMessage?: string, details?: any, stack?: string): DataApiError {
return {
code,
message: customMessage || ERROR_MESSAGES[code],
status: ERROR_STATUS_MAP[code],
details,
stack: stack || undefined
}
}
/**
* Create a validation error with field-specific details
*/
static validation(fieldErrors: Record<string, string[]>, message?: string): DataApiError {
return this.create(ErrorCode.VALIDATION_ERROR, message || 'Request validation failed', { fieldErrors })
}
/**
* Create a not found error for specific resource
*/
static notFound(resource: string, id?: string): DataApiError {
const message = id ? `${resource} with id '${id}' not found` : `${resource} not found`
return this.create(ErrorCode.NOT_FOUND, message, { resource, id })
}
/**
* Create a database error with query details
*/
static database(originalError: Error, operation?: string): DataApiError {
return this.create(
ErrorCode.DATABASE_ERROR,
`Database operation failed${operation ? `: ${operation}` : ''}`,
{
originalError: originalError.message,
operation
},
originalError.stack
)
}
/**
* Create a permission denied error
*/
static permissionDenied(action: string, resource?: string): DataApiError {
const message = resource ? `Permission denied: Cannot ${action} ${resource}` : `Permission denied: Cannot ${action}`
return this.create(ErrorCode.PERMISSION_DENIED, message, { action, resource })
}
/**
* Create an internal server error from an unexpected error
*/
static internal(originalError: Error, context?: string): DataApiError {
const message = context
? `Internal error in ${context}: ${originalError.message}`
: `Internal error: ${originalError.message}`
return this.create(
ErrorCode.INTERNAL_SERVER_ERROR,
message,
{ originalError: originalError.message, context },
originalError.stack
)
}
/**
* Create a rate limit exceeded error
*/
static rateLimit(limit: number, windowMs: number): DataApiError {
return this.create(ErrorCode.RATE_LIMIT_EXCEEDED, `Rate limit exceeded: ${limit} requests per ${windowMs}ms`, {
limit,
windowMs
})
}
/**
* Create a resource locked error
*/
static resourceLocked(resource: string, id: string, lockedBy?: string): DataApiError {
const message = lockedBy
? `${resource} '${id}' is locked by ${lockedBy}`
: `${resource} '${id}' is currently locked`
return this.create(ErrorCode.RESOURCE_LOCKED, message, { resource, id, lockedBy })
}
/**
* Create a concurrent modification error
*/
static concurrentModification(resource: string, id: string): DataApiError {
return this.create(ErrorCode.CONCURRENT_MODIFICATION, `${resource} '${id}' was modified by another user`, {
resource,
id
})
}
}
/**
* Check if an error is a Data API error
*/
export function isDataApiError(error: any): error is DataApiError {
return (
error &&
typeof error === 'object' &&
typeof error.code === 'string' &&
typeof error.message === 'string' &&
typeof error.status === 'number'
)
}
/**
* Convert a generic error to a DataApiError
*/
export function toDataApiError(error: unknown, context?: string): DataApiError {
if (isDataApiError(error)) {
return error
}
if (error instanceof Error) {
return DataApiErrorFactory.internal(error, context)
}
return DataApiErrorFactory.create(
ErrorCode.INTERNAL_SERVER_ERROR,
`Unknown error${context ? ` in ${context}` : ''}: ${String(error)}`,
{ originalError: error, context }
)
}

View File

@@ -0,0 +1,121 @@
/**
* Cherry Studio Data API - Barrel Exports
*
* This file provides a centralized entry point for all data API types,
* schemas, and utilities. Import everything you need from this single location.
*
* @example
* ```typescript
* import { Topic, CreateTopicDto, ApiSchemas, DataRequest, ErrorCode } from '@/shared/data'
* ```
*/
// Core data API types and infrastructure
export type {
BatchRequest,
BatchResponse,
CacheOptions,
DataApiError,
DataRequest,
DataResponse,
HttpMethod,
Middleware,
PaginatedResponse,
PaginationParams,
RequestContext,
ServiceOptions,
ServiceResult,
SubscriptionCallback,
SubscriptionOptions,
TransactionRequest
} from './apiTypes'
export { ErrorCode, SubscriptionEvent } from './apiTypes'
// Domain models and DTOs
export type {
BulkOperationRequest,
BulkOperationResponse,
CreateTestItemDto,
TestItem,
UpdateTestItemDto
} from './apiModels'
// API schema definitions and type helpers
export type {
ApiBody,
ApiClient,
ApiMethods,
ApiParams,
ApiPaths,
ApiQuery,
ApiResponse,
ApiSchemas
} from './apiSchemas'
// Path type utilities for template literal types
export type {
BodyForPath,
ConcreteApiPaths,
MatchApiPath,
QueryParamsForPath,
ResolvedPath,
ResponseForPath
} from './apiPaths'
// Error handling utilities
export {
ErrorCode as DataApiErrorCode,
DataApiErrorFactory,
ERROR_MESSAGES,
ERROR_STATUS_MAP,
isDataApiError,
toDataApiError
} from './errorCodes'
/**
* Re-export commonly used type combinations for convenience
*/
// Import types for re-export convenience types
import type { CreateTestItemDto, TestItem, UpdateTestItemDto } from './apiModels'
import type {
BatchRequest,
BatchResponse,
DataApiError,
DataRequest,
DataResponse,
ErrorCode,
PaginatedResponse,
PaginationParams,
TransactionRequest
} from './apiTypes'
import type { DataApiErrorFactory } from './errorCodes'
/** All test item-related types */
export type TestItemTypes = {
TestItem: TestItem
CreateTestItemDto: CreateTestItemDto
UpdateTestItemDto: UpdateTestItemDto
}
/** All error-related types and utilities */
export type ErrorTypes = {
DataApiError: DataApiError
ErrorCode: ErrorCode
ErrorFactory: typeof DataApiErrorFactory
}
/** All request/response types */
export type RequestTypes = {
DataRequest: DataRequest
DataResponse: DataResponse
BatchRequest: BatchRequest
BatchResponse: BatchResponse
TransactionRequest: TransactionRequest
}
/** All pagination-related types */
export type PaginationTypes = {
PaginationParams: PaginationParams
PaginatedResponse: PaginatedResponse<any>
}

Some files were not shown because too many files have changed in this diff Show More