Mirrors the BYOK dialog suggested in issue #2: - UserAiConfig gains an optional instructions column (schema.sql + migration 016); PUT validates (<=4000 chars) and full-replaces it. - Instructions ride along on the assistant chat system prompt only (chatSystemWith); the automation compiler and page-extraction prompts stay server-owned contracts. - Settings -> AI: labeled fields, per-provider suggested-model dropdown with a custom-model escape hatch, API key show/hide toggle, and the instructions textarea. - Tests: projection echo, omission clears, cap validation, and the system-prompt assertion via a recorded fake provider body.
119 lines
5.2 KiB
Go
119 lines
5.2 KiB
Go
package http
|
|
|
|
import (
|
|
"net"
|
|
"net/http"
|
|
"net/http/cookiejar"
|
|
"strings"
|
|
"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)
|
|
|
|
// --- user instructions ride along on the assistant system prompt ---
|
|
// A BYO config resolves even with the server key unset. Instructions
|
|
// apply to THIS prompt only — never to the compiler/extraction contracts.
|
|
alice.request("PUT", "/api/ai/config", map[string]any{
|
|
"provider": "openai-compatible", "baseUrl": "http://" + host + ":" + port + "/v1",
|
|
"model": "byo-model", "apiKey": "sk-byo-chat", "instructions": "Answer like a pirate.",
|
|
}, 201)
|
|
fake.setReply(`{"reply":"Arr.","automation":null}`)
|
|
out = alice.request("POST", "/api/ai/chat", msgs("hello"), 200)
|
|
if out["reply"] != "Arr." {
|
|
t.Fatalf("byo chat reply = %v", out["reply"])
|
|
}
|
|
body := fake.lastRequest()
|
|
if !strings.Contains(body, "Answer like a pirate.") {
|
|
t.Fatal("user instructions missing from the assistant system prompt")
|
|
}
|
|
if !strings.Contains(body, "USER INSTRUCTIONS") {
|
|
t.Fatal("instructions must be appended as a delimited user section")
|
|
}
|
|
|
|
// 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)
|
|
}
|