release gate / check (push) Failing after 6m42s
The plan matrix's 'use your own AI' rows, made real. internal/ai is now pure implementation: three provider adapters — openai-compatible (OpenRouter, OpenAI, Grok, Groq, Ollama, any house gateway), native Anthropic (/v1/messages, x-api-key) and native Gemini (generateContent; the key travels in the x-goog-api-key HEADER, never the URL, because Go's HTTP error strings include URLs and errors get logged). One netguard-dialed client, per-source outbound budgets (ai:user:<id> vs ai:server). Configuration is data: UserAiConfig (migration 015) — one row per user with provider, base URL, model and an API key encrypted at rest via internal/crypto (the IMAP-password format), masked in every response; a PUT echoing the mask or leaving the key blank keeps the stored value; version contract on updates. New endpoints: GET/PUT/DELETE /api/ai/config, POST /api/ai/test (one probe completion through the resolved config), GET /api/ai/status (plan-gated availability, no secrets). Resolution chain (ai.ResolveForUser): the user's enabled BYO config first on EVERY plan; else the server env key (AI_API_KEY/AI_MODEL/AI_BASE_URL/ AI_PROVIDER) only when the tenant's plan may spend it — new entitlements.AllowServerAI: premium (credits), core (house gateway) and selfhosted (operator IS the user); free/standard are BYO-only, exactly the matrix. No AI available => 428 with a pointer to Settings -> AI (was a global 503): the precondition is per-user now. Agent compile and url_watch extraction resolve per owner, so different users' tasks can run on different providers. Web: Settings -> AI tab (provider picker with per-provider defaults and model hints, write-only key input, Test button, effective-source badge with plan context, enable switch, remove). The Automations tab reads /api/ai/status for a proactive banner and treats 428 as 'not configured'. Preparatory refactors (behavior-preserving): agent.AutomationSchema extracted as the single spec text shared by the compiler prompt (and the upcoming chat assistant), and ai.CompleteMessages for multi-turn conversations with per-provider role mapping (assistant -> model on Gemini). Tests: all three adapters against one loopback fake (asserting each provider's auth-header shape), masked-key lifecycle incl. mask-echo preservation across a provider switch, encrypted-at-rest verification, plan gate both directions (free refuses the server key, premium/core/ selfhosted allow it), BYO precedence over the server key, validation rejects, 428 paths, and compile resolution through a BYO config. Full suite green (-race), converge green (015), web lint/SSR/build clean. Docs: API.md AI section, RUNNING.md setup rewritten around BYO-first + plan-gated server fallback, .env.example (AI_PROVIDER + the precedence story), compose passthrough, AGENTS.md invariant (config vs implementation, Gemini key-in-header rule).
249 lines
9.9 KiB
Go
249 lines
9.9 KiB
Go
package http
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/http/cookiejar"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// fakeOpenAI is a loopback OpenAI-compatible chat-completions server with a
|
|
// programmable reply, standing in for OpenRouter in tests.
|
|
type fakeOpenAI struct {
|
|
ln net.Listener
|
|
srv *http.Server
|
|
mu sync.Mutex
|
|
next string // canned assistant message content
|
|
hits int
|
|
}
|
|
|
|
func newFakeOpenAI(t *testing.T) *fakeOpenAI {
|
|
t.Helper()
|
|
ln, e := net.Listen("tcp", "127.0.0.1:0")
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
f := &fakeOpenAI{ln: ln}
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("/v1/chat/completions", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Header.Get("Authorization") == "" {
|
|
w.WriteHeader(401)
|
|
return
|
|
}
|
|
body, _ := io.ReadAll(r.Body)
|
|
f.mu.Lock()
|
|
f.hits++
|
|
reply := f.next
|
|
f.mu.Unlock()
|
|
if strings.Contains(string(body), "extract one fact") || strings.Contains(string(body), "You extract one fact") {
|
|
// extraction call: default fact reply unless the test set one
|
|
f.mu.Lock()
|
|
if f.next == "" {
|
|
reply = `{"found":true,"value":350,"text":"","summary":"Cheapest round trip is $350"}`
|
|
}
|
|
f.mu.Unlock()
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"choices": []map[string]any{{"message": map[string]any{"role": "assistant", "content": reply}}},
|
|
})
|
|
})
|
|
f.srv = &http.Server{Handler: mux}
|
|
go f.srv.Serve(ln)
|
|
t.Cleanup(func() { f.srv.Close() })
|
|
return f
|
|
}
|
|
|
|
func (f *fakeOpenAI) setReply(s string) {
|
|
f.mu.Lock()
|
|
f.next = s
|
|
f.mu.Unlock()
|
|
}
|
|
|
|
// fakeWatchTarget serves a fixed "flights" page for url_watch evaluation.
|
|
func fakeWatchTarget(t *testing.T) string {
|
|
t.Helper()
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
_, _ = io.WriteString(w, `<html><body><script>var x=1;</script>
|
|
<div>Denver to Indianapolis, round trip from <b>$350</b></div></body></html>`)
|
|
})
|
|
ln, e := net.Listen("tcp", "127.0.0.1:0")
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
srv := &http.Server{Handler: mux}
|
|
go srv.Serve(ln)
|
|
t.Cleanup(func() { srv.Close() })
|
|
return "http://" + ln.Addr().String() + "/flights"
|
|
}
|
|
|
|
func TestAgentCompileAndTasks(t *testing.T) {
|
|
srv, d := 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")
|
|
t.Setenv("NEXTAUTH_URL", "https://superbrain.test")
|
|
|
|
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)
|
|
|
|
// --- compile: model success is re-validated, not trusted ---
|
|
fake.setReply(`Sure! Here you go:
|
|
` + "```json" + `
|
|
{"name":"Flights under 400","spec":{"condition":{"type":"url_watch","url":"https://flights.test/q","question":"cheapest round trip price in USD","op":"lt","threshold":400},"action":{"type":"email","to":"david@email.test","title":"Flight deal","body":"Under $400!"},"pollMinutes":60,"once":true}}
|
|
` + "```")
|
|
out := alice.request("POST", "/api/agent/compile", map[string]any{"text": "watch flights and email david when under 400"}, 200)
|
|
if out["name"] != "Flights under 400" {
|
|
t.Fatalf("compile name = %v", out["name"])
|
|
}
|
|
spec := out["spec"].(map[string]any)
|
|
if spec["condition"].(map[string]any)["op"] != "lt" || !strings.Contains(out["summary"].(string), "david@email.test") {
|
|
t.Fatalf("compile proposal wrong: %v / %v", spec, out["summary"])
|
|
}
|
|
|
|
// --- compile: model refusal surfaces as 422 with its reason ---
|
|
fake.setReply(`{"error":"Superbrain cannot book flights; it can only watch a page and notify you."}`)
|
|
res := alice.request("POST", "/api/agent/compile", map[string]any{"text": "book me a flight"}, 422)
|
|
if !strings.Contains(res["error"].(string), "cannot book") {
|
|
t.Fatalf("refusal not surfaced: %v", res)
|
|
}
|
|
|
|
// --- compile: a spec that fails validation is rejected even though the
|
|
// model "succeeded" (the validator is the boundary, not the prompt) ---
|
|
fake.setReply(`{"name":"bad","spec":{"condition":{"type":"url_watch","url":"ftp://nope","question":"x"},"action":{"type":"email","to":"not-an-email"}}}`)
|
|
alice.request("POST", "/api/agent/compile", map[string]any{"text": "do something weird"}, 422)
|
|
|
|
// --- task CRUD: server-side validation on direct create too ---
|
|
alice.request("POST", "/api/agent/tasks", map[string]any{"name": "bad", "spec": map[string]any{
|
|
"condition": map[string]any{"type": "url_watch", "url": "javascript:alert(1)", "question": "x"},
|
|
"action": map[string]any{"type": "email", "to": "david@email.test"},
|
|
}}, 400)
|
|
alice.request("POST", "/api/agent/tasks", map[string]any{"name": "no channel", "spec": map[string]any{
|
|
"condition": map[string]any{"type": "signal"},
|
|
"action": map[string]any{"type": "notify"},
|
|
}}, 400)
|
|
|
|
watchURL := fakeWatchTarget(t)
|
|
task := alice.request("POST", "/api/agent/tasks", map[string]any{"name": "Flights DEN-IND under $400", "spec": map[string]any{
|
|
"condition": map[string]any{"type": "url_watch", "url": watchURL, "question": "cheapest round trip price in USD", "op": "lt", "threshold": 400},
|
|
"action": map[string]any{"type": "email", "to": "david@email.test", "title": "Flight deal", "body": "Round trip under $400."},
|
|
"pollMinutes": 60, "once": true,
|
|
}}, 201)
|
|
taskID := task["id"].(string)
|
|
if task["summary"] == nil || task["status"] != "active" {
|
|
t.Fatalf("task projection wrong: %v", task)
|
|
}
|
|
|
|
// Version contract on PATCH.
|
|
alice.request("PATCH", "/api/agent/tasks/"+taskID, map[string]any{"name": "renamed"}, 400)
|
|
alice.request("PATCH", "/api/agent/tasks/"+taskID, map[string]any{"name": "renamed", "version": 99}, 409)
|
|
alice.request("PATCH", "/api/agent/tasks/"+taskID, map[string]any{"name": "renamed", "version": int(task["version"].(float64))}, 200)
|
|
|
|
// --- engine: manual run fetches the target, extracts with the model,
|
|
// fires the email action, and applies once-semantics ---
|
|
smtpHost, smtpPort := startSMTPForAgent(t)
|
|
t.Setenv("SMTP_HOST", smtpHost)
|
|
t.Setenv("SMTP_PORT", smtpPort)
|
|
t.Setenv("SMTP_FROM", "superbrain@superbrain.test")
|
|
fake.setReply(`{"found":true,"value":350,"text":"","summary":"Cheapest round trip is $350"}`)
|
|
|
|
run := alice.request("POST", "/api/agent/tasks/"+taskID+"/run", nil, 200)
|
|
if run["outcome"] != "fired" {
|
|
t.Fatalf("run outcome = %v, want fired", run["outcome"])
|
|
}
|
|
msg := agentWaitForMail(t, smtpHost, 1)
|
|
if !strings.Contains(msg, "david@email.test") {
|
|
t.Fatalf("email action did not reach the recipient: %s", msg)
|
|
}
|
|
|
|
// once=true completed the task; runs are recorded.
|
|
var status string
|
|
var fireCount int
|
|
if e := d.QueryRow(`SELECT status, "fireCount" FROM "AgentTask" WHERE id=$1`, taskID).Scan(&status, &fireCount); e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
if status != "done" || fireCount != 1 {
|
|
t.Fatalf("once-semantics broken: status=%s fireCount=%d", status, fireCount)
|
|
}
|
|
runs := alice.request("GET", "/api/agent/runs?taskId="+taskID, nil, 200)
|
|
_ = runs
|
|
|
|
// --- signal condition: a new mailbox signal matching the keyword fires
|
|
// the action (existing signals infrastructure, no AI call involved) ---
|
|
bm := alice.request("POST", "/api/bookmarks", map[string]any{"url": "https://example.org/invoices", "title": "Invoices"}, 201)
|
|
sigTask := alice.request("POST", "/api/agent/tasks", map[string]any{"name": "Invoice signals", "spec": map[string]any{
|
|
"condition": map[string]any{"type": "signal", "keyword": "invoice"},
|
|
"action": map[string]any{"type": "email", "to": "david@email.test", "title": "Invoice signal"},
|
|
"pollMinutes": 15,
|
|
}}, 201)
|
|
if _, e := d.Exec(`
|
|
INSERT INTO "Signal"(id,"sourceType",title,summary,"bookmarkId","ownerId")
|
|
SELECT 'sig-a1','email','Your invoice is ready','from billing', $1, u.id
|
|
FROM "User" u WHERE u.email='alice@superbrain.test'`, bm["id"].(string)); e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
run2 := alice.request("POST", "/api/agent/tasks/"+sigTask["id"].(string)+"/run", nil, 200)
|
|
if run2["outcome"] != "fired" {
|
|
t.Fatalf("signal run outcome = %v, want fired", run2["outcome"])
|
|
}
|
|
if msg := agentWaitForMail(t, "", 2); !strings.Contains(msg, "invoice") {
|
|
t.Fatalf("signal email missing: %s", msg)
|
|
}
|
|
// A second run with no NEW signals does not re-fire.
|
|
run3 := alice.request("POST", "/api/agent/tasks/"+sigTask["id"].(string)+"/run", nil, 200)
|
|
if run3["outcome"] != "checked" {
|
|
t.Fatalf("rerun outcome = %v, want checked (no new signals)", run3["outcome"])
|
|
}
|
|
|
|
// --- plan cap via the entitlement catalog (override to 0 => refuse) ---
|
|
if _, e := d.Exec(`INSERT INTO "TenantEntitlement"(id,"tenantId",key,value) VALUES('te-1','tenant-default','ai_tasks','0')`); e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
alice.request("POST", "/api/agent/tasks", map[string]any{"name": "capped", "spec": map[string]any{
|
|
"condition": map[string]any{"type": "signal"},
|
|
"action": map[string]any{"type": "email", "to": "david@email.test"},
|
|
}}, 403)
|
|
|
|
// --- AI not configured for this user: compile answers 428 (a per-user
|
|
// precondition, pointing at Settings → AI) ---
|
|
t.Setenv("AI_API_KEY", "")
|
|
alice.request("POST", "/api/agent/compile", map[string]any{"text": "anything"}, 428)
|
|
}
|
|
|
|
// startSMTPForAgent reuses the loopback SMTP fake from the reset tests and
|
|
// returns its host/port.
|
|
func startSMTPForAgent(t *testing.T) (string, string) {
|
|
t.Helper()
|
|
f := newFakeSMTP(t)
|
|
host, port, _ := net.SplitHostPort(f.ln.Addr().String())
|
|
agentSMTP = f
|
|
return host, port
|
|
}
|
|
|
|
var agentSMTP *fakeSMTP
|
|
|
|
func agentWaitForMail(t *testing.T, _ string, n int) string {
|
|
t.Helper()
|
|
deadline := time.Now().Add(10 * time.Second)
|
|
for time.Now().Before(deadline) {
|
|
msgs := agentSMTP.messages()
|
|
if len(msgs) >= n {
|
|
return msgs[n-1][0] + "\n" + msgs[n-1][1]
|
|
}
|
|
time.Sleep(20 * time.Millisecond)
|
|
}
|
|
t.Fatalf("no mail arrived at the fake SMTP relay (wanted %d)", n)
|
|
return ""
|
|
}
|