Files
superbrain/web/components/automations-settings.tsx
T
Andrew S Erwin 167f74c6b4
release gate / check (push) Failing after 6m42s
Separate AI config from implementation: BYO provider, model and key per user
The plan matrix's 'use your own AI' rows, made real. internal/ai is now
pure implementation: three provider adapters — openai-compatible
(OpenRouter, OpenAI, Grok, Groq, Ollama, any house gateway), native
Anthropic (/v1/messages, x-api-key) and native Gemini (generateContent;
the key travels in the x-goog-api-key HEADER, never the URL, because Go's
HTTP error strings include URLs and errors get logged). One netguard-dialed
client, per-source outbound budgets (ai:user:<id> vs ai:server).

Configuration is data: UserAiConfig (migration 015) — one row per user
with provider, base URL, model and an API key encrypted at rest via
internal/crypto (the IMAP-password format), masked in every response; a
PUT echoing the mask or leaving the key blank keeps the stored value;
version contract on updates. New endpoints: GET/PUT/DELETE /api/ai/config,
POST /api/ai/test (one probe completion through the resolved config),
GET /api/ai/status (plan-gated availability, no secrets).

Resolution chain (ai.ResolveForUser): the user's enabled BYO config first
on EVERY plan; else the server env key (AI_API_KEY/AI_MODEL/AI_BASE_URL/
AI_PROVIDER) only when the tenant's plan may spend it — new
entitlements.AllowServerAI: premium (credits), core (house gateway) and
selfhosted (operator IS the user); free/standard are BYO-only, exactly the
matrix. No AI available => 428 with a pointer to Settings -> AI (was a
global 503): the precondition is per-user now. Agent compile and url_watch
extraction resolve per owner, so different users' tasks can run on
different providers.

Web: Settings -> AI tab (provider picker with per-provider defaults and
model hints, write-only key input, Test button, effective-source badge
with plan context, enable switch, remove). The Automations tab reads
/api/ai/status for a proactive banner and treats 428 as 'not configured'.

Preparatory refactors (behavior-preserving): agent.AutomationSchema
extracted as the single spec text shared by the compiler prompt (and the
upcoming chat assistant), and ai.CompleteMessages for multi-turn
conversations with per-provider role mapping (assistant -> model on
Gemini).

