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.
281 lines
13 KiB
TypeScript
281 lines
13 KiB
TypeScript
'use client'
|
|
|
|
// The Superbrain assistant: an ephemeral chat drawer (conversation lives in
|
|
// component state — "Save to page" is the persistence path) that doubles as
|
|
// the agent front-end: when the server returns an automation proposal, it
|
|
// renders a confirm-before-create card wired to the regular tasks endpoint.
|
|
// The server owns all trust decisions; this UI never constructs specs.
|
|
|
|
import { useRef, useState } from 'react'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Textarea } from '@/components/ui/textarea'
|
|
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet'
|
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
|
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 }
|
|
action: { type: string; channelId?: string; to?: string; title?: string; body?: string; url?: string }
|
|
pollMinutes: number
|
|
once: boolean
|
|
}
|
|
type Proposal = { name: string; spec: Spec; summary: string }
|
|
type ChatMessage = { role: 'user' | 'assistant'; content: string; proposal?: Proposal; proposalState?: 'pending' | 'created' }
|
|
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 Assistant() {
|
|
const [open, setOpen] = useState(false)
|
|
const [messages, setMessages] = useState<ChatMessage[]>([])
|
|
const [input, setInput] = useState('')
|
|
const [busy, setBusy] = useState(false)
|
|
const [unavailable, setUnavailable] = useState(false)
|
|
const [channels, setChannels] = useState<ChannelOption[] | null>(null)
|
|
const scrollRef = useRef<HTMLDivElement>(null)
|
|
|
|
const scrollToEnd = () => {
|
|
// Layout effect would warn; a microtask-deferred scroll is enough here.
|
|
Promise.resolve().then(() => {
|
|
scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight })
|
|
})
|
|
}
|
|
|
|
const send = async () => {
|
|
const text = input.trim()
|
|
if (!text || busy) return
|
|
const next: ChatMessage[] = [...messages, { role: 'user', content: text }]
|
|
setMessages(next)
|
|
setInput('')
|
|
setBusy(true)
|
|
scrollToEnd()
|
|
try {
|
|
const res = await api('/api/ai/chat', {
|
|
method: 'POST',
|
|
body: JSON.stringify({
|
|
messages: next.slice(-20).map(m => ({ role: m.role, content: m.content })),
|
|
}),
|
|
})
|
|
const data = await res.json().catch(() => null)
|
|
if (res.ok && data) {
|
|
setUnavailable(false)
|
|
setMessages([...next, {
|
|
role: 'assistant',
|
|
content: data.reply ?? '',
|
|
proposal: data.proposal ?? undefined,
|
|
proposalState: data.proposal ? 'pending' : undefined,
|
|
}])
|
|
if (data.proposal) loadChannels()
|
|
} else if (res.status === 428) {
|
|
setUnavailable(true)
|
|
toast.error(data?.error ?? 'AI is not configured — add your key in Settings → AI.')
|
|
} else {
|
|
toast.error(data?.error ?? 'The assistant could not answer.')
|
|
}
|
|
} catch {
|
|
toast.error('The assistant could not be reached.')
|
|
} finally {
|
|
setBusy(false)
|
|
scrollToEnd()
|
|
}
|
|
}
|
|
|
|
const loadChannels = () => {
|
|
if (channels) return
|
|
api('/api/notifications/channels')
|
|
.then(r => r.json())
|
|
.then(ch => { if (Array.isArray(ch)) setChannels(ch.filter((c: ChannelOption) => c.enabled)) })
|
|
.catch(() => { /* the card falls back to a hint */ })
|
|
}
|
|
|
|
const createAutomation = async (msgIndex: number) => {
|
|
const msg = messages[msgIndex]
|
|
if (!msg?.proposal) return
|
|
const spec = msg.proposal.spec
|
|
if (spec.action.type === 'notify' && !spec.action.channelId) {
|
|
toast.error('Pick a notification channel first')
|
|
return
|
|
}
|
|
const res = await api('/api/agent/tasks', {
|
|
method: 'POST',
|
|
body: JSON.stringify({ name: msg.proposal.name, spec }),
|
|
})
|
|
const data = await res.json().catch(() => null)
|
|
if (res.ok) {
|
|
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')
|
|
}
|
|
}
|
|
|
|
const setProposalChannel = (msgIndex: number, channelId: string) => {
|
|
setMessages(messages.map((m, i) => {
|
|
if (i !== msgIndex || !m.proposal) return m
|
|
return { ...m, proposal: { ...m.proposal, spec: { ...m.proposal.spec, action: { ...m.proposal.spec.action, channelId } } } }
|
|
}))
|
|
}
|
|
|
|
const setProposalTo = (msgIndex: number, to: string) => {
|
|
setMessages(messages.map((m, i) => {
|
|
if (i !== msgIndex || !m.proposal) return m
|
|
return { ...m, proposal: { ...m.proposal, spec: { ...m.proposal.spec, action: { ...m.proposal.spec.action, to } } } }
|
|
}))
|
|
}
|
|
|
|
const saveToPage = async () => {
|
|
if (messages.length === 0) { toast.error('Nothing to save yet'); return }
|
|
const day = new Date().toISOString().slice(0, 10)
|
|
const body = messages
|
|
.map(m => `**${m.role === 'user' ? 'You' : 'Superbrain'}:**\n\n${m.content}`)
|
|
.join('\n\n---\n\n')
|
|
const res = await api('/api/pages', {
|
|
method: 'POST',
|
|
body: JSON.stringify({ title: `Assistant chat — ${day}`, content: body }),
|
|
})
|
|
if (res.ok) toast.success('Saved to Pages')
|
|
else {
|
|
const data = await res.json().catch(() => null)
|
|
toast.error(data?.error ?? 'Could not save the page')
|
|
}
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<button
|
|
onClick={() => setOpen(true)}
|
|
className="fixed bottom-5 right-5 z-40 flex h-12 w-12 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg hover:opacity-90 transition-opacity"
|
|
aria-label="Ask Superbrain"
|
|
title="Ask Superbrain"
|
|
>
|
|
<Sparkles className="h-5 w-5" />
|
|
</button>
|
|
|
|
<Sheet open={open} onOpenChange={setOpen}>
|
|
<SheetContent side="right" className="w-full sm:max-w-md flex flex-col p-0">
|
|
<SheetHeader className="border-b px-4 py-3">
|
|
<SheetTitle className="flex items-center gap-2 text-base">
|
|
<Sparkles className="h-4 w-4" /> Ask Superbrain
|
|
<span className="ml-auto">
|
|
<Button size="sm" variant="ghost" onClick={saveToPage} className="gap-1.5 text-xs font-normal" aria-label="Save conversation to a page">
|
|
<FilePlus2 className="h-3.5 w-3.5" /> Save to page
|
|
</Button>
|
|
</span>
|
|
</SheetTitle>
|
|
</SheetHeader>
|
|
|
|
<div ref={scrollRef} className="flex-1 overflow-y-auto px-4 py-3 space-y-4">
|
|
{messages.length === 0 && (
|
|
<div className="text-sm text-muted-foreground space-y-2 pt-6">
|
|
<p>Ask anything, or describe an automation:</p>
|
|
<ul className="list-disc pl-5 space-y-1 text-xs">
|
|
<li>“when the round trip on https://… drops below $400, email david@example.com”</li>
|
|
<li>“tell me when my inbox gets an invoice”</li>
|
|
<li>“summarize this text for me: …”</li>
|
|
</ul>
|
|
<p className="text-xs">Proposals are reviewed by you before anything is created. Conversations are not stored — use <em>Save to page</em> to keep one.</p>
|
|
</div>
|
|
)}
|
|
{unavailable && (
|
|
<p className="text-xs text-destructive">
|
|
No AI available — add your provider and key in Settings → AI (the Automations page shows the same hint).
|
|
</p>
|
|
)}
|
|
{messages.map((m, i) => (
|
|
<div key={i} className={m.role === 'user' ? 'flex justify-end' : 'flex justify-start'}>
|
|
<div className={m.role === 'user'
|
|
? 'max-w-[85%] rounded-lg bg-primary text-primary-foreground px-3 py-2 text-sm whitespace-pre-wrap'
|
|
: 'max-w-[92%] space-y-2'}>
|
|
{m.role === 'assistant' ? (
|
|
<div className="rounded-lg bg-muted/60 px-3 py-2 text-sm">
|
|
<div className="prose prose-sm dark:prose-invert max-w-none">
|
|
<ReactMarkdown remarkPlugins={[remarkGfm]}>{m.content}</ReactMarkdown>
|
|
</div>
|
|
</div>
|
|
) : m.content}
|
|
{m.proposal && (
|
|
<div className="rounded-lg border bg-background p-3 space-y-2">
|
|
<p className="text-xs font-medium flex items-center gap-1.5"><Wand2 className="h-3.5 w-3.5" /> Automation proposal</p>
|
|
<p className="text-sm font-medium">{m.proposal.name}</p>
|
|
<p className="text-xs text-muted-foreground">{m.proposal.summary}</p>
|
|
<p className="text-xs text-muted-foreground">
|
|
every {m.proposal.spec.pollMinutes} min{m.proposal.spec.once ? ' · one-shot' : ' · ongoing'}
|
|
</p>
|
|
{m.proposalState === 'created' ? (
|
|
<p className="text-xs text-primary flex items-center gap-1"><Check className="h-3.5 w-3.5" /> Created</p>
|
|
) : (
|
|
<>
|
|
{m.proposal.spec.action.type === 'notify' && (
|
|
channels && channels.length > 0 ? (
|
|
<Select
|
|
value={m.proposal.spec.action.channelId || ''}
|
|
onValueChange={(v: string) => setProposalChannel(i, v)}
|
|
>
|
|
<SelectTrigger className="h-8 text-xs" aria-label="Notification channel">
|
|
<SelectValue placeholder="Choose a channel" />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
{channels.map(c => (
|
|
<SelectItem key={c.id} value={c.id}>{c.name} ({c.kind})</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
) : (
|
|
<p className="text-xs text-muted-foreground">Create a notification channel in Settings → Notifications first.</p>
|
|
)
|
|
)}
|
|
{m.proposal.spec.action.type === 'email' && (
|
|
<input
|
|
className="w-full rounded border bg-background px-2 py-1 text-xs"
|
|
aria-label="Recipient"
|
|
value={m.proposal.spec.action.to ?? ''}
|
|
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setProposalTo(i, e.target.value)}
|
|
/>
|
|
)}
|
|
<Button size="sm" className="w-full" onClick={() => createAutomation(i)}>
|
|
Create automation
|
|
</Button>
|
|
</>
|
|
)}
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
))}
|
|
{busy && (
|
|
<div className="flex justify-start">
|
|
<div className="rounded-lg bg-muted/60 px-3 py-2 text-sm text-muted-foreground flex items-center gap-2">
|
|
<Loader2 className="h-3.5 w-3.5 animate-spin" /> thinking…
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<div className="border-t p-3 space-y-2">
|
|
<Textarea
|
|
value={input}
|
|
onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setInput(e.target.value)}
|
|
onKeyDown={(e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
|
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send() }
|
|
}}
|
|
placeholder="Ask Superbrain… (Enter to send)"
|
|
rows={2}
|
|
aria-label="Message"
|
|
/>
|
|
<Button className="w-full gap-1.5" onClick={send} disabled={busy || !input.trim()}>
|
|
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />} Send
|
|
</Button>
|
|
</div>
|
|
</SheetContent>
|
|
</Sheet>
|
|
</>
|
|
)
|
|
}
|