'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 } type Task = { 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 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 { 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([]) const [groups, setGroups] = useState([]) const [runs, setRuns] = useState([]) const [taskRuns, setTaskRuns] = useState([]) const [channels, setChannels] = useState([]) 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(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, 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 => { 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) } } if (loading) { return
Loading automations…
} // --- detail view ---------------------------------------------------------- if (initialTask && !selected) { return (

That automation no longer exists.

) } if (selected) { const t = selected const group = groups.find(g => g.id === t.groupId) return (
/ {group?.name ?? 'Ungrouped'}

{t.name}

{t.status} {frequencyLabel(t.spec)}
Group
{/* Prompt card */}

Original prompt

{!editing ? ( <>

{t.prompt || t.summary}

{!t.prompt &&

Created before prompts were stored — add one to enable editing.

} ) : (
setEditName(e.target.value)} maxLength={120} />