diff --git a/CHANGELOG.md b/CHANGELOG.md index bb4a5f27..f92204c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,7 @@ All notable changes to this project are documented in this file. The format is b - **Custom-tool placeholders are substituted once**: `renderTemplate` replaces each `{name}` in the original template only. A value that itself contains `{other}` stays text, including after shell quoting, and an unknown placeholder is left as written. - **Traffic host delete leaves the store directories in place**: a requested host whose sanitized name is `_index`, `_blobs`, `_ca`, `_delete_staging`, `.`, or `..` is not used as a directory. Those paths are the capture index, the blob store, the MITM CA, the delete staging area, or the traffic directory itself. Index rows for that host are still removed. - **Asset insert applies the JSON body cap**: `POST /api/assets` decodes through the shared JSON limit, including a `multipart/` request that the upload middleware leaves uncapped. A body over the cap is rejected before the database is touched. +- **The LLM connection test honours the output-cap field name**: `POST /api/llm/test` never read a profile's `max_tokens_field`, so the Test button always sent the cap as `max_tokens`. An OpenAI reasoning model (o-series, GPT-5) rejects that with `unsupported_parameter` and a 400, so a profile set to `max_completion_tokens` failed the test even though conversations with it worked. The test now resolves the field from the form, falling back to the stored profile for the list-view test button, and normalises it the same way a profile save does (only the openai format with `max_completion_tokens` is kept). - **The LLM connection test sends no tools**: the test passes an empty tool list, but the agent SDK still added its background-task tools (`TaskOutput`, `TaskStop`, `TaskList`, `Monitor`), so some models answered with a call to one of them or with tool-like text instead of `OK`, and a local reasoning model could spend the whole 30-second budget deciding whether to use them. The test now turns those tools off, the same way goal decomposition does (#526). - **Missing Docker buildx is reported before the build**: without the buildx plugin, Compose only warns and falls back to the legacy builder, which fails on the Dockerfile's first `FROM --platform=$BUILDPLATFORM` with `failed to parse platform`. `install.sh` (all-Docker) and `update.sh` (Docker update) now check `docker buildx version` first and stop with an install hint, and the automatic Docker install on apt-based distros not covered by get.docker.com installs the buildx package as well. The README Docker section names buildx as a requirement. - **A goal URL followed by punctuation is still seeded**: a goal such as `Assess http://juiceshop:3000.` no longer logs `could not parse a target host/IP` and skips the site. Trailing punctuation, including full-width `。` and a closing bracket that has no matching opener, is trimmed from the URL before it is parsed, so `http://[::1]` is left alone. The scheme the goal names is kept and a final period does not end up in the host. diff --git a/server/llm_test_max_tokens_field_test.go b/server/llm_test_max_tokens_field_test.go new file mode 100644 index 00000000..b515a0a6 --- /dev/null +++ b/server/llm_test_max_tokens_field_test.go @@ -0,0 +1,125 @@ +package server + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "sync" + "testing" + + "github.com/Autumn-27/artex/db" +) + +// The llm/test button must send the output cap under the key the profile is +// configured with. OpenAI reasoning models reject max_tokens with +// unsupported_parameter, so a profile set to max_completion_tokens used to fail +// the connection test with a 400 while conversations with it worked. +func TestLLMTestHonorsMaxTokensField(t *testing.T) { + skipWithoutDSN(t) + m, err := NewManager(t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { m.Close() }) + if m.pg == nil { + db.SkipNoPG(t) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir()) + + var mu sync.Mutex + var lastBody map[string]any + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + var body map[string]any + _ = json.Unmarshal(raw, &body) + mu.Lock() + lastBody = body + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"c","object":"chat.completion","model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"OK"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`)) + })) + t.Cleanup(fake.Close) + + pid, err := m.pg.SaveProfile(&db.LLMProfile{ + Name: "mct-field", Format: "openai", Model: "gpt-x", + BaseURL: fake.URL, APIKey: "k1", MaxTokensField: "max_completion_tokens", + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _, _ = m.pg.Exec("DELETE FROM llm_profiles WHERE id=$1", pid) }) + + run := func(t *testing.T, form map[string]any) map[string]any { + t.Helper() + mu.Lock() + lastBody = nil + mu.Unlock() + body, _ := json.Marshal(form) + req := httptest.NewRequest(http.MethodPost, "/api/llm/test", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + s.testLLM(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("handler status %d: %s", rec.Code, rec.Body.String()) + } + mu.Lock() + defer mu.Unlock() + if lastBody == nil { + t.Fatalf("the test request never reached the endpoint: %s", rec.Body.String()) + } + return lastBody + } + wantKey := func(t *testing.T, body map[string]any, want, absent string) { + t.Helper() + if _, ok := body[want]; !ok { + t.Fatalf("request must carry %q, body keys: %v", want, bodyKeys(body)) + } + if _, ok := body[absent]; ok { + t.Fatalf("request must not carry %q, body keys: %v", absent, bodyKeys(body)) + } + } + + t.Run("form value", func(t *testing.T) { + body := run(t, map[string]any{ + "provider": "openai", "model": "gpt-x", "base_url": fake.URL, + "api_key": "k1", "streaming": false, "max_tokens_field": "max_completion_tokens", + }) + wantKey(t, body, "max_completion_tokens", "max_tokens") + }) + + t.Run("stored profile fallback", func(t *testing.T) { + // List-view test button: only the profile id, the field comes from the row. + body := run(t, map[string]any{"profile_id": pid, "api_key": "", "streaming": false}) + wantKey(t, body, "max_completion_tokens", "max_tokens") + }) + + t.Run("form override to default", func(t *testing.T) { + // An explicit empty value in the form wins over the stored choice. + body := run(t, map[string]any{ + "provider": "openai", "model": "gpt-x", "base_url": fake.URL, + "api_key": "", "profile_id": pid, "streaming": false, "max_tokens_field": "", + }) + wantKey(t, body, "max_tokens", "max_completion_tokens") + }) + + t.Run("unknown value falls back to default", func(t *testing.T) { + body := run(t, map[string]any{ + "provider": "openai", "model": "gpt-x", "base_url": fake.URL, + "api_key": "k1", "streaming": false, "max_tokens_field": "bogus", + }) + wantKey(t, body, "max_tokens", "max_completion_tokens") + }) +} + +func bodyKeys(m map[string]any) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + return out +} diff --git a/server/server.go b/server/server.go index 4b846d09..662b8835 100644 --- a/server/server.go +++ b/server/server.go @@ -1593,6 +1593,9 @@ func (s *Server) testLLM(w http.ResponseWriter, r *http.Request) { SessionHeaderKey string `json:"session_header_key"` // non-empty = the test also sends this custom session header, with a one-off random session id as the value UserAgent string `json:"user_agent"` // non-empty = the test overrides the User-Agent header with this value (mirrors production) CustomHeaders string `json:"custom_headers"` + // Which request key carries the output cap (openai format only): "" = max_tokens, + // "max_completion_tokens" = the newer key. Omitted (nil) = the stored profile's choice. + MaxTokensField *string `json:"max_tokens_field"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { writeErr(w, 400, err.Error()) @@ -1651,6 +1654,18 @@ func (s *Server) testLLM(w http.ResponseWriter, r *http.Request) { if req.Streaming != nil { cfg.Stream = *req.Streaming } + // The output-cap key follows the profile as well: OpenAI reasoning models reject + // max_tokens with unsupported_parameter, so a profile set to max_completion_tokens + // must be tested with that key, or the test 400s while conversations would work. + // Same normalization as saving a profile: only openai + the known value survives. + if req.MaxTokensField != nil { + cfg.MaxTokensField = strings.TrimSpace(*req.MaxTokensField) + } else if stored != nil { + cfg.MaxTokensField = stored.MaxTokensField + } + if cfg.Format != llm.FormatOpenAI || cfg.MaxTokensField != llm.MaxTokensFieldCompletion { + cfg.MaxTokensField = "" + } // The custom session header name follows that profile too: when non-empty, the test request also sends it (value is a one-off random session id, // see TestConnection). Endpoints like opencode zen that mandate x-opencode-session return // 400 without it, so the test path must send it too — otherwise "chat works, test 400s". diff --git a/web/src/app/(main)/system/llm/page.tsx b/web/src/app/(main)/system/llm/page.tsx index 224dd66a..bf263022 100644 --- a/web/src/app/(main)/system/llm/page.tsx +++ b/web/src/app/(main)/system/llm/page.tsx @@ -456,6 +456,8 @@ function ProfileSheet({ sessionHeaderKey.trim(), userAgent.trim(), customHeaders, + // Test with the output-cap key the profile would actually send (OpenAI reasoning models reject max_tokens). + format === "openai" ? toStore(maxTokensField) : "", ); // Show the reply too: only when the model demonstrably spoke is this the same as working inside a session. if (r.ok) diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index c4512ea4..801e9d0b 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -1159,6 +1159,7 @@ export const api = { session_header_key = "", // non-empty = the test request also carries this custom session header (value is a one-off session id) user_agent = "", // non-empty = the test overrides the User-Agent header with this value custom_headers = "", + max_tokens_field?: string, // ""=max_tokens | "max_completion_tokens"; omitted = the stored profile's choice ) => // reply = the model's actual reply (truncated); the backend marks a profile that replies with nothing as failed post<{ ok: boolean; error?: string; latency_ms?: number; model?: string; reply?: string }>("/llm/test", { @@ -1174,6 +1175,7 @@ export const api = { session_header_key, user_agent, custom_headers, + max_tokens_field, }), llmProfiles: () => get<{ profiles: LLMProfile[] }>("/llm/profiles").then((r) => arr(r.profiles)), saveLLMProfile: (p: {