import { useState, useMemo, useCallback } from 'react' import { Button } from '@/components/ui/button' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' import { Badge } from '@/components/ui/badge' import { Input } from '@/components/ui/input' import { Loader2, Check, X, Shield, ChevronDown, ChevronRight, Key, Search, Pencil, Trash2 } from 'lucide-react' import { providerCredentialsApi, getProviders } from '@/api/providers' import type { Provider } from '@/api/providers' import { oauthApi, type OAuthAuthorizeResponse } from '@/api/oauth' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { OAuthAuthorizeDialog } from './OAuthAuthorizeDialog' import { OAuthCallbackDialog } from './OAuthCallbackDialog' import { ApiKeyDialog } from '@/components/model/ApiKeyDialog' export function ProviderSettings() { const [selectedProvider, setSelectedProvider] = useState(null) const [oauthDialogOpen, setOauthDialogOpen] = useState(false) const [oauthCallbackDialogOpen, setOauthCallbackDialogOpen] = useState(false) const [oauthResponse, setOauthResponse] = useState(null) const [connectedExpanded, setConnectedExpanded] = useState(false) const [availableExpanded, setAvailableExpanded] = useState(false) const [availableSearch, setAvailableSearch] = useState('') const [apiKeyDialogOpen, setApiKeyDialogOpen] = useState(false) const [apiKeyProvider, setApiKeyProvider] = useState(null) const [apiKeyMode, setApiKeyMode] = useState<'add' | 'edit'>('add') const queryClient = useQueryClient() const { data: providersData, isLoading: providersLoading } = useQuery({ queryKey: ['providers'], queryFn: () => getProviders(), staleTime: 300000, }) const providers = providersData?.providers const { data: credentialsList, isLoading: credentialsLoading } = useQuery({ queryKey: ['provider-credentials'], queryFn: () => providerCredentialsApi.list(), }) const { data: authMethods } = useQuery({ queryKey: ['provider-auth-methods'], queryFn: () => oauthApi.getAuthMethods(), }) const deleteCredentialMutation = useMutation({ mutationFn: (providerId: string) => providerCredentialsApi.delete(providerId), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['provider-credentials'] }) queryClient.invalidateQueries({ queryKey: ['providers'] }) queryClient.invalidateQueries({ queryKey: ['providers-with-models'] }) }, }) const handleDeleteCredential = (providerId: string) => { if (confirm(`Remove credentials for ${providerId}?`)) { deleteCredentialMutation.mutate(providerId) } } const handleOAuthAuthorize = (response: OAuthAuthorizeResponse) => { setOauthResponse(response) setOauthDialogOpen(false) setOauthCallbackDialogOpen(true) } const handleOAuthDialogClose = () => { setOauthDialogOpen(false) setSelectedProvider(null) } const handleOAuthSuccess = () => { queryClient.invalidateQueries({ queryKey: ['provider-credentials'] }) setOauthCallbackDialogOpen(false) setOauthResponse(null) setSelectedProvider(null) } const supportsOAuth = useCallback((providerId: string) => { const methods = authMethods?.[providerId] || [] return methods.some(method => method.type === 'oauth') }, [authMethods]) const hasCredentials = useCallback((providerId: string) => { return credentialsList?.includes(providerId) || false }, [credentialsList]) const oauthProviders = useMemo(() => { if (!providers || !authMethods) return [] return providers.filter(provider => supportsOAuth(provider.id)) }, [providers, authMethods, supportsOAuth]) const apiKeyProviders = useMemo(() => { if (!providers || !authMethods) return { connected: [], available: [] } const nonOAuthProviders = providers.filter(provider => !supportsOAuth(provider.id)) const connected = nonOAuthProviders.filter(provider => hasCredentials(provider.id)) const available = nonOAuthProviders.filter(provider => !hasCredentials(provider.id)) return { connected, available } }, [providers, authMethods, supportsOAuth, hasCredentials]) const filteredAvailableProviders = useMemo(() => { if (!availableSearch.trim()) return apiKeyProviders.available const search = availableSearch.toLowerCase() return apiKeyProviders.available.filter(provider => provider.name.toLowerCase().includes(search) || provider.id.toLowerCase().includes(search) ) }, [apiKeyProviders.available, availableSearch]) const selectedProviderName = useMemo(() => { if (!selectedProvider) return '' return providers?.find(p => p.id === selectedProvider)?.name || selectedProvider }, [selectedProvider, providers]) const handleAddApiKey = useCallback((provider: Provider) => { setApiKeyProvider(provider) setApiKeyMode('add') setApiKeyDialogOpen(true) }, []) const handleEditApiKey = useCallback((provider: Provider) => { setApiKeyProvider(provider) setApiKeyMode('edit') setApiKeyDialogOpen(true) }, []) const handleApiKeySuccess = useCallback(() => { setApiKeyDialogOpen(false) setApiKeyProvider(null) queryClient.invalidateQueries({ queryKey: ['provider-credentials'] }) queryClient.invalidateQueries({ queryKey: ['providers'] }) queryClient.invalidateQueries({ queryKey: ['providers-with-models'] }) }, [queryClient]) const handleApiKeyDialogClose = useCallback((open: boolean) => { setApiKeyDialogOpen(open) if (!open) { setApiKeyProvider(null) } }, []) if (providersLoading || credentialsLoading) { return (
) } return (

OAuth Providers

Connect to AI providers using OAuth authentication.

{oauthProviders.length === 0 ? (

No OAuth-capable providers available.

) : (
{oauthProviders.map((provider) => { const hasKey = hasCredentials(provider.id) const modelCount = Object.keys(provider.models || {}).length return (
{provider.name || provider.id} {hasKey ? ( Connected ) : ( Not Connected )}
{modelCount > 0 && ( {modelCount} model{modelCount !== 1 ? 's' : ''} )}
{hasKey && ( )}
) })}
)} {selectedProvider && ( )} {selectedProvider && oauthResponse && ( )}

API Keys

Manage API keys for AI providers.

{connectedExpanded && (
{apiKeyProviders.connected.length === 0 ? (

No providers configured. Add an API key below to get started.

) : ( apiKeyProviders.connected.map((provider) => { const modelCount = Object.keys(provider.models || {}).length return (
{provider.name || provider.id} {modelCount > 0 && ( {modelCount} model{modelCount !== 1 ? 's' : ''} )}
Connected
) }) )}
)}
{availableExpanded && (
setAvailableSearch(e.target.value)} className="pl-9 md:text-sm" />
{filteredAvailableProviders.length === 0 ? (

{availableSearch ? 'No providers match your search.' : 'No available providers.'}

) : ( filteredAvailableProviders.map((provider, index) => { const modelCount = Object.keys(provider.models || {}).length return (
{provider.name || provider.id} {modelCount > 0 && ( {modelCount} model{modelCount !== 1 ? 's' : ''} )}
) }) )}
)}
{apiKeyProvider && ( ({ id, name: model.name || id, })), source: 'builtin', isConnected: hasCredentials(apiKeyProvider.id), }} onSuccess={handleApiKeySuccess} mode={apiKeyMode} /> )}
) }