Files
supermarket/internal/ai/ai_test.go
T
davidandClaude Opus 5.5 81a7d0596c Let Supermarket use Hermes' Anthropic key and model
Hermes is already set up with an Anthropic key, so AI needn't be set up
twice. `supermarket hermes` asks once, then it and update.sh copy just
the key and model to hermes-ai.json in the data folder (0600). The app
uses them when it has no key of its own, re-reading the file on each use.

Generation still calls the model directly rather than through Hermes'
API: post writing feeds it text from the web, which must not reach an
agent with a terminal, a browser and write access to the CRM.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:58:06 -07:00

155 lines
4.8 KiB
Go

package ai
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"supermarket/internal/db"
"supermarket/internal/secrets"
)
func TestNormalizeBaseURL(t *testing.T) {
for in, want := range map[string]string{
"llm.lan:11434": "http://llm.lan:11434/v1",
"http://llm.lan:11434/": "http://llm.lan:11434/v1",
"https://openrouter.ai/api/v1": "https://openrouter.ai/api/v1",
" ": "",
} {
if got := NormalizeBaseURL(in); got != want {
t.Errorf("NormalizeBaseURL(%q) = %q, want %q", in, got, want)
}
}
}
func TestDecodeJSONToleratesFences(t *testing.T) {
var out struct{ Name string }
if err := decodeJSON("Here you go:\n```json\n{\"Name\": \"Acme\"}\n```", &out); err != nil || out.Name != "Acme" {
t.Errorf("%+v %v", out, err)
}
if err := decodeJSON("no json here", &out); err == nil {
t.Error("expected an error")
}
}
func TestOpenAICompatible(t *testing.T) {
var got map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/v1/models":
w.Write([]byte(`{"data":[{"id":"qwen3"},{"id":"llama3.3"}]}`))
case "/v1/chat/completions":
json.NewDecoder(r.Body).Decode(&got)
w.Write([]byte(`{"choices":[{"message":{"content":" {\"ok\": true} "},"finish_reason":"stop"}]}`))
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
models, err := ListModels(context.Background(), srv.URL, "")
if err != nil || len(models) != 2 || models[0] != "llama3.3" {
t.Fatalf("models: %v %v", models, err)
}
cfg := Config{Provider: ProviderOpenAI, Model: "qwen3", BaseURL: srv.URL, TaskModels: map[string]string{TaskProfile: "llama3.3"}}
c, err := New(cfg, mustSecrets(t))
if err != nil {
t.Fatal(err)
}
var out struct{ OK bool }
err = GenerateJSON(context.Background(), c, Request{Task: TaskProfile, System: "s", Prompt: "p", Schema: map[string]any{"type": "object"}}, &out)
if err != nil || !out.OK {
t.Fatalf("%+v %v", out, err)
}
if got["model"] != "llama3.3" {
t.Errorf("task model not used: %v", got["model"])
}
if msgs := got["messages"].([]any); len(msgs) != 2 {
t.Errorf("messages: %v", msgs)
}
if got["response_format"] == nil {
t.Error("schema not sent")
}
}
func TestNewNeedsCredentials(t *testing.T) {
sec := mustSecrets(t)
if _, err := New(Config{Provider: ProviderAnthropic, Model: DefaultAnthropicModel}, sec); err == nil {
t.Error("anthropic without a key should fail")
}
if _, err := New(Config{Provider: ProviderOpenAI, Model: "m"}, sec); err == nil {
t.Error("openai without an address should fail")
}
sec.Set(map[string]string{secrets.AnthropicAPIKey: "k"})
if _, err := New(Config{Provider: ProviderAnthropic, Model: DefaultAnthropicModel}, sec); err != nil {
t.Error(err)
}
}
func TestConfigDefaults(t *testing.T) {
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
if err != nil {
t.Fatal(err)
}
defer d.Close()
c, err := LoadConfig(d)
if err != nil || c.Provider != ProviderAnthropic || c.Model != DefaultAnthropicModel || c.Effort != "medium" {
t.Errorf("%+v %v", c, err)
}
}
func mustSecrets(t *testing.T) *secrets.Store {
t.Helper()
s, err := secrets.Open(filepath.Join(t.TempDir(), "secrets.json"))
if err != nil {
t.Fatal(err)
}
return s
}
func TestSharedKey(t *testing.T) {
dir := t.TempDir()
d, err := db.Open(filepath.Join(dir, "app.db"))
if err != nil {
t.Fatal(err)
}
defer d.Close()
sec, _ := secrets.Open(filepath.Join(dir, "secrets.json"))
defer func() { SharedFile = "" }()
SharedFile = filepath.Join(dir, "hermes-ai.json")
if _, err := New(Config{Provider: ProviderAnthropic}, sec); !errors.Is(err, ErrNotConfigured) {
t.Fatalf("no key anywhere: %v", err)
}
os.WriteFile(SharedFile, []byte(`{"provider":"anthropic","model":"claude-sonnet-5-5","api_key":"sk-hermes"}`), 0600)
if key, shared := AnthropicKey(sec); key != "sk-hermes" || !shared {
t.Errorf("shared key = %q, %v", key, shared)
}
if _, err := New(Config{Provider: ProviderAnthropic}, sec); err != nil {
t.Errorf("with Hermes' key: %v", err)
}
if c, _ := LoadConfig(d); c.Model != "claude-sonnet-5-5" {
t.Errorf("default model = %q, want Hermes'", c.Model)
}
// A saved config, or a key of Supermarket's own, wins.
_ = SaveConfig(d, Config{Provider: ProviderAnthropic, Model: "claude-opus-5-5"})
if c, _ := LoadConfig(d); c.Model != "claude-opus-5-5" {
t.Errorf("saved model = %q", c.Model)
}
_ = sec.Set(map[string]string{secrets.AnthropicAPIKey: "sk-own"})
if key, shared := AnthropicKey(sec); key != "sk-own" || shared {
t.Errorf("own key = %q, %v", key, shared)
}
// Anything but an Anthropic key is ignored.
os.WriteFile(SharedFile, []byte(`{"provider":"openrouter","api_key":"x"}`), 0600)
if LoadShared() != nil {
t.Error("non-Anthropic share accepted")
}
}