Files
superbrain/web/components/ai-settings.tsx
T
Andrew S Erwin 09f8a5d933
release gate / check (push) Failing after 6m26s
release / smoke (push) Successful in 10m16s
release / publish (push) Failing after 9m57s
BYO AI settings: custom instructions, model picker, key show/hide
Mirrors the BYOK dialog suggested in issue #2:
- UserAiConfig gains an optional instructions column (schema.sql +
  migration 016); PUT validates (<=4000 chars) and full-replaces it.
- Instructions ride along on the assistant chat system prompt only
  (chatSystemWith); the automation compiler and page-extraction prompts
  stay server-owned contracts.
- Settings -> AI: labeled fields, per-provider suggested-model dropdown
  with a custom-model escape hatch, API key show/hide toggle, and the
  instructions textarea.
- Tests: projection echo, omission clears, cap validation, and the
  system-prompt assertion via a recorded fake provider body.
2026-10-31 19:09:44 -05:00

315 lines
13 KiB
TypeScript

'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<string, { label: string; defaultBase: string; models: string[] }> = {
'openai-compatible': {
label: 'OpenAI-compatible (OpenRouter, OpenAI, Grok, Groq, Ollama, …)',
defaultBase: 'https://openrouter.ai/api/v1',
models: ['gpt-4o-mini', 'gpt-4o', 'recursive/flint-v1.0: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<Response> {
return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init })
}
function FieldLabel({ children }: { children: React.ReactNode }) {
return <label className="text-xs font-medium">{children}</label>
}
export function AiSettings() {
const [config, setConfig] = useState<AiConfig | null>(null)
const [status, setStatus] = useState<AiStatus | null>(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<string, unknown> = {
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 <div className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin" /> Loading AI settings…</div>
}
const suggested = PROVIDERS[provider].models
const modelChoice = suggested.includes(model) ? model : CUSTOM_MODEL
return (
<div className="space-y-6">
<div className="rounded-lg border p-4 space-y-3">
<h3 className="font-medium flex items-center gap-2"><Bot className="h-4 w-4" /> Bring your own AI</h3>
<p className="text-xs text-muted-foreground">
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.'}
</p>
<div className="flex items-center gap-2 text-xs">
<span className="text-muted-foreground">Effective source:</span>
<Badge variant={status?.effective === 'none' ? 'destructive' : 'default'}>
{status?.effective === 'user' ? 'your key' : status?.effective === 'server' ? 'server key (plan)' : 'none — AI features disabled'}
</Badge>
{config && (
<span className="ml-auto flex items-center gap-2">
<span className="text-muted-foreground">Enabled</span>
<Switch checked={config.enabled} onCheckedChange={(v: boolean) => toggleEnabled(v)} aria-label="Enable AI config" />
</span>
)}
</div>
<div className="space-y-3 border-t pt-3">
<div className="space-y-1">
<FieldLabel>Model providers</FieldLabel>
<Select value={provider} onValueChange={changeProvider}>
<SelectTrigger aria-label="Provider"><SelectValue /></SelectTrigger>
<SelectContent>
{Object.entries(PROVIDERS).map(([k, p]) => (
<SelectItem key={k} value={k}>{p.label}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<FieldLabel>Base URL (optional)</FieldLabel>
<Input
placeholder={`blank = ${PROVIDERS[provider].defaultBase}`}
value={baseUrl}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setBaseUrl(e.target.value)}
aria-label="Base URL"
/>
</div>
<div className="space-y-1">
<FieldLabel>API key {config && <span className="text-muted-foreground">(leave blank to keep the current key)</span>}</FieldLabel>
<div className="relative">
<Input
type={showKey ? 'text' : 'password'}
className="pr-10"
placeholder={config ? KEY_MASK : 'sk-…'}
value={apiKey}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setApiKey(e.target.value)}
aria-label="API key"
autoComplete="off"
/>
<button
type="button"
onClick={() => setShowKey(v => !v)}
aria-label={showKey ? 'Hide API key' : 'Show API key'}
className="absolute inset-y-0 right-0 flex items-center pr-3 text-muted-foreground hover:text-foreground"
>
{showKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</button>
</div>
</div>
<div className="space-y-1">
<FieldLabel>Default model</FieldLabel>
<Select value={modelChoice} onValueChange={(v: string) => setModel(v === CUSTOM_MODEL ? '' : v)}>
<SelectTrigger aria-label="Default model"><SelectValue /></SelectTrigger>
<SelectContent>
{suggested.map(m => (
<SelectItem key={m} value={m}>{m}</SelectItem>
))}
<SelectItem value={CUSTOM_MODEL}>Custom model…</SelectItem>
</SelectContent>
</Select>
{modelChoice === CUSTOM_MODEL && (
<Input
className="mt-2"
placeholder={`Model ID — e.g. ${suggested[0]}`}
value={model}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setModel(e.target.value)}
aria-label="Custom model"
/>
)}
</div>
<div className="space-y-1">
<FieldLabel>Instructions (optional)</FieldLabel>
<Textarea
placeholder="Custom system instructions for the AI. Leave empty for defaults."
value={instructions}
rows={3}
maxLength={INSTRUCTIONS_MAX}
onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setInstructions(e.target.value.slice(0, INSTRUCTIONS_MAX))}
aria-label="Instructions"
/>
<p className="text-xs text-muted-foreground">
Refines the in-app assistant&rsquo;s tone and focus. Automation and page-reading prompts
stay server-owned, so hard limits always apply.
</p>
</div>
<div className="flex gap-2">
<Button size="sm" onClick={save} loading={saving}>{config ? 'Save changes' : 'Save AI settings'}</Button>
<Button size="sm" variant="outline" onClick={test} loading={testing} className="gap-1.5">
<PlugZap className="h-3.5 w-3.5" /> Test
</Button>
{config && (
<Button size="sm" variant="ghost" onClick={remove} className="gap-1.5 text-muted-foreground">
<Trash2 className="h-3.5 w-3.5" /> Remove my key
</Button>
)}
</div>
</div>
</div>
</div>
)
}