Tests: all three adapters against one loopback fake (asserting each
provider's auth-header shape), masked-key lifecycle incl. mask-echo
preservation across a provider switch, encrypted-at-rest verification,
plan gate both directions (free refuses the server key, premium/core/
selfhosted allow it), BYO precedence over the server key, validation
rejects, 428 paths, and compile resolution through a BYO config.
Full suite green (-race), converge green (015), web lint/SSR/build clean.

Docs: API.md AI section, RUNNING.md setup rewritten around BYO-first +
plan-gated server fallback, .env.example (AI_PROVIDER + the precedence
story), compose passthrough, AGENTS.md invariant (config vs
implementation, Gemini key-in-header rule).
2026-10-28 19:16:17 -05:00

286 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use client'
// Automations ("hey superbrain"): compile a natural-language request into a
// validated task proposal, let the user confirm/edit it, then manage tasks
// and watch their runs. The server compiles AND re-validates; this UI never
// treats the model's output as trusted — the proposal is shown in plain
// language plus its raw spec before anything is stored.
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 { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Sparkles, Trash2, Play, Loader2, Wand2 } from 'lucide-react'
import { SafeTime } from '@/components/safe-format'
import { toast } from 'sonner'
type Condition = {
type: string; url?: string; question?: string; op?: string
threshold?: number; text?: string; keyword?: string
}
type ActionT = {
type: string; channelId?: string; to?: string
title?: string; body?: string; url?: string
}
type Spec = { condition: Condition; action: ActionT; pollMinutes: number; once: boolean }
type Task = {
id: string; name: string; spec: Spec; summary: string; enabled: boolean
status: string; fireCount: number; lastCheckedAt: string | null
lastFiredAt: string | null; version: number; createdAt: string
}
type Run = { id: string; taskId: string; outcome: string; detail: string | null; createdAt: string }
type ChannelOption = { id: string; name: string; kind: string; enabled: boolean }
async function api(path: string, init?: RequestInit): Promise<Response> {
return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init })
}
export function AutomationsSettings() {
const [tasks, setTasks] = useState<Task[]>([])
const [runs, setRuns] = useState<Run[]>([])
const [channels, setChannels] = useState<ChannelOption[]>([])
const [loading, setLoading] = useState(true)
const [available, setAvailable] = useState(true)
// Composer state
const [text, setText] = useState('')
const [compiling, setCompiling] = useState(false)
const [proposal, setProposal] = useState<{ name: string; spec: Spec; summary: string } | null>(null)
const [showRaw, setShowRaw] = useState(false)
const [runningId, setRunningId] = useState<string | null>(null)
const reload = useCallback(() =>
Promise.all([
api('/api/agent/tasks').then(r => r.json()),
api('/api/agent/runs').then(r => r.json()),
api('/api/notifications/channels').then(r => r.json()),
api('/api/ai/status').then(r => r.json()).catch(() => null),
])
.then(([tk, rn, ch, st]) => {
if (Array.isArray(tk)) setTasks(tk)
if (Array.isArray(rn)) setRuns(rn.slice(0, 10))
if (Array.isArray(ch)) setChannels(ch)
if (st && typeof st === 'object') setAvailable(st.effective !== 'none')
})
.catch(() => { toast.error('Could not load automations') })
.finally(() => { setLoading(false) }), [])
useEffect(() => { reload() }, [reload])
const reportError = async (res: Response, fallback: string): Promise<string | null> => {
let msg = fallback
try {
const data = await res.json()
if (data?.error) msg = data.error
} catch { /* non-JSON body */ }
if (res.status === 428) setAvailable(false)
toast.error(msg)
return msg
}
const compile = async () => {
if (!text.trim()) { toast.error('Describe what should happen first'); return }
setCompiling(true)
setProposal(null)
try {
const res = await api('/api/agent/compile', { method: 'POST', body: JSON.stringify({ text }) })
if (res.ok) {
const data = await res.json()
setProposal({ name: data.name, spec: data.spec, summary: data.summary })
setAvailable(true)
} else {
await reportError(res, 'Could not understand that request')
}
} catch {
toast.error('Could not reach the AI service')
} finally {
setCompiling(false)
}
}
const createTask = async () => {
if (!proposal) return
// A compiled notify action has no channel id (the model never knows
// them); the user must pick one before creation.
if (proposal.spec.action.type === 'notify' && !proposal.spec.action.channelId) {
toast.error('Pick a notification channel for this task')
return
}
const res = await api('/api/agent/tasks', {
method: 'POST',
body: JSON.stringify({ name: proposal.name, spec: proposal.spec }),
})
if (res.ok) {
toast.success('Automation created')
setProposal(null)
setText('')
await reload()
} else {
await reportError(res, 'Could not create the automation')
}
}
const toggleTask = async (t: Task, enabled: boolean) => {
const res = await api(`/api/agent/tasks/${t.id}`, {
method: 'PATCH', body: JSON.stringify({ enabled, version: t.version }),
})
if (res.ok) await reload()
else await reportError(res, 'Could not update the task')
}
const runNow = async (t: Task) => {
setRunningId(t.id)
try {
const res = await api(`/api/agent/tasks/${t.id}/run`, { method: 'POST' })
if (res.ok) {
const data = await res.json()
toast.info(`Run finished: ${data.outcome}`)
await reload()
} else {
await reportError(res, 'Run failed')
}
} finally { setRunningId(null) }
}
const removeTask = async (t: Task) => {
const res = await api(`/api/agent/tasks/${t.id}`, { method: 'DELETE' })
if (res.ok) { toast.success('Automation deleted'); await reload() }
else await reportError(res, 'Could not delete the task')
}
if (loading) {
return <div className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin" /> Loading automations…</div>
}
return (
<div className="space-y-6">
{/* Composer */}
<div className="rounded-lg border p-4 space-y-3">
<h3 className="font-medium flex items-center gap-2"><Sparkles className="h-4 w-4" /> Hey Superbrain</h3>
<p className="text-xs text-muted-foreground">
Describe an automation in plain language. Superbrain compiles it into a task you review
before anything is saved. It can watch a public web page and answer one question about it
(prices, availability, a phrase), or react to new mailbox signals — then notify you,
email someone, or save a bookmark. It cannot log in to sites, book anything, or chain
multiple sites yet.
</p>
{!available && (
<p className="text-xs text-destructive">
No AI is available to you yet — open the <strong>AI</strong> tab in Settings and add
your own provider and API key{` `}
(or your plan may include the server-provided key once the operator enables it).
Signal-condition tasks run without AI.
</p>
)}
<Textarea
placeholder='e.g. "when the round trip on https://flights.example/q/123 drops below $400, email david@email.com"'
value={text}
onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setText(e.target.value)}
rows={3}
/>
<div className="flex gap-2">
<Button onClick={compile} loading={compiling} size="sm" className="gap-1.5">
<Wand2 className="h-3.5 w-3.5" /> Compile
</Button>
{proposal && (
<Button variant="outline" size="sm" onClick={() => setShowRaw(v => !v)}>
{showRaw ? 'Hide details' : 'Review details'}
</Button>
)}
</div>
{proposal && (
<div className="space-y-3 rounded-md border bg-muted/30 p-3">
<div>
<p className="text-sm font-medium">{proposal.name}</p>
<p className="text-sm text-muted-foreground">{proposal.summary}</p>
<p className="text-xs text-muted-foreground mt-1">
Checks every {proposal.spec.pollMinutes} min
{proposal.spec.once ? ' · one-shot (completes after firing)' : ' · ongoing'}
</p>
</div>
{proposal.spec.action.type === 'notify' && (
<Select
value={proposal.spec.action.channelId || ''}
onValueChange={(v: string) => setProposal(p => p ? {
...p,
spec: { ...p.spec, action: { ...p.spec.action, channelId: v } },
} : p)}
>
<SelectTrigger aria-label="Notification channel"><SelectValue placeholder="Choose a notification channel" /></SelectTrigger>
<SelectContent>
{channels.filter(c => c.enabled).map(c => (
<SelectItem key={c.id} value={c.id}>{c.name} ({c.kind})</SelectItem>
))}
</SelectContent>
</Select>
)}
{proposal.spec.action.type === 'email' && (
<Input
aria-label="Recipient"
value={proposal.spec.action.to ?? ''}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setProposal(p => p ? {
...p,
spec: { ...p.spec, action: { ...p.spec.action, to: e.target.value } },
} : p)}
/>
)}
{showRaw && (
<pre className="text-xs bg-background rounded border p-2 overflow-x-auto">{JSON.stringify(proposal.spec, null, 2)}</pre>
)}
<div className="flex gap-2">
<Button size="sm" onClick={createTask}>Create automation</Button>
<Button size="sm" variant="ghost" onClick={() => setProposal(null)}>Discard</Button>
</div>
</div>
)}
</div>
{/* Tasks */}
<div className="rounded-lg border p-4 space-y-3">
<h3 className="font-medium">Automations</h3>
{tasks.length === 0 && <p className="text-sm text-muted-foreground">No automations yet.</p>}
{tasks.map(t => (
<div key={t.id} className="flex items-center gap-3 rounded-md border p-3">
<div className="min-w-0 flex-1">
<p className="text-sm font-medium truncate">{t.name}</p>
<p className="text-xs text-muted-foreground truncate">{t.summary}</p>
<p className="text-xs text-muted-foreground">
every {t.spec.pollMinutes}m · fired {t.fireCount}×
{t.lastFiredAt ? <> · last fired <SafeTime date={t.lastFiredAt} localize /></> : ''}
</p>
</div>
<Badge variant={t.status === 'active' ? 'default' : t.status === 'done' ? 'secondary' : 'destructive'}>
{t.status}
</Badge>
<Button size="sm" variant="outline" onClick={() => runNow(t)} disabled={runningId === t.id} aria-label="Run now">
{runningId === t.id ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Play className="h-3.5 w-3.5" />}
</Button>
<Switch checked={t.enabled} onCheckedChange={(v: boolean) => toggleTask(t, v)} aria-label="Enable automation" />
<Button size="sm" variant="ghost" onClick={() => removeTask(t)} aria-label="Delete automation">
<Trash2 className="h-3.5 w-3.5 text-muted-foreground" />
</Button>
</div>
))}
</div>
{/* Runs */}
<div className="rounded-lg border p-4 space-y-3">
<h3 className="font-medium">Recent runs</h3>
{runs.length === 0 && <p className="text-sm text-muted-foreground">Nothing has run yet.</p>}
{runs.map(rn => (
<div key={rn.id} className="flex items-center gap-2 text-sm">
<Badge variant={rn.outcome === 'fired' ? 'default' : rn.outcome === 'failed' ? 'destructive' : 'secondary'}>
{rn.outcome}
</Badge>
<span className="truncate flex-1 text-muted-foreground">{rn.detail ?? ''}</span>
<span className="text-xs text-muted-foreground shrink-0"><SafeTime date={rn.createdAt} localize /></span>
</div>
))}
</div>
</div>
)
}