|
| 1 | +package ai |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "net/http" |
| 7 | + "net/http/httptest" |
| 8 | + "strings" |
| 9 | + "testing" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/flatrun/agent/pkg/config" |
| 13 | +) |
| 14 | + |
| 15 | +func TestNewDisabled(t *testing.T) { |
| 16 | + if _, err := New(&config.AIConfig{Enabled: false}); err != ErrDisabled { |
| 17 | + t.Errorf("err = %v, want ErrDisabled", err) |
| 18 | + } |
| 19 | + if _, err := New(nil); err != ErrDisabled { |
| 20 | + t.Errorf("nil cfg err = %v, want ErrDisabled", err) |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +func TestRedactor(t *testing.T) { |
| 25 | + r := NewRedactor([]string{"hunter2secret", "short", " spaced-secret-value "}) |
| 26 | + |
| 27 | + cases := []struct { |
| 28 | + name string |
| 29 | + in string |
| 30 | + contains []string |
| 31 | + excludes []string |
| 32 | + minCount int |
| 33 | + }{ |
| 34 | + { |
| 35 | + name: "known secret value", |
| 36 | + in: "db error: auth failed for password hunter2secret retrying", |
| 37 | + excludes: []string{"hunter2secret"}, |
| 38 | + minCount: 1, |
| 39 | + }, |
| 40 | + { |
| 41 | + name: "short values stay", |
| 42 | + in: "level=short msg=ok", |
| 43 | + contains: []string{"short"}, |
| 44 | + }, |
| 45 | + { |
| 46 | + name: "credential assignment", |
| 47 | + in: "MYSQL_ROOT_PASSWORD=supersafe123\napi_key: abc123def\nDEBUG=true", |
| 48 | + contains: []string{"MYSQL_ROOT_PASSWORD=[REDACTED]", "api_key: [REDACTED]", "DEBUG=true"}, |
| 49 | + excludes: []string{"supersafe123", "abc123def"}, |
| 50 | + minCount: 2, |
| 51 | + }, |
| 52 | + { |
| 53 | + name: "trimmed secret", |
| 54 | + in: "token is spaced-secret-value here", |
| 55 | + excludes: []string{"spaced-secret-value"}, |
| 56 | + minCount: 1, |
| 57 | + }, |
| 58 | + } |
| 59 | + |
| 60 | + for _, tc := range cases { |
| 61 | + t.Run(tc.name, func(t *testing.T) { |
| 62 | + out, count := r.Redact(tc.in) |
| 63 | + for _, want := range tc.contains { |
| 64 | + if !strings.Contains(out, want) { |
| 65 | + t.Errorf("output %q missing %q", out, want) |
| 66 | + } |
| 67 | + } |
| 68 | + for _, banned := range tc.excludes { |
| 69 | + if strings.Contains(out, banned) { |
| 70 | + t.Errorf("output %q still contains %q", out, banned) |
| 71 | + } |
| 72 | + } |
| 73 | + if count < tc.minCount { |
| 74 | + t.Errorf("count = %d, want >= %d", count, tc.minCount) |
| 75 | + } |
| 76 | + }) |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +func TestOpenAICompatibleComplete(t *testing.T) { |
| 81 | + var gotAuth string |
| 82 | + var gotPayload map[string]interface{} |
| 83 | + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 84 | + gotAuth = r.Header.Get("Authorization") |
| 85 | + if r.URL.Path != "/v1/chat/completions" { |
| 86 | + t.Errorf("path = %s", r.URL.Path) |
| 87 | + } |
| 88 | + _ = json.NewDecoder(r.Body).Decode(&gotPayload) |
| 89 | + _ = json.NewEncoder(w).Encode(map[string]interface{}{ |
| 90 | + "model": "test-model", |
| 91 | + "choices": []map[string]interface{}{ |
| 92 | + {"message": map[string]string{"role": "assistant", "content": "diagnosis here"}}, |
| 93 | + }, |
| 94 | + "usage": map[string]int{"prompt_tokens": 10, "completion_tokens": 5}, |
| 95 | + }) |
| 96 | + })) |
| 97 | + defer fake.Close() |
| 98 | + |
| 99 | + p, err := New(&config.AIConfig{ |
| 100 | + Enabled: true, |
| 101 | + BaseURL: fake.URL + "/v1/", |
| 102 | + APIKey: "sk-test", |
| 103 | + Model: "test-model", |
| 104 | + Timeout: 5 * time.Second, |
| 105 | + }) |
| 106 | + if err != nil { |
| 107 | + t.Fatal(err) |
| 108 | + } |
| 109 | + |
| 110 | + resp, err := p.Complete(context.Background(), Request{ |
| 111 | + Messages: []Message{{Role: "user", Content: "hi"}}, |
| 112 | + }) |
| 113 | + if err != nil { |
| 114 | + t.Fatal(err) |
| 115 | + } |
| 116 | + if resp.Content != "diagnosis here" || resp.Model != "test-model" { |
| 117 | + t.Errorf("resp = %+v", resp) |
| 118 | + } |
| 119 | + if resp.Usage.PromptTokens != 10 { |
| 120 | + t.Errorf("usage = %+v", resp.Usage) |
| 121 | + } |
| 122 | + if gotAuth != "Bearer sk-test" { |
| 123 | + t.Errorf("auth header = %q", gotAuth) |
| 124 | + } |
| 125 | + if gotPayload["model"] != "test-model" { |
| 126 | + t.Errorf("payload model = %v", gotPayload["model"]) |
| 127 | + } |
| 128 | +} |
| 129 | + |
| 130 | +func TestOpenAICompatibleToolCalling(t *testing.T) { |
| 131 | + var sentPayload map[string]interface{} |
| 132 | + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 133 | + _ = json.NewDecoder(r.Body).Decode(&sentPayload) |
| 134 | + _ = json.NewEncoder(w).Encode(map[string]interface{}{ |
| 135 | + "model": "test-model", |
| 136 | + "choices": []map[string]interface{}{{ |
| 137 | + "message": map[string]interface{}{ |
| 138 | + "role": "assistant", |
| 139 | + "content": "", |
| 140 | + "tool_calls": []map[string]interface{}{{ |
| 141 | + "id": "call_1", |
| 142 | + "type": "function", |
| 143 | + "function": map[string]interface{}{"name": "list_networks", "arguments": "{}"}, |
| 144 | + }}, |
| 145 | + }, |
| 146 | + }}, |
| 147 | + }) |
| 148 | + })) |
| 149 | + defer fake.Close() |
| 150 | + |
| 151 | + p, _ := New(&config.AIConfig{Enabled: true, BaseURL: fake.URL, Model: "test-model", Timeout: 5 * time.Second}) |
| 152 | + resp, err := p.Complete(context.Background(), Request{ |
| 153 | + Messages: []Message{ |
| 154 | + {Role: "user", Content: "what networks exist?"}, |
| 155 | + {Role: "assistant", ToolCalls: []ToolCall{{ID: "x", Name: "noop", Arguments: "{}"}}}, |
| 156 | + {Role: "tool", ToolCallID: "x", Name: "noop", Content: "done"}, |
| 157 | + }, |
| 158 | + Tools: []Tool{{ |
| 159 | + Name: "list_networks", |
| 160 | + Description: "List docker networks", |
| 161 | + Parameters: map[string]interface{}{"type": "object", "properties": map[string]interface{}{}}, |
| 162 | + }}, |
| 163 | + }) |
| 164 | + if err != nil { |
| 165 | + t.Fatal(err) |
| 166 | + } |
| 167 | + if len(resp.ToolCalls) != 1 || resp.ToolCalls[0].Name != "list_networks" { |
| 168 | + t.Fatalf("tool calls = %+v", resp.ToolCalls) |
| 169 | + } |
| 170 | + |
| 171 | + tools := sentPayload["tools"].([]interface{}) |
| 172 | + if len(tools) != 1 { |
| 173 | + t.Fatalf("tools not sent: %v", sentPayload["tools"]) |
| 174 | + } |
| 175 | + fn := tools[0].(map[string]interface{})["function"].(map[string]interface{}) |
| 176 | + if fn["name"] != "list_networks" { |
| 177 | + t.Errorf("tool name = %v", fn["name"]) |
| 178 | + } |
| 179 | + |
| 180 | + // The assistant tool-call message and the tool result must reach the |
| 181 | + // wire in OpenAI's nested shape. |
| 182 | + msgs := sentPayload["messages"].([]interface{}) |
| 183 | + assistant := msgs[1].(map[string]interface{}) |
| 184 | + if _, ok := assistant["tool_calls"]; !ok { |
| 185 | + t.Error("assistant tool_calls not serialized") |
| 186 | + } |
| 187 | + toolMsg := msgs[2].(map[string]interface{}) |
| 188 | + if toolMsg["tool_call_id"] != "x" || toolMsg["role"] != "tool" { |
| 189 | + t.Errorf("tool result message = %v", toolMsg) |
| 190 | + } |
| 191 | +} |
| 192 | + |
| 193 | +func TestOpenAICompatibleKeyless(t *testing.T) { |
| 194 | + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 195 | + if auth := r.Header.Get("Authorization"); auth != "" { |
| 196 | + t.Errorf("keyless request sent auth header %q", auth) |
| 197 | + } |
| 198 | + _ = json.NewEncoder(w).Encode(map[string]interface{}{ |
| 199 | + "choices": []map[string]interface{}{{"message": map[string]string{"content": "ok"}}}, |
| 200 | + }) |
| 201 | + })) |
| 202 | + defer fake.Close() |
| 203 | + |
| 204 | + p, _ := New(&config.AIConfig{Enabled: true, BaseURL: fake.URL, Model: "llama3"}) |
| 205 | + resp, err := p.Complete(context.Background(), Request{Messages: []Message{{Role: "user", Content: "hi"}}}) |
| 206 | + if err != nil { |
| 207 | + t.Fatal(err) |
| 208 | + } |
| 209 | + if resp.Model != "llama3" { |
| 210 | + t.Errorf("model fallback = %q, want configured model", resp.Model) |
| 211 | + } |
| 212 | +} |
| 213 | + |
| 214 | +func TestOpenAICompatibleErrorMapping(t *testing.T) { |
| 215 | + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 216 | + w.WriteHeader(http.StatusUnauthorized) |
| 217 | + _, _ = w.Write([]byte(`{"error":{"message":"invalid api key"}}`)) |
| 218 | + })) |
| 219 | + defer fake.Close() |
| 220 | + |
| 221 | + p, _ := New(&config.AIConfig{Enabled: true, BaseURL: fake.URL, Model: "m"}) |
| 222 | + _, err := p.Complete(context.Background(), Request{Messages: []Message{{Role: "user", Content: "hi"}}}) |
| 223 | + if err == nil || !strings.Contains(err.Error(), "invalid api key") || !strings.Contains(err.Error(), "401") { |
| 224 | + t.Errorf("err = %v, want provider message and status", err) |
| 225 | + } |
| 226 | +} |
| 227 | + |
| 228 | +func TestBuildAssistMessagesTruncates(t *testing.T) { |
| 229 | + long := strings.Repeat("x", contextBudget*2) |
| 230 | + intent, ok := GetIntent("diagnose") |
| 231 | + if !ok { |
| 232 | + t.Fatal("diagnose intent missing") |
| 233 | + } |
| 234 | + msgs := BuildAssistMessages(intent, "deployment myapp", []Section{ |
| 235 | + {Label: "docker-compose.yml", Content: "services: {}", Format: "yaml"}, |
| 236 | + {Label: "Recent logs", Content: long}, |
| 237 | + }, "why does it crash?", "https://flatrun.dev/docs/") |
| 238 | + |
| 239 | + if len(msgs) != 2 { |
| 240 | + t.Fatalf("got %d messages", len(msgs)) |
| 241 | + } |
| 242 | + if msgs[0].Role != "system" || msgs[1].Role != "user" { |
| 243 | + t.Errorf("roles = %s/%s", msgs[0].Role, msgs[1].Role) |
| 244 | + } |
| 245 | + if len(msgs[1].Content) > contextBudget+2000 { |
| 246 | + t.Errorf("user message not truncated: %d chars", len(msgs[1].Content)) |
| 247 | + } |
| 248 | + if !strings.Contains(msgs[1].Content, "[... truncated ...]") { |
| 249 | + t.Error("truncation marker missing") |
| 250 | + } |
| 251 | + if !strings.Contains(msgs[1].Content, strings.Repeat("x", 100)) { |
| 252 | + t.Error("log tail missing from prompt") |
| 253 | + } |
| 254 | + if !strings.Contains(msgs[1].Content, "why does it crash?") { |
| 255 | + t.Error("operator question missing from prompt") |
| 256 | + } |
| 257 | + if !strings.Contains(msgs[1].Content, "deployment myapp") { |
| 258 | + t.Error("scope label missing from prompt") |
| 259 | + } |
| 260 | + if !strings.Contains(msgs[0].Content, "https://flatrun.dev/docs/") { |
| 261 | + t.Error("docs link missing from system prompt") |
| 262 | + } |
| 263 | +} |
| 264 | + |
| 265 | +func TestIntentRegistry(t *testing.T) { |
| 266 | + for _, key := range []string{"diagnose", "improve", "secure", "explain"} { |
| 267 | + intent, ok := GetIntent(key) |
| 268 | + if !ok { |
| 269 | + t.Errorf("intent %q missing", key) |
| 270 | + continue |
| 271 | + } |
| 272 | + msgs := BuildAssistMessages(intent, "the FlatRun host", []Section{{Label: "Output", Content: "boom"}}, "", "") |
| 273 | + hasSuggestionFormat := strings.Contains(msgs[0].Content, "suggestions") |
| 274 | + if intent.AllowSuggestions && !hasSuggestionFormat { |
| 275 | + t.Errorf("intent %q should request suggestions", key) |
| 276 | + } |
| 277 | + if !intent.AllowSuggestions && hasSuggestionFormat { |
| 278 | + t.Errorf("intent %q should not request suggestions", key) |
| 279 | + } |
| 280 | + } |
| 281 | + if _, ok := GetIntent("nonsense"); ok { |
| 282 | + t.Error("unknown intent should not resolve") |
| 283 | + } |
| 284 | +} |
0 commit comments