From 8e3d17136e314c0fda5f8329ef9671ae5ac2dc2b Mon Sep 17 00:00:00 2001 From: GabriMarch3 Date: Thu, 26 Nov 2026 12:54:04 +0100 Subject: [PATCH 1/3] fix(llm): honor max_tokens_field in the connection test The Test button on System -> LLM always sent the output cap as max_tokens, because POST /api/llm/test never read the profile's max_tokens_field. OpenAI reasoning models (o-series, GPT-5) reject max_tokens with unsupported_parameter, so a profile set to max_completion_tokens failed the test with HTTP 400 while conversations with the same profile worked. testLLM now accepts max_tokens_field from the form and falls back to the stored profile's value when the field is omitted (list-view test). It is normalized like profile saves: only the openai format with max_completion_tokens keeps it. The form passes its current selection. Co-Authored-By: Claude Opus 5.5 --- server/llm_test_max_tokens_field_test.go | 125 +++++++++++++++++++++++ server/server.go | 15 +++ web/src/app/(main)/system/llm/page.tsx | 2 + web/src/lib/api.ts | 2 + 4 files changed, 144 insertions(+) create mode 100644 server/llm_test_max_tokens_field_test.go 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 d2d85f57..933655fa 100644 --- a/server/server.go +++ b/server/server.go @@ -1583,6 +1583,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()) @@ -1641,6 +1644,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 52ac7c9d..5363127b 100644 --- a/web/src/app/(main)/system/llm/page.tsx +++ b/web/src/app/(main)/system/llm/page.tsx @@ -449,6 +449,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 7a1035c0..afa93039 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -1145,6 +1145,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", { @@ -1160,6 +1161,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: { From 823fb27becaa28bdd9a26d2242a4d6eff0f65f3e Mon Sep 17 00:00:00 2001 From: GabriMarch3 Date: Thu, 26 Nov 2026 17:10:33 +0100 Subject: [PATCH 2/3] docs(changelog): note the llm connection-test max_tokens_field fix Co-Authored-By: Claude Opus 4.8 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f46c990..17878955 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ All notable changes to this project are documented in this file. The format is b ### Fixed +- **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). - **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. - **Task timeout triggers fire for every task**: `on_task_timeout` used the task id as a watermark, but tasks time out in deadline order. Once a newer task timed out first, an older task that timed out later was never fired for. Fired timeouts are now kept in a persisted set, like met goals; on first start the set is seeded with the tasks already timed out, so nothing replays. From 1d1471ed42e76eeff48f121877327fcd58a2c237 Mon Sep 17 00:00:00 2001 From: BaaRai <130491490+BaaRai@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:40:10 +0100 Subject: [PATCH 3/3] synthetic main: +#558 --- CHANGELOG.md | 1 + server/assets.go | 17 +++++++++++------ server/decode_limit_test.go | 21 +++++++++++++++++++++ 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bf0554a5..bb4a5f27 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,7 @@ All notable changes to this project are documented in this file. The format is b - **The `traffic_search` host example no longer names a real IP**: the tool description shown to the model used a routable third-party address; it now uses `192.0.2.10` (RFC 5737). - **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 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/assets.go b/server/assets.go index 2d7a7597..043d33a3 100644 --- a/server/assets.go +++ b/server/assets.go @@ -477,11 +477,6 @@ func (s *Server) deleteAssets(w http.ResponseWriter, r *http.Request) { // ===================================================================== func (s *Server) insertAssets(w http.ResponseWriter, r *http.Request) { - as := s.assetStore() - if as == nil { - writeErr(w, 503, "database unavailable") - return - } var req struct { TaskID int64 `json:"task_id"` Assets []struct { @@ -518,10 +513,20 @@ func (s *Server) insertAssets(w http.ResponseWriter, r *http.Request) { Params []map[string]any `json:"params"` } `json:"assets"` } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + if err := decode(w, r, &req); err != nil { + var tooLarge *http.MaxBytesError + if errors.As(err, &tooLarge) { + writeErr(w, http.StatusRequestEntityTooLarge, "Request body too large") + return + } writeErr(w, 400, "invalid JSON: "+err.Error()) return } + as := s.assetStore() + if as == nil { + writeErr(w, 503, "database unavailable") + return + } type result struct { Index int `json:"index"` diff --git a/server/decode_limit_test.go b/server/decode_limit_test.go index 3d827809..702da5c0 100644 --- a/server/decode_limit_test.go +++ b/server/decode_limit_test.go @@ -89,6 +89,27 @@ func (zeroReader) Read(p []byte) (int, error) { return len(p), nil } +func TestInsertAssetsCapsMultipartBody(t *testing.T) { + s := &Server{m: &Manager{}} + h := limitRequestBody(http.HandlerFunc(s.insertAssets)) + + large := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/assets", strings.NewReader(`{"assets":[{"type":"`+strings.Repeat("a", decodeMaxBytes)+`"}]}`)) + req.Header.Set("Content-Type", "multipart/form-data; boundary=abc") + h.ServeHTTP(large, req) + if large.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("status=%d body=%s, want 413", large.Code, large.Body.String()) + } + + small := httptest.NewRecorder() + ok := httptest.NewRequest(http.MethodPost, "/api/assets", strings.NewReader(`{"assets":[]}`)) + ok.Header.Set("Content-Type", "multipart/form-data; boundary=abc") + h.ServeHTTP(small, ok) + if small.Code != http.StatusServiceUnavailable { + t.Fatalf("status=%d body=%s, want 503 without a store", small.Code, small.Body.String()) + } +} + func TestMultipartBodyIsNotGivenTheJSONCap(t *testing.T) { h := limitRequestBody(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if _, ok := r.Body.(*limitedBody); ok {