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.
This commit is contained in:
@@ -15,6 +15,7 @@ import { Sparkles, Loader2, Send, FilePlus2, Wand2, Check } from 'lucide-react'
|
||||
import ReactMarkdown from 'react-markdown'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import { toast } from 'sonner'
|
||||
import { notifyAutomationsChanged } from '@/lib/automations'
|
||||
|
||||
type Spec = {
|
||||
condition: { type: string; url?: string; question?: string; op?: string; threshold?: number; text?: string; keyword?: string }
|
||||
@@ -107,7 +108,8 @@ export function Assistant() {
|
||||
})
|
||||
const data = await res.json().catch(() => null)
|
||||
if (res.ok) {
|
||||
toast.success('Automation created — see Settings → Automations')
|
||||
toast.success('Automation created — see Automations in the sidebar')
|
||||
notifyAutomationsChanged()
|
||||
setMessages(messages.map((m, i) => i === msgIndex ? { ...m, proposalState: 'created' as const } : m))
|
||||
} else {
|
||||
toast.error(data?.error ?? 'Could not create the automation')
|
||||
@@ -183,7 +185,7 @@ export function Assistant() {
|
||||
)}
|
||||
{unavailable && (
|
||||
<p className="text-xs text-destructive">
|
||||
No AI available — add your provider and key in Settings → AI (Automations tab shows the same hint).
|
||||
No AI available — add your provider and key in Settings → AI (the Automations page shows the same hint).
|
||||
</p>
|
||||
)}
|
||||
{messages.map((m, i) => (
|
||||
|
||||
@@ -1,285 +0,0 @@
|
||||
'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>
|
||||
)
|
||||
}
|
||||
@@ -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,
|
||||
FileText, Pin, PinOff, Plus, Shield, Search, MoreHorizontal, Trash2, Pencil, Layers, GripVertical, X, Sparkles,
|
||||
} from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
@@ -22,6 +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 { reorderPages } from '@/lib/page-order'
|
||||
|
||||
// Dragging a page from "Untagged Pages" onto a tag assigns that tag. A custom
|
||||
@@ -32,6 +33,19 @@ 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 }
|
||||
|
||||
// Status dot for the Automations dropdown: enabled tasks show their engine
|
||||
// status; a disabled task is muted regardless (it will not run).
|
||||
function automationDot(t: AutomationRow): string {
|
||||
if (!t.enabled) return '#9ca3af'
|
||||
switch (t.status) {
|
||||
case 'active': return '#10b981'
|
||||
case 'done': return '#9ca3af'
|
||||
case 'paused': return '#f59e0b'
|
||||
default: return '#ef4444'
|
||||
}
|
||||
}
|
||||
|
||||
// Section collapse state persists per browser. useSyncExternalStore keeps it
|
||||
// hydration-safe (server snapshot uses the default; the client snapshot reads
|
||||
@@ -255,6 +269,7 @@ function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathna
|
||||
const [columns, setColumns] = useState<ColumnRow[]>([])
|
||||
const [collections, setCollections] = useState<CollectionRow[]>([])
|
||||
const [contacts, setContacts] = useState<ContactRow[]>([])
|
||||
const [automations, setAutomations] = useState<AutomationRow[]>([])
|
||||
const [pagesExpanded, setPagesExpanded] = usePersistentState('superbrain:sidebar:pages', true)
|
||||
const [bookmarksExpanded, setBookmarksExpanded] = usePersistentState('superbrain:sidebar:bookmarks', true)
|
||||
const [allPagesExpanded, setAllPagesExpanded] = usePersistentState('superbrain:sidebar:allpages', true)
|
||||
@@ -264,6 +279,7 @@ function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathna
|
||||
const [kanbanExpanded, setKanbanExpanded] = usePersistentState('superbrain:sidebar:kanban', false)
|
||||
const [collectionsExpanded, setCollectionsExpanded] = usePersistentState('superbrain:sidebar:collections', false)
|
||||
const [contactsExpanded, setContactsExpanded] = usePersistentState('superbrain:sidebar:contacts', false)
|
||||
const [automationsExpanded, setAutomationsExpanded] = usePersistentState('superbrain:sidebar:automations', false)
|
||||
const [renamingId, setRenamingId] = useState<string | null>(null)
|
||||
const [renameValue, setRenameValue] = useState('')
|
||||
const [pageDrop, setPageDrop] = useState<{ id: string; after: boolean } | null>(null)
|
||||
@@ -293,6 +309,20 @@ function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathna
|
||||
get('/api/kanban/columns').then((d) => setColumns(Array.isArray(d) ? d : []))
|
||||
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 : []))
|
||||
}, [])
|
||||
|
||||
// The automations workspace announces creates/toggles/deletes so the
|
||||
// dropdown stays live without a navigation (the pages-changed pattern).
|
||||
useEffect(() => {
|
||||
const reloadAutomations = () => {
|
||||
fetch('/api/agent/tasks')
|
||||
.then((r) => (r.ok ? r.json() : []))
|
||||
.then((d) => setAutomations(Array.isArray(d) ? d : []))
|
||||
.catch(() => { /* non-fatal */ })
|
||||
}
|
||||
window.addEventListener(AUTOMATIONS_CHANGED, reloadAutomations)
|
||||
return () => window.removeEventListener(AUTOMATIONS_CHANGED, reloadAutomations)
|
||||
}, [])
|
||||
|
||||
const createPage = async (parentId?: string | null) => {
|
||||
@@ -434,6 +464,7 @@ function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathna
|
||||
{ href: '/kanban', icon: Kanban, label: 'Kanban' },
|
||||
{ href: '/collections', icon: Layers, label: 'Collections' },
|
||||
{ href: '/contacts', icon: Users, label: 'Contacts' },
|
||||
{ href: '/automations', icon: Sparkles, label: 'Automations' },
|
||||
{ href: '/trash', icon: Trash2, label: 'Trash' },
|
||||
...(isAdmin ? [{ href: '/admin', icon: Shield, label: 'Admin' }] : []),
|
||||
]
|
||||
@@ -672,6 +703,21 @@ 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>
|
||||
</div>
|
||||
|
||||
<div className="pt-2">
|
||||
<NavLink href="/trash" icon={Trash2} label="Trash" active={pathname === '/trash'} />
|
||||
{isAdmin && <NavLink href="/admin" icon={Shield} label="Admin" active={pathname === '/admin'} />}
|
||||
|
||||
Reference in New Issue
Block a user