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, `
Denver to Indianapolis, round trip from $350
`) }) 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: compile answers 503 (global property) --- t.Setenv("AI_API_KEY", "") alice.request("POST", "/api/agent/compile", map[string]any{"text": "anything"}, 503) } // 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 "" }