Automations workspace phase 1: sidebar groups, detail view, recompile-to-edit, named runs

Promotes Automations to a top-level sidebar group (below Bookmarks) with
user-defined AgentGroup folders (migration 025, FK SET NULL on delete).
The /automations page becomes master-detail: overview (composer + grouped
list + named global runs) and per-task detail (original prompt, group
assignment, run-now/pause/delete, per-task run timeline with true/false/
error pills). Editing recompiles through /api/agent/compile and confirms
the proposal before a versioned PATCH applies spec+prompt — the model
never writes. Tasks store prompt+groupId; projections add runCount/
errorCount; runs carry taskName. The engine is untouched: groups/prompt
are metadata, the validated spec remains the only thing it executes.
Chaining, refinements and dry-run stay phase 2.

Verified: full DB integration suite under -race, db-converge + migration
atomicity, web lint/SSR/build, and a rewritten browser regression covering
the sidebar folder, detail prompt, per-task runs, recompile-to-edit and
named global runs.
This commit is contained in:
Andrew S Erwin
2026-11-25 14:16:45 -06:00
parent e32eed93ea
commit 060a8115ec
10 changed files with 719 additions and 192 deletions
+316 -158
View File
@@ -1,71 +1,95 @@
'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.
// 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 { 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 { 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 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
id: string; name: string; spec: Spec; summary: string; prompt: string; groupId: string | null
runCount: number; errorCount: number; enabled: boolean; status: string
fireCount: number; lastFiredAt: string | null; version: number
}
type Run = { id: string; taskId: string; outcome: string; detail: string | null; createdAt: string }
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.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 state
// 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)
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, rn, ch, st]) => {
.then(([tk, gr, rn, ch, st]) => {
if (Array.isArray(tk)) setTasks(tk)
if (Array.isArray(rn)) setRuns(rn.slice(0, 10))
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')
})
@@ -74,23 +98,27 @@ export function AutomationsClient({ initialTask }: { initialTask: string | null
useEffect(() => { reload() }, [reload])
// Sidebar deep-link: bring the targeted task card into view once loaded.
// Per-task run timeline for the detail view.
useEffect(() => {
if (!initialTask || loading) return
document.getElementById(`automation-${initialTask}`)?.scrollIntoView({ block: 'center', behavior: 'smooth' })
}, [initialTask, loading, tasks.length])
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 reportError = async (res: Response, fallback: string): Promise<string | null> => {
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 body */ }
try { const data = await res.json(); if (data?.error) msg = data.error } catch { /* non-JSON */ }
if (res.status === 428) setAvailable(false)
toast.error(msg)
return msg
}
// --- composer -------------------------------------------------------------
const compile = async () => {
if (!text.trim()) { toast.error('Describe what should happen first'); return }
setCompiling(true)
@@ -102,44 +130,35 @@ export function AutomationsClient({ initialTask }: { initialTask: string | null
setProposal({ name: data.name, spec: data.spec, summary: data.summary })
setAvailable(true)
} else {
await reportError(res, 'Could not understand that request')
toast.error(await reportError(res, 'Could not understand that request'))
}
} catch {
toast.error('Could not reach the AI service')
} finally {
setCompiling(false)
}
} 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
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 }),
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('')
await reload()
notifyAutomationsChanged()
setProposal(null); setText(''); setNewGroup('')
await reload(); notifyAutomationsChanged()
} else {
await reportError(res, 'Could not create the automation')
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 }),
})
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')
else toast.error(await reportError(res, 'Could not update the task'))
}
const runNow = async (t: Task) => {
@@ -149,108 +168,263 @@ export function AutomationsClient({ initialTask }: { initialTask: string | null
if (res.ok) {
const data = await res.json()
toast.info(`Run finished: ${data.outcome}`)
await reload()
notifyAutomationsChanged()
} else {
await reportError(res, 'Run failed')
}
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() }
else await reportError(res, 'Could not delete the task')
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) }
}
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>
</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>}
<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>
{/* 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>
<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 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>
<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.
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: React.ChangeEvent<HTMLTextAreaElement>) => setText(e.target.value)}
rows={3}
value={text} onChange={e => 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 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">
Checks every {proposal.spec.pollMinutes} min
{proposal.spec.once ? ' · one-shot (completes after firing)' : ' · ongoing'}
</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: string) => setProposal(p => p ? {
...p,
spec: { ...p.spec, action: { ...p.spec.action, channelId: v } },
} : p)}
>
<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>
))}
{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>
<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>
@@ -259,54 +433,38 @@ export function AutomationsClient({ initialTask }: { initialTask: string | null
)}
</div>
{/* Tasks */}
<div className="rounded-lg border p-4 space-y-3">
<h3 className="font-medium">Your automations</h3>
{/* Grouped list */}
<div className="space-y-4">
{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>
{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>
{/* Runs */}
<div className="rounded-lg border p-4 space-y-3">
{/* 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.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>
))}
{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>
)
+2 -1
View File
@@ -1,6 +1,7 @@
import { AutomationsClient } from './client'
// Sidebar deep-link: /automations?task=<id> scrolls to that automation.
// Sidebar deep-link: /automations?task=<id> opens that automation's detail;
// the bare route is the overview with the composer.
export default async function AutomationsPage({ searchParams }: { searchParams: Promise<{ task?: string }> }) {
const { task } = await searchParams
return <AutomationsClient initialTask={task ?? null} />
+68 -15
View File
@@ -13,7 +13,7 @@ import { cn } from '@/lib/utils'
import { BrandIcon } from '@/components/brand-icon'
import {
Calendar, Tags, Users, Kanban, Link2, Settings, ChevronLeft, ChevronRight, ChevronDown,
FileText, Pin, PinOff, Plus, Shield, Search, MoreHorizontal, Trash2, Pencil, Layers, GripVertical, X, Sparkles,
FileText, Pin, PinOff, Plus, Shield, Search, MoreHorizontal, Trash2, Pencil, Layers, GripVertical, X, Sparkles, Folder,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
@@ -22,7 +22,7 @@ import {
} from '@/components/ui/dropdown-menu'
import { toast } from 'sonner'
import { PAGES_CHANGED, nextUntitledTitle, notifyPagesChanged, type PageSummary } from '@/lib/pages'
import { AUTOMATIONS_CHANGED } from '@/lib/automations'
import { AUTOMATIONS_CHANGED, notifyAutomationsChanged } from '@/lib/automations'
import { reorderPages } from '@/lib/page-order'
// Dragging a page from "Untagged Pages" onto a tag assigns that tag. A custom
@@ -33,7 +33,8 @@ type TagRow = { id: string; name: string; color: string }
type ColumnRow = { id: string; label: string; color?: string }
type CollectionRow = { id: string; name: string; icon?: string | null }
type ContactRow = { id: string; displayName: string }
type AutomationRow = { id: string; name: string; status: string; enabled: boolean }
type AutomationRow = { id: string; name: string; status: string; enabled: boolean; groupId?: string | null }
type AutomationGroup = { id: string; name: string }
// Status dot for the Automations dropdown: enabled tasks show their engine
// status; a disabled task is muted regardless (it will not run).
@@ -270,6 +271,9 @@ function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathna
const [collections, setCollections] = useState<CollectionRow[]>([])
const [contacts, setContacts] = useState<ContactRow[]>([])
const [automations, setAutomations] = useState<AutomationRow[]>([])
const [automationGroups, setAutomationGroups] = useState<AutomationGroup[]>([])
const [openGroups, setOpenGroups] = useState<Record<string, boolean>>({})
const [newGroupName, setNewGroupName] = useState<string | null>(null)
const [pagesExpanded, setPagesExpanded] = usePersistentState('superbrain:sidebar:pages', true)
const [bookmarksExpanded, setBookmarksExpanded] = usePersistentState('superbrain:sidebar:bookmarks', true)
const [allPagesExpanded, setAllPagesExpanded] = usePersistentState('superbrain:sidebar:allpages', true)
@@ -310,6 +314,7 @@ function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathna
get('/api/collections').then((d) => setCollections(Array.isArray(d) ? d : []))
get('/api/contacts').then((d) => setContacts(Array.isArray(d) ? d : []))
get('/api/agent/tasks').then((d) => setAutomations(Array.isArray(d) ? d : []))
get('/api/agent/groups').then((d) => setAutomationGroups(Array.isArray(d) ? d : []))
}, [])
// The automations workspace announces creates/toggles/deletes so the
@@ -320,11 +325,29 @@ function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathna
.then((r) => (r.ok ? r.json() : []))
.then((d) => setAutomations(Array.isArray(d) ? d : []))
.catch(() => { /* non-fatal */ })
fetch('/api/agent/groups')
.then((r) => (r.ok ? r.json() : []))
.then((d) => setAutomationGroups(Array.isArray(d) ? d : []))
.catch(() => { /* non-fatal */ })
}
window.addEventListener(AUTOMATIONS_CHANGED, reloadAutomations)
return () => window.removeEventListener(AUTOMATIONS_CHANGED, reloadAutomations)
}, [])
const createGroup = async () => {
const name = (newGroupName ?? '').trim()
setNewGroupName(null)
if (!name) return
try {
const res = await fetch('/api/agent/groups', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name }),
})
if (!res.ok) { toast.error('Could not create group'); return }
notifyAutomationsChanged()
} catch { toast.error('Could not create group') }
}
const createPage = async (parentId?: string | null) => {
const title = nextUntitledTitle(pages.map((p) => p.title))
try {
@@ -704,18 +727,48 @@ function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathna
</div>
<div className="pt-2">
<NavSection icon={Sparkles} label="Automations" href="/automations" expanded={automationsExpanded} onToggle={() => setAutomationsExpanded(!automationsExpanded)} count={automations.length}>
{automations.map((t) => (
<ChildLink
key={t.id}
href={`/automations?task=${t.id}`}
label={t.name}
dot={automationDot(t)}
active={pathname === '/automations' && searchParams.get('task') === t.id}
/>
))}
{automations.length === 0 && <p className="px-2 py-1 text-xs text-muted-foreground/70">No automations yet</p>}
</NavSection>
<GroupHeader label="Automations" expanded={automationsExpanded} onToggle={() => setAutomationsExpanded(!automationsExpanded)} action={{ label: 'New automation', onClick: () => router.push('/automations') }} />
{automationsExpanded && (
<>
{automationGroups.map((g) => {
const members = automations.filter((t) => t.groupId === g.id)
const isOpen = openGroups[g.id] !== false
return (
<NavSection key={g.id} icon={Folder} label={g.name} expanded={isOpen} onToggle={() => setOpenGroups((s) => ({ ...s, [g.id]: !isOpen }))} count={members.length}>
{members.map((t) => (
<ChildLink key={t.id} href={`/automations?task=${t.id}`} label={t.name} dot={automationDot(t)} active={pathname === '/automations' && searchParams.get('task') === t.id} />
))}
{members.length === 0 && <p className="px-2 py-1 text-xs text-muted-foreground/70">Empty group</p>}
</NavSection>
)
})}
{automations.filter((t) => !t.groupId).map((t) => (
<ChildLink key={t.id} href={`/automations?task=${t.id}`} label={t.name} dot={automationDot(t)} active={pathname === '/automations' && searchParams.get('task') === t.id} />
))}
{automations.length === 0 && <p className="px-2 py-1 text-xs text-muted-foreground/70">No automations yet</p>}
{newGroupName !== null ? (
<div className="px-1 py-0.5">
<Input
autoFocus
value={newGroupName}
onChange={(e) => setNewGroupName(e.target.value)}
onBlur={createGroup}
onKeyDown={(e) => {
if (e.key === 'Enter') { e.preventDefault(); (e.target as HTMLInputElement).blur() }
if (e.key === 'Escape') setNewGroupName(null)
}}
className="h-7 text-sm"
aria-label="New group name"
placeholder="Group name…"
/>
</div>
) : (
<button onClick={() => setNewGroupName('')} className="flex w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground">
<Plus className="h-3.5 w-3.5" /> New group
</button>
)}
</>
)}
</div>
<div className="pt-2">