'use client' // Settings → AI: per-user BYO provider configuration ("Bring Your Own AI"). // 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. The optional instructions field is the user's own system-prompt // refinement for the in-app assistant (server contracts stay server-owned). import { useCallback, useEffect, useState } from 'react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Textarea } from '@/components/ui/textarea' 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, Eye, EyeOff } from 'lucide-react' import { toast } from 'sonner' const KEY_MASK = '••••••••' const INSTRUCTIONS_MAX = 4000 // mirrors the server cap (handlers/ai.go) type AiConfig = { id: string; provider: string; baseUrl: string; model: string instructions: 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', models: ['gpt-4o-mini', 'gpt-4o', 'nvidia/nemotron-3-ultra-550b-a55b:free', 'google/gemma-4-31b-it:free'], }, anthropic: { label: 'Anthropic (Claude)', defaultBase: 'https://api.anthropic.com', models: ['claude-sonnet-4-5', 'claude-opus-4-1', 'claude-3-5-haiku-latest'], }, gemini: { label: 'Google Gemini', defaultBase: 'https://generativelanguage.googleapis.com', models: ['gemini-2.5-flash', 'gemini-2.5-pro', 'gemini-2.0-flash'], }, } // Sentinel for "none of the suggested models — type your own" (OpenRouter // catalogs, local Ollama names, …). The API itself accepts any model string; // the dropdown is a convenience, not an allowlist. const CUSTOM_MODEL = '__custom__' async function api(path: string, init?: RequestInit): Promise { return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init }) } function FieldLabel({ children }: { children: React.ReactNode }) { return } 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(PROVIDERS['openai-compatible'].models[0]) const [apiKey, setApiKey] = useState('') const [showKey, setShowKey] = useState(false) const [instructions, setInstructions] = 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 ?? '') setInstructions(cfg.instructions ?? '') 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 changeProvider = (v: string) => { setProvider(v) setBaseUrl('') // The suggested-model list is per provider; fall back to its first entry // when the current model belongs to the old provider. if (!PROVIDERS[v].models.includes(model)) setModel(PROVIDERS[v].models[0]) } 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(), instructions: instructions.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('') setShowKey(false) 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(''); setShowKey(false); setInstructions('') setBaseUrl(''); setModel(PROVIDERS[provider].models[0]) 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, instructions: config.instructions, 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…
} const suggested = PROVIDERS[provider].models const modelChoice = suggested.includes(model) ? model : CUSTOM_MODEL return (

Bring your own AI

Connect your own LLM API key so Superbrain can run AI features for your account. Your key is stored encrypted in the server database — it is never shown again in the browser and is only ever sent to the provider you choose. {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" /> )}
Model providers
Base URL (optional) ) => setBaseUrl(e.target.value)} aria-label="Base URL" />
API key {config && (leave blank to keep the current key)}
) => setApiKey(e.target.value)} aria-label="API key" autoComplete="off" />
Default model {modelChoice === CUSTOM_MODEL && ( ) => setModel(e.target.value)} aria-label="Custom model" /> )}
Instructions (optional)