Files
superbrain/web/app/(app)/automations/client.tsx
T
Andrew S Erwin c84d694a03 Automations phase 2: chaining, refinements, dry run
Chaining: spec gains calls:[ids] + calledOnly. On fire, a task calls its
same-owner callees in order; each callee evaluates its OWN condition and
may call onward. Safety: write-time cycle rejection (owner-graph DFS) plus
a runtime visited-set + depth cap (5); calledOnly tasks skip the schedule;
existing per-task fire caps and the owner daily email cap still apply
across the chain. The LLM never chooses calls — the user wires the graph.

Refinements: AgentTask.refinements jsonb (migration 026) stores added
constraints; the UI composes prompt+refinements into the compile text and
shows removable chips. Dry run: condition-check is split from fire() so
POST /api/agent/dry-run evaluates a spec without acting or recording —
the 'Extend → Try it' preview ('result would be false right now').

UI: detail view gains the 'If true, call' card (picker disables
loop-creating options), refinement chips + Extend/Try it/Add flow, called-by
breadcrumb, and a 'when called' frequency label.

Verified: full DB integration suite under -race (chaining fires callees,
cycle rejected at write + runtime guard terminates a DB-injected cycle,
calledOnly skips schedule, dry run records nothing, refinements capped),
db-converge + atomicity, web lint/SSR/build, browser regression extended
for chaining + refinement + dry run.
2026-11-25 14:57:41 -06:00

