Files
superbrain/web/app/(app)/automations/client.tsx
T
Andrew S Erwin 53127cc8fa Automations: move from Settings to a sidebar workspace with a task dropdown
The Automations caret in the main sidebar lists the user's tasks (status
dot, persisted expand state, live refresh via AUTOMATIONS_CHANGED) and
deep-links /automations?task=<id>, which scrolls to the card and highlights
it. The management surface (compiler, task list, run history) moves to the
standalone /automations route; the settings tab is removed and legacy
?tab=automations deep links redirect. Assistant proposal creation notifies
the sidebar too. README/RUNNING/help wording follows; browser regression
covers the dropdown, deep link, redirect and mobile overflow.
2026-11-23 14:19:37 -06:00

314 lines
13 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") — the standalone workspace at /automations
// (moved out of Settings; the sidebar's Automations caret lists the user's
// tasks and deep-links here via ?task=<id>). 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. Mutations
// notify the sidebar (AUTOMATIONS_CHANGED) so its dropdown stays live.
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'
import { notifyAutomationsChanged } from '@/lib/automations'
import { cn } from '@/lib/utils'
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 AutomationsClient({ initialTask }: { initialTask: string | null }) {
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])
// Sidebar deep-link: bring the targeted task card into view once loaded.
useEffect(() => {
if (!initialTask || loading) return
document.getElementById(`automation-${initialTask}`)?.scrollIntoView({ block: 'center', behavior: 'smooth' })
}, [initialTask, loading, tasks.length])
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()
notifyAutomationsChanged()
} 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(); notifyAutomationsChanged() }
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()
notifyAutomationsChanged()
} 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(); notifyAutomationsChanged() }
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">
<div>
<h1 className="font-display text-2xl font-bold tracking-tight">Automations</h1>
<p className="text-sm text-muted-foreground mt-1">
Stored tasks that watch a page or your mailbox signals, then notify you, email someone,
or save a bookmark. The assistant can propose them; nothing runs until you confirm.
</p>
</div>
{/* 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">Your automations</h3>
{tasks.length === 0 && <p className="text-sm text-muted-foreground">No automations yet.</p>}
{tasks.map(t => (
<div
key={t.id}
id={`automation-${t.id}`}
className={cn(
'flex items-center gap-3 rounded-md border p-3',
initialTask === t.id && 'ring-1 ring-primary/60'
)}
>
<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>
)
}