feat(providers): implement secure API key storage and provider management
Add complete provider configuration system with the following features: - Secure API key storage using Electron's safeStorage encryption - Provider CRUD operations with IPC handlers - Lazy-loaded electron-store for ESM compatibility - Provider settings UI component with add/edit/delete functionality - API key masking for display (shows first/last 4 chars) - Basic API key format validation per provider type - Default provider selection - Provider enable/disable toggle New files: - electron/utils/secure-storage.ts: Encrypted key storage and provider config - src/stores/providers.ts: Zustand store for provider state - src/components/settings/ProvidersSettings.tsx: Provider management UI
This commit is contained in:
@@ -8,11 +8,12 @@
|
|||||||
### Completed:
|
### Completed:
|
||||||
* [commit_1] Project skeleton - Electron + React + TypeScript foundation (v0.1.0-alpha)
|
* [commit_1] Project skeleton - Electron + React + TypeScript foundation (v0.1.0-alpha)
|
||||||
* [commit_2] Gateway refinements - Auto-reconnection, health checks, better state management
|
* [commit_2] Gateway refinements - Auto-reconnection, health checks, better state management
|
||||||
|
* [commit_3] Setup wizard - Multi-step onboarding flow with provider, channel, skill selection
|
||||||
|
|
||||||
### Plan:
|
### Plan:
|
||||||
1. ~~Initialize project structure~~ ✅
|
1. ~~Initialize project structure~~ ✅
|
||||||
2. ~~Add Gateway process management refinements~~ ✅
|
2. ~~Add Gateway process management refinements~~ ✅
|
||||||
3. Implement Setup wizard with actual functionality
|
3. ~~Implement Setup wizard with actual functionality~~ ✅
|
||||||
4. Add Provider configuration (API Key management)
|
4. Add Provider configuration (API Key management)
|
||||||
5. Implement Channel connection flows
|
5. Implement Channel connection flows
|
||||||
6. Add auto-update functionality
|
6. Add auto-update functionality
|
||||||
|
|||||||
@@ -4,6 +4,21 @@
|
|||||||
*/
|
*/
|
||||||
import { ipcMain, BrowserWindow, shell, dialog, app } from 'electron';
|
import { ipcMain, BrowserWindow, shell, dialog, app } from 'electron';
|
||||||
import { GatewayManager } from '../gateway/manager';
|
import { GatewayManager } from '../gateway/manager';
|
||||||
|
import {
|
||||||
|
storeApiKey,
|
||||||
|
getApiKey,
|
||||||
|
deleteApiKey,
|
||||||
|
hasApiKey,
|
||||||
|
saveProvider,
|
||||||
|
getProvider,
|
||||||
|
getAllProviders,
|
||||||
|
deleteProvider,
|
||||||
|
setDefaultProvider,
|
||||||
|
getDefaultProvider,
|
||||||
|
getAllProvidersWithKeyInfo,
|
||||||
|
isEncryptionAvailable,
|
||||||
|
type ProviderConfig,
|
||||||
|
} from '../utils/secure-storage';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register all IPC handlers
|
* Register all IPC handlers
|
||||||
@@ -15,6 +30,9 @@ export function registerIpcHandlers(
|
|||||||
// Gateway handlers
|
// Gateway handlers
|
||||||
registerGatewayHandlers(gatewayManager, mainWindow);
|
registerGatewayHandlers(gatewayManager, mainWindow);
|
||||||
|
|
||||||
|
// Provider handlers
|
||||||
|
registerProviderHandlers();
|
||||||
|
|
||||||
// Shell handlers
|
// Shell handlers
|
||||||
registerShellHandlers();
|
registerShellHandlers();
|
||||||
|
|
||||||
@@ -136,6 +154,136 @@ function registerGatewayHandlers(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Provider-related IPC handlers
|
||||||
|
*/
|
||||||
|
function registerProviderHandlers(): void {
|
||||||
|
// Check if encryption is available
|
||||||
|
ipcMain.handle('provider:encryptionAvailable', () => {
|
||||||
|
return isEncryptionAvailable();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get all providers with key info
|
||||||
|
ipcMain.handle('provider:list', async () => {
|
||||||
|
return await getAllProvidersWithKeyInfo();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get a specific provider
|
||||||
|
ipcMain.handle('provider:get', async (_, providerId: string) => {
|
||||||
|
return await getProvider(providerId);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Save a provider configuration
|
||||||
|
ipcMain.handle('provider:save', async (_, config: ProviderConfig, apiKey?: string) => {
|
||||||
|
try {
|
||||||
|
// Save the provider config
|
||||||
|
await saveProvider(config);
|
||||||
|
|
||||||
|
// Store the API key if provided
|
||||||
|
if (apiKey) {
|
||||||
|
await storeApiKey(config.id, apiKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
return { success: false, error: String(error) };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Delete a provider
|
||||||
|
ipcMain.handle('provider:delete', async (_, providerId: string) => {
|
||||||
|
try {
|
||||||
|
await deleteProvider(providerId);
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
return { success: false, error: String(error) };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Update API key for a provider
|
||||||
|
ipcMain.handle('provider:setApiKey', async (_, providerId: string, apiKey: string) => {
|
||||||
|
try {
|
||||||
|
await storeApiKey(providerId, apiKey);
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
return { success: false, error: String(error) };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Delete API key for a provider
|
||||||
|
ipcMain.handle('provider:deleteApiKey', async (_, providerId: string) => {
|
||||||
|
try {
|
||||||
|
await deleteApiKey(providerId);
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
return { success: false, error: String(error) };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Check if a provider has an API key
|
||||||
|
ipcMain.handle('provider:hasApiKey', async (_, providerId: string) => {
|
||||||
|
return await hasApiKey(providerId);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get the actual API key (for internal use only - be careful!)
|
||||||
|
ipcMain.handle('provider:getApiKey', async (_, providerId: string) => {
|
||||||
|
return await getApiKey(providerId);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Set default provider
|
||||||
|
ipcMain.handle('provider:setDefault', async (_, providerId: string) => {
|
||||||
|
try {
|
||||||
|
await setDefaultProvider(providerId);
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
return { success: false, error: String(error) };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get default provider
|
||||||
|
ipcMain.handle('provider:getDefault', async () => {
|
||||||
|
return await getDefaultProvider();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Validate API key by making a test request (simulated for now)
|
||||||
|
ipcMain.handle('provider:validateKey', async (_, providerId: string, apiKey: string) => {
|
||||||
|
// In a real implementation, this would make a test API call to the provider
|
||||||
|
// For now, we'll just do basic format validation
|
||||||
|
try {
|
||||||
|
// Basic validation based on provider type
|
||||||
|
const provider = await getProvider(providerId);
|
||||||
|
if (!provider) {
|
||||||
|
return { valid: false, error: 'Provider not found' };
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (provider.type) {
|
||||||
|
case 'anthropic':
|
||||||
|
if (!apiKey.startsWith('sk-ant-')) {
|
||||||
|
return { valid: false, error: 'Anthropic keys should start with sk-ant-' };
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'openai':
|
||||||
|
if (!apiKey.startsWith('sk-')) {
|
||||||
|
return { valid: false, error: 'OpenAI keys should start with sk-' };
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'google':
|
||||||
|
if (apiKey.length < 20) {
|
||||||
|
return { valid: false, error: 'Google API key seems too short' };
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Simulate API validation delay
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||||
|
|
||||||
|
return { valid: true };
|
||||||
|
} catch (error) {
|
||||||
|
return { valid: false, error: String(error) };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Shell-related IPC handlers
|
* Shell-related IPC handlers
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -52,6 +52,17 @@ const electronAPI = {
|
|||||||
'env:setApiKey',
|
'env:setApiKey',
|
||||||
'env:deleteApiKey',
|
'env:deleteApiKey',
|
||||||
// Provider
|
// Provider
|
||||||
|
'provider:encryptionAvailable',
|
||||||
|
'provider:list',
|
||||||
|
'provider:get',
|
||||||
|
'provider:save',
|
||||||
|
'provider:delete',
|
||||||
|
'provider:setApiKey',
|
||||||
|
'provider:deleteApiKey',
|
||||||
|
'provider:hasApiKey',
|
||||||
|
'provider:getApiKey',
|
||||||
|
'provider:setDefault',
|
||||||
|
'provider:getDefault',
|
||||||
'provider:validateKey',
|
'provider:validateKey',
|
||||||
// Cron
|
// Cron
|
||||||
'cron:list',
|
'cron:list',
|
||||||
|
|||||||
273
electron/utils/secure-storage.ts
Normal file
273
electron/utils/secure-storage.ts
Normal file
@@ -0,0 +1,273 @@
|
|||||||
|
/**
|
||||||
|
* Secure Storage Utility
|
||||||
|
* Uses Electron's safeStorage for encrypting sensitive data like API keys
|
||||||
|
*/
|
||||||
|
import { safeStorage } from 'electron';
|
||||||
|
|
||||||
|
// Lazy-load electron-store (ESM module)
|
||||||
|
let store: any = null;
|
||||||
|
let providerStore: any = null;
|
||||||
|
|
||||||
|
async function getStore() {
|
||||||
|
if (!store) {
|
||||||
|
const Store = (await import('electron-store')).default;
|
||||||
|
store = new Store({
|
||||||
|
name: 'clawx-secure',
|
||||||
|
defaults: {
|
||||||
|
encryptedKeys: {},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return store;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getProviderStore() {
|
||||||
|
if (!providerStore) {
|
||||||
|
const Store = (await import('electron-store')).default;
|
||||||
|
providerStore = new Store({
|
||||||
|
name: 'clawx-providers',
|
||||||
|
defaults: {
|
||||||
|
providers: {},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return providerStore;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Provider configuration
|
||||||
|
*/
|
||||||
|
export interface ProviderConfig {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
type: 'anthropic' | 'openai' | 'google' | 'ollama' | 'custom';
|
||||||
|
baseUrl?: string;
|
||||||
|
model?: string;
|
||||||
|
enabled: boolean;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if encryption is available
|
||||||
|
*/
|
||||||
|
export function isEncryptionAvailable(): boolean {
|
||||||
|
return safeStorage.isEncryptionAvailable();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Store an API key securely
|
||||||
|
*/
|
||||||
|
export async function storeApiKey(providerId: string, apiKey: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const s = await getStore();
|
||||||
|
|
||||||
|
if (!safeStorage.isEncryptionAvailable()) {
|
||||||
|
console.warn('Encryption not available, storing key in plain text');
|
||||||
|
// Fallback to plain storage (not recommended for production)
|
||||||
|
const keys = s.get('encryptedKeys') as Record<string, string>;
|
||||||
|
keys[providerId] = Buffer.from(apiKey).toString('base64');
|
||||||
|
s.set('encryptedKeys', keys);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Encrypt the API key
|
||||||
|
const encrypted = safeStorage.encryptString(apiKey);
|
||||||
|
const keys = s.get('encryptedKeys') as Record<string, string>;
|
||||||
|
keys[providerId] = encrypted.toString('base64');
|
||||||
|
s.set('encryptedKeys', keys);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to store API key:', error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve an API key
|
||||||
|
*/
|
||||||
|
export async function getApiKey(providerId: string): Promise<string | null> {
|
||||||
|
try {
|
||||||
|
const s = await getStore();
|
||||||
|
const keys = s.get('encryptedKeys') as Record<string, string>;
|
||||||
|
const encryptedBase64 = keys[providerId];
|
||||||
|
|
||||||
|
if (!encryptedBase64) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!safeStorage.isEncryptionAvailable()) {
|
||||||
|
// Fallback for plain storage
|
||||||
|
return Buffer.from(encryptedBase64, 'base64').toString('utf-8');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decrypt the API key
|
||||||
|
const encrypted = Buffer.from(encryptedBase64, 'base64');
|
||||||
|
return safeStorage.decryptString(encrypted);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to retrieve API key:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete an API key
|
||||||
|
*/
|
||||||
|
export async function deleteApiKey(providerId: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const s = await getStore();
|
||||||
|
const keys = s.get('encryptedKeys') as Record<string, string>;
|
||||||
|
delete keys[providerId];
|
||||||
|
s.set('encryptedKeys', keys);
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to delete API key:', error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if an API key exists for a provider
|
||||||
|
*/
|
||||||
|
export async function hasApiKey(providerId: string): Promise<boolean> {
|
||||||
|
const s = await getStore();
|
||||||
|
const keys = s.get('encryptedKeys') as Record<string, string>;
|
||||||
|
return providerId in keys;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List all provider IDs that have stored keys
|
||||||
|
*/
|
||||||
|
export async function listStoredKeyIds(): Promise<string[]> {
|
||||||
|
const s = await getStore();
|
||||||
|
const keys = s.get('encryptedKeys') as Record<string, string>;
|
||||||
|
return Object.keys(keys);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Provider Configuration ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save a provider configuration
|
||||||
|
*/
|
||||||
|
export async function saveProvider(config: ProviderConfig): Promise<void> {
|
||||||
|
const s = await getProviderStore();
|
||||||
|
const providers = s.get('providers') as Record<string, ProviderConfig>;
|
||||||
|
providers[config.id] = config;
|
||||||
|
s.set('providers', providers);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a provider configuration
|
||||||
|
*/
|
||||||
|
export async function getProvider(providerId: string): Promise<ProviderConfig | null> {
|
||||||
|
const s = await getProviderStore();
|
||||||
|
const providers = s.get('providers') as Record<string, ProviderConfig>;
|
||||||
|
return providers[providerId] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all provider configurations
|
||||||
|
*/
|
||||||
|
export async function getAllProviders(): Promise<ProviderConfig[]> {
|
||||||
|
const s = await getProviderStore();
|
||||||
|
const providers = s.get('providers') as Record<string, ProviderConfig>;
|
||||||
|
return Object.values(providers);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a provider configuration
|
||||||
|
*/
|
||||||
|
export async function deleteProvider(providerId: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
// Delete the API key first
|
||||||
|
await deleteApiKey(providerId);
|
||||||
|
|
||||||
|
// Delete the provider config
|
||||||
|
const s = await getProviderStore();
|
||||||
|
const providers = s.get('providers') as Record<string, ProviderConfig>;
|
||||||
|
delete providers[providerId];
|
||||||
|
s.set('providers', providers);
|
||||||
|
|
||||||
|
// Clear default if this was the default
|
||||||
|
if (s.get('defaultProvider') === providerId) {
|
||||||
|
s.delete('defaultProvider');
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to delete provider:', error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the default provider
|
||||||
|
*/
|
||||||
|
export async function setDefaultProvider(providerId: string): Promise<void> {
|
||||||
|
const s = await getProviderStore();
|
||||||
|
s.set('defaultProvider', providerId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the default provider
|
||||||
|
*/
|
||||||
|
export async function getDefaultProvider(): Promise<string | undefined> {
|
||||||
|
const s = await getProviderStore();
|
||||||
|
return s.get('defaultProvider') as string | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get provider with masked key info (for UI display)
|
||||||
|
*/
|
||||||
|
export async function getProviderWithKeyInfo(providerId: string): Promise<(ProviderConfig & { hasKey: boolean; keyMasked: string | null }) | null> {
|
||||||
|
const provider = await getProvider(providerId);
|
||||||
|
if (!provider) return null;
|
||||||
|
|
||||||
|
const apiKey = await getApiKey(providerId);
|
||||||
|
let keyMasked: string | null = null;
|
||||||
|
|
||||||
|
if (apiKey) {
|
||||||
|
// Show first 4 and last 4 characters
|
||||||
|
if (apiKey.length > 12) {
|
||||||
|
keyMasked = `${apiKey.substring(0, 4)}${'*'.repeat(apiKey.length - 8)}${apiKey.substring(apiKey.length - 4)}`;
|
||||||
|
} else {
|
||||||
|
keyMasked = '*'.repeat(apiKey.length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...provider,
|
||||||
|
hasKey: !!apiKey,
|
||||||
|
keyMasked,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all providers with key info (for UI display)
|
||||||
|
*/
|
||||||
|
export async function getAllProvidersWithKeyInfo(): Promise<Array<ProviderConfig & { hasKey: boolean; keyMasked: string | null }>> {
|
||||||
|
const providers = await getAllProviders();
|
||||||
|
const results: Array<ProviderConfig & { hasKey: boolean; keyMasked: string | null }> = [];
|
||||||
|
|
||||||
|
for (const provider of providers) {
|
||||||
|
const apiKey = await getApiKey(provider.id);
|
||||||
|
let keyMasked: string | null = null;
|
||||||
|
|
||||||
|
if (apiKey) {
|
||||||
|
if (apiKey.length > 12) {
|
||||||
|
keyMasked = `${apiKey.substring(0, 4)}${'*'.repeat(apiKey.length - 8)}${apiKey.substring(apiKey.length - 4)}`;
|
||||||
|
} else {
|
||||||
|
keyMasked = '*'.repeat(apiKey.length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
results.push({
|
||||||
|
...provider,
|
||||||
|
hasKey: !!apiKey,
|
||||||
|
keyMasked,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
441
src/components/settings/ProvidersSettings.tsx
Normal file
441
src/components/settings/ProvidersSettings.tsx
Normal file
@@ -0,0 +1,441 @@
|
|||||||
|
/**
|
||||||
|
* Providers Settings Component
|
||||||
|
* Manage AI provider configurations and API keys
|
||||||
|
*/
|
||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import {
|
||||||
|
Plus,
|
||||||
|
Trash2,
|
||||||
|
Edit,
|
||||||
|
Eye,
|
||||||
|
EyeOff,
|
||||||
|
Check,
|
||||||
|
X,
|
||||||
|
Loader2,
|
||||||
|
Star,
|
||||||
|
Key,
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Separator } from '@/components/ui/separator';
|
||||||
|
import { Switch } from '@/components/ui/switch';
|
||||||
|
import { useProviderStore, type ProviderWithKeyInfo } from '@/stores/providers';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
|
||||||
|
// Provider type definitions
|
||||||
|
const providerTypes = [
|
||||||
|
{ id: 'anthropic', name: 'Anthropic', icon: '🤖', placeholder: 'sk-ant-api03-...' },
|
||||||
|
{ id: 'openai', name: 'OpenAI', icon: '💚', placeholder: 'sk-proj-...' },
|
||||||
|
{ id: 'google', name: 'Google', icon: '🔷', placeholder: 'AIza...' },
|
||||||
|
{ id: 'ollama', name: 'Ollama', icon: '🦙', placeholder: 'Not required' },
|
||||||
|
{ id: 'custom', name: 'Custom', icon: '⚙️', placeholder: 'API key...' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function ProvidersSettings() {
|
||||||
|
const {
|
||||||
|
providers,
|
||||||
|
defaultProviderId,
|
||||||
|
loading,
|
||||||
|
fetchProviders,
|
||||||
|
addProvider,
|
||||||
|
updateProvider,
|
||||||
|
deleteProvider,
|
||||||
|
setApiKey,
|
||||||
|
setDefaultProvider,
|
||||||
|
validateApiKey,
|
||||||
|
} = useProviderStore();
|
||||||
|
|
||||||
|
const [showAddDialog, setShowAddDialog] = useState(false);
|
||||||
|
const [editingProvider, setEditingProvider] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Fetch providers on mount
|
||||||
|
useEffect(() => {
|
||||||
|
fetchProviders();
|
||||||
|
}, [fetchProviders]);
|
||||||
|
|
||||||
|
const handleAddProvider = async (type: string, name: string, apiKey: string) => {
|
||||||
|
try {
|
||||||
|
await addProvider({
|
||||||
|
id: `${type}-${Date.now()}`,
|
||||||
|
type: type as 'anthropic' | 'openai' | 'google' | 'ollama' | 'custom',
|
||||||
|
name,
|
||||||
|
enabled: true,
|
||||||
|
}, apiKey || undefined);
|
||||||
|
|
||||||
|
setShowAddDialog(false);
|
||||||
|
toast.success('Provider added successfully');
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(`Failed to add provider: ${error}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDeleteProvider = async (providerId: string) => {
|
||||||
|
try {
|
||||||
|
await deleteProvider(providerId);
|
||||||
|
toast.success('Provider deleted');
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(`Failed to delete provider: ${error}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSetDefault = async (providerId: string) => {
|
||||||
|
try {
|
||||||
|
await setDefaultProvider(providerId);
|
||||||
|
toast.success('Default provider updated');
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(`Failed to set default: ${error}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleToggleEnabled = async (provider: ProviderWithKeyInfo) => {
|
||||||
|
try {
|
||||||
|
await updateProvider(provider.id, { enabled: !provider.enabled });
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(`Failed to update provider: ${error}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg font-medium">AI Providers</h3>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Configure your AI model providers and API keys
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button onClick={() => setShowAddDialog(true)}>
|
||||||
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
|
Add Provider
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{loading ? (
|
||||||
|
<div className="flex items-center justify-center py-8">
|
||||||
|
<Loader2 className="h-6 w-6 animate-spin" />
|
||||||
|
</div>
|
||||||
|
) : providers.length === 0 ? (
|
||||||
|
<Card>
|
||||||
|
<CardContent className="flex flex-col items-center justify-center py-12">
|
||||||
|
<Key className="h-12 w-12 text-muted-foreground mb-4" />
|
||||||
|
<h3 className="text-lg font-medium mb-2">No providers configured</h3>
|
||||||
|
<p className="text-muted-foreground text-center mb-4">
|
||||||
|
Add an AI provider to start using ClawX
|
||||||
|
</p>
|
||||||
|
<Button onClick={() => setShowAddDialog(true)}>
|
||||||
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
|
Add Your First Provider
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{providers.map((provider) => (
|
||||||
|
<ProviderCard
|
||||||
|
key={provider.id}
|
||||||
|
provider={provider}
|
||||||
|
isDefault={provider.id === defaultProviderId}
|
||||||
|
isEditing={editingProvider === provider.id}
|
||||||
|
onEdit={() => setEditingProvider(provider.id)}
|
||||||
|
onCancelEdit={() => setEditingProvider(null)}
|
||||||
|
onDelete={() => handleDeleteProvider(provider.id)}
|
||||||
|
onSetDefault={() => handleSetDefault(provider.id)}
|
||||||
|
onToggleEnabled={() => handleToggleEnabled(provider)}
|
||||||
|
onUpdateKey={async (key) => {
|
||||||
|
await setApiKey(provider.id, key);
|
||||||
|
setEditingProvider(null);
|
||||||
|
}}
|
||||||
|
onValidateKey={(key) => validateApiKey(provider.id, key)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Add Provider Dialog */}
|
||||||
|
{showAddDialog && (
|
||||||
|
<AddProviderDialog
|
||||||
|
onClose={() => setShowAddDialog(false)}
|
||||||
|
onAdd={handleAddProvider}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ProviderCardProps {
|
||||||
|
provider: ProviderWithKeyInfo;
|
||||||
|
isDefault: boolean;
|
||||||
|
isEditing: boolean;
|
||||||
|
onEdit: () => void;
|
||||||
|
onCancelEdit: () => void;
|
||||||
|
onDelete: () => void;
|
||||||
|
onSetDefault: () => void;
|
||||||
|
onToggleEnabled: () => void;
|
||||||
|
onUpdateKey: (key: string) => Promise<void>;
|
||||||
|
onValidateKey: (key: string) => Promise<{ valid: boolean; error?: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProviderCard({
|
||||||
|
provider,
|
||||||
|
isDefault,
|
||||||
|
isEditing,
|
||||||
|
onEdit,
|
||||||
|
onCancelEdit,
|
||||||
|
onDelete,
|
||||||
|
onSetDefault,
|
||||||
|
onToggleEnabled,
|
||||||
|
onUpdateKey,
|
||||||
|
onValidateKey,
|
||||||
|
}: ProviderCardProps) {
|
||||||
|
const [newKey, setNewKey] = useState('');
|
||||||
|
const [showKey, setShowKey] = useState(false);
|
||||||
|
const [validating, setValidating] = useState(false);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
|
const typeInfo = providerTypes.find((t) => t.id === provider.type);
|
||||||
|
|
||||||
|
const handleSaveKey = async () => {
|
||||||
|
if (!newKey) return;
|
||||||
|
|
||||||
|
setValidating(true);
|
||||||
|
const result = await onValidateKey(newKey);
|
||||||
|
setValidating(false);
|
||||||
|
|
||||||
|
if (!result.valid) {
|
||||||
|
toast.error(result.error || 'Invalid API key');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
await onUpdateKey(newKey);
|
||||||
|
setNewKey('');
|
||||||
|
toast.success('API key updated');
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(`Failed to save key: ${error}`);
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className={cn(isDefault && 'ring-2 ring-primary')}>
|
||||||
|
<CardHeader className="pb-3">
|
||||||
|
<div className="flex items-start justify-between">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<span className="text-2xl">{typeInfo?.icon || '⚙️'}</span>
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<CardTitle className="text-lg">{provider.name}</CardTitle>
|
||||||
|
{isDefault && (
|
||||||
|
<Badge variant="default" className="text-xs">Default</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<CardDescription className="capitalize">{provider.type}</CardDescription>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Switch
|
||||||
|
checked={provider.enabled}
|
||||||
|
onCheckedChange={onToggleEnabled}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{isEditing ? (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>API Key</Label>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<div className="relative flex-1">
|
||||||
|
<Input
|
||||||
|
type={showKey ? 'text' : 'password'}
|
||||||
|
placeholder={typeInfo?.placeholder}
|
||||||
|
value={newKey}
|
||||||
|
onChange={(e) => setNewKey(e.target.value)}
|
||||||
|
className="pr-10"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowKey(!showKey)}
|
||||||
|
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||||
|
>
|
||||||
|
{showKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={handleSaveKey}
|
||||||
|
disabled={!newKey || validating || saving}
|
||||||
|
>
|
||||||
|
{validating || saving ? (
|
||||||
|
<Loader2 className="h-4 w-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Check className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" onClick={onCancelEdit}>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Key className="h-4 w-4 text-muted-foreground" />
|
||||||
|
<span className="text-sm font-mono">
|
||||||
|
{provider.hasKey ? provider.keyMasked : 'No API key set'}
|
||||||
|
</span>
|
||||||
|
{provider.hasKey && (
|
||||||
|
<Badge variant="secondary" className="text-xs">Configured</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-1">
|
||||||
|
{!isDefault && (
|
||||||
|
<Button variant="ghost" size="icon" onClick={onSetDefault} title="Set as default">
|
||||||
|
<Star className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button variant="ghost" size="icon" onClick={onEdit} title="Edit API key">
|
||||||
|
<Edit className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="icon" onClick={onDelete} title="Delete provider">
|
||||||
|
<Trash2 className="h-4 w-4 text-destructive" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AddProviderDialogProps {
|
||||||
|
onClose: () => void;
|
||||||
|
onAdd: (type: string, name: string, apiKey: string) => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function AddProviderDialog({ onClose, onAdd }: AddProviderDialogProps) {
|
||||||
|
const [selectedType, setSelectedType] = useState<string | null>(null);
|
||||||
|
const [name, setName] = useState('');
|
||||||
|
const [apiKey, setApiKey] = useState('');
|
||||||
|
const [showKey, setShowKey] = useState(false);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
|
const typeInfo = providerTypes.find((t) => t.id === selectedType);
|
||||||
|
|
||||||
|
const handleAdd = async () => {
|
||||||
|
if (!selectedType) return;
|
||||||
|
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
await onAdd(selectedType, name || typeInfo?.name || selectedType, apiKey);
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center">
|
||||||
|
<Card className="w-full max-w-md">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Add AI Provider</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Configure a new AI model provider
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
{!selectedType ? (
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
{providerTypes.map((type) => (
|
||||||
|
<button
|
||||||
|
key={type.id}
|
||||||
|
onClick={() => {
|
||||||
|
setSelectedType(type.id);
|
||||||
|
setName(type.name);
|
||||||
|
}}
|
||||||
|
className="p-4 rounded-lg border hover:bg-accent transition-colors text-center"
|
||||||
|
>
|
||||||
|
<span className="text-2xl">{type.icon}</span>
|
||||||
|
<p className="font-medium mt-2">{type.name}</p>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-center gap-3 p-3 rounded-lg bg-muted">
|
||||||
|
<span className="text-2xl">{typeInfo?.icon}</span>
|
||||||
|
<div>
|
||||||
|
<p className="font-medium">{typeInfo?.name}</p>
|
||||||
|
<button
|
||||||
|
onClick={() => setSelectedType(null)}
|
||||||
|
className="text-sm text-muted-foreground hover:text-foreground"
|
||||||
|
>
|
||||||
|
Change provider
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="name">Display Name</Label>
|
||||||
|
<Input
|
||||||
|
id="name"
|
||||||
|
placeholder={typeInfo?.name}
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="apiKey">API Key</Label>
|
||||||
|
<div className="relative">
|
||||||
|
<Input
|
||||||
|
id="apiKey"
|
||||||
|
type={showKey ? 'text' : 'password'}
|
||||||
|
placeholder={typeInfo?.placeholder}
|
||||||
|
value={apiKey}
|
||||||
|
onChange={(e) => setApiKey(e.target.value)}
|
||||||
|
className="pr-10"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowKey(!showKey)}
|
||||||
|
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||||
|
>
|
||||||
|
{showKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Your API key will be securely encrypted and stored locally.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Separator />
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
<Button variant="outline" onClick={onClose}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={handleAdd}
|
||||||
|
disabled={!selectedType || saving}
|
||||||
|
>
|
||||||
|
{saving ? (
|
||||||
|
<Loader2 className="h-4 w-4 animate-spin mr-2" />
|
||||||
|
) : null}
|
||||||
|
Add Provider
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
Loader2,
|
Loader2,
|
||||||
Terminal,
|
Terminal,
|
||||||
ExternalLink,
|
ExternalLink,
|
||||||
|
Key,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
@@ -20,6 +21,7 @@ import { Separator } from '@/components/ui/separator';
|
|||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
import { useSettingsStore } from '@/stores/settings';
|
import { useSettingsStore } from '@/stores/settings';
|
||||||
import { useGatewayStore } from '@/stores/gateway';
|
import { useGatewayStore } from '@/stores/gateway';
|
||||||
|
import { ProvidersSettings } from '@/components/settings/ProvidersSettings';
|
||||||
|
|
||||||
export function Settings() {
|
export function Settings() {
|
||||||
const {
|
const {
|
||||||
@@ -109,6 +111,20 @@ export function Settings() {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
{/* AI Providers */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center gap-2">
|
||||||
|
<Key className="h-5 w-5" />
|
||||||
|
AI Providers
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription>Configure your AI model providers and API keys</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<ProvidersSettings />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
{/* Gateway */}
|
{/* Gateway */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
|
|||||||
198
src/stores/providers.ts
Normal file
198
src/stores/providers.ts
Normal file
@@ -0,0 +1,198 @@
|
|||||||
|
/**
|
||||||
|
* Provider State Store
|
||||||
|
* Manages AI provider configurations
|
||||||
|
*/
|
||||||
|
import { create } from 'zustand';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Provider configuration
|
||||||
|
*/
|
||||||
|
export interface ProviderConfig {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
type: 'anthropic' | 'openai' | 'google' | 'ollama' | 'custom';
|
||||||
|
baseUrl?: string;
|
||||||
|
model?: string;
|
||||||
|
enabled: boolean;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Provider with key info (for display)
|
||||||
|
*/
|
||||||
|
export interface ProviderWithKeyInfo extends ProviderConfig {
|
||||||
|
hasKey: boolean;
|
||||||
|
keyMasked: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ProviderState {
|
||||||
|
providers: ProviderWithKeyInfo[];
|
||||||
|
defaultProviderId: string | null;
|
||||||
|
loading: boolean;
|
||||||
|
error: string | null;
|
||||||
|
|
||||||
|
// Actions
|
||||||
|
fetchProviders: () => Promise<void>;
|
||||||
|
addProvider: (config: Omit<ProviderConfig, 'createdAt' | 'updatedAt'>, apiKey?: string) => Promise<void>;
|
||||||
|
updateProvider: (providerId: string, updates: Partial<ProviderConfig>, apiKey?: string) => Promise<void>;
|
||||||
|
deleteProvider: (providerId: string) => Promise<void>;
|
||||||
|
setApiKey: (providerId: string, apiKey: string) => Promise<void>;
|
||||||
|
deleteApiKey: (providerId: string) => Promise<void>;
|
||||||
|
setDefaultProvider: (providerId: string) => Promise<void>;
|
||||||
|
validateApiKey: (providerId: string, apiKey: string) => Promise<{ valid: boolean; error?: string }>;
|
||||||
|
getApiKey: (providerId: string) => Promise<string | null>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useProviderStore = create<ProviderState>((set, get) => ({
|
||||||
|
providers: [],
|
||||||
|
defaultProviderId: null,
|
||||||
|
loading: false,
|
||||||
|
error: null,
|
||||||
|
|
||||||
|
fetchProviders: async () => {
|
||||||
|
set({ loading: true, error: null });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const providers = await window.electron.ipcRenderer.invoke('provider:list') as ProviderWithKeyInfo[];
|
||||||
|
const defaultId = await window.electron.ipcRenderer.invoke('provider:getDefault') as string | null;
|
||||||
|
|
||||||
|
set({
|
||||||
|
providers,
|
||||||
|
defaultProviderId: defaultId,
|
||||||
|
loading: false
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
set({ error: String(error), loading: false });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
addProvider: async (config, apiKey) => {
|
||||||
|
try {
|
||||||
|
const fullConfig: ProviderConfig = {
|
||||||
|
...config,
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await window.electron.ipcRenderer.invoke('provider:save', fullConfig, apiKey) as { success: boolean; error?: string };
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
throw new Error(result.error || 'Failed to save provider');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh the list
|
||||||
|
await get().fetchProviders();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to add provider:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
updateProvider: async (providerId, updates, apiKey) => {
|
||||||
|
try {
|
||||||
|
const existing = get().providers.find((p) => p.id === providerId);
|
||||||
|
if (!existing) {
|
||||||
|
throw new Error('Provider not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const updatedConfig: ProviderConfig = {
|
||||||
|
...existing,
|
||||||
|
...updates,
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await window.electron.ipcRenderer.invoke('provider:save', updatedConfig, apiKey) as { success: boolean; error?: string };
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
throw new Error(result.error || 'Failed to update provider');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh the list
|
||||||
|
await get().fetchProviders();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to update provider:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
deleteProvider: async (providerId) => {
|
||||||
|
try {
|
||||||
|
const result = await window.electron.ipcRenderer.invoke('provider:delete', providerId) as { success: boolean; error?: string };
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
throw new Error(result.error || 'Failed to delete provider');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh the list
|
||||||
|
await get().fetchProviders();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to delete provider:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
setApiKey: async (providerId, apiKey) => {
|
||||||
|
try {
|
||||||
|
const result = await window.electron.ipcRenderer.invoke('provider:setApiKey', providerId, apiKey) as { success: boolean; error?: string };
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
throw new Error(result.error || 'Failed to set API key');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh the list
|
||||||
|
await get().fetchProviders();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to set API key:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
deleteApiKey: async (providerId) => {
|
||||||
|
try {
|
||||||
|
const result = await window.electron.ipcRenderer.invoke('provider:deleteApiKey', providerId) as { success: boolean; error?: string };
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
throw new Error(result.error || 'Failed to delete API key');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh the list
|
||||||
|
await get().fetchProviders();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to delete API key:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
setDefaultProvider: async (providerId) => {
|
||||||
|
try {
|
||||||
|
const result = await window.electron.ipcRenderer.invoke('provider:setDefault', providerId) as { success: boolean; error?: string };
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
throw new Error(result.error || 'Failed to set default provider');
|
||||||
|
}
|
||||||
|
|
||||||
|
set({ defaultProviderId: providerId });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to set default provider:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
validateApiKey: async (providerId, apiKey) => {
|
||||||
|
try {
|
||||||
|
const result = await window.electron.ipcRenderer.invoke('provider:validateKey', providerId, apiKey) as { valid: boolean; error?: string };
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
return { valid: false, error: String(error) };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
getApiKey: async (providerId) => {
|
||||||
|
try {
|
||||||
|
return await window.electron.ipcRenderer.invoke('provider:getApiKey', providerId) as string | null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}));
|
||||||
Reference in New Issue
Block a user