628 lines
33 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 workspace (phase 1 of the redesign): a master-detail surface
// at /automations. The sidebar promotes Automations to a top-level group
// with user-defined folders; this page shows either the overview (composer
// + grouped list + named global runs) or one automation's detail (prompt
// editing through the same compile→confirm discipline, group assignment,
// run-now/pause, and a per-task run timeline). The engine is unchanged:
// editing a prompt recompiles via /api/agent/compile and applies the
// validated spec through the versioned PATCH — the model never writes.
import { useCallback, useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
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, Folder, ChevronDown, ChevronRight, ArrowLeft, Pencil } 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; calls?: string[]; calledOnly?: boolean }
type Task = {
id: string; name: string; spec: Spec; summary: string; prompt: string; groupId: string | null
refinements: string[]; calls?: string[]; calledOnly?: boolean
runCount: number; errorCount: number; enabled: boolean; status: string
fireCount: number; lastFiredAt: string | null; version: number
}
type Group = { id: string; name: string; version: number }
type Run = { id: string; taskId: string; taskName?: 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 })
}
function frequencyLabel(spec: Spec): string {
if (spec.calledOnly) return 'when called'
if (spec.condition?.type === 'signal') return 'on new mail'
if (spec.once) return 'one-shot'
return `every ${spec.pollMinutes}m`
}
function outcomeMeta(outcome: string): { label: string; cls: string } {
switch (outcome) {
case 'fired': return { label: 'true', cls: 'bg-green-500/15 text-green-700 dark:text-green-400' }
case 'failed': return { label: 'error', cls: 'bg-destructive/15 text-destructive' }
case 'checked': return { label: 'false', cls: 'bg-muted text-muted-foreground' }
default: return { label: outcome, cls: 'bg-muted text-muted-foreground' }
}
}
export function AutomationsClient({ initialTask }: { initialTask: string | null }) {
const router = useRouter()
const [tasks, setTasks] = useState<Task[]>([])
const [groups, setGroups] = useState<Group[]>([])
const [runs, setRuns] = useState<Run[]>([])
const [taskRuns, setTaskRuns] = useState<Run[]>([])
const [channels, setChannels] = useState<ChannelOption[]>([])
const [loading, setLoading] = useState(true)
const [available, setAvailable] = useState(true)
// Composer
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 [newGroup, setNewGroup] = useState('')
// Detail / editing
const [runningId, setRunningId] = useState<string | null>(null)
const [editing, setEditing] = useState(false)
const [editName, setEditName] = useState('')
const [editPrompt, setEditPrompt] = useState('')
const [preview, setPreview] = useState<{ spec: Spec; summary: string } | null>(null)
const [editError, setEditError] = useState('')
const [saving, setSaving] = useState(false)
const [runsOpen, setRunsOpen] = useState(true)
// Phase 2: chaining + refinements
const [callAdding, setCallAdding] = useState(false)
const [callPick, setCallPick] = useState('')
const [trial, setTrial] = useState('')
const [trialBusy, setTrialBusy] = useState(false)
const [trialResult, setTrialResult] = useState<{ matched: boolean; detail: string; spec: Spec } | null>(null)
const [trialError, setTrialError] = useState('')
const reload = useCallback(() =>
Promise.all([
api('/api/agent/tasks').then(r => r.json()),
api('/api/agent/groups').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, gr, rn, ch, st]) => {
if (Array.isArray(tk)) setTasks(tk)
if (Array.isArray(gr)) setGroups(gr)
if (Array.isArray(rn)) setRuns(rn)
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])
// Per-task run timeline for the detail view.
useEffect(() => {
if (!initialTask) return
let cancelled = false
api(`/api/agent/runs?taskId=${initialTask}`)
.then(r => r.json())
.then(d => { if (!cancelled) setTaskRuns(Array.isArray(d) ? d : []) })
.catch(() => { /* non-fatal */ })
return () => { cancelled = true }
}, [initialTask, tasks])
const selected = initialTask ? tasks.find(t => t.id === initialTask) ?? null : null
const reportError = async (res: Response, fallback: string): Promise<string> => {
let msg = fallback
try { const data = await res.json(); if (data?.error) msg = data.error } catch { /* non-JSON */ }
if (res.status === 428) setAvailable(false)
return msg
}
// --- composer -------------------------------------------------------------
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 {
toast.error(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
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, prompt: text.trim(), groupId: newGroup || undefined }),
})
if (res.ok) {
toast.success('Automation created')
setProposal(null); setText(''); setNewGroup('')
await reload(); notifyAutomationsChanged()
} else {
toast.error(await reportError(res, 'Could not create the automation'))
}
}
// --- detail actions -------------------------------------------------------
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 toast.error(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 toast.error(await reportError(res, 'Run failed'))
} finally { setRunningId(null) }
}
const removeTask = async (t: Task) => {
if (!confirm(`Delete automation "${t.name}"? Its run history goes with it.`)) return
const res = await api(`/api/agent/tasks/${t.id}`, { method: 'DELETE' })
if (res.ok) {
toast.success('Automation deleted')
await reload(); notifyAutomationsChanged()
router.push('/automations')
} else toast.error(await reportError(res, 'Could not delete the task'))
}
const assignGroup = async (t: Task, groupId: string) => {
const res = await api(`/api/agent/tasks/${t.id}`, {
method: 'PATCH', body: JSON.stringify({ groupId: groupId || null, version: t.version }),
})
if (res.ok) { await reload(); notifyAutomationsChanged() }
else toast.error(await reportError(res, 'Could not move the automation'))
}
// --- editing (compile → confirm → versioned PATCH) ------------------------
const startEdit = (t: Task) => {
setEditing(true); setEditName(t.name); setEditPrompt(t.prompt || ''); setPreview(null); setEditError('')
}
const saveEdit = async (t: Task) => {
setSaving(true); setEditError('')
try {
const promptChanged = editPrompt.trim() !== (t.prompt || '')
if (promptChanged && editPrompt.trim()) {
// Recompile through the same endpoint as creation; show the proposal
// before anything is written.
const res = await api('/api/agent/compile', { method: 'POST', body: JSON.stringify({ text: editPrompt.trim() }) })
if (!res.ok) { setEditError(await reportError(res, 'Could not understand that request')); return }
const data = await res.json()
setPreview({ spec: data.spec, summary: data.summary })
return
}
const res = await api(`/api/agent/tasks/${t.id}`, {
method: 'PATCH', body: JSON.stringify({ name: editName.trim(), version: t.version }),
})
if (!res.ok) { setEditError(await reportError(res, 'Could not save')); return }
setEditing(false); await reload(); notifyAutomationsChanged()
} finally { setSaving(false) }
}
const applyPreview = async (t: Task) => {
if (!preview) return
setSaving(true)
try {
const res = await api(`/api/agent/tasks/${t.id}`, {
method: 'PATCH',
body: JSON.stringify({ name: editName.trim(), prompt: editPrompt.trim(), spec: preview.spec, version: t.version }),
})
if (!res.ok) { setEditError(await reportError(res, 'Could not save')); return }
setEditing(false); setPreview(null); await reload(); notifyAutomationsChanged()
toast.success('Automation updated')
} finally { setSaving(false) }
}
// --- phase 2: chaining ----------------------------------------------------
const patchSpec = async (t: Task, spec: Spec) => {
const res = await api(`/api/agent/tasks/${t.id}`, { method: 'PATCH', body: JSON.stringify({ spec, version: t.version }) })
if (res.ok) { await reload(); notifyAutomationsChanged() }
else toast.error(await reportError(res, 'Could not update the automation'))
return res.ok
}
// Would adding t -> target create a loop? True if target already reaches t.
const wouldLoop = (t: Task, target: string): boolean => {
const graph: Record<string, string[]> = {}
for (const x of tasks) graph[x.id] = x.spec.calls ?? []
const seen = new Set<string>()
const reaches = (n: string): boolean => {
if (n === t.id) return true
if (seen.has(n)) return false
seen.add(n)
return (graph[n] ?? []).some(reaches)
}
return reaches(target)
}
const addCall = async (t: Task) => {
if (!callPick) return
if (wouldLoop(t, callPick)) { toast.error('That would create a loop'); return }
const spec = { ...t.spec, calls: [...(t.spec.calls ?? []), callPick] }
if (await patchSpec(t, spec)) { setCallAdding(false); setCallPick('') }
}
const removeCall = async (t: Task, cid: string) => {
const spec = { ...t.spec, calls: (t.spec.calls ?? []).filter(x => x !== cid) }
await patchSpec(t, spec)
}
// --- phase 2: refinements + dry run ---------------------------------------
const removeRefinement = async (t: Task, idx: number) => {
const refs = t.refinements.filter((_, i) => i !== idx)
const res = await api(`/api/agent/tasks/${t.id}`, { method: 'PATCH', body: JSON.stringify({ refinements: refs, version: t.version }) })
if (res.ok) { await reload(); notifyAutomationsChanged() }
else toast.error(await reportError(res, 'Could not update refinements'))
}
const composePrompt = (t: Task, extra?: string) =>
[t.prompt || t.summary, ...t.refinements, ...(extra ? [extra] : [])].filter(Boolean).join('\n')
const tryIt = async (t: Task) => {
const text = trial.trim()
if (!text) { setTrialError('Describe the change first'); return }
setTrialBusy(true); setTrialError(''); setTrialResult(null)
try {
const cr = await api('/api/agent/compile', { method: 'POST', body: JSON.stringify({ text: composePrompt(t, text) }) })
if (!cr.ok) { setTrialError(await reportError(cr, 'Could not understand that request')); return }
const compiled = await cr.json()
const dr = await api('/api/agent/dry-run', { method: 'POST', body: JSON.stringify({ spec: compiled.spec, name: t.name }) })
if (!dr.ok) { setTrialError(await reportError(dr, 'Could not test the condition')); return }
const result = await dr.json()
setTrialResult({ matched: result.matched, detail: result.detail, spec: compiled.spec })
} catch { setTrialError('Could not reach the AI service') }
finally { setTrialBusy(false) }
}
const addRefinement = async (t: Task) => {
if (!trialResult) return
const res = await api(`/api/agent/tasks/${t.id}`, {
method: 'PATCH',
body: JSON.stringify({ refinements: [...t.refinements, trial.trim()], spec: trialResult.spec, version: t.version }),
})
if (res.ok) {
setTrial(''); setTrialResult(null); await reload(); notifyAutomationsChanged()
toast.success('Refinement added')
} else toast.error(await reportError(res, 'Could not add the refinement'))
}
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>
}
// --- detail view ----------------------------------------------------------
if (initialTask && !selected) {
return (
<div className="space-y-3">
<Button variant="ghost" size="sm" onClick={() => router.push('/automations')}><ArrowLeft className="h-4 w-4 mr-1" /> All automations</Button>
<p className="text-sm text-muted-foreground">That automation no longer exists.</p>
</div>
)
}
if (selected) {
const t = selected
const group = groups.find(g => g.id === t.groupId)
return (
<div className="space-y-4">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Button variant="ghost" size="sm" className="-ml-2" onClick={() => router.push('/automations')}><ArrowLeft className="h-3.5 w-3.5 mr-1" /> All automations</Button>
<span>/</span><span className="flex items-center gap-1"><Folder className="h-3 w-3" /> {group?.name ?? 'Ungrouped'}</span>
{tasks.filter(x => (x.spec.calls ?? []).includes(t.id)).map(x => (
<span key={x.id} className="flex items-center gap-1">· called by
<button className="font-medium hover:underline" onClick={() => router.push(`/automations?task=${x.id}`)}>{x.name}</button>
</span>
))}
</div>
<div className="flex flex-wrap items-center gap-2">
<h1 className="font-display text-xl font-bold tracking-tight">{t.name}</h1>
<Badge variant={t.status === 'active' ? 'default' : 'secondary'}>{t.status}</Badge>
<span className="text-xs text-muted-foreground">{frequencyLabel(t.spec)}</span>
<span className="ml-auto flex items-center gap-1">
<Button size="sm" variant="outline" onClick={() => runNow(t)} disabled={runningId === t.id}>
{runningId === t.id ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Play className="h-3.5 w-3.5" />} Run now
</Button>
<Button size="sm" variant="outline" onClick={() => toggleTask(t, !t.enabled)}>{t.enabled ? 'Pause' : 'Resume'}</Button>
<Button size="sm" variant="ghost" onClick={() => startEdit(t)} aria-label="Edit automation"><Pencil className="h-3.5 w-3.5" /></Button>
<Button size="sm" variant="ghost" onClick={() => removeTask(t)} aria-label="Delete automation"><Trash2 className="h-3.5 w-3.5 text-muted-foreground hover:text-destructive" /></Button>
</span>
</div>
<div className="flex items-center gap-2 text-sm">
<span className="text-xs text-muted-foreground">Group</span>
<Select value={t.groupId ?? 'none'} onValueChange={v => assignGroup(t, v === 'none' ? '' : v)}>
<SelectTrigger className="h-8 w-56"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="none">Ungrouped</SelectItem>
{groups.map(g => <SelectItem key={g.id} value={g.id}>{g.name}</SelectItem>)}
</SelectContent>
</Select>
</div>
{/* Prompt card */}
<div className="rounded-lg border p-4 space-y-3">
<p className="text-xs font-medium text-muted-foreground flex items-center gap-2"><Sparkles className="h-3.5 w-3.5" /> Original prompt</p>
{!editing ? (
<>
<p className="font-serif text-[15px] italic leading-relaxed">{t.prompt || t.summary}</p>
{!t.prompt && <p className="text-xs text-muted-foreground">Created before prompts were stored — add one to enable editing.</p>}
{t.refinements.length > 0 && (
<div className="space-y-1 border-t pt-2">
{t.refinements.map((r, i) => (
<div key={i} className="flex items-center gap-2 text-sm">
<span className="text-muted-foreground">↳</span>
<span className="flex-1">{r}</span>
<span className="rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">refinement {i + 1}</span>
<button onClick={() => removeRefinement(t, i)} aria-label={`Remove refinement ${i + 1}`} className="text-muted-foreground hover:text-destructive">×</button>
</div>
))}
</div>
)}
<div className="border-t pt-2 space-y-2">
<p className="text-xs font-medium text-muted-foreground flex items-center gap-1"><Sparkles className="h-3 w-3" /> Extend this automation</p>
<div className="flex gap-2">
<Input value={trial} onChange={e => { setTrial(e.target.value); setTrialError('') }} placeholder="Also require a checked bag included" className="flex-1" />
<Button size="sm" variant="outline" onClick={() => tryIt(t)} loading={trialBusy}>Try it</Button>
</div>
{trialError && <p className="text-xs text-destructive">{trialError}</p>}
{trialResult && (
<div className="rounded-md bg-muted/40 p-2 space-y-2">
<p className="text-xs text-muted-foreground">Test run with “{trial}”</p>
<p className="text-sm">Condition understood. Result would be <strong>{trialResult.matched ? 'true' : 'false'}</strong> right now{trialResult.matched ? '' : ', so nothing would be called'}.</p>
<p className="text-xs text-muted-foreground">{trialResult.detail}</p>
<div className="flex gap-2">
<Button size="sm" onClick={() => addRefinement(t)}>Add to automation</Button>
<Button size="sm" variant="ghost" onClick={() => setTrialResult(null)}>Discard</Button>
</div>
</div>
)}
</div>
<Button size="sm" variant="outline" onClick={() => startEdit(t)}><Pencil className="h-3.5 w-3.5 mr-1" /> Edit</Button>
</>
) : (
<div className="space-y-3">
<div>
<label className="text-xs font-medium">Name</label>
<Input value={editName} onChange={e => setEditName(e.target.value)} maxLength={120} />
</div>
<div>
<label className="text-xs font-medium">Prompt</label>
<Textarea value={editPrompt} onChange={e => setEditPrompt(e.target.value)} rows={3} placeholder="Describe what should happen…" />
<p className="mt-1 text-xs text-muted-foreground">Changing the prompt recompiles it — you review the result before it applies.</p>
</div>
{editError && <p className="text-xs text-destructive">{editError}</p>}
{preview && (
<div className="rounded-md border bg-muted/30 p-3 space-y-2">
<p className="text-xs font-medium text-muted-foreground">Recompiled proposal</p>
<p className="text-sm">{preview.summary}</p>
<p className="text-xs text-muted-foreground">{frequencyLabel(preview.spec)} · {preview.spec.action.type}</p>
<div className="flex gap-2">
<Button size="sm" onClick={() => applyPreview(t)} loading={saving}>Apply changes</Button>
<Button size="sm" variant="ghost" onClick={() => setPreview(null)}>Back</Button>
</div>
</div>
)}
{!preview && (
<div className="flex gap-2">
<Button size="sm" onClick={() => saveEdit(t)} loading={saving}>{editPrompt.trim() !== (t.prompt || '') ? 'Recompile' : 'Save'}</Button>
<Button size="sm" variant="ghost" onClick={() => { setEditing(false); setPreview(null); setEditError('') }}>Cancel</Button>
</div>
)}
</div>
)}
</div>
{/* If true, call */}
<div className="rounded-lg border p-4 space-y-2">
<p className="text-xs font-medium text-muted-foreground">If true, call</p>
{(t.spec.calls ?? []).length === 0 && !callAdding && (
<p className="text-xs text-muted-foreground">When this automation's condition is true, it can call other automations in order.</p>
)}
{(t.spec.calls ?? []).map(cid => {
const callee = tasks.find(x => x.id === cid)
return (
<div key={cid} className="flex items-center gap-2 rounded-md border px-2 py-1.5 text-sm">
<span className="rounded bg-muted px-1.5 py-0.5 font-mono text-[10px]">IF TRUE</span>
<span className="text-muted-foreground">→</span>
<span className="rounded bg-muted px-1.5 py-0.5 font-mono text-[10px]">CALL</span>
<button className="flex-1 truncate text-left font-medium hover:underline" onClick={() => router.push(`/automations?task=${cid}`)}>{callee?.name ?? 'Unknown automation'}</button>
<button onClick={() => removeCall(t, cid)} aria-label="Remove call" className="text-muted-foreground hover:text-destructive">×</button>
</div>
)
})}
{callAdding ? (
<div className="space-y-2">
<div className="flex gap-2">
<Select value={callPick} onValueChange={setCallPick}>
<SelectTrigger className="flex-1"><SelectValue placeholder="Choose an automation" /></SelectTrigger>
<SelectContent>
{tasks.filter(x => x.id !== t.id && !(t.spec.calls ?? []).includes(x.id)).map(x => (
<SelectItem key={x.id} value={x.id} disabled={wouldLoop(t, x.id)}>{x.name}{wouldLoop(t, x.id) ? ' (would loop)' : ''}</SelectItem>
))}
</SelectContent>
</Select>
<Button size="sm" onClick={() => addCall(t)} disabled={!callPick}>Add</Button>
<Button size="sm" variant="ghost" onClick={() => { setCallAdding(false); setCallPick('') }}>Cancel</Button>
</div>
</div>
) : (
<Button size="sm" variant="outline" onClick={() => setCallAdding(true)}>+ Call an automation</Button>
)}
</div>
{/* Run timeline */}
<div className="rounded-lg border p-4">
<button className="flex w-full items-center gap-2 text-xs font-medium text-muted-foreground" onClick={() => setRunsOpen(v => !v)}>
{runsOpen ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
Recent runs ({taskRuns.length})
{t.errorCount > 0 && <span className="text-destructive">· {t.errorCount} errors</span>}
<span className="ml-auto">{runsOpen ? 'Hide' : 'Show'}</span>
</button>
{runsOpen && (
taskRuns.length === 0
? <p className="mt-2 text-sm text-muted-foreground">Hasn't run yet.</p>
: <div className="mt-2 space-y-1">
{taskRuns.map(rn => {
const m = outcomeMeta(rn.outcome)
return (
<div key={rn.id} className="flex items-center gap-2 text-sm">
<span className={cn('rounded px-1.5 py-0.5 text-[11px] font-medium', m.cls)}>{m.label}</span>
<span className="flex-1 truncate text-muted-foreground">{rn.detail ?? ''}</span>
<span className="shrink-0 text-xs text-muted-foreground"><SafeTime date={rn.createdAt} localize /></span>
</div>
)
})}
</div>
)}
</div>
</div>
)
}
// --- overview -------------------------------------------------------------
const grouped = groups.map(g => ({ group: g, members: tasks.filter(t => t.groupId === g.id) })).filter(x => x.members.length > 0)
const ungrouped = tasks.filter(t => !t.groupId)
const taskRow = (t: Task) => (
<button key={t.id} onClick={() => router.push(`/automations?task=${t.id}`)} className="flex w-full items-center gap-3 rounded-md border p-3 text-left hover:bg-accent/40">
<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>
</div>
<span className="text-xs text-muted-foreground">{frequencyLabel(t.spec)}</span>
<span className="text-xs text-muted-foreground">{t.runCount} runs{t.errorCount > 0 && <span className="text-destructive"> · {t.errorCount} errors</span>}</span>
<Badge variant={t.status === 'active' ? 'default' : 'secondary'}>{t.status}</Badge>
</button>
)
return (
<div className="space-y-6">
<div className="flex items-start justify-between gap-3">
<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>
</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>
{!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. 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 => setText(e.target.value)} rows={3}
/>
<div className="flex flex-wrap 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">{frequencyLabel(proposal.spec)}</p>
</div>
{proposal.spec.action.type === 'notify' && (
<Select value={proposal.spec.action.channelId || ''} onValueChange={v => 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 => setProposal(p => p ? { ...p, spec: { ...p.spec, action: { ...p.spec.action, to: e.target.value } } } : p)} />
)}
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">Group</span>
<Select value={newGroup || 'none'} onValueChange={v => setNewGroup(v === 'none' ? '' : v)}>
<SelectTrigger className="h-8 w-48"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="none">Ungrouped</SelectItem>
{groups.map(g => <SelectItem key={g.id} value={g.id}>{g.name}</SelectItem>)}
</SelectContent>
</Select>
</div>
{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>
{/* Grouped list */}
<div className="space-y-4">
{tasks.length === 0 && <p className="text-sm text-muted-foreground">No automations yet.</p>}
{grouped.map(({ group, members }) => (
<div key={group.id} className="space-y-2">
<p className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground"><Folder className="h-3.5 w-3.5" /> {group.name} <span className="font-normal">({members.length})</span></p>
<div className="space-y-2">{members.map(taskRow)}</div>
</div>
))}
{ungrouped.length > 0 && (
<div className="space-y-2">
{grouped.length > 0 && <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Ungrouped</p>}
<div className="space-y-2">{ungrouped.map(taskRow)}</div>
</div>
)}
</div>
{/* Global runs */}
<div className="rounded-lg border p-4 space-y-2">
<h3 className="font-medium">Recent runs</h3>
{runs.length === 0 && <p className="text-sm text-muted-foreground">Nothing has run yet.</p>}
{runs.slice(0, 10).map(rn => {
const m = outcomeMeta(rn.outcome)
return (
<div key={rn.id} className="flex items-center gap-2 text-sm">
<span className={cn('rounded px-1.5 py-0.5 text-[11px] font-medium', m.cls)}>{m.label}</span>
<button className="shrink-0 font-medium hover:underline" onClick={() => router.push(`/automations?task=${rn.taskId}`)}>{rn.taskName ?? 'Automation'}</button>
<span className="flex-1 truncate text-muted-foreground">{rn.detail ?? ''}</span>
<span className="shrink-0 text-xs text-muted-foreground"><SafeTime date={rn.createdAt} localize /></span>
</div>
)
})}
</div>
</div>
)
}