BYO AI settings: custom instructions, model picker, key show/hide
release gate / check (push) Failing after 6m26s
release / smoke (push) Successful in 10m16s
release / publish (push) Failing after 9m57s

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.
This commit is contained in:
Andrew S Erwin
2026-10-31 19:09:44 -05:00
parent 1dfd41986c
commit 09f8a5d933
10 changed files with 272 additions and 81 deletions
+140 -46
View File
@@ -1,45 +1,66 @@
'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.
// 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 } from 'lucide-react'
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
apiKey: string; enabled: boolean; version: number
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; modelHint: 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',
modelHint: 'e.g. recursive/flint-v1.0:free or gpt-4o-mini',
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'],
},
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' },
}
// 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)
@@ -49,8 +70,10 @@ export function AiSettings() {
const [provider, setProvider] = useState('openai-compatible')
const [baseUrl, setBaseUrl] = useState('')
const [model, setModel] = 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).
@@ -65,6 +88,7 @@ export function AiSettings() {
setProvider(cfg.provider)
setBaseUrl(cfg.baseUrl ?? '')
setModel(cfg.model ?? '')
setInstructions(cfg.instructions ?? '')
setApiKey('') // never prefill secrets; empty keeps the stored key
} else {
setConfig(null)
@@ -76,6 +100,14 @@ export function AiSettings() {
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 }
@@ -85,6 +117,7 @@ export function AiSettings() {
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 : ''),
@@ -94,6 +127,7 @@ export function AiSettings() {
if (res.ok) {
toast.success('AI settings saved')
setApiKey('')
setShowKey(false)
await reload()
} else {
const data = await res.json().catch(() => null)
@@ -119,7 +153,8 @@ export function AiSettings() {
const res = await api('/api/ai/config', { method: 'DELETE' })
if (res.ok) {
toast.success('Your AI key was removed')
setConfig(null); setApiKey(''); setModel(''); setBaseUrl('')
setConfig(null); setApiKey(''); setShowKey(false); setInstructions('')
setBaseUrl(''); setModel(PROVIDERS[provider].models[0])
await reload()
} else {
const data = await res.json().catch(() => null)
@@ -133,6 +168,7 @@ export function AiSettings() {
method: 'PUT',
body: JSON.stringify({
provider: config.provider, baseUrl: config.baseUrl, model: config.model,
instructions: config.instructions,
apiKey: KEY_MASK, enabled, version: config.version,
}),
})
@@ -147,14 +183,17 @@ export function AiSettings() {
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" /> Your AI provider</h3>
<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">
Superbrain uses AI for <strong>Automations</strong> (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.
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.'}
@@ -173,35 +212,90 @@ export function AiSettings() {
)}
</div>
<div className="space-y-2 border-t pt-3">
<Select value={provider} onValueChange={(v: string) => { setProvider(v); setBaseUrl('') }}>
<SelectTrigger aria-label="Provider"><SelectValue /></SelectTrigger>
<SelectContent>
{Object.entries(PROVIDERS).map(([k, p]) => (
<SelectItem key={k} value={k}>{p.label}</SelectItem>
))}
</SelectContent>
</Select>
<Input
placeholder={`Base URL (blank = ${PROVIDERS[provider].defaultBase})`}
value={baseUrl}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setBaseUrl(e.target.value)}
aria-label="Base URL"
/>
<Input
placeholder={`Model — ${PROVIDERS[provider].modelHint}`}
value={model}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setModel(e.target.value)}
aria-label="Model"
/>
<Input
type="password"
placeholder={config ? 'API key (leave blank to keep the current key)' : 'API key'}
value={apiKey}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setApiKey(e.target.value)}
aria-label="API key"
autoComplete="off"
/>
<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">