feat(provider): mainly support moonshot / siliconflow on setup (#43)
This commit is contained in:
committed by
GitHub
Unverified
parent
563fcd2f24
commit
1b508d5bde
@@ -22,20 +22,14 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
|
||||
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 { useProviderStore, type ProviderConfig, type ProviderWithKeyInfo } from '@/stores/providers';
|
||||
import {
|
||||
PROVIDER_TYPE_INFO,
|
||||
type ProviderType,
|
||||
} from '@/lib/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: 'openrouter', name: 'OpenRouter', icon: '🌐', placeholder: 'sk-or-v1-...' },
|
||||
{ id: 'ollama', name: 'Ollama', icon: '🦙', placeholder: 'Not required' },
|
||||
{ id: 'custom', name: 'Custom', icon: '⚙️', placeholder: 'API key...' },
|
||||
];
|
||||
|
||||
export function ProvidersSettings() {
|
||||
const {
|
||||
providers,
|
||||
@@ -45,7 +39,7 @@ export function ProvidersSettings() {
|
||||
addProvider,
|
||||
updateProvider,
|
||||
deleteProvider,
|
||||
setApiKey,
|
||||
updateProviderWithKey,
|
||||
setDefaultProvider,
|
||||
validateApiKey,
|
||||
} = useProviderStore();
|
||||
@@ -58,15 +52,33 @@ export function ProvidersSettings() {
|
||||
fetchProviders();
|
||||
}, [fetchProviders]);
|
||||
|
||||
const handleAddProvider = async (type: string, name: string, apiKey: string) => {
|
||||
const handleAddProvider = async (
|
||||
type: ProviderType,
|
||||
name: string,
|
||||
apiKey: string,
|
||||
options?: { baseUrl?: string; model?: string }
|
||||
) => {
|
||||
// Only custom supports multiple instances.
|
||||
// Built-in providers remain singleton by type.
|
||||
const id = type === 'custom' ? `custom-${crypto.randomUUID()}` : type;
|
||||
try {
|
||||
await addProvider({
|
||||
id: `${type}-${Date.now()}`,
|
||||
type: type as 'anthropic' | 'openai' | 'google' | 'ollama' | 'custom',
|
||||
name,
|
||||
enabled: true,
|
||||
}, apiKey || undefined);
|
||||
|
||||
await addProvider(
|
||||
{
|
||||
id,
|
||||
type,
|
||||
name,
|
||||
baseUrl: options?.baseUrl,
|
||||
model: options?.model,
|
||||
enabled: true,
|
||||
},
|
||||
apiKey.trim() || undefined
|
||||
);
|
||||
|
||||
// Auto-set as default if this is the first provider
|
||||
if (providers.length === 0) {
|
||||
await setDefaultProvider(id);
|
||||
}
|
||||
|
||||
setShowAddDialog(false);
|
||||
toast.success('Provider added successfully');
|
||||
} catch (error) {
|
||||
@@ -140,8 +152,12 @@ export function ProvidersSettings() {
|
||||
onDelete={() => handleDeleteProvider(provider.id)}
|
||||
onSetDefault={() => handleSetDefault(provider.id)}
|
||||
onToggleEnabled={() => handleToggleEnabled(provider)}
|
||||
onUpdateKey={async (key) => {
|
||||
await setApiKey(provider.id, key);
|
||||
onSaveEdits={async (payload) => {
|
||||
await updateProviderWithKey(
|
||||
provider.id,
|
||||
payload.updates || {},
|
||||
payload.newApiKey
|
||||
);
|
||||
setEditingProvider(null);
|
||||
}}
|
||||
onValidateKey={(key) => validateApiKey(provider.id, key)}
|
||||
@@ -153,8 +169,10 @@ export function ProvidersSettings() {
|
||||
{/* Add Provider Dialog */}
|
||||
{showAddDialog && (
|
||||
<AddProviderDialog
|
||||
existingTypes={new Set(providers.map((p) => p.type))}
|
||||
onClose={() => setShowAddDialog(false)}
|
||||
onAdd={handleAddProvider}
|
||||
onValidateKey={(type, key) => validateApiKey(type, key)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -170,7 +188,7 @@ interface ProviderCardProps {
|
||||
onDelete: () => void;
|
||||
onSetDefault: () => void;
|
||||
onToggleEnabled: () => void;
|
||||
onUpdateKey: (key: string) => Promise<void>;
|
||||
onSaveEdits: (payload: { newApiKey?: string; updates?: Partial<ProviderConfig> }) => Promise<void>;
|
||||
onValidateKey: (key: string) => Promise<{ valid: boolean; error?: string }>;
|
||||
}
|
||||
|
||||
@@ -198,37 +216,78 @@ function ProviderCard({
|
||||
onDelete,
|
||||
onSetDefault,
|
||||
onToggleEnabled,
|
||||
onUpdateKey,
|
||||
onSaveEdits,
|
||||
onValidateKey,
|
||||
}: ProviderCardProps) {
|
||||
const [newKey, setNewKey] = useState('');
|
||||
const [baseUrl, setBaseUrl] = useState(provider.baseUrl || '');
|
||||
const [modelId, setModelId] = useState(provider.model || '');
|
||||
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;
|
||||
const typeInfo = PROVIDER_TYPE_INFO.find((t) => t.id === provider.type);
|
||||
const canEditConfig = Boolean(typeInfo?.showBaseUrl || typeInfo?.showModelId);
|
||||
|
||||
useEffect(() => {
|
||||
if (isEditing) {
|
||||
setNewKey('');
|
||||
setShowKey(false);
|
||||
setBaseUrl(provider.baseUrl || '');
|
||||
setModelId(provider.model || '');
|
||||
}
|
||||
|
||||
}, [isEditing, provider.baseUrl, provider.model]);
|
||||
|
||||
const handleSaveEdits = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
await onUpdateKey(newKey);
|
||||
const payload: { newApiKey?: string; updates?: Partial<ProviderConfig> } = {};
|
||||
|
||||
if (newKey.trim()) {
|
||||
setValidating(true);
|
||||
const result = await onValidateKey(newKey);
|
||||
setValidating(false);
|
||||
if (!result.valid) {
|
||||
toast.error(result.error || 'Invalid API key');
|
||||
setSaving(false);
|
||||
return;
|
||||
}
|
||||
payload.newApiKey = newKey.trim();
|
||||
}
|
||||
|
||||
if (canEditConfig) {
|
||||
if (typeInfo?.showModelId && !modelId.trim()) {
|
||||
toast.error('Model ID is required');
|
||||
setSaving(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const updates: Partial<ProviderConfig> = {};
|
||||
if ((baseUrl.trim() || undefined) !== (provider.baseUrl || undefined)) {
|
||||
updates.baseUrl = baseUrl.trim() || undefined;
|
||||
}
|
||||
if ((modelId.trim() || undefined) !== (provider.model || undefined)) {
|
||||
updates.model = modelId.trim() || undefined;
|
||||
}
|
||||
if (Object.keys(updates).length > 0) {
|
||||
payload.updates = updates;
|
||||
}
|
||||
}
|
||||
|
||||
if (!payload.newApiKey && !payload.updates) {
|
||||
onCancelEdit();
|
||||
setSaving(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await onSaveEdits(payload);
|
||||
setNewKey('');
|
||||
toast.success('API key updated');
|
||||
toast.success('Provider updated');
|
||||
} catch (error) {
|
||||
toast.error(`Failed to save key: ${error}`);
|
||||
toast.error(`Failed to save provider: ${error}`);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
setValidating(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -258,11 +317,37 @@ function ProviderCard({
|
||||
{/* Key row */}
|
||||
{isEditing ? (
|
||||
<div className="space-y-2">
|
||||
{canEditConfig && (
|
||||
<>
|
||||
{typeInfo?.showBaseUrl && (
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Base URL</Label>
|
||||
<Input
|
||||
value={baseUrl}
|
||||
onChange={(e) => setBaseUrl(e.target.value)}
|
||||
placeholder="https://api.example.com/v1"
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{typeInfo?.showModelId && (
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs">Model ID</Label>
|
||||
<Input
|
||||
value={modelId}
|
||||
onChange={(e) => setModelId(e.target.value)}
|
||||
placeholder={typeInfo.modelIdPlaceholder || 'provider/model-id'}
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Input
|
||||
type={showKey ? 'text' : 'password'}
|
||||
placeholder={typeInfo?.placeholder}
|
||||
placeholder={typeInfo?.requiresApiKey ? typeInfo?.placeholder : 'Optional: update API key'}
|
||||
value={newKey}
|
||||
onChange={(e) => setNewKey(e.target.value)}
|
||||
className="pr-10 h-9 text-sm"
|
||||
@@ -278,8 +363,17 @@ function ProviderCard({
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleSaveKey}
|
||||
disabled={!newKey || validating || saving}
|
||||
onClick={handleSaveEdits}
|
||||
disabled={
|
||||
validating
|
||||
|| saving
|
||||
|| (
|
||||
!newKey.trim()
|
||||
&& (baseUrl.trim() || undefined) === (provider.baseUrl || undefined)
|
||||
&& (modelId.trim() || undefined) === (provider.model || undefined)
|
||||
)
|
||||
|| Boolean(typeInfo?.showModelId && !modelId.trim())
|
||||
}
|
||||
>
|
||||
{validating || saving ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
@@ -324,25 +418,75 @@ function ProviderCard({
|
||||
}
|
||||
|
||||
interface AddProviderDialogProps {
|
||||
existingTypes: Set<string>;
|
||||
onClose: () => void;
|
||||
onAdd: (type: string, name: string, apiKey: string) => Promise<void>;
|
||||
onAdd: (
|
||||
type: ProviderType,
|
||||
name: string,
|
||||
apiKey: string,
|
||||
options?: { baseUrl?: string; model?: string }
|
||||
) => Promise<void>;
|
||||
onValidateKey: (type: string, apiKey: string) => Promise<{ valid: boolean; error?: string }>;
|
||||
}
|
||||
|
||||
function AddProviderDialog({ onClose, onAdd }: AddProviderDialogProps) {
|
||||
const [selectedType, setSelectedType] = useState<string | null>(null);
|
||||
function AddProviderDialog({ existingTypes, onClose, onAdd, onValidateKey }: AddProviderDialogProps) {
|
||||
const [selectedType, setSelectedType] = useState<ProviderType | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [apiKey, setApiKey] = useState('');
|
||||
const [baseUrl, setBaseUrl] = useState('');
|
||||
const [modelId, setModelId] = useState('');
|
||||
const [showKey, setShowKey] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [validationError, setValidationError] = useState<string | null>(null);
|
||||
|
||||
const typeInfo = providerTypes.find((t) => t.id === selectedType);
|
||||
const typeInfo = PROVIDER_TYPE_INFO.find((t) => t.id === selectedType);
|
||||
|
||||
// Only custom can be added multiple times.
|
||||
const availableTypes = PROVIDER_TYPE_INFO.filter(
|
||||
(t) => t.id === 'custom' || !existingTypes.has(t.id),
|
||||
);
|
||||
|
||||
const handleAdd = async () => {
|
||||
if (!selectedType) return;
|
||||
|
||||
|
||||
setSaving(true);
|
||||
setValidationError(null);
|
||||
|
||||
try {
|
||||
await onAdd(selectedType, name || typeInfo?.name || selectedType, apiKey);
|
||||
// Validate key first if the provider requires one and a key was entered
|
||||
const requiresKey = typeInfo?.requiresApiKey ?? false;
|
||||
if (requiresKey && !apiKey.trim()) {
|
||||
setValidationError('API key is required');
|
||||
setSaving(false);
|
||||
return;
|
||||
}
|
||||
if (requiresKey && apiKey) {
|
||||
const result = await onValidateKey(selectedType, apiKey);
|
||||
if (!result.valid) {
|
||||
setValidationError(result.error || 'Invalid API key');
|
||||
setSaving(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const requiresModel = typeInfo?.showModelId ?? false;
|
||||
if (requiresModel && !modelId.trim()) {
|
||||
setValidationError('Model ID is required');
|
||||
setSaving(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await onAdd(
|
||||
selectedType,
|
||||
name || typeInfo?.name || selectedType,
|
||||
apiKey.trim(),
|
||||
{
|
||||
baseUrl: baseUrl.trim() || undefined,
|
||||
model: (typeInfo?.defaultModelId || modelId.trim()) || undefined,
|
||||
}
|
||||
);
|
||||
} catch {
|
||||
// error already handled via toast in parent
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -360,12 +504,14 @@ function AddProviderDialog({ onClose, onAdd }: AddProviderDialogProps) {
|
||||
<CardContent className="space-y-4">
|
||||
{!selectedType ? (
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{providerTypes.map((type) => (
|
||||
{availableTypes.map((type) => (
|
||||
<button
|
||||
key={type.id}
|
||||
onClick={() => {
|
||||
setSelectedType(type.id);
|
||||
setName(type.name);
|
||||
setBaseUrl(type.defaultBaseUrl || '');
|
||||
setModelId(type.defaultModelId || '');
|
||||
}}
|
||||
className="p-4 rounded-lg border hover:bg-accent transition-colors text-center"
|
||||
>
|
||||
@@ -381,7 +527,12 @@ function AddProviderDialog({ onClose, onAdd }: AddProviderDialogProps) {
|
||||
<div>
|
||||
<p className="font-medium">{typeInfo?.name}</p>
|
||||
<button
|
||||
onClick={() => setSelectedType(null)}
|
||||
onClick={() => {
|
||||
setSelectedType(null);
|
||||
setValidationError(null);
|
||||
setBaseUrl('');
|
||||
setModelId('');
|
||||
}}
|
||||
className="text-sm text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
Change provider
|
||||
@@ -407,7 +558,10 @@ function AddProviderDialog({ onClose, onAdd }: AddProviderDialogProps) {
|
||||
type={showKey ? 'text' : 'password'}
|
||||
placeholder={typeInfo?.placeholder}
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
onChange={(e) => {
|
||||
setApiKey(e.target.value);
|
||||
setValidationError(null);
|
||||
}}
|
||||
className="pr-10"
|
||||
/>
|
||||
<button
|
||||
@@ -418,10 +572,40 @@ function AddProviderDialog({ onClose, onAdd }: AddProviderDialogProps) {
|
||||
{showKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
{validationError && (
|
||||
<p className="text-xs text-destructive">{validationError}</p>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Your API key will be securely encrypted and stored locally.
|
||||
Your API key is stored locally on your machine.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{typeInfo?.showBaseUrl && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="baseUrl">Base URL</Label>
|
||||
<Input
|
||||
id="baseUrl"
|
||||
placeholder="https://api.example.com/v1"
|
||||
value={baseUrl}
|
||||
onChange={(e) => setBaseUrl(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{typeInfo?.showModelId && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="modelId">Model ID</Label>
|
||||
<Input
|
||||
id="modelId"
|
||||
placeholder={typeInfo.modelIdPlaceholder || 'provider/model-id'}
|
||||
value={modelId}
|
||||
onChange={(e) => {
|
||||
setModelId(e.target.value);
|
||||
setValidationError(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -433,7 +617,7 @@ function AddProviderDialog({ onClose, onAdd }: AddProviderDialogProps) {
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleAdd}
|
||||
disabled={!selectedType || saving}
|
||||
disabled={!selectedType || saving || ((typeInfo?.showModelId ?? false) && modelId.trim().length === 0)}
|
||||
>
|
||||
{saving ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin mr-2" />
|
||||
|
||||
30
src/components/ui/select.tsx
Normal file
30
src/components/ui/select.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Select Component
|
||||
* Styled native select matching shadcn/ui conventions
|
||||
*/
|
||||
import * as React from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export type SelectProps = React.SelectHTMLAttributes<HTMLSelectElement>;
|
||||
|
||||
const Select = React.forwardRef<HTMLSelectElement, SelectProps>(
|
||||
({ className, children, ...props }, ref) => {
|
||||
return (
|
||||
<select
|
||||
className={cn(
|
||||
'flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 appearance-none bg-[length:16px_16px] bg-[right_12px_center] bg-no-repeat',
|
||||
'bg-[url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2216%22%20height%3D%2216%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%23888%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22m6%209%206%206%206-6%22/%3E%3C/svg%3E")]',
|
||||
'pr-10',
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</select>
|
||||
);
|
||||
}
|
||||
);
|
||||
Select.displayName = 'Select';
|
||||
|
||||
export { Select };
|
||||
74
src/lib/providers.ts
Normal file
74
src/lib/providers.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* Provider Types & UI Metadata — single source of truth for the frontend.
|
||||
*
|
||||
* NOTE: When adding a new provider type, also update
|
||||
* electron/utils/provider-registry.ts (env vars, models, configs).
|
||||
*/
|
||||
|
||||
export const PROVIDER_TYPES = [
|
||||
'anthropic',
|
||||
'openai',
|
||||
'google',
|
||||
'openrouter',
|
||||
'moonshot',
|
||||
'siliconflow',
|
||||
'ollama',
|
||||
'custom',
|
||||
] as const;
|
||||
export type ProviderType = (typeof PROVIDER_TYPES)[number];
|
||||
|
||||
export interface ProviderConfig {
|
||||
id: string;
|
||||
name: string;
|
||||
type: ProviderType;
|
||||
baseUrl?: string;
|
||||
model?: string;
|
||||
enabled: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ProviderWithKeyInfo extends ProviderConfig {
|
||||
hasKey: boolean;
|
||||
keyMasked: string | null;
|
||||
}
|
||||
|
||||
export interface ProviderTypeInfo {
|
||||
id: ProviderType;
|
||||
name: string;
|
||||
icon: string;
|
||||
placeholder: string;
|
||||
/** Model brand name for display (e.g. "Claude", "GPT") */
|
||||
model?: string;
|
||||
requiresApiKey: boolean;
|
||||
/** Pre-filled base URL (for proxy/compatible providers like SiliconFlow) */
|
||||
defaultBaseUrl?: string;
|
||||
/** Whether the user can edit the base URL in setup */
|
||||
showBaseUrl?: boolean;
|
||||
/** Whether to show a Model ID input field (for providers where user picks the model) */
|
||||
showModelId?: boolean;
|
||||
/** Default / example model ID placeholder */
|
||||
modelIdPlaceholder?: string;
|
||||
/** Default model ID to pre-fill */
|
||||
defaultModelId?: string;
|
||||
}
|
||||
|
||||
/** All supported provider types with UI metadata */
|
||||
export const PROVIDER_TYPE_INFO: ProviderTypeInfo[] = [
|
||||
{ id: 'anthropic', name: 'Anthropic', icon: '🤖', placeholder: 'sk-ant-api03-...', model: 'Claude', requiresApiKey: true },
|
||||
{ id: 'openai', name: 'OpenAI', icon: '💚', placeholder: 'sk-proj-...', model: 'GPT', requiresApiKey: true },
|
||||
{ id: 'google', name: 'Google', icon: '🔷', placeholder: 'AIza...', model: 'Gemini', requiresApiKey: true },
|
||||
{ id: 'openrouter', name: 'OpenRouter', icon: '🌐', placeholder: 'sk-or-v1-...', model: 'Multi-Model', requiresApiKey: true },
|
||||
{ id: 'moonshot', name: 'Moonshot', icon: '🌙', placeholder: 'sk-...', model: 'Kimi', requiresApiKey: true, defaultBaseUrl: 'https://api.moonshot.cn/v1', defaultModelId: 'kimi-k2.5' },
|
||||
{ id: 'siliconflow', name: 'SiliconFlow', icon: '🌊', placeholder: 'sk-...', model: 'Multi-Model', requiresApiKey: true, defaultBaseUrl: 'https://api.siliconflow.com/v1', defaultModelId: 'moonshotai/Kimi-K2.5' },
|
||||
{ id: 'ollama', name: 'Ollama', icon: '🦙', placeholder: 'Not required', requiresApiKey: false, defaultBaseUrl: 'http://localhost:11434', showBaseUrl: true, showModelId: true, modelIdPlaceholder: 'qwen3:latest' },
|
||||
{ id: 'custom', name: 'Custom', icon: '⚙️', placeholder: 'API key...', requiresApiKey: true, showBaseUrl: true, showModelId: true, modelIdPlaceholder: 'your-provider/model-id' },
|
||||
];
|
||||
|
||||
/** Provider list shown in the Setup wizard */
|
||||
export const SETUP_PROVIDERS = PROVIDER_TYPE_INFO;
|
||||
|
||||
/** Get type info by provider type id */
|
||||
export function getProviderTypeInfo(type: ProviderType): ProviderTypeInfo | undefined {
|
||||
return PROVIDER_TYPE_INFO.find((t) => t.id === type);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { useNavigate } from 'react-router-dom';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import {
|
||||
Check,
|
||||
ChevronDown,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Loader2,
|
||||
@@ -97,52 +98,45 @@ const defaultSkills: DefaultSkill[] = [
|
||||
{ id: 'terminal', name: 'Terminal', description: 'Shell command execution' },
|
||||
];
|
||||
|
||||
// Provider types
|
||||
interface Provider {
|
||||
id: string;
|
||||
name: string;
|
||||
model: string;
|
||||
icon: string;
|
||||
placeholder: string;
|
||||
}
|
||||
import { SETUP_PROVIDERS, type ProviderTypeInfo } from '@/lib/providers';
|
||||
|
||||
const providers: Provider[] = [
|
||||
{ id: 'anthropic', name: 'Anthropic', model: 'Claude', icon: '🤖', placeholder: 'sk-ant-...' },
|
||||
{ id: 'openai', name: 'OpenAI', model: 'GPT-4', icon: '💚', placeholder: 'sk-...' },
|
||||
{ id: 'google', name: 'Google', model: 'Gemini', icon: '🔷', placeholder: 'AI...' },
|
||||
{ id: 'openrouter', name: 'OpenRouter', model: 'Multi-Model', icon: '🌐', placeholder: 'sk-or-...' },
|
||||
];
|
||||
// Use the shared provider registry for setup providers
|
||||
const providers = SETUP_PROVIDERS;
|
||||
|
||||
// NOTE: Channel types moved to Settings > Channels page
|
||||
// NOTE: Skill bundles moved to Settings > Skills page - auto-install essential skills during setup
|
||||
|
||||
export function Setup() {
|
||||
const navigate = useNavigate();
|
||||
const [currentStep, setCurrentStep] = useState(0);
|
||||
const [currentStep, setCurrentStep] = useState<number>(STEP.WELCOME);
|
||||
|
||||
// Setup state
|
||||
const [selectedProvider, setSelectedProvider] = useState<string | null>(null);
|
||||
const [providerConfigured, setProviderConfigured] = useState(false);
|
||||
const [apiKey, setApiKey] = useState('');
|
||||
// Installation state for the Installing step
|
||||
const [installedSkills, setInstalledSkills] = useState<string[]>([]);
|
||||
// Runtime check status
|
||||
const [runtimeChecksPassed, setRuntimeChecksPassed] = useState(false);
|
||||
|
||||
const step = steps[currentStep];
|
||||
const isFirstStep = currentStep === 0;
|
||||
const isLastStep = currentStep === steps.length - 1;
|
||||
const safeStepIndex = Number.isInteger(currentStep)
|
||||
? Math.min(Math.max(currentStep, STEP.WELCOME), steps.length - 1)
|
||||
: STEP.WELCOME;
|
||||
const step = steps[safeStepIndex] ?? steps[STEP.WELCOME];
|
||||
const isFirstStep = safeStepIndex === STEP.WELCOME;
|
||||
const isLastStep = safeStepIndex === steps.length - 1;
|
||||
|
||||
const markSetupComplete = useSettingsStore((state) => state.markSetupComplete);
|
||||
|
||||
// Derive canProceed based on current step - computed directly to avoid useEffect
|
||||
const canProceed = useMemo(() => {
|
||||
switch (currentStep) {
|
||||
switch (safeStepIndex) {
|
||||
case STEP.WELCOME:
|
||||
return true;
|
||||
case STEP.RUNTIME:
|
||||
return runtimeChecksPassed;
|
||||
case STEP.PROVIDER:
|
||||
return selectedProvider !== null && apiKey.length > 0;
|
||||
return providerConfigured;
|
||||
case STEP.CHANNEL:
|
||||
return true; // Always allow proceeding — channel step is optional
|
||||
case STEP.INSTALLING:
|
||||
@@ -152,7 +146,7 @@ export function Setup() {
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}, [currentStep, selectedProvider, apiKey, runtimeChecksPassed]);
|
||||
}, [safeStepIndex, providerConfigured, runtimeChecksPassed]);
|
||||
|
||||
const handleNext = async () => {
|
||||
if (isLastStep) {
|
||||
@@ -193,14 +187,14 @@ export function Setup() {
|
||||
<div
|
||||
className={cn(
|
||||
'flex h-8 w-8 items-center justify-center rounded-full border-2 transition-colors',
|
||||
i < currentStep
|
||||
i < safeStepIndex
|
||||
? 'border-primary bg-primary text-primary-foreground'
|
||||
: i === currentStep
|
||||
: i === safeStepIndex
|
||||
? 'border-primary text-primary'
|
||||
: 'border-slate-600 text-slate-600'
|
||||
)}
|
||||
>
|
||||
{i < currentStep ? (
|
||||
{i < safeStepIndex ? (
|
||||
<Check className="h-4 w-4" />
|
||||
) : (
|
||||
<span className="text-sm">{i + 1}</span>
|
||||
@@ -210,7 +204,7 @@ export function Setup() {
|
||||
<div
|
||||
className={cn(
|
||||
'h-0.5 w-8 transition-colors',
|
||||
i < currentStep ? 'bg-primary' : 'bg-slate-600'
|
||||
i < safeStepIndex ? 'bg-primary' : 'bg-slate-600'
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
@@ -235,26 +229,27 @@ export function Setup() {
|
||||
|
||||
{/* Step-specific content */}
|
||||
<div className="rounded-xl bg-white/10 backdrop-blur p-8 mb-8">
|
||||
{currentStep === STEP.WELCOME && <WelcomeContent />}
|
||||
{currentStep === STEP.RUNTIME && <RuntimeContent onStatusChange={setRuntimeChecksPassed} />}
|
||||
{currentStep === STEP.PROVIDER && (
|
||||
{safeStepIndex === STEP.WELCOME && <WelcomeContent />}
|
||||
{safeStepIndex === STEP.RUNTIME && <RuntimeContent onStatusChange={setRuntimeChecksPassed} />}
|
||||
{safeStepIndex === STEP.PROVIDER && (
|
||||
<ProviderContent
|
||||
providers={providers}
|
||||
selectedProvider={selectedProvider}
|
||||
onSelectProvider={setSelectedProvider}
|
||||
apiKey={apiKey}
|
||||
onApiKeyChange={setApiKey}
|
||||
onConfiguredChange={setProviderConfigured}
|
||||
/>
|
||||
)}
|
||||
{currentStep === STEP.CHANNEL && <SetupChannelContent />}
|
||||
{currentStep === STEP.INSTALLING && (
|
||||
{safeStepIndex === STEP.CHANNEL && <SetupChannelContent />}
|
||||
{safeStepIndex === STEP.INSTALLING && (
|
||||
<InstallingContent
|
||||
skills={defaultSkills}
|
||||
onComplete={handleInstallationComplete}
|
||||
onSkip={() => setCurrentStep((i) => i + 1)}
|
||||
/>
|
||||
)}
|
||||
{currentStep === STEP.COMPLETE && (
|
||||
{safeStepIndex === STEP.COMPLETE && (
|
||||
<CompleteContent
|
||||
selectedProvider={selectedProvider}
|
||||
installedSkills={installedSkills}
|
||||
@@ -263,7 +258,7 @@ export function Setup() {
|
||||
</div>
|
||||
|
||||
{/* Navigation - hidden during installation step */}
|
||||
{currentStep !== STEP.INSTALLING && (
|
||||
{safeStepIndex !== STEP.INSTALLING && (
|
||||
<div className="flex justify-between">
|
||||
<div>
|
||||
{!isFirstStep && (
|
||||
@@ -274,12 +269,12 @@ export function Setup() {
|
||||
)}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{currentStep === STEP.CHANNEL && (
|
||||
{safeStepIndex === STEP.CHANNEL && (
|
||||
<Button variant="ghost" onClick={handleNext}>
|
||||
Skip this step
|
||||
</Button>
|
||||
)}
|
||||
{!isLastStep && currentStep !== STEP.RUNTIME && currentStep !== STEP.CHANNEL && (
|
||||
{!isLastStep && safeStepIndex !== STEP.RUNTIME && safeStepIndex !== STEP.CHANNEL && (
|
||||
<Button variant="ghost" onClick={handleSkip}>
|
||||
Skip Setup
|
||||
</Button>
|
||||
@@ -641,11 +636,12 @@ function RuntimeContent({ onStatusChange }: RuntimeContentProps) {
|
||||
}
|
||||
|
||||
interface ProviderContentProps {
|
||||
providers: Provider[];
|
||||
providers: ProviderTypeInfo[];
|
||||
selectedProvider: string | null;
|
||||
onSelectProvider: (id: string | null) => void;
|
||||
apiKey: string;
|
||||
onApiKeyChange: (key: string) => void;
|
||||
onConfiguredChange: (configured: boolean) => void;
|
||||
}
|
||||
|
||||
function ProviderContent({
|
||||
@@ -653,24 +649,39 @@ function ProviderContent({
|
||||
selectedProvider,
|
||||
onSelectProvider,
|
||||
apiKey,
|
||||
onApiKeyChange
|
||||
onApiKeyChange,
|
||||
onConfiguredChange,
|
||||
}: ProviderContentProps) {
|
||||
const [showKey, setShowKey] = useState(false);
|
||||
const [validating, setValidating] = useState(false);
|
||||
const [keyValid, setKeyValid] = useState<boolean | null>(null);
|
||||
const [baseUrl, setBaseUrl] = useState('');
|
||||
const [modelId, setModelId] = useState('');
|
||||
|
||||
// On mount, try to restore previously configured provider
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const list = await window.electron.ipcRenderer.invoke('provider:list') as Array<{ id: string; hasKey: boolean }>;
|
||||
const list = await window.electron.ipcRenderer.invoke('provider:list') as Array<{ id: string; type: string; hasKey: boolean }>;
|
||||
const defaultId = await window.electron.ipcRenderer.invoke('provider:getDefault') as string | null;
|
||||
const preferred = (defaultId && list.find((p) => p.id === defaultId && p.hasKey)) || list.find((p) => p.hasKey);
|
||||
const setupProviderTypes = new Set<string>(providers.map((p) => p.id));
|
||||
const setupCandidates = list.filter((p) => setupProviderTypes.has(p.type));
|
||||
const preferred =
|
||||
(defaultId && setupCandidates.find((p) => p.id === defaultId))
|
||||
|| setupCandidates.find((p) => p.hasKey)
|
||||
|| setupCandidates[0];
|
||||
if (preferred && !cancelled) {
|
||||
onSelectProvider(preferred.id);
|
||||
onSelectProvider(preferred.type);
|
||||
const typeInfo = providers.find((p) => p.id === preferred.type);
|
||||
const requiresKey = typeInfo?.requiresApiKey ?? false;
|
||||
onConfiguredChange(!requiresKey || preferred.hasKey);
|
||||
const storedKey = await window.electron.ipcRenderer.invoke('provider:getApiKey', preferred.id) as string | null;
|
||||
if (storedKey) {
|
||||
onApiKeyChange(storedKey);
|
||||
}
|
||||
} else if (!cancelled) {
|
||||
onConfiguredChange(false);
|
||||
}
|
||||
} catch (error) {
|
||||
if (!cancelled) {
|
||||
@@ -679,15 +690,36 @@ function ProviderContent({
|
||||
}
|
||||
})();
|
||||
return () => { cancelled = true; };
|
||||
}, [onApiKeyChange, onSelectProvider]);
|
||||
}, [onApiKeyChange, onConfiguredChange, onSelectProvider, providers]);
|
||||
|
||||
// When provider changes, load stored key + reset base URL
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
if (!selectedProvider) return;
|
||||
try {
|
||||
const storedKey = await window.electron.ipcRenderer.invoke('provider:getApiKey', selectedProvider) as string | null;
|
||||
if (!cancelled && storedKey) {
|
||||
onApiKeyChange(storedKey);
|
||||
const list = await window.electron.ipcRenderer.invoke('provider:list') as Array<{ id: string; type: string; hasKey: boolean }>;
|
||||
const defaultId = await window.electron.ipcRenderer.invoke('provider:getDefault') as string | null;
|
||||
const sameType = list.filter((p) => p.type === selectedProvider);
|
||||
const preferredInstance =
|
||||
(defaultId && sameType.find((p) => p.id === defaultId))
|
||||
|| sameType.find((p) => p.hasKey)
|
||||
|| sameType[0];
|
||||
const providerIdForLoad = preferredInstance?.id || selectedProvider;
|
||||
|
||||
const savedProvider = await window.electron.ipcRenderer.invoke(
|
||||
'provider:get',
|
||||
providerIdForLoad
|
||||
) as { baseUrl?: string; model?: string } | null;
|
||||
const storedKey = await window.electron.ipcRenderer.invoke('provider:getApiKey', providerIdForLoad) as string | null;
|
||||
if (!cancelled) {
|
||||
if (storedKey) {
|
||||
onApiKeyChange(storedKey);
|
||||
}
|
||||
|
||||
const info = providers.find((p) => p.id === selectedProvider);
|
||||
setBaseUrl(savedProvider?.baseUrl || info?.defaultBaseUrl || '');
|
||||
setModelId(savedProvider?.model || info?.defaultModelId || '');
|
||||
}
|
||||
} catch (error) {
|
||||
if (!cancelled) {
|
||||
@@ -696,95 +728,177 @@ function ProviderContent({
|
||||
}
|
||||
})();
|
||||
return () => { cancelled = true; };
|
||||
}, [onApiKeyChange, selectedProvider]);
|
||||
}, [onApiKeyChange, selectedProvider, providers]);
|
||||
|
||||
const selectedProviderData = providers.find((p) => p.id === selectedProvider);
|
||||
const showBaseUrlField = selectedProviderData?.showBaseUrl ?? false;
|
||||
const showModelIdField = selectedProviderData?.showModelId ?? false;
|
||||
const requiresKey = selectedProviderData?.requiresApiKey ?? false;
|
||||
|
||||
const handleValidateKey = async () => {
|
||||
if (!apiKey || !selectedProvider) return;
|
||||
const handleValidateAndSave = async () => {
|
||||
if (!selectedProvider) return;
|
||||
|
||||
setValidating(true);
|
||||
setKeyValid(null);
|
||||
|
||||
try {
|
||||
// Call real API validation
|
||||
const result = await window.electron.ipcRenderer.invoke(
|
||||
'provider:validateKey',
|
||||
selectedProvider,
|
||||
apiKey
|
||||
) as { valid: boolean; error?: string };
|
||||
|
||||
setKeyValid(result.valid);
|
||||
|
||||
if (result.valid) {
|
||||
// Save the API key to both ClawX secure storage and OpenClaw auth-profiles
|
||||
try {
|
||||
await window.electron.ipcRenderer.invoke(
|
||||
'provider:save',
|
||||
{
|
||||
id: selectedProvider,
|
||||
name: selectedProviderData?.name || selectedProvider,
|
||||
type: selectedProvider,
|
||||
enabled: true,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
apiKey
|
||||
);
|
||||
} catch (saveErr) {
|
||||
console.warn('Failed to persist API key:', saveErr);
|
||||
// Validate key if the provider requires one and a key was entered
|
||||
if (requiresKey && apiKey) {
|
||||
const result = await window.electron.ipcRenderer.invoke(
|
||||
'provider:validateKey',
|
||||
selectedProvider,
|
||||
apiKey
|
||||
) as { valid: boolean; error?: string };
|
||||
|
||||
setKeyValid(result.valid);
|
||||
|
||||
if (!result.valid) {
|
||||
toast.error(result.error || 'Invalid API key');
|
||||
setValidating(false);
|
||||
return;
|
||||
}
|
||||
toast.success('API key validated and saved');
|
||||
} else {
|
||||
toast.error(result.error || 'Invalid API key');
|
||||
setKeyValid(true);
|
||||
}
|
||||
|
||||
const effectiveModelId =
|
||||
selectedProviderData?.defaultModelId ||
|
||||
modelId.trim() ||
|
||||
undefined;
|
||||
|
||||
// Save provider config + API key, then set as default
|
||||
const saveResult = await window.electron.ipcRenderer.invoke(
|
||||
'provider:save',
|
||||
{
|
||||
id: selectedProvider,
|
||||
name: selectedProviderData?.name || selectedProvider,
|
||||
type: selectedProvider,
|
||||
baseUrl: baseUrl.trim() || undefined,
|
||||
model: effectiveModelId,
|
||||
enabled: true,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
apiKey || undefined
|
||||
) as { success: boolean; error?: string };
|
||||
|
||||
if (!saveResult.success) {
|
||||
throw new Error(saveResult.error || 'Failed to save provider config');
|
||||
}
|
||||
|
||||
const defaultResult = await window.electron.ipcRenderer.invoke(
|
||||
'provider:setDefault',
|
||||
selectedProvider
|
||||
) as { success: boolean; error?: string };
|
||||
|
||||
if (!defaultResult.success) {
|
||||
throw new Error(defaultResult.error || 'Failed to set default provider');
|
||||
}
|
||||
|
||||
onConfiguredChange(true);
|
||||
toast.success('Provider configured');
|
||||
} catch (error) {
|
||||
setKeyValid(false);
|
||||
toast.error('Validation failed: ' + String(error));
|
||||
onConfiguredChange(false);
|
||||
toast.error('Configuration failed: ' + String(error));
|
||||
} finally {
|
||||
setValidating(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Can the user submit?
|
||||
const canSubmit =
|
||||
selectedProvider
|
||||
&& (requiresKey ? apiKey.length > 0 : true)
|
||||
&& (showModelIdField ? modelId.trim().length > 0 : true);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="text-xl font-semibold mb-2">Select AI Provider</h2>
|
||||
<p className="text-slate-300">
|
||||
Choose your preferred AI model provider
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
{providers.map((provider) => (
|
||||
<button
|
||||
key={provider.id}
|
||||
onClick={() => {
|
||||
onSelectProvider(provider.id);
|
||||
{/* Provider selector — dropdown */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="provider">Model Provider</Label>
|
||||
<div className="relative">
|
||||
<select
|
||||
id="provider"
|
||||
value={selectedProvider || ''}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value || null;
|
||||
onSelectProvider(val);
|
||||
onConfiguredChange(false);
|
||||
onApiKeyChange('');
|
||||
setKeyValid(null);
|
||||
}}
|
||||
className={cn(
|
||||
'p-4 rounded-lg bg-white/5 hover:bg-white/10 transition-all text-center',
|
||||
selectedProvider === provider.id && 'ring-2 ring-primary bg-white/10'
|
||||
'appearance-none rounded-md border border-white/10 bg-white/5 px-3 py-2 pr-8',
|
||||
'w-full text-sm text-white cursor-pointer',
|
||||
'focus:outline-none focus:ring-2 focus:ring-ring',
|
||||
)}
|
||||
>
|
||||
<span className="text-3xl">{provider.icon}</span>
|
||||
<p className="font-medium mt-2">{provider.name}</p>
|
||||
<p className="text-sm text-slate-400">{provider.model}</p>
|
||||
</button>
|
||||
))}
|
||||
<option value="" disabled className="bg-slate-800 text-slate-400">Select a provider...</option>
|
||||
{providers.map((p) => (
|
||||
<option key={p.id} value={p.id} className="bg-slate-800 text-white">
|
||||
{p.icon} {p.name}{p.model ? ` — ${p.model}` : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<ChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-slate-400 pointer-events-none" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
{/* Dynamic config fields based on selected provider */}
|
||||
{selectedProvider && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, height: 0 }}
|
||||
animate={{ opacity: 1, height: 'auto' }}
|
||||
key={selectedProvider}
|
||||
initial={{ opacity: 0, y: 8 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="space-y-4"
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="apiKey">API Key</Label>
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
{/* Base URL field (for siliconflow, ollama, custom) */}
|
||||
{showBaseUrlField && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="baseUrl">Base URL</Label>
|
||||
<Input
|
||||
id="baseUrl"
|
||||
type="text"
|
||||
placeholder="https://api.example.com/v1"
|
||||
value={baseUrl}
|
||||
onChange={(e) => {
|
||||
setBaseUrl(e.target.value);
|
||||
onConfiguredChange(false);
|
||||
}}
|
||||
autoComplete="off"
|
||||
className="bg-white/5 border-white/10"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Model ID field (for siliconflow etc.) */}
|
||||
{showModelIdField && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="modelId">Model ID</Label>
|
||||
<Input
|
||||
id="modelId"
|
||||
type="text"
|
||||
placeholder={selectedProviderData?.modelIdPlaceholder || 'e.g. deepseek-ai/DeepSeek-V3'}
|
||||
value={modelId}
|
||||
onChange={(e) => {
|
||||
setModelId(e.target.value);
|
||||
onConfiguredChange(false);
|
||||
}}
|
||||
autoComplete="off"
|
||||
className="bg-white/5 border-white/10"
|
||||
/>
|
||||
<p className="text-xs text-slate-500">
|
||||
The model identifier from your provider (e.g. deepseek-ai/DeepSeek-V3)
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* API Key field (hidden for ollama) */}
|
||||
{requiresKey && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="apiKey">API Key</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="apiKey"
|
||||
type={showKey ? 'text' : 'password'}
|
||||
@@ -792,6 +906,7 @@ function ProviderContent({
|
||||
value={apiKey}
|
||||
onChange={(e) => {
|
||||
onApiKeyChange(e.target.value);
|
||||
onConfiguredChange(false);
|
||||
setKeyValid(null);
|
||||
}}
|
||||
autoComplete="off"
|
||||
@@ -805,27 +920,29 @@ function ProviderContent({
|
||||
{showKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleValidateKey}
|
||||
disabled={!apiKey || validating}
|
||||
>
|
||||
{validating ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
'Validate'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
{keyValid !== null && (
|
||||
<p className={cn('text-sm', keyValid ? 'text-green-400' : 'text-red-400')}>
|
||||
{keyValid ? '✓ API key is valid' : '✗ Invalid API key'}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-slate-400">
|
||||
Your API key will be securely stored in the system keychain.
|
||||
)}
|
||||
|
||||
{/* Validate & Save */}
|
||||
<Button
|
||||
onClick={handleValidateAndSave}
|
||||
disabled={!canSubmit || validating}
|
||||
className="w-full"
|
||||
>
|
||||
{validating ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin mr-2" />
|
||||
) : null}
|
||||
{requiresKey ? 'Validate & Save' : 'Save'}
|
||||
</Button>
|
||||
|
||||
{keyValid !== null && (
|
||||
<p className={cn('text-sm text-center', keyValid ? 'text-green-400' : 'text-red-400')}>
|
||||
{keyValid ? '✓ Provider configured successfully' : '✗ Invalid API key'}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<p className="text-sm text-slate-400 text-center">
|
||||
Your API key is stored locally on your machine.
|
||||
</p>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
@@ -283,6 +283,8 @@ export const useChatStore = create<ChatState>((set, get) => ({
|
||||
set({ error: result.error || 'Failed to send message', sending: false });
|
||||
} else if (result.result?.runId) {
|
||||
set({ activeRunId: result.result.runId });
|
||||
} else {
|
||||
// No runId from gateway; keep sending state and wait for events.
|
||||
}
|
||||
} catch (err) {
|
||||
set({ error: String(err), sending: false });
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
import { create } from 'zustand';
|
||||
import type { GatewayStatus } from '../types/gateway';
|
||||
|
||||
let gatewayInitPromise: Promise<void> | null = null;
|
||||
|
||||
interface GatewayHealth {
|
||||
ok: boolean;
|
||||
error?: string;
|
||||
@@ -39,47 +41,79 @@ export const useGatewayStore = create<GatewayState>((set, get) => ({
|
||||
|
||||
init: async () => {
|
||||
if (get().isInitialized) return;
|
||||
|
||||
try {
|
||||
// Get initial status
|
||||
const status = await window.electron.ipcRenderer.invoke('gateway:status') as GatewayStatus;
|
||||
set({ status, isInitialized: true });
|
||||
|
||||
// Listen for status changes
|
||||
window.electron.ipcRenderer.on('gateway:status-changed', (newStatus) => {
|
||||
set({ status: newStatus as GatewayStatus });
|
||||
});
|
||||
|
||||
// Listen for errors
|
||||
window.electron.ipcRenderer.on('gateway:error', (error) => {
|
||||
set({ lastError: String(error) });
|
||||
});
|
||||
|
||||
// Listen for notifications
|
||||
window.electron.ipcRenderer.on('gateway:notification', (notification) => {
|
||||
console.log('Gateway notification:', notification);
|
||||
});
|
||||
|
||||
// Listen for chat events from the gateway and forward to chat store
|
||||
window.electron.ipcRenderer.on('gateway:chat-message', (data) => {
|
||||
try {
|
||||
// Dynamic import to avoid circular dependency
|
||||
import('./chat').then(({ useChatStore }) => {
|
||||
const chatData = data as { message?: Record<string, unknown> } | Record<string, unknown>;
|
||||
const event = ('message' in chatData && typeof chatData.message === 'object')
|
||||
? chatData.message as Record<string, unknown>
|
||||
: chatData as Record<string, unknown>;
|
||||
useChatStore.getState().handleChatEvent(event);
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('Failed to forward chat event:', err);
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize Gateway:', error);
|
||||
set({ lastError: String(error) });
|
||||
if (gatewayInitPromise) {
|
||||
await gatewayInitPromise;
|
||||
return;
|
||||
}
|
||||
|
||||
gatewayInitPromise = (async () => {
|
||||
try {
|
||||
// Get initial status first
|
||||
const status = await window.electron.ipcRenderer.invoke('gateway:status') as GatewayStatus;
|
||||
set({ status, isInitialized: true });
|
||||
|
||||
// Listen for status changes
|
||||
window.electron.ipcRenderer.on('gateway:status-changed', (newStatus) => {
|
||||
set({ status: newStatus as GatewayStatus });
|
||||
});
|
||||
|
||||
// Listen for errors
|
||||
window.electron.ipcRenderer.on('gateway:error', (error) => {
|
||||
set({ lastError: String(error) });
|
||||
});
|
||||
|
||||
// Some Gateway builds stream chat events via generic "agent" notifications.
|
||||
// Normalize and forward them to the chat store.
|
||||
window.electron.ipcRenderer.on('gateway:notification', (notification) => {
|
||||
const payload = notification as { method?: string; params?: Record<string, unknown> } | undefined;
|
||||
if (!payload || payload.method !== 'agent' || !payload.params || typeof payload.params !== 'object') {
|
||||
return;
|
||||
}
|
||||
|
||||
const p = payload.params;
|
||||
const data = (p.data && typeof p.data === 'object') ? (p.data as Record<string, unknown>) : {};
|
||||
const normalizedEvent: Record<string, unknown> = {
|
||||
...data,
|
||||
runId: p.runId ?? data.runId,
|
||||
sessionKey: p.sessionKey ?? data.sessionKey,
|
||||
stream: p.stream ?? data.stream,
|
||||
seq: p.seq ?? data.seq,
|
||||
};
|
||||
|
||||
import('./chat')
|
||||
.then(({ useChatStore }) => {
|
||||
useChatStore.getState().handleChatEvent(normalizedEvent);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.warn('Failed to forward gateway notification event:', err);
|
||||
});
|
||||
});
|
||||
|
||||
// Listen for chat events from the gateway and forward to chat store
|
||||
window.electron.ipcRenderer.on('gateway:chat-message', (data) => {
|
||||
try {
|
||||
// Dynamic import to avoid circular dependency
|
||||
import('./chat').then(({ useChatStore }) => {
|
||||
const chatData = data as { message?: Record<string, unknown> } | Record<string, unknown>;
|
||||
const event = ('message' in chatData && typeof chatData.message === 'object')
|
||||
? chatData.message as Record<string, unknown>
|
||||
: chatData as Record<string, unknown>;
|
||||
useChatStore.getState().handleChatEvent(event);
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('Failed to forward chat event:', err);
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize Gateway:', error);
|
||||
set({ lastError: String(error) });
|
||||
} finally {
|
||||
gatewayInitPromise = null;
|
||||
}
|
||||
})();
|
||||
|
||||
await gatewayInitPromise;
|
||||
},
|
||||
|
||||
start: async () => {
|
||||
|
||||
@@ -3,28 +3,10 @@
|
||||
* Manages AI provider configurations
|
||||
*/
|
||||
import { create } from 'zustand';
|
||||
import type { ProviderConfig, ProviderWithKeyInfo } from '@/lib/providers';
|
||||
|
||||
/**
|
||||
* Provider configuration
|
||||
*/
|
||||
export interface ProviderConfig {
|
||||
id: string;
|
||||
name: string;
|
||||
type: 'anthropic' | 'openai' | 'google' | 'openrouter' | '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;
|
||||
}
|
||||
// Re-export types for consumers that imported from here
|
||||
export type { ProviderConfig, ProviderWithKeyInfo } from '@/lib/providers';
|
||||
|
||||
interface ProviderState {
|
||||
providers: ProviderWithKeyInfo[];
|
||||
@@ -38,6 +20,11 @@ interface ProviderState {
|
||||
updateProvider: (providerId: string, updates: Partial<ProviderConfig>, apiKey?: string) => Promise<void>;
|
||||
deleteProvider: (providerId: string) => Promise<void>;
|
||||
setApiKey: (providerId: string, apiKey: string) => Promise<void>;
|
||||
updateProviderWithKey: (
|
||||
providerId: string,
|
||||
updates: Partial<ProviderConfig>,
|
||||
apiKey?: string
|
||||
) => Promise<void>;
|
||||
deleteApiKey: (providerId: string) => Promise<void>;
|
||||
setDefaultProvider: (providerId: string) => Promise<void>;
|
||||
validateApiKey: (providerId: string, apiKey: string) => Promise<{ valid: boolean; error?: string }>;
|
||||
@@ -95,9 +82,11 @@ export const useProviderStore = create<ProviderState>((set, get) => ({
|
||||
if (!existing) {
|
||||
throw new Error('Provider not found');
|
||||
}
|
||||
|
||||
const { hasKey: _hasKey, keyMasked: _keyMasked, ...providerConfig } = existing;
|
||||
|
||||
const updatedConfig: ProviderConfig = {
|
||||
...existing,
|
||||
...providerConfig,
|
||||
...updates,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
@@ -147,6 +136,26 @@ export const useProviderStore = create<ProviderState>((set, get) => ({
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
updateProviderWithKey: async (providerId, updates, apiKey) => {
|
||||
try {
|
||||
const result = await window.electron.ipcRenderer.invoke(
|
||||
'provider:updateWithKey',
|
||||
providerId,
|
||||
updates,
|
||||
apiKey
|
||||
) as { success: boolean; error?: string };
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.error || 'Failed to update provider');
|
||||
}
|
||||
|
||||
await get().fetchProviders();
|
||||
} catch (error) {
|
||||
console.error('Failed to update provider with key:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
deleteApiKey: async (providerId) => {
|
||||
try {
|
||||
|
||||
@@ -448,4 +448,4 @@ export function getPrimaryChannels(): ChannelType[] {
|
||||
*/
|
||||
export function getAllChannels(): ChannelType[] {
|
||||
return Object.keys(CHANNEL_META) as ChannelType[];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user