Files
cc-switch/src/types.ts

166 lines
5.1 KiB
TypeScript
Raw Normal View History

export type ProviderCategory =
| "official" // 官方
| "cn_official" // 开源官方(原"国产官方"
| "aggregator" // 聚合网站
| "third_party" // 第三方供应商
| "custom"; // 自定义
2025-08-04 22:16:26 +08:00
export interface Provider {
id: string;
name: string;
settingsConfig: Record<string, any>; // 应用配置对象Claude 为 settings.jsonCodex 为 { auth, config }
websiteUrl?: string;
// 新增:供应商分类(用于差异化提示/能力开关)
category?: ProviderCategory;
createdAt?: number; // 添加时间戳(毫秒)
sortIndex?: number; // 排序索引(用于自定义拖拽排序)
// 新增:是否为商业合作伙伴
isPartner?: boolean;
feat: Implement Speed Test Function * feat: add unified endpoint speed test for API providers Add a comprehensive endpoint latency testing system that allows users to: - Test multiple API endpoints concurrently - Auto-select the fastest endpoint based on latency - Add/remove custom endpoints dynamically - View latency results with color-coded indicators Backend (Rust): - Implement parallel HTTP HEAD requests with configurable timeout - Handle various error scenarios (timeout, connection failure, invalid URL) - Return structured latency data with status codes Frontend (React): - Create interactive speed test UI component with auto-sort by latency - Support endpoint management (add/remove custom endpoints) - Extract and update Codex base_url from TOML configuration - Integrate with provider presets for default endpoint candidates This feature improves user experience when selecting optimal API endpoints, especially useful for users with multiple provider options or proxy setups. * refactor: convert endpoint speed test to modal dialog - Transform EndpointSpeedTest component into a modal dialog - Add "Advanced" button next to base URL input to open modal - Support ESC key and backdrop click to close modal - Apply Linear design principles: minimal styling, clean layout - Remove unused showBaseUrlInput variable - Implement same modal pattern for both Claude and Codex * fix: prevent modal cascade closing when ESC is pressed - Add state checks to prevent parent modal from closing when child modals (endpoint speed test or template wizard) are open - Update ESC key handler dependencies to track all modal states - Ensures only the topmost modal responds to ESC key * refactor: unify speed test panel UI with project design system UI improvements: - Update modal border radius from rounded-lg to rounded-xl - Unify header padding from px-6 py-4 to p-6 - Change speed test button color to blue theme (bg-blue-500) for consistency - Update footer background from bg-gray-50 to bg-gray-100 - Style "Done" button as primary action button with blue theme - Adjust footer button spacing and hover states Simplify endpoint display: - Remove endpoint labels (e.g., "Current Address", "Custom 1") - Display only URL for cleaner interface - Clean up all label-related logic: * Remove label field from EndpointCandidate interface * Remove label generation in buildInitialEntries function * Remove label handling in useEffect merge logic * Remove label generation in handleAddEndpoint * Remove label parameters from claudeSpeedTestEndpoints * Remove label parameters from codexSpeedTestEndpoints * refactor: improve endpoint list UI consistency - Show delete button for all endpoints on hover for uniform UI - Change selected state to use blue theme matching main interface: * Blue border (border-blue-500) for selected items * Light blue background (bg-blue-50/dark:bg-blue-900/20) * Blue indicator dot (bg-blue-500/dark:bg-blue-400) - Switch from compact list (space-y-px) to card-based layout (space-y-2) - Add rounded corners to each endpoint item for better visual separation * feat: persist custom endpoints to settings.json - Extend AppSettings to store custom endpoints for Claude and Codex - Add Tauri commands: get/add/remove/update custom endpoints - Update frontend API with endpoint persistence methods - Modify EndpointSpeedTest to load/save custom endpoints via API - Track endpoint last used time for future sorting/cleanup - Store endpoints per app type in settings.json instead of localStorage * - feat(types): add Provider.meta and ProviderMeta (snake_case) with custom_endpoints map - feat(provider-form): persist custom endpoints on provider create by merging EndpointSpeedTest’s custom URLs into meta.custom_endpoints on submit - feat(endpoint-speed-test): add onCustomEndpointsChange callback emitting normalized custom URLs; wire it for both Claude/Codex modals - fix(api): send alias param names (app/appType/app_type and provider_id/providerId) in Tauri invokes to avoid “missing providerId” with older backends - storage: custom endpoints are stored in ~/.cc-switch/config.json under providers[<id>].meta.custom_endpoints (not in settings.json) - behavior: edit flow remains immediate writes; create flow now writes once via addProvider, removing the providerId dependency during creation * feat: add endpoint candidates support and code formatting improvements - Add endpointCandidates field to ProviderPreset and CodexProviderPreset interfaces - Integrate preset endpoint candidates into speed test endpoint selection - Add multiple endpoint options for PackyCode providers (Claude & Codex) - Apply consistent code formatting (trailing commas, line breaks) - Improve template value type safety and readability * refactor: improve endpoint management button UX Replace ambiguous "Advanced" text with intuitive "Manage & Test" label accompanied by Zap icon, making the endpoint management panel entry point more discoverable and self-explanatory for both Claude and Codex configurations. * - merge: merge origin/main, resolve conflicts and preserve both feature sets - feat(tauri): register import/export and file dialogs; keep endpoint speed test and custom endpoints - feat(api): add updateTrayMenu and onProviderSwitched; wire import/export APIs - feat(types): extend global API declarations (import/export) - chore(presets): GLM preset supports both new and legacy model keys - chore(rust): add chrono dependency; refresh lockfile --------- Co-authored-by: Jason <farion1231@gmail.com>
2025-10-07 19:14:32 +08:00
// 可选:供应商元数据(仅存于 ~/.cc-switch/config.json不写入 live 配置)
meta?: ProviderMeta;
2025-08-04 22:16:26 +08:00
}
export interface AppConfig {
providers: Record<string, Provider>;
current: string;
2025-08-04 22:16:26 +08:00
}
feat: Implement Speed Test Function * feat: add unified endpoint speed test for API providers Add a comprehensive endpoint latency testing system that allows users to: - Test multiple API endpoints concurrently - Auto-select the fastest endpoint based on latency - Add/remove custom endpoints dynamically - View latency results with color-coded indicators Backend (Rust): - Implement parallel HTTP HEAD requests with configurable timeout - Handle various error scenarios (timeout, connection failure, invalid URL) - Return structured latency data with status codes Frontend (React): - Create interactive speed test UI component with auto-sort by latency - Support endpoint management (add/remove custom endpoints) - Extract and update Codex base_url from TOML configuration - Integrate with provider presets for default endpoint candidates This feature improves user experience when selecting optimal API endpoints, especially useful for users with multiple provider options or proxy setups. * refactor: convert endpoint speed test to modal dialog - Transform EndpointSpeedTest component into a modal dialog - Add "Advanced" button next to base URL input to open modal - Support ESC key and backdrop click to close modal - Apply Linear design principles: minimal styling, clean layout - Remove unused showBaseUrlInput variable - Implement same modal pattern for both Claude and Codex * fix: prevent modal cascade closing when ESC is pressed - Add state checks to prevent parent modal from closing when child modals (endpoint speed test or template wizard) are open - Update ESC key handler dependencies to track all modal states - Ensures only the topmost modal responds to ESC key * refactor: unify speed test panel UI with project design system UI improvements: - Update modal border radius from rounded-lg to rounded-xl - Unify header padding from px-6 py-4 to p-6 - Change speed test button color to blue theme (bg-blue-500) for consistency - Update footer background from bg-gray-50 to bg-gray-100 - Style "Done" button as primary action button with blue theme - Adjust footer button spacing and hover states Simplify endpoint display: - Remove endpoint labels (e.g., "Current Address", "Custom 1") - Display only URL for cleaner interface - Clean up all label-related logic: * Remove label field from EndpointCandidate interface * Remove label generation in buildInitialEntries function * Remove label handling in useEffect merge logic * Remove label generation in handleAddEndpoint * Remove label parameters from claudeSpeedTestEndpoints * Remove label parameters from codexSpeedTestEndpoints * refactor: improve endpoint list UI consistency - Show delete button for all endpoints on hover for uniform UI - Change selected state to use blue theme matching main interface: * Blue border (border-blue-500) for selected items * Light blue background (bg-blue-50/dark:bg-blue-900/20) * Blue indicator dot (bg-blue-500/dark:bg-blue-400) - Switch from compact list (space-y-px) to card-based layout (space-y-2) - Add rounded corners to each endpoint item for better visual separation * feat: persist custom endpoints to settings.json - Extend AppSettings to store custom endpoints for Claude and Codex - Add Tauri commands: get/add/remove/update custom endpoints - Update frontend API with endpoint persistence methods - Modify EndpointSpeedTest to load/save custom endpoints via API - Track endpoint last used time for future sorting/cleanup - Store endpoints per app type in settings.json instead of localStorage * - feat(types): add Provider.meta and ProviderMeta (snake_case) with custom_endpoints map - feat(provider-form): persist custom endpoints on provider create by merging EndpointSpeedTest’s custom URLs into meta.custom_endpoints on submit - feat(endpoint-speed-test): add onCustomEndpointsChange callback emitting normalized custom URLs; wire it for both Claude/Codex modals - fix(api): send alias param names (app/appType/app_type and provider_id/providerId) in Tauri invokes to avoid “missing providerId” with older backends - storage: custom endpoints are stored in ~/.cc-switch/config.json under providers[<id>].meta.custom_endpoints (not in settings.json) - behavior: edit flow remains immediate writes; create flow now writes once via addProvider, removing the providerId dependency during creation * feat: add endpoint candidates support and code formatting improvements - Add endpointCandidates field to ProviderPreset and CodexProviderPreset interfaces - Integrate preset endpoint candidates into speed test endpoint selection - Add multiple endpoint options for PackyCode providers (Claude & Codex) - Apply consistent code formatting (trailing commas, line breaks) - Improve template value type safety and readability * refactor: improve endpoint management button UX Replace ambiguous "Advanced" text with intuitive "Manage & Test" label accompanied by Zap icon, making the endpoint management panel entry point more discoverable and self-explanatory for both Claude and Codex configurations. * - merge: merge origin/main, resolve conflicts and preserve both feature sets - feat(tauri): register import/export and file dialogs; keep endpoint speed test and custom endpoints - feat(api): add updateTrayMenu and onProviderSwitched; wire import/export APIs - feat(types): extend global API declarations (import/export) - chore(presets): GLM preset supports both new and legacy model keys - chore(rust): add chrono dependency; refresh lockfile --------- Co-authored-by: Jason <farion1231@gmail.com>
2025-10-07 19:14:32 +08:00
// 自定义端点配置
export interface CustomEndpoint {
url: string;
addedAt: number;
lastUsed?: number;
}
// 端点候选项(用于端点测速弹窗)
export interface EndpointCandidate {
id?: string;
url: string;
isCustom?: boolean;
}
feat: add provider usage query with JavaScript scripting support (#101) * feat: add provider usage query functionality - Updated `Cargo.toml` to include `regex` and `rquickjs` dependencies for usage script execution. - Implemented `query_provider_usage` command in `commands.rs` to handle usage queries. - Created `UsageScript` and `UsageData` structs in `provider.rs` for managing usage script configurations and results. - Added `execute_usage_script` function in `usage_script.rs` to run user-defined scripts for querying usage. - Enhanced `ProviderList` component to include a button for configuring usage scripts and a modal for editing scripts. - Introduced `UsageFooter` component to display usage information and status. - Added `UsageScriptModal` for editing and testing usage scripts with preset templates. - Updated Tauri API to support querying provider usage. - Modified types in `types.ts` to include structures for usage scripts and results. * feat(usage): support multi-plan usage display for providers - 【Feature】 - Update `UsageResult` to support an array of `UsageData` for displaying multiple usage plans per provider. - Refactor `query_provider_usage` command to parse both single `UsageData` objects (for backward compatibility) and arrays of `UsageData`. - Enhance `usage_script` validation to accept either a single usage object or an array of usage objects. - 【Frontend】 - Redesign `UsageFooter` to iterate and display details for all available usage plans, introducing `UsagePlanItem` for individual plan rendering. - Improve usage display with color-coded remaining balance and clear plan information. - Update `UsageScriptModal` test notification to summarize all returned plans. - Remove redundant `isCurrent` prop from `UsageFooter` in `ProviderList`. - 【Build】 - Change frontend development server port from `3000` to `3005` in `tauri.conf.json` and `vite.config.mts`. * feat(usage): enhance query flexibility and display - 【`src/types.ts`, `src-tauri/src/provider.rs`】Make `UsageData` fields optional and introduce `extra` and `invalidMessage` for more flexible reporting. - `expiresAt` replaced by generic `extra` field. - `isValid`, `remaining`, `unit` are now optional. - Added `invalidMessage` to provide specific reasons for invalid status. - 【`src-tauri/src/usage_script.rs`】Relax usage script result validation to accommodate optional fields in `UsageData`. - 【`src/components/UsageFooter.tsx`】Update UI to display `extra` field and `invalidMessage`, and conditionally render `remaining` and `unit` based on availability. - 【`src/components/UsageScriptModal.tsx`】 - Add a new `NewAPI` preset template demonstrating advanced extractor logic for complex API responses. - Update script instructions to reflect optional fields and new variable syntax (`{{apiKey}}`). - Remove old "DeepSeek" and "OpenAI" templates. - Remove basic syntax check for `return` statement. - 【`.vscode/settings.json`】Add `dish-ai-commit.base.language` setting. - 【`src-tauri/src/commands.rs`】Adjust usage logging to handle optional `remaining` and `unit` fields. * chore(config): remove VS Code settings from version control - delete .vscode/settings.json to remove editor-specific configurations - add /.vscode to .gitignore to prevent tracking of local VS Code settings - ensure personalized editor preferences are not committed to the repository * fix(provider): preserve usage script during provider update - When updating a provider, the `usage_script` configuration within `ProviderMeta` was not explicitly merged. - This could lead to the accidental loss of `usage_script` settings if the incoming `provider` object in the update request did not contain this field. - Ensure `usage_script` is cloned from the existing provider's meta when merging `ProviderMeta` during an update. * refactor(provider): enforce base_url for usage scripts and update dev ports - 【Backend】 - `src-tauri/src/commands.rs`: Made `ANTHROPIC_BASE_URL` a required field for Claude providers and `base_url` a required field in `config.toml` for Codex providers when extracting credentials for usage script execution. This improves error handling by explicitly failing if these critical URLs are missing or malformed. - 【Frontend】 - `src/App.tsx`, `src/components/ProviderList.tsx`: Passed `appType` prop to `ProviderList` component to ensure `updateProvider` calls within `handleSaveUsageScript` correctly identify the application type. - 【Config】 - `src-tauri/tauri.conf.json`, `vite.config.mts`: Updated development server ports from `3005` to `3000` to standardize local development environment. * refactor(usage): improve usage data fetching logic - Prevent redundant API calls by tracking last fetched parameters in `useEffect`. - Avoid concurrent API requests by adding a guard in `fetchUsage`. - Clear usage data and last fetch parameters when usage query is disabled. - Add `queryProviderUsage` API declaration to `window.api` interface. * fix(usage-script): ensure usage script updates and improve reactivity - correctly update `usage_script` from new provider meta during updates - replace full page reload with targeted provider data refresh after saving usage script settings - trigger usage data fetch or clear when `usageEnabled` status changes in `UsageFooter` - reduce logging verbosity for usage script execution in backend commands and script execution * style(usage-footer): adjust usage plan item layout - Decrease width of extra field column from 35% to 30% - Increase width of usage information column from 40% to 45% - Improve visual balance and readability of usage plan items
2025-10-15 09:15:25 +08:00
// 用量查询脚本配置
export interface UsageScript {
enabled: boolean; // 是否启用用量查询
language: "javascript"; // 脚本语言
code: string; // 脚本代码JSON 格式配置)
timeout?: number; // 超时时间(秒,默认 10
apiKey?: string; // 用量查询专用的 API Key通用模板使用
baseUrl?: string; // 用量查询专用的 Base URL通用和 NewAPI 模板使用)
accessToken?: string; // 访问令牌NewAPI 模板使用)
userId?: string; // 用户IDNewAPI 模板使用)
autoQueryInterval?: number; // 自动查询间隔单位分钟0 表示禁用)
feat: add provider usage query with JavaScript scripting support (#101) * feat: add provider usage query functionality - Updated `Cargo.toml` to include `regex` and `rquickjs` dependencies for usage script execution. - Implemented `query_provider_usage` command in `commands.rs` to handle usage queries. - Created `UsageScript` and `UsageData` structs in `provider.rs` for managing usage script configurations and results. - Added `execute_usage_script` function in `usage_script.rs` to run user-defined scripts for querying usage. - Enhanced `ProviderList` component to include a button for configuring usage scripts and a modal for editing scripts. - Introduced `UsageFooter` component to display usage information and status. - Added `UsageScriptModal` for editing and testing usage scripts with preset templates. - Updated Tauri API to support querying provider usage. - Modified types in `types.ts` to include structures for usage scripts and results. * feat(usage): support multi-plan usage display for providers - 【Feature】 - Update `UsageResult` to support an array of `UsageData` for displaying multiple usage plans per provider. - Refactor `query_provider_usage` command to parse both single `UsageData` objects (for backward compatibility) and arrays of `UsageData`. - Enhance `usage_script` validation to accept either a single usage object or an array of usage objects. - 【Frontend】 - Redesign `UsageFooter` to iterate and display details for all available usage plans, introducing `UsagePlanItem` for individual plan rendering. - Improve usage display with color-coded remaining balance and clear plan information. - Update `UsageScriptModal` test notification to summarize all returned plans. - Remove redundant `isCurrent` prop from `UsageFooter` in `ProviderList`. - 【Build】 - Change frontend development server port from `3000` to `3005` in `tauri.conf.json` and `vite.config.mts`. * feat(usage): enhance query flexibility and display - 【`src/types.ts`, `src-tauri/src/provider.rs`】Make `UsageData` fields optional and introduce `extra` and `invalidMessage` for more flexible reporting. - `expiresAt` replaced by generic `extra` field. - `isValid`, `remaining`, `unit` are now optional. - Added `invalidMessage` to provide specific reasons for invalid status. - 【`src-tauri/src/usage_script.rs`】Relax usage script result validation to accommodate optional fields in `UsageData`. - 【`src/components/UsageFooter.tsx`】Update UI to display `extra` field and `invalidMessage`, and conditionally render `remaining` and `unit` based on availability. - 【`src/components/UsageScriptModal.tsx`】 - Add a new `NewAPI` preset template demonstrating advanced extractor logic for complex API responses. - Update script instructions to reflect optional fields and new variable syntax (`{{apiKey}}`). - Remove old "DeepSeek" and "OpenAI" templates. - Remove basic syntax check for `return` statement. - 【`.vscode/settings.json`】Add `dish-ai-commit.base.language` setting. - 【`src-tauri/src/commands.rs`】Adjust usage logging to handle optional `remaining` and `unit` fields. * chore(config): remove VS Code settings from version control - delete .vscode/settings.json to remove editor-specific configurations - add /.vscode to .gitignore to prevent tracking of local VS Code settings - ensure personalized editor preferences are not committed to the repository * fix(provider): preserve usage script during provider update - When updating a provider, the `usage_script` configuration within `ProviderMeta` was not explicitly merged. - This could lead to the accidental loss of `usage_script` settings if the incoming `provider` object in the update request did not contain this field. - Ensure `usage_script` is cloned from the existing provider's meta when merging `ProviderMeta` during an update. * refactor(provider): enforce base_url for usage scripts and update dev ports - 【Backend】 - `src-tauri/src/commands.rs`: Made `ANTHROPIC_BASE_URL` a required field for Claude providers and `base_url` a required field in `config.toml` for Codex providers when extracting credentials for usage script execution. This improves error handling by explicitly failing if these critical URLs are missing or malformed. - 【Frontend】 - `src/App.tsx`, `src/components/ProviderList.tsx`: Passed `appType` prop to `ProviderList` component to ensure `updateProvider` calls within `handleSaveUsageScript` correctly identify the application type. - 【Config】 - `src-tauri/tauri.conf.json`, `vite.config.mts`: Updated development server ports from `3005` to `3000` to standardize local development environment. * refactor(usage): improve usage data fetching logic - Prevent redundant API calls by tracking last fetched parameters in `useEffect`. - Avoid concurrent API requests by adding a guard in `fetchUsage`. - Clear usage data and last fetch parameters when usage query is disabled. - Add `queryProviderUsage` API declaration to `window.api` interface. * fix(usage-script): ensure usage script updates and improve reactivity - correctly update `usage_script` from new provider meta during updates - replace full page reload with targeted provider data refresh after saving usage script settings - trigger usage data fetch or clear when `usageEnabled` status changes in `UsageFooter` - reduce logging verbosity for usage script execution in backend commands and script execution * style(usage-footer): adjust usage plan item layout - Decrease width of extra field column from 35% to 30% - Increase width of usage information column from 40% to 45% - Improve visual balance and readability of usage plan items
2025-10-15 09:15:25 +08:00
}
// 单个套餐用量数据
export interface UsageData {
planName?: string; // 套餐名称(可选)
extra?: string; // 扩展字段,可自由补充需要展示的文本(可选)
isValid?: boolean; // 套餐是否有效(可选)
invalidMessage?: string; // 失效原因说明(可选,当 isValid 为 false 时显示)
total?: number; // 总额度(可选)
used?: number; // 已用额度(可选)
remaining?: number; // 剩余额度(可选)
unit?: string; // 单位(可选)
}
// 用量查询结果(支持多套餐)
export interface UsageResult {
success: boolean;
data?: UsageData[]; // 改为数组,支持返回多个套餐
error?: string;
}
feat: Implement Speed Test Function * feat: add unified endpoint speed test for API providers Add a comprehensive endpoint latency testing system that allows users to: - Test multiple API endpoints concurrently - Auto-select the fastest endpoint based on latency - Add/remove custom endpoints dynamically - View latency results with color-coded indicators Backend (Rust): - Implement parallel HTTP HEAD requests with configurable timeout - Handle various error scenarios (timeout, connection failure, invalid URL) - Return structured latency data with status codes Frontend (React): - Create interactive speed test UI component with auto-sort by latency - Support endpoint management (add/remove custom endpoints) - Extract and update Codex base_url from TOML configuration - Integrate with provider presets for default endpoint candidates This feature improves user experience when selecting optimal API endpoints, especially useful for users with multiple provider options or proxy setups. * refactor: convert endpoint speed test to modal dialog - Transform EndpointSpeedTest component into a modal dialog - Add "Advanced" button next to base URL input to open modal - Support ESC key and backdrop click to close modal - Apply Linear design principles: minimal styling, clean layout - Remove unused showBaseUrlInput variable - Implement same modal pattern for both Claude and Codex * fix: prevent modal cascade closing when ESC is pressed - Add state checks to prevent parent modal from closing when child modals (endpoint speed test or template wizard) are open - Update ESC key handler dependencies to track all modal states - Ensures only the topmost modal responds to ESC key * refactor: unify speed test panel UI with project design system UI improvements: - Update modal border radius from rounded-lg to rounded-xl - Unify header padding from px-6 py-4 to p-6 - Change speed test button color to blue theme (bg-blue-500) for consistency - Update footer background from bg-gray-50 to bg-gray-100 - Style "Done" button as primary action button with blue theme - Adjust footer button spacing and hover states Simplify endpoint display: - Remove endpoint labels (e.g., "Current Address", "Custom 1") - Display only URL for cleaner interface - Clean up all label-related logic: * Remove label field from EndpointCandidate interface * Remove label generation in buildInitialEntries function * Remove label handling in useEffect merge logic * Remove label generation in handleAddEndpoint * Remove label parameters from claudeSpeedTestEndpoints * Remove label parameters from codexSpeedTestEndpoints * refactor: improve endpoint list UI consistency - Show delete button for all endpoints on hover for uniform UI - Change selected state to use blue theme matching main interface: * Blue border (border-blue-500) for selected items * Light blue background (bg-blue-50/dark:bg-blue-900/20) * Blue indicator dot (bg-blue-500/dark:bg-blue-400) - Switch from compact list (space-y-px) to card-based layout (space-y-2) - Add rounded corners to each endpoint item for better visual separation * feat: persist custom endpoints to settings.json - Extend AppSettings to store custom endpoints for Claude and Codex - Add Tauri commands: get/add/remove/update custom endpoints - Update frontend API with endpoint persistence methods - Modify EndpointSpeedTest to load/save custom endpoints via API - Track endpoint last used time for future sorting/cleanup - Store endpoints per app type in settings.json instead of localStorage * - feat(types): add Provider.meta and ProviderMeta (snake_case) with custom_endpoints map - feat(provider-form): persist custom endpoints on provider create by merging EndpointSpeedTest’s custom URLs into meta.custom_endpoints on submit - feat(endpoint-speed-test): add onCustomEndpointsChange callback emitting normalized custom URLs; wire it for both Claude/Codex modals - fix(api): send alias param names (app/appType/app_type and provider_id/providerId) in Tauri invokes to avoid “missing providerId” with older backends - storage: custom endpoints are stored in ~/.cc-switch/config.json under providers[<id>].meta.custom_endpoints (not in settings.json) - behavior: edit flow remains immediate writes; create flow now writes once via addProvider, removing the providerId dependency during creation * feat: add endpoint candidates support and code formatting improvements - Add endpointCandidates field to ProviderPreset and CodexProviderPreset interfaces - Integrate preset endpoint candidates into speed test endpoint selection - Add multiple endpoint options for PackyCode providers (Claude & Codex) - Apply consistent code formatting (trailing commas, line breaks) - Improve template value type safety and readability * refactor: improve endpoint management button UX Replace ambiguous "Advanced" text with intuitive "Manage & Test" label accompanied by Zap icon, making the endpoint management panel entry point more discoverable and self-explanatory for both Claude and Codex configurations. * - merge: merge origin/main, resolve conflicts and preserve both feature sets - feat(tauri): register import/export and file dialogs; keep endpoint speed test and custom endpoints - feat(api): add updateTrayMenu and onProviderSwitched; wire import/export APIs - feat(types): extend global API declarations (import/export) - chore(presets): GLM preset supports both new and legacy model keys - chore(rust): add chrono dependency; refresh lockfile --------- Co-authored-by: Jason <farion1231@gmail.com>
2025-10-07 19:14:32 +08:00
// 供应商元数据(字段名与后端一致,保持 snake_case
export interface ProviderMeta {
// 自定义端点:以 URL 为键,值为端点信息
custom_endpoints?: Record<string, CustomEndpoint>;
feat: add provider usage query with JavaScript scripting support (#101) * feat: add provider usage query functionality - Updated `Cargo.toml` to include `regex` and `rquickjs` dependencies for usage script execution. - Implemented `query_provider_usage` command in `commands.rs` to handle usage queries. - Created `UsageScript` and `UsageData` structs in `provider.rs` for managing usage script configurations and results. - Added `execute_usage_script` function in `usage_script.rs` to run user-defined scripts for querying usage. - Enhanced `ProviderList` component to include a button for configuring usage scripts and a modal for editing scripts. - Introduced `UsageFooter` component to display usage information and status. - Added `UsageScriptModal` for editing and testing usage scripts with preset templates. - Updated Tauri API to support querying provider usage. - Modified types in `types.ts` to include structures for usage scripts and results. * feat(usage): support multi-plan usage display for providers - 【Feature】 - Update `UsageResult` to support an array of `UsageData` for displaying multiple usage plans per provider. - Refactor `query_provider_usage` command to parse both single `UsageData` objects (for backward compatibility) and arrays of `UsageData`. - Enhance `usage_script` validation to accept either a single usage object or an array of usage objects. - 【Frontend】 - Redesign `UsageFooter` to iterate and display details for all available usage plans, introducing `UsagePlanItem` for individual plan rendering. - Improve usage display with color-coded remaining balance and clear plan information. - Update `UsageScriptModal` test notification to summarize all returned plans. - Remove redundant `isCurrent` prop from `UsageFooter` in `ProviderList`. - 【Build】 - Change frontend development server port from `3000` to `3005` in `tauri.conf.json` and `vite.config.mts`. * feat(usage): enhance query flexibility and display - 【`src/types.ts`, `src-tauri/src/provider.rs`】Make `UsageData` fields optional and introduce `extra` and `invalidMessage` for more flexible reporting. - `expiresAt` replaced by generic `extra` field. - `isValid`, `remaining`, `unit` are now optional. - Added `invalidMessage` to provide specific reasons for invalid status. - 【`src-tauri/src/usage_script.rs`】Relax usage script result validation to accommodate optional fields in `UsageData`. - 【`src/components/UsageFooter.tsx`】Update UI to display `extra` field and `invalidMessage`, and conditionally render `remaining` and `unit` based on availability. - 【`src/components/UsageScriptModal.tsx`】 - Add a new `NewAPI` preset template demonstrating advanced extractor logic for complex API responses. - Update script instructions to reflect optional fields and new variable syntax (`{{apiKey}}`). - Remove old "DeepSeek" and "OpenAI" templates. - Remove basic syntax check for `return` statement. - 【`.vscode/settings.json`】Add `dish-ai-commit.base.language` setting. - 【`src-tauri/src/commands.rs`】Adjust usage logging to handle optional `remaining` and `unit` fields. * chore(config): remove VS Code settings from version control - delete .vscode/settings.json to remove editor-specific configurations - add /.vscode to .gitignore to prevent tracking of local VS Code settings - ensure personalized editor preferences are not committed to the repository * fix(provider): preserve usage script during provider update - When updating a provider, the `usage_script` configuration within `ProviderMeta` was not explicitly merged. - This could lead to the accidental loss of `usage_script` settings if the incoming `provider` object in the update request did not contain this field. - Ensure `usage_script` is cloned from the existing provider's meta when merging `ProviderMeta` during an update. * refactor(provider): enforce base_url for usage scripts and update dev ports - 【Backend】 - `src-tauri/src/commands.rs`: Made `ANTHROPIC_BASE_URL` a required field for Claude providers and `base_url` a required field in `config.toml` for Codex providers when extracting credentials for usage script execution. This improves error handling by explicitly failing if these critical URLs are missing or malformed. - 【Frontend】 - `src/App.tsx`, `src/components/ProviderList.tsx`: Passed `appType` prop to `ProviderList` component to ensure `updateProvider` calls within `handleSaveUsageScript` correctly identify the application type. - 【Config】 - `src-tauri/tauri.conf.json`, `vite.config.mts`: Updated development server ports from `3005` to `3000` to standardize local development environment. * refactor(usage): improve usage data fetching logic - Prevent redundant API calls by tracking last fetched parameters in `useEffect`. - Avoid concurrent API requests by adding a guard in `fetchUsage`. - Clear usage data and last fetch parameters when usage query is disabled. - Add `queryProviderUsage` API declaration to `window.api` interface. * fix(usage-script): ensure usage script updates and improve reactivity - correctly update `usage_script` from new provider meta during updates - replace full page reload with targeted provider data refresh after saving usage script settings - trigger usage data fetch or clear when `usageEnabled` status changes in `UsageFooter` - reduce logging verbosity for usage script execution in backend commands and script execution * style(usage-footer): adjust usage plan item layout - Decrease width of extra field column from 35% to 30% - Increase width of usage information column from 40% to 45% - Improve visual balance and readability of usage plan items
2025-10-15 09:15:25 +08:00
// 用量查询脚本配置
usage_script?: UsageScript;
feat(gemini): add Gemini provider integration (#202) * feat(gemini): add Gemini provider integration - Add gemini_config.rs module for .env file parsing - Extend AppType enum to support Gemini - Implement GeminiConfigEditor and GeminiFormFields components - Add GeminiIcon with standardized 1024x1024 viewBox - Add Gemini provider presets configuration - Update i18n translations for Gemini support - Extend ProviderService and McpService for Gemini * fix(gemini): resolve TypeScript errors, add i18n support, and fix MCP logic **Critical Fixes:** - Fix TS2741 errors in tests/msw/state.ts by adding missing Gemini type definitions - Fix ProviderCard.extractApiUrl to support GOOGLE_GEMINI_BASE_URL display - Add missing apps.gemini i18n keys (zh/en) for proper app name display - Fix MCP service Gemini cross-app duplication logic to prevent self-copy **Technical Details:** - tests/msw/state.ts: Add gemini default providers, current ID, and MCP config - ProviderCard.tsx: Check both ANTHROPIC_BASE_URL and GOOGLE_GEMINI_BASE_URL - services/mcp.rs: Skip Gemini in sync_other_side logic with unreachable!() guards - Run pnpm format to auto-fix code style issues **Verification:** - ✅ pnpm typecheck passes - ✅ pnpm format completed * feat(gemini): enhance authentication and config parsing - Add strict and lenient .env parsing modes - Implement PackyCode partner authentication detection - Support Google OAuth official authentication - Auto-configure security.auth.selectedType for PackyCode - Add comprehensive test coverage for all auth types - Update i18n for OAuth hints and Gemini config --------- Co-authored-by: Jason <farion1231@gmail.com>
2025-11-12 10:47:34 +08:00
// 是否为官方合作伙伴
isPartner?: boolean;
// 合作伙伴促销 key用于后端识别 PackyCode 等)
partnerPromotionKey?: string;
feat: Implement Speed Test Function * feat: add unified endpoint speed test for API providers Add a comprehensive endpoint latency testing system that allows users to: - Test multiple API endpoints concurrently - Auto-select the fastest endpoint based on latency - Add/remove custom endpoints dynamically - View latency results with color-coded indicators Backend (Rust): - Implement parallel HTTP HEAD requests with configurable timeout - Handle various error scenarios (timeout, connection failure, invalid URL) - Return structured latency data with status codes Frontend (React): - Create interactive speed test UI component with auto-sort by latency - Support endpoint management (add/remove custom endpoints) - Extract and update Codex base_url from TOML configuration - Integrate with provider presets for default endpoint candidates This feature improves user experience when selecting optimal API endpoints, especially useful for users with multiple provider options or proxy setups. * refactor: convert endpoint speed test to modal dialog - Transform EndpointSpeedTest component into a modal dialog - Add "Advanced" button next to base URL input to open modal - Support ESC key and backdrop click to close modal - Apply Linear design principles: minimal styling, clean layout - Remove unused showBaseUrlInput variable - Implement same modal pattern for both Claude and Codex * fix: prevent modal cascade closing when ESC is pressed - Add state checks to prevent parent modal from closing when child modals (endpoint speed test or template wizard) are open - Update ESC key handler dependencies to track all modal states - Ensures only the topmost modal responds to ESC key * refactor: unify speed test panel UI with project design system UI improvements: - Update modal border radius from rounded-lg to rounded-xl - Unify header padding from px-6 py-4 to p-6 - Change speed test button color to blue theme (bg-blue-500) for consistency - Update footer background from bg-gray-50 to bg-gray-100 - Style "Done" button as primary action button with blue theme - Adjust footer button spacing and hover states Simplify endpoint display: - Remove endpoint labels (e.g., "Current Address", "Custom 1") - Display only URL for cleaner interface - Clean up all label-related logic: * Remove label field from EndpointCandidate interface * Remove label generation in buildInitialEntries function * Remove label handling in useEffect merge logic * Remove label generation in handleAddEndpoint * Remove label parameters from claudeSpeedTestEndpoints * Remove label parameters from codexSpeedTestEndpoints * refactor: improve endpoint list UI consistency - Show delete button for all endpoints on hover for uniform UI - Change selected state to use blue theme matching main interface: * Blue border (border-blue-500) for selected items * Light blue background (bg-blue-50/dark:bg-blue-900/20) * Blue indicator dot (bg-blue-500/dark:bg-blue-400) - Switch from compact list (space-y-px) to card-based layout (space-y-2) - Add rounded corners to each endpoint item for better visual separation * feat: persist custom endpoints to settings.json - Extend AppSettings to store custom endpoints for Claude and Codex - Add Tauri commands: get/add/remove/update custom endpoints - Update frontend API with endpoint persistence methods - Modify EndpointSpeedTest to load/save custom endpoints via API - Track endpoint last used time for future sorting/cleanup - Store endpoints per app type in settings.json instead of localStorage * - feat(types): add Provider.meta and ProviderMeta (snake_case) with custom_endpoints map - feat(provider-form): persist custom endpoints on provider create by merging EndpointSpeedTest’s custom URLs into meta.custom_endpoints on submit - feat(endpoint-speed-test): add onCustomEndpointsChange callback emitting normalized custom URLs; wire it for both Claude/Codex modals - fix(api): send alias param names (app/appType/app_type and provider_id/providerId) in Tauri invokes to avoid “missing providerId” with older backends - storage: custom endpoints are stored in ~/.cc-switch/config.json under providers[<id>].meta.custom_endpoints (not in settings.json) - behavior: edit flow remains immediate writes; create flow now writes once via addProvider, removing the providerId dependency during creation * feat: add endpoint candidates support and code formatting improvements - Add endpointCandidates field to ProviderPreset and CodexProviderPreset interfaces - Integrate preset endpoint candidates into speed test endpoint selection - Add multiple endpoint options for PackyCode providers (Claude & Codex) - Apply consistent code formatting (trailing commas, line breaks) - Improve template value type safety and readability * refactor: improve endpoint management button UX Replace ambiguous "Advanced" text with intuitive "Manage & Test" label accompanied by Zap icon, making the endpoint management panel entry point more discoverable and self-explanatory for both Claude and Codex configurations. * - merge: merge origin/main, resolve conflicts and preserve both feature sets - feat(tauri): register import/export and file dialogs; keep endpoint speed test and custom endpoints - feat(api): add updateTrayMenu and onProviderSwitched; wire import/export APIs - feat(types): extend global API declarations (import/export) - chore(presets): GLM preset supports both new and legacy model keys - chore(rust): add chrono dependency; refresh lockfile --------- Co-authored-by: Jason <farion1231@gmail.com>
2025-10-07 19:14:32 +08:00
}
// 应用设置类型(用于设置对话框与 Tauri API
export interface Settings {
// 是否在系统托盘macOS 菜单栏)显示图标
showInTray: boolean;
// 点击关闭按钮时是否最小化到托盘而不是关闭应用
minimizeToTrayOnClose: boolean;
// 启用 Claude 插件联动(写入 ~/.claude/config.json 的 primaryApiKey
enableClaudePluginIntegration?: boolean;
// 覆盖 Claude Code 配置目录(可选)
claudeConfigDir?: string;
// 覆盖 Codex 配置目录(可选)
codexConfigDir?: string;
// 首选语言(可选,默认中文)
language?: "en" | "zh";
feat: Implement Speed Test Function * feat: add unified endpoint speed test for API providers Add a comprehensive endpoint latency testing system that allows users to: - Test multiple API endpoints concurrently - Auto-select the fastest endpoint based on latency - Add/remove custom endpoints dynamically - View latency results with color-coded indicators Backend (Rust): - Implement parallel HTTP HEAD requests with configurable timeout - Handle various error scenarios (timeout, connection failure, invalid URL) - Return structured latency data with status codes Frontend (React): - Create interactive speed test UI component with auto-sort by latency - Support endpoint management (add/remove custom endpoints) - Extract and update Codex base_url from TOML configuration - Integrate with provider presets for default endpoint candidates This feature improves user experience when selecting optimal API endpoints, especially useful for users with multiple provider options or proxy setups. * refactor: convert endpoint speed test to modal dialog - Transform EndpointSpeedTest component into a modal dialog - Add "Advanced" button next to base URL input to open modal - Support ESC key and backdrop click to close modal - Apply Linear design principles: minimal styling, clean layout - Remove unused showBaseUrlInput variable - Implement same modal pattern for both Claude and Codex * fix: prevent modal cascade closing when ESC is pressed - Add state checks to prevent parent modal from closing when child modals (endpoint speed test or template wizard) are open - Update ESC key handler dependencies to track all modal states - Ensures only the topmost modal responds to ESC key * refactor: unify speed test panel UI with project design system UI improvements: - Update modal border radius from rounded-lg to rounded-xl - Unify header padding from px-6 py-4 to p-6 - Change speed test button color to blue theme (bg-blue-500) for consistency - Update footer background from bg-gray-50 to bg-gray-100 - Style "Done" button as primary action button with blue theme - Adjust footer button spacing and hover states Simplify endpoint display: - Remove endpoint labels (e.g., "Current Address", "Custom 1") - Display only URL for cleaner interface - Clean up all label-related logic: * Remove label field from EndpointCandidate interface * Remove label generation in buildInitialEntries function * Remove label handling in useEffect merge logic * Remove label generation in handleAddEndpoint * Remove label parameters from claudeSpeedTestEndpoints * Remove label parameters from codexSpeedTestEndpoints * refactor: improve endpoint list UI consistency - Show delete button for all endpoints on hover for uniform UI - Change selected state to use blue theme matching main interface: * Blue border (border-blue-500) for selected items * Light blue background (bg-blue-50/dark:bg-blue-900/20) * Blue indicator dot (bg-blue-500/dark:bg-blue-400) - Switch from compact list (space-y-px) to card-based layout (space-y-2) - Add rounded corners to each endpoint item for better visual separation * feat: persist custom endpoints to settings.json - Extend AppSettings to store custom endpoints for Claude and Codex - Add Tauri commands: get/add/remove/update custom endpoints - Update frontend API with endpoint persistence methods - Modify EndpointSpeedTest to load/save custom endpoints via API - Track endpoint last used time for future sorting/cleanup - Store endpoints per app type in settings.json instead of localStorage * - feat(types): add Provider.meta and ProviderMeta (snake_case) with custom_endpoints map - feat(provider-form): persist custom endpoints on provider create by merging EndpointSpeedTest’s custom URLs into meta.custom_endpoints on submit - feat(endpoint-speed-test): add onCustomEndpointsChange callback emitting normalized custom URLs; wire it for both Claude/Codex modals - fix(api): send alias param names (app/appType/app_type and provider_id/providerId) in Tauri invokes to avoid “missing providerId” with older backends - storage: custom endpoints are stored in ~/.cc-switch/config.json under providers[<id>].meta.custom_endpoints (not in settings.json) - behavior: edit flow remains immediate writes; create flow now writes once via addProvider, removing the providerId dependency during creation * feat: add endpoint candidates support and code formatting improvements - Add endpointCandidates field to ProviderPreset and CodexProviderPreset interfaces - Integrate preset endpoint candidates into speed test endpoint selection - Add multiple endpoint options for PackyCode providers (Claude & Codex) - Apply consistent code formatting (trailing commas, line breaks) - Improve template value type safety and readability * refactor: improve endpoint management button UX Replace ambiguous "Advanced" text with intuitive "Manage & Test" label accompanied by Zap icon, making the endpoint management panel entry point more discoverable and self-explanatory for both Claude and Codex configurations. * - merge: merge origin/main, resolve conflicts and preserve both feature sets - feat(tauri): register import/export and file dialogs; keep endpoint speed test and custom endpoints - feat(api): add updateTrayMenu and onProviderSwitched; wire import/export APIs - feat(types): extend global API declarations (import/export) - chore(presets): GLM preset supports both new and legacy model keys - chore(rust): add chrono dependency; refresh lockfile --------- Co-authored-by: Jason <farion1231@gmail.com>
2025-10-07 19:14:32 +08:00
// Claude 自定义端点列表
customEndpointsClaude?: Record<string, CustomEndpoint>;
// Codex 自定义端点列表
customEndpointsCodex?: Record<string, CustomEndpoint>;
feat(gemini): add Gemini provider integration (#202) * feat(gemini): add Gemini provider integration - Add gemini_config.rs module for .env file parsing - Extend AppType enum to support Gemini - Implement GeminiConfigEditor and GeminiFormFields components - Add GeminiIcon with standardized 1024x1024 viewBox - Add Gemini provider presets configuration - Update i18n translations for Gemini support - Extend ProviderService and McpService for Gemini * fix(gemini): resolve TypeScript errors, add i18n support, and fix MCP logic **Critical Fixes:** - Fix TS2741 errors in tests/msw/state.ts by adding missing Gemini type definitions - Fix ProviderCard.extractApiUrl to support GOOGLE_GEMINI_BASE_URL display - Add missing apps.gemini i18n keys (zh/en) for proper app name display - Fix MCP service Gemini cross-app duplication logic to prevent self-copy **Technical Details:** - tests/msw/state.ts: Add gemini default providers, current ID, and MCP config - ProviderCard.tsx: Check both ANTHROPIC_BASE_URL and GOOGLE_GEMINI_BASE_URL - services/mcp.rs: Skip Gemini in sync_other_side logic with unreachable!() guards - Run pnpm format to auto-fix code style issues **Verification:** - ✅ pnpm typecheck passes - ✅ pnpm format completed * feat(gemini): enhance authentication and config parsing - Add strict and lenient .env parsing modes - Implement PackyCode partner authentication detection - Support Google OAuth official authentication - Auto-configure security.auth.selectedType for PackyCode - Add comprehensive test coverage for all auth types - Update i18n for OAuth hints and Gemini config --------- Co-authored-by: Jason <farion1231@gmail.com>
2025-11-12 10:47:34 +08:00
// 安全设置(兼容未来扩展)
security?: {
auth?: {
selectedType?: string;
};
};
}
// MCP 服务器连接参数(宽松:允许扩展字段)
export interface McpServerSpec {
// 可选:社区常见 .mcp.json 中 stdio 配置可不写 type
type?: "stdio" | "http";
// stdio 字段
command?: string;
args?: string[];
env?: Record<string, string>;
cwd?: string;
// http 字段
url?: string;
headers?: Record<string, string>;
// 通用字段
[key: string]: any;
}
// v3.7.0: MCP 服务器应用启用状态
export interface McpApps {
claude: boolean;
codex: boolean;
gemini: boolean;
}
// MCP 服务器条目v3.7.0 统一结构)
export interface McpServer {
id: string;
name: string;
server: McpServerSpec;
apps: McpApps; // v3.7.0: 标记应用到哪些客户端
description?: string;
tags?: string[];
homepage?: string;
docs?: string;
// 兼容旧字段v3.6.x 及以前)
enabled?: boolean; // 已废弃v3.7.0 使用 apps 字段
source?: string;
[key: string]: any;
}
// MCP 服务器映射id -> McpServer
export type McpServersMap = Record<string, McpServer>;
// MCP 配置状态
export interface McpStatus {
userConfigPath: string;
userConfigExists: boolean;
serverCount: number;
}
// 新:来自 config.json 的 MCP 列表响应
export interface McpConfigResponse {
configPath: string;
servers: Record<string, McpServer>;
}