Add the Superbrain assistant: ephemeral chat drawer with automation proposals
release gate / check (push) Failing after 6m21s
release gate / check (push) Failing after 6m21s
The A+B slice: one conversation surface for questions AND automations.
Backend: POST /api/ai/chat — ephemeral multi-turn chat through the same
per-user AI resolution as everything else (BYO key -> plan-gated server
key -> 428). The server is stateless per request: the browser owns
history, the handler caps it anyway (40 messages accepted, last 20 used,
8k chars each, last turn must be the user's). Per-user rate limit
(30/hour, keyed on the account not the IP) and a 50-second budget inside
the proxy's 55s window.
The chat system prompt embeds agent.AutomationSchema — the SAME contract
text the compiler uses — so chat proposals and compiled tasks can never
drift. The model answers in a {reply, automation|null} JSON envelope; a
proposal reaches the client only if its spec passes agent.ValidateSpec
(invalid ones are dropped silently, the reply survives), and model-
invented channelIds are scrubbed so the UI always picks from the user's
real channels. A model that ignores the envelope degrades gracefully: raw
text becomes the reply, no proposal.
Web: components/assistant.tsx — floating launcher on every signed-in
screen (mounted once in AppShellWrapper so conversations survive in-app
navigation), Sheet drawer with markdown rendering (house ReactMarkdown +
remarkGfm pattern), proposal cards (channel picker for notify, editable
recipient for email, Create automation -> the regular tasks endpoint),
and Save to page (Markdown transcript into Pages — the only persistence,
by design). Enter sends, Shift+Enter newline.
Tests: envelope parsing, valid proposal + channelId scrub, invalid-spec
drop with reply intact, non-JSON graceful fallback, request validation
(empty/assistant-last/system-role), multi-turn passthrough, 428 path.
Full suite green (-race); web lint/SSR-eslint/build clean.
Docs: API.md chat endpoint, RUNNING.md 'two doors' framing (drawer +
Settings), README feature bullet, plan/notes docs updated.
This commit is contained in:
@@ -299,6 +299,7 @@ BYO-only) → else 428. Budgets are per user (`ai:user:<id>`) or shared
|
||||
| DELETE | `/api/ai/config` | `{ok:true}` |
|
||||
| POST | `/api/ai/test` | One probe completion through the resolved config → `{ok,source,model,reply}`; 428 when nothing is available; 502 with a truncated provider error |
|
||||
| GET | `/api/ai/status` | `{userConfigured,userEnabled,serverAvailable,effective,plan}` — `serverAvailable` is already plan-gated; no secrets |
|
||||
| POST | `/api/ai/chat` | Assistant chat (ephemeral; the browser owns history). `{messages:[{role:user\|assistant,content}]}` (≤40 sent, last 20 used, ≤8000 chars each, last must be `user`) → `{reply, proposal?}`. `proposal` = `{name,spec,summary}` when the model suggested an automation whose spec passes `agent.ValidateSpec` (invalid proposals are silently dropped; model-supplied `channelId`s are scrubbed — the UI picks real channels). Confirming a proposal is a regular `POST /api/agent/tasks`. Per-user limited (30/hour); 428 without AI; 50-second budget inside the proxy window |
|
||||
| GET | `/api/alerts/check` | Undismissed bookmarks due within 15 minutes, soonest first |
|
||||
| DELETE | `/api/alerts/{bookmarkId}` | `{ok:true}`; sets `alertSent` |
|
||||
| GET | `/api/contacts` | Synced contacts with `_count.bookmarks` |
|
||||
|
||||
@@ -176,16 +176,21 @@ install it); the index-backed page search depends on it.
|
||||
- **AI automations ("hey superbrain")**: describe an automation in plain
|
||||
language — *"when the round trip on https://… drops below $400, email
|
||||
david@example.com"* — and Superbrain compiles it into a task you review
|
||||
and confirm before anything is saved. Tasks watch a public web page on a
|
||||
schedule (one extracted fact per check, e.g. a price threshold) or react
|
||||
to new mailbox signals, then notify a channel, email a recipient, or save
|
||||
a bookmark. The AI only ever *proposes* validated specs; actions are a
|
||||
fixed, bounded set (no logins, no bookings, no deletes, no multi-step
|
||||
chains yet), every fetch goes through the same private-range network
|
||||
guard as previews, and email actions are hard-capped. Requires
|
||||
`AI_API_KEY` (OpenRouter by default; any OpenAI-compatible gateway via
|
||||
`AI_BASE_URL`/`AI_MODEL`); without it, signal-based tasks still run.
|
||||
Usage guide: RUNNING.md → "AI automations". Settings → Automations.
|
||||
and confirm before anything is saved. Two doors: the floating **Ask
|
||||
Superbrain** assistant drawer (ephemeral chat on every screen; automation
|
||||
requests come back as confirm-before-create proposal cards; *Save to
|
||||
page* keeps a conversation) and Settings → Automations (form + task list
|
||||
+ delivery history). Tasks watch a public web page on a schedule (one
|
||||
extracted fact per check, e.g. a price threshold) or react to new mailbox
|
||||
signals, then notify a channel, email a recipient, or save a bookmark.
|
||||
The AI only ever *proposes* validated specs; actions are a fixed, bounded
|
||||
set (no logins, no bookings, no deletes, no multi-step chains yet),
|
||||
every fetch goes through the same private-range network guard as
|
||||
previews, and email actions are hard-capped. AI is **bring-your-own-key**
|
||||
per user (Settings → AI: provider, model, key — encrypted at rest) with
|
||||
an optional server-wide key for plans that include it; without any key,
|
||||
AI features report "not configured" and everything else keeps working.
|
||||
Details: RUNNING.md → "AI automations".
|
||||
|
||||
### Connecting Authelia (OIDC)
|
||||
|
||||
|
||||
+11
@@ -293,6 +293,17 @@ an automation in plain language; the AI **compiles it into a task proposal
|
||||
that you review and confirm** — nothing is saved, and nothing can run,
|
||||
without that confirmation.
|
||||
|
||||
There are two doors into it:
|
||||
|
||||
- **The assistant drawer** — the floating **Ask Superbrain** button
|
||||
(bottom-right of every signed-in screen) opens an ephemeral chat. Ask
|
||||
questions, draft text, or describe an automation; when the assistant
|
||||
recognizes one it renders a **proposal card** (pick the channel or
|
||||
recipient, then *Create automation*). Conversations are not stored —
|
||||
**Save to page** keeps one as a Markdown page.
|
||||
- **Settings → Automations** — the same compiler behind a form, plus the
|
||||
task list, *Run now*, and the delivery history.
|
||||
|
||||
### Setup
|
||||
|
||||
AI configuration is **separate from the implementation**: the server ships
|
||||
|
||||
@@ -10,13 +10,16 @@ package handlers
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/agent"
|
||||
"github.com/andrew/superbrain/internal/ai"
|
||||
"github.com/andrew/superbrain/internal/auth"
|
||||
"github.com/andrew/superbrain/internal/config"
|
||||
crypt "github.com/andrew/superbrain/internal/crypto"
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
@@ -260,3 +263,137 @@ func HandleAiStatus(w http.ResponseWriter, r *http.Request) {
|
||||
"plan": string(plan),
|
||||
}, nil)
|
||||
}
|
||||
|
||||
// --- Assistant chat (ephemeral, proposal-capable) ---------------------------
|
||||
|
||||
// chatLimiter bounds chat turns per USER (not per IP: one NAT could
|
||||
// otherwise starve a household, and the cost center is the account).
|
||||
var chatLimiter = auth.NewLimiterStore()
|
||||
|
||||
// ChatLimiter rate-limits chat messages per authenticated user.
|
||||
func ChatLimiter(next http.HandlerFunc) http.HandlerFunc {
|
||||
return auth.LimiterKeyed(chatLimiter, 30, time.Hour, user)(next)
|
||||
}
|
||||
|
||||
// chatSystem is the assistant persona. It shares the automation contract
|
||||
// with the compiler (agent.AutomationSchema) so chat proposals and compiled
|
||||
// tasks can never drift. The envelope is JSON so proposals are separable
|
||||
// from prose; a model that answers in plain text anyway is handled
|
||||
// gracefully (the text becomes the reply, no proposal).
|
||||
const chatSystem = `You are Superbrain's in-app assistant: concise, practical, warm but not gushy. Answer in GitHub-flavored markdown.
|
||||
|
||||
You help with: general questions; drafting, summarizing and rewriting text; explaining Superbrain features (bookmarks with previews/tags/due dates, Markdown pages with backlinks, collections with typed properties and saved views, kanban boards, shared calendar dates, contacts, mailbox signals, notification rules, automations); and proposing automations.
|
||||
|
||||
You have NO access to the user's data and CANNOT perform actions — never claim to have looked anything up, saved anything, or sent anything. When the user wants something done in their workspace, explain where the feature lives, or propose an automation.
|
||||
|
||||
AUTOMATIONS: when — and only when — the user asks to watch/monitor/be told about something that fits the schema below, include an "automation" object; otherwise "automation": null. The same hard limits as the compiler apply: one condition, one action, no logins, no purchases, no invented URLs, no multi-step chains — refuse those in your reply text with automation null.
|
||||
|
||||
` + agent.AutomationSchema + `
|
||||
|
||||
REPLY FORMAT — always ONE JSON object, no prose outside it:
|
||||
{"reply": "<your markdown answer>", "automation": {"name": "...", "spec": <Spec>} or null}`
|
||||
|
||||
// HandleAiChat is the assistant endpoint: ephemeral multi-turn chat with
|
||||
// optional automation proposals. The browser keeps the history; the server
|
||||
// is stateless per request (bounded message count/size, oldest turns
|
||||
// dropped server-side too so a hand-rolled client cannot smuggle a novel).
|
||||
//
|
||||
// POST /api/ai/chat {messages:[{role,content},...]}
|
||||
// 200 {reply, proposal?} proposal = {name, spec, summary} when the
|
||||
// model suggested a VALID automation
|
||||
// 428 no AI available for this user
|
||||
func HandleAiChat(w http.ResponseWriter, r *http.Request) {
|
||||
b, ok := read(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
rawMsgs, _ := b["messages"].([]any)
|
||||
if len(rawMsgs) == 0 {
|
||||
respond(w, 0, nil, bad("messages is required"))
|
||||
return
|
||||
}
|
||||
if len(rawMsgs) > 40 {
|
||||
respond(w, 0, nil, bad("conversation too long (max 40 messages)"))
|
||||
return
|
||||
}
|
||||
msgs := make([]ai.Message, 0, len(rawMsgs))
|
||||
for _, m := range rawMsgs {
|
||||
mm, _ := m.(map[string]any)
|
||||
role, _ := mm["role"].(string)
|
||||
content, _ := mm["content"].(string)
|
||||
if role != "user" && role != "assistant" {
|
||||
respond(w, 0, nil, bad("message roles must be user or assistant"))
|
||||
return
|
||||
}
|
||||
content = strings.TrimSpace(content)
|
||||
if content == "" || len([]rune(content)) > 8000 {
|
||||
respond(w, 0, nil, bad("messages must be 1-8000 characters"))
|
||||
return
|
||||
}
|
||||
msgs = append(msgs, ai.Message{Role: role, Content: content})
|
||||
}
|
||||
// The last turn must be the user's; the assistant never answers itself.
|
||||
if msgs[len(msgs)-1].Role != "user" {
|
||||
respond(w, 0, nil, bad("the last message must be from the user"))
|
||||
return
|
||||
}
|
||||
// Keep only the most recent window regardless of what the client sent.
|
||||
if len(msgs) > 20 {
|
||||
msgs = msgs[len(msgs)-20:]
|
||||
}
|
||||
|
||||
// 50s: inside the web proxy's 55s budget and Go's 60s WriteTimeout.
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 50*time.Second)
|
||||
defer cancel()
|
||||
resolved, e := ai.ResolveForUser(ctx, database(r), user(r))
|
||||
if e != nil {
|
||||
if errors.Is(e, ai.ErrNoAI) {
|
||||
respond(w, 428, Error{Error: "AI is not configured. Add your own provider and API key in Settings → AI."}, nil)
|
||||
return
|
||||
}
|
||||
respond(w, 0, nil, e)
|
||||
return
|
||||
}
|
||||
reply, e := ai.CompleteMessages(ctx, resolved, chatSystem, msgs)
|
||||
if e != nil {
|
||||
respond(w, 502, Error{Error: "The AI provider could not be reached"}, nil)
|
||||
return
|
||||
}
|
||||
|
||||
// Parse the envelope. Graceful degradation: a model that ignored the
|
||||
// JSON contract still produces a usable chat reply — the raw text
|
||||
// becomes the message and no proposal is offered.
|
||||
out := object{"reply": strings.TrimSpace(reply)}
|
||||
if raw, jerr := ai.ExtractJSON(reply); jerr == nil {
|
||||
var env struct {
|
||||
Reply string `json:"reply"`
|
||||
Automation *struct {
|
||||
Name string `json:"name"`
|
||||
Spec agent.Spec `json:"spec"`
|
||||
} `json:"automation"`
|
||||
}
|
||||
if json.Unmarshal(raw, &env) == nil && strings.TrimSpace(env.Reply) != "" {
|
||||
out["reply"] = strings.TrimSpace(env.Reply)
|
||||
if env.Automation != nil {
|
||||
spec := env.Automation.Spec
|
||||
// The validator, not the model, decides what a proposal is.
|
||||
if verr := agent.ValidateSpec(&spec); verr == nil {
|
||||
name := strings.TrimSpace(env.Automation.Name)
|
||||
if name == "" {
|
||||
name = "Automation"
|
||||
}
|
||||
if len([]rune(name)) > 120 {
|
||||
name = string([]rune(name)[:120])
|
||||
}
|
||||
// Never echo a model-invented channel id: the UI picks
|
||||
// from the user's real channels.
|
||||
if spec.Action.Type == "notify" {
|
||||
spec.Action.ChannelID = ""
|
||||
}
|
||||
out["proposal"] = object{"name": name, "spec": spec, "summary": agent.Summary(spec)}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
respond(w, 200, out, nil)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The assistant endpoint: envelope parsing, proposal validation (the model
|
||||
// never gets to smuggle a spec through), graceful degradation when the
|
||||
// model ignores the JSON contract, and the 428 precondition.
|
||||
func TestAiChat(t *testing.T) {
|
||||
srv, _ := testServerDB(t)
|
||||
fake := newFakeOpenAI(t)
|
||||
host, port, _ := net.SplitHostPort(fake.ln.Addr().String())
|
||||
t.Setenv("AI_API_KEY", "test-key")
|
||||
t.Setenv("AI_BASE_URL", "http://"+host+":"+port+"/v1")
|
||||
t.Setenv("AI_MODEL", "test-model")
|
||||
|
||||
jar, _ := cookiejar.New(nil)
|
||||
alice := apiClient{t, &http.Client{Jar: jar}, srv.URL}
|
||||
alice.request("POST", "/api/signup", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 201)
|
||||
alice.request("POST", "/api/auth/login", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 200)
|
||||
|
||||
msgs := func(s string) map[string]any {
|
||||
return map[string]any{"messages": []map[string]any{{"role": "user", "content": s}}}
|
||||
}
|
||||
|
||||
// --- plain chat reply ---
|
||||
fake.setReply(`{"reply":"Hello! I can help with bookmarks, pages and automations.","automation":null}`)
|
||||
out := alice.request("POST", "/api/ai/chat", msgs("hi"), 200)
|
||||
if out["reply"] != "Hello! I can help with bookmarks, pages and automations." {
|
||||
t.Fatalf("reply = %v", out["reply"])
|
||||
}
|
||||
if _, has := out["proposal"]; has {
|
||||
t.Fatal("null automation must not surface a proposal")
|
||||
}
|
||||
|
||||
// --- valid proposal, with a model-invented channelId that must be
|
||||
// scrubbed (the UI picks from the user's real channels) ---
|
||||
fake.setReply(`{"reply":"I can watch that page for you.","automation":{"name":"Price watch","spec":{"condition":{"type":"url_watch","url":"https://shop.test/item","question":"current price in USD","op":"lt","threshold":50},"action":{"type":"notify","channelId":"invented-id"},"pollMinutes":60,"once":true}}}`)
|
||||
out = alice.request("POST", "/api/ai/chat", msgs("tell me when the price drops below 50"), 200)
|
||||
prop, ok := out["proposal"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("proposal missing: %v", out)
|
||||
}
|
||||
if prop["name"] != "Price watch" || prop["summary"] == nil {
|
||||
t.Fatalf("proposal projection wrong: %v", prop)
|
||||
}
|
||||
action := prop["spec"].(map[string]any)["action"].(map[string]any)
|
||||
if v, present := action["channelId"]; present && v != "" {
|
||||
t.Fatalf("model-invented channelId was not scrubbed: %v", v)
|
||||
}
|
||||
|
||||
// --- invalid proposal spec: dropped, reply survives ---
|
||||
fake.setReply(`{"reply":"Sure!","automation":{"name":"bad","spec":{"condition":{"type":"telepathy"},"action":{"type":"email","to":"nope"}}}}`)
|
||||
out = alice.request("POST", "/api/ai/chat", msgs("read my mind"), 200)
|
||||
if _, has := out["proposal"]; has {
|
||||
t.Fatal("an invalid spec must never reach the client as a proposal")
|
||||
}
|
||||
if out["reply"] != "Sure!" {
|
||||
t.Fatalf("reply lost: %v", out["reply"])
|
||||
}
|
||||
|
||||
// --- model ignored the JSON contract: graceful raw-text fallback ---
|
||||
fake.setReply(`I'm sorry, I can only watch public pages.`)
|
||||
out = alice.request("POST", "/api/ai/chat", msgs("book me a flight"), 200)
|
||||
if out["reply"] != "I'm sorry, I can only watch public pages." {
|
||||
t.Fatalf("raw fallback broken: %v", out["reply"])
|
||||
}
|
||||
|
||||
// --- request validation ---
|
||||
alice.request("POST", "/api/ai/chat", map[string]any{"messages": []any{}}, 400)
|
||||
alice.request("POST", "/api/ai/chat", map[string]any{"messages": []map[string]any{{"role": "assistant", "content": "hi"}}}, 400)
|
||||
alice.request("POST", "/api/ai/chat", map[string]any{"messages": []map[string]any{{"role": "system", "content": "hi"}}}, 400)
|
||||
|
||||
// --- multi-turn is accepted and the assistant turn passes through ---
|
||||
fake.setReply(`{"reply":"Follow-up answered.","automation":null}`)
|
||||
out = alice.request("POST", "/api/ai/chat", map[string]any{"messages": []map[string]any{
|
||||
{"role": "user", "content": "first"},
|
||||
{"role": "assistant", "content": "answer"},
|
||||
{"role": "user", "content": "second"},
|
||||
}}, 200)
|
||||
if out["reply"] != "Follow-up answered." {
|
||||
t.Fatalf("multi-turn reply = %v", out["reply"])
|
||||
}
|
||||
|
||||
// --- no AI available: 428 with the settings pointer ---
|
||||
t.Setenv("AI_API_KEY", "")
|
||||
alice.request("POST", "/api/ai/chat", msgs("anything"), 428)
|
||||
|
||||
// The chat route is session-authenticated like every /api/ai route.
|
||||
anon, _ := cookiejar.New(nil)
|
||||
stranger := apiClient{t, &http.Client{Jar: anon}, srv.URL}
|
||||
stranger.request("GET", "/api/me", nil, 401)
|
||||
}
|
||||
@@ -144,6 +144,10 @@ func NewServer(cfg *config.Config, database *db.DB) *http.Server {
|
||||
mux.HandleFunc("DELETE /api/ai/config", authed(handlers.HandleAiConfigDelete))
|
||||
mux.HandleFunc("POST /api/ai/test", authed(handlers.HandleAiTest))
|
||||
mux.HandleFunc("GET /api/ai/status", authed(handlers.HandleAiStatus))
|
||||
// Assistant chat: ephemeral multi-turn with automation proposals
|
||||
// (per-user rate limited; proposals ride the same validated spec path
|
||||
// as the compiler — confirm-before-create on the client).
|
||||
mux.HandleFunc("POST /api/ai/chat", authed(handlers.ChatLimiter(handlers.HandleAiChat)))
|
||||
|
||||
// 4.8 Alerts, contacts, email, dates, users
|
||||
mux.HandleFunc("GET /api/alerts/check", authed(handlers.HandleAlertsCheck))
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { SessionProvider } from 'next-auth/react'
|
||||
import type { Session } from 'next-auth'
|
||||
import { AppShell } from '@/components/app-shell'
|
||||
import { Assistant } from '@/components/assistant'
|
||||
|
||||
// Nested provider seeded with the server session: useSession() in AppShell
|
||||
// has data during SSR, so the signed-in shell is server-rendered.
|
||||
@@ -10,6 +11,9 @@ export function AppShellWrapper({ session, children }: { session: Session; child
|
||||
return (
|
||||
<SessionProvider session={session}>
|
||||
<AppShell>{children}</AppShell>
|
||||
{/* Ephemeral assistant drawer: mounted once per signed-in shell so the
|
||||
conversation survives in-app navigation. */}
|
||||
<Assistant />
|
||||
</SessionProvider>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
'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<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 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 (
|
||||
<>
|
||||
<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 (Automations tab 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>
|
||||
</>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user