'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' 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 { return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init }) } export function Assistant() { const [open, setOpen] = useState(false) const [messages, setMessages] = useState([]) const [input, setInput] = useState('') const [busy, setBusy] = useState(false) const [unavailable, setUnavailable] = useState(false) const [channels, setChannels] = useState(null) const scrollRef = useRef(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 Settings → Automations') 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 ( <> Ask Superbrain
{messages.length === 0 && (

Ask anything, or describe an automation:

  • “when the round trip on https://… drops below $400, email david@example.com”
  • “tell me when my inbox gets an invoice”
  • “summarize this text for me: …”

Proposals are reviewed by you before anything is created. Conversations are not stored — use Save to page to keep one.

)} {unavailable && (

No AI available — add your provider and key in Settings → AI (Automations tab shows the same hint).

)} {messages.map((m, i) => (
{m.role === 'assistant' ? (
{m.content}
) : m.content} {m.proposal && (

Automation proposal

{m.proposal.name}

{m.proposal.summary}

every {m.proposal.spec.pollMinutes} min{m.proposal.spec.once ? ' · one-shot' : ' · ongoing'}

{m.proposalState === 'created' ? (

Created

) : ( <> {m.proposal.spec.action.type === 'notify' && ( channels && channels.length > 0 ? ( ) : (

Create a notification channel in Settings → Notifications first.

) )} {m.proposal.spec.action.type === 'email' && ( ) => setProposalTo(i, e.target.value)} /> )} )}
)}
))} {busy && (
thinking…
)}