'use client' // Settings → AI: per-user BYO provider configuration. Config is data // (UserAiConfig row), implementation is server-side adapters — the UI only // ever sees masked keys and the resolved availability status. The server // key (operator env) shows as a fallback the user's plan may or may not // include; the UI never learns whether the key itself exists beyond that. import { useCallback, useEffect, useState } from 'react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Switch } from '@/components/ui/switch' import { Badge } from '@/components/ui/badge' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' import { Bot, Loader2, Trash2, PlugZap } from 'lucide-react' import { toast } from 'sonner' const KEY_MASK = '••••••••' type AiConfig = { id: string; provider: string; baseUrl: string; model: string apiKey: string; enabled: boolean; version: number } type AiStatus = { userConfigured: boolean; userEnabled: boolean serverAvailable: boolean; effective: string; plan: string } const PROVIDERS: Record = { 'openai-compatible': { label: 'OpenAI-compatible (OpenRouter, OpenAI, Grok, Groq, Ollama, …)', defaultBase: 'https://openrouter.ai/api/v1', modelHint: 'e.g. recursive/flint-v1.0:free or gpt-4o-mini', }, anthropic: { label: 'Anthropic (Claude)', defaultBase: 'https://api.anthropic.com', modelHint: 'e.g. claude-sonnet-4-5' }, gemini: { label: 'Google Gemini', defaultBase: 'https://generativelanguage.googleapis.com', modelHint: 'e.g. gemini-2.0-flash' }, } async function api(path: string, init?: RequestInit): Promise { return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init }) } export function AiSettings() { const [config, setConfig] = useState(null) const [status, setStatus] = useState(null) const [loading, setLoading] = useState(true) const [saving, setSaving] = useState(false) const [testing, setTesting] = useState(false) const [provider, setProvider] = useState('openai-compatible') const [baseUrl, setBaseUrl] = useState('') const [model, setModel] = useState('') const [apiKey, setApiKey] = useState('') // Promise-chain loading (house pattern: no synchronous setState in // effects — the SSR lint refuses cascading renders). const reload = useCallback(() => Promise.all([ api('/api/ai/config').then(r => r.json()), api('/api/ai/status').then(r => r.json()), ]) .then(([cfg, st]) => { if (cfg && typeof cfg === 'object' && cfg.id) { setConfig(cfg) setProvider(cfg.provider) setBaseUrl(cfg.baseUrl ?? '') setModel(cfg.model ?? '') setApiKey('') // never prefill secrets; empty keeps the stored key } else { setConfig(null) } if (st && typeof st === 'object') setStatus(st) }) .catch(() => { toast.error('Could not load AI settings') }) .finally(() => { setLoading(false) }), []) useEffect(() => { reload() }, [reload]) const save = async () => { if (!model.trim()) { toast.error('Model is required'); return } if (!config && !apiKey.trim()) { toast.error('API key is required'); return } setSaving(true) try { const body: Record = { provider, baseUrl: baseUrl.trim() || PROVIDERS[provider].defaultBase, model: model.trim(), // Empty input on an existing config keeps the stored key (same // write-only contract as the mask). apiKey: apiKey.trim() || (config ? KEY_MASK : ''), } if (config) body.version = config.version const res = await api('/api/ai/config', { method: 'PUT', body: JSON.stringify(body) }) if (res.ok) { toast.success('AI settings saved') setApiKey('') await reload() } else { const data = await res.json().catch(() => null) toast.error(data?.error ?? 'Could not save AI settings') } } finally { setSaving(false) } } const test = async () => { setTesting(true) try { const res = await api('/api/ai/test', { method: 'POST' }) const data = await res.json().catch(() => null) if (res.ok) { toast.success(`AI reachable via ${data?.source === 'user' ? 'your key' : 'the server key'} (${data?.model}): “${data?.reply}”`) } else { toast.error(data?.error ?? 'AI test failed') } } finally { setTesting(false) } } const remove = async () => { const res = await api('/api/ai/config', { method: 'DELETE' }) if (res.ok) { toast.success('Your AI key was removed') setConfig(null); setApiKey(''); setModel(''); setBaseUrl('') await reload() } else { const data = await res.json().catch(() => null) toast.error(data?.error ?? 'Could not remove the config') } } const toggleEnabled = async (enabled: boolean) => { if (!config) return const res = await api('/api/ai/config', { method: 'PUT', body: JSON.stringify({ provider: config.provider, baseUrl: config.baseUrl, model: config.model, apiKey: KEY_MASK, enabled, version: config.version, }), }) if (res.ok) await reload() else { const data = await res.json().catch(() => null) toast.error(data?.error ?? 'Could not update') } } if (loading) { return
Loading AI settings…
} return (

Your AI provider

Superbrain uses AI for Automations (compiling “hey superbrain” requests and reading watched pages). Bring your own provider and key — it is stored encrypted, never shown again, and used only for your requests. {status?.serverAvailable ? ' This server also provides a shared AI key included in your plan; your own key takes precedence.' : ' Your plan is bring-your-own-key, so automations need a key here.'}

Effective source: {status?.effective === 'user' ? 'your key' : status?.effective === 'server' ? 'server key (plan)' : 'none — AI features disabled'} {config && ( Enabled toggleEnabled(v)} aria-label="Enable AI config" /> )}
) => setBaseUrl(e.target.value)} aria-label="Base URL" /> ) => setModel(e.target.value)} aria-label="Model" /> ) => setApiKey(e.target.value)} aria-label="API key" autoComplete="off" />
{config && ( )}
) }