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.
472 lines
24 KiB
TypeScript
472 lines
24 KiB
TypeScript
'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<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
|
|
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, 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) }
|
|
}
|
|
|
|
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 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>
|
|
)
|
|
}
|