Files
magpie/internal/gateway/codex_effort_change_test.go
T
ggbdpq 6f041c292c gateway: a Codex compaction relayed to a vendor that isn't OpenAI's asks as system, not developer (#2955)
forVendor, the fitting a relayed Responses request gets before it goes to
a provider that isn't OpenAI's, now turns the developer messages of a
summary ask magpie made itself (codexCompact) into system ones, where
they stand (developerItemsAsSystem). Codex's own turns keep the role the
client sent, which a relay may be checking them by (#350, #1758), and
OpenAI's own API and the ChatGPT backend, which take developer as Codex
sends it, get the compaction as it came too.

Why: on a provider whose Responses endpoint fronts a chat-only vendor (a
relay of one; DeepSeek's preset names one base for chat and responses
alike), every Codex compaction failed there with 400 "developer is not
one of ['system', 'assistant', 'user', 'tool', 'function']", retried five
times, while the turns around it passed: the summary request is relayed
as Codex sent it (tools: [], #378), and the compaction carries a
developer message its turns don't. The translated route already lifts
such messages into the system prompt; the summary ask now says them as
system on the relayed route too, in place, so a thread's cached prefix
keeps its shape (#502) — what Zed's cloud is already given (ZedBody) and
what a Chat Completions upstream is given (developerAsSystem).

Run: TestCodexCompactDeveloperAsSystemOnAVendorRelay (red before, green
after; ablated and mutated), the compaction families (TestCodexCompact*,
TestLocalCompaction*, TestNativeCompaction*, TestVendorRelay*,
TestAdditionalTools*, TestCodexOpenAIFields*), the full gateway package,
-race over the families, go vet and go build of the package on darwin,
linux and windows.

Refs #2955

Landing record (yetone):
Run at the pushed batch head (tree a6b084d0b, on origin/main 616405061),
go1.26.8:
- go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway,
internal/redact, internal/provider and internal/plugin (this batch's
packages and those main changed since the full run): all ok. gofmt -l
clean; go vet ./... (darwin), GOOS=linux and GOOS=windows go vet -tags
nogui ./... clean. internal/gui on macOS (mote-run):
TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestMainWindowCorners
(#3949), both red at main too.
- The full go test ./... -timeout 45m -count=1 ran one rebase earlier,
at tree 66a7a4c17 on origin/main 3a3bdb9f2 (main then gained 5bfa9f076's
group stand-in, b19d08593, f856d381a and 616405061). It ran on Linux
(wsl-run): 82 packages ok. internal/agent has 4 reds, all red at
origin/main on that box as well: TestInstalledVersion,
TestGrokInstalled, TestOmpDetectedWithPiDir and
TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, #3548). The root
package and internal/cli need gtk4 to build, so they ran on macOS
(mote-run): ok. TestColdTurnsTaken (#4510) was red there once. An
earlier full run at base d307aa648 was red once in
TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone at both
the head and main.
- Each landed patch's diff matches the head ggbdpq posted last on its
issue (patch-id).
- No GUI file is touched, so no GUI test file was run.
Broken by hand: developerItemsAsSystem made to return the body
unchanged: TestCodexCompactDeveloperAsSystemOnAVendorRelay goes red with
the fake vendor's 400 "developer is not one of"; restored, green.
Not tried: the reporter's vendor relay itself; the refusal is the fake
vendor's copy of its words.

Landing record (yetone):
Run at tree 7d7955eb9 (this batch on origin/main 3cfba2e37), go1.26.8:
- go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway,
internal/redact, internal/provider, internal/agent and internal/usage
(this batch's packages, plus those main changed since the full run): all
ok except internal/agent's TestInstalledVersion, TestGrokInstalled and
TestOmpDetectedWithPiDir, red at origin/main on that box too (#4033,
#3548). gofmt -l clean; go vet ./... (darwin), GOOS=linux and
GOOS=windows go vet -tags nogui ./... clean. On macOS (mote-run), the
root package and internal/cli ok; internal/gui red in
TestSettingsSaveKeepsWhatItDoesNotSend (#4514), TestMainWindowCorners
(#3949) and TestColdTurnsTaken (#4510), the first two red at main too.
- The full go test ./... -timeout 45m -count=1 ran two rebases earlier,
at tree 66a7a4c17 on origin/main 3a3bdb9f2, on Linux (wsl-run): 82
packages ok, internal/agent's 4 reds as above, plus
TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, red at main). The
root package, internal/cli and internal/gui need gtk4 to build, so they
ran on macOS as above. An earlier full run at base d307aa648 was red
once in TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone
at both the head and main.
- Each landed patch's diff matches the head ggbdpq posted last on its
issue (patch-id).
- No GUI file is touched, so no GUI test file was run.
- Rebased after these runs onto origin/main c1457f2ee. Its two commits
since 3cfba2e37 (3f2faef62 gui, c1457f2ee agent) touch neither
internal/gateway nor internal/redact, nor any file this batch changes,
and were not run again here.
Broken by hand: developerItemsAsSystem made to return the body
unchanged: TestCodexCompactDeveloperAsSystemOnAVendorRelay goes red with
the fake vendor's 400 "developer is not one of"; restored, green.
Not tried: the reporter's vendor relay itself; the refusal is the fake
vendor's copy of its words.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 06:38:00 +08:00

123 lines
5.1 KiB
Go

package gateway
import (
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// codexEffortChanged is a turn as Codex 0.162.1 sends it with its
// reasoning_effort_override feature on, after the thread, started at
// medium, was switched to xhigh (/model, Extra high, "s"): the top stays
// at medium and the change goes as a configuration_update after the
// user's message (captured from the real binary, its long developer
// messages and metadata left out; zzzkl3994 on Discord).
const codexEffortChanged = `{"model":"%s","stream":true,"tool_choice":"auto","parallel_tool_calls":false,"reasoning":{"effort":"medium","context":"all_turns"},"store":false,"include":["reasoning.encrypted_content"],"input":[` +
`{"type":"message","role":"user","content":[{"type":"input_text","text":"say ok"}]},` +
`{"type":"configuration_update","reasoning":{"effort":"medium"}},` +
`{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]},` +
`{"type":"message","role":"user","content":[{"type":"input_text","text":"again"}]},` +
`{"type":"configuration_update","reasoning":{"effort":"xhigh"}}]}`
func codexTurnAt(model string) string {
return strings.Replace(codexEffortChanged, "%s", model, 1)
}
// The effort a thread was switched to is the one Routing shows, and the
// one a Responses vendor that doesn't read the items is asked: it was
// shown, and sent, at the thread's first.
func TestCodexEffortChangeShownAndSent(t *testing.T) {
f := &fake{t: t, reply: sse(
`data: {"type":"response.created","response":{"id":"r1","model":"m1"}}`,
`data: {"type":"response.completed","response":{"id":"r1","output":[],"usage":{"input_tokens":5,"output_tokens":2}}}`)}
setup(t, provider.Responses, f)
s := New()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(codexTurnAt("fake/m1")))
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
r := lastRoute(s)
if r.Effort != "xhigh" || len(r.Tries) != 1 || r.Tries[0].Effort != "xhigh" {
t.Errorf("route at %q, tries %+v; want xhigh", r.Effort, r.Tries)
}
var got struct {
Reasoning map[string]any `json:"reasoning"`
Input []map[string]any `json:"input"`
}
json.Unmarshal(f.got, &got)
if got.Reasoning["effort"] != "xhigh" {
t.Errorf("sent reasoning %v, want xhigh", got.Reasoning)
}
for _, it := range got.Input {
if it["type"] == "configuration_update" {
t.Errorf("an update reached the vendor: %s", f.got)
}
}
}
// Translated to Chat, the turn is asked at the effort it was switched to.
func TestCodexEffortChangeReachesChatVendor(t *testing.T) {
f := &fake{t: t, reply: sse(
`data: {"id":"c1","model":"m1","choices":[{"delta":{"role":"assistant","content":"hi"}}]}`,
`data: {"id":"c1","choices":[{"delta":{},"finish_reason":"stop"}]}`,
`data: [DONE]`)}
setup(t, provider.Chat, f)
if code, body := post(t, "/v1/responses", codexTurnAt("fake/m1")); code != 200 {
t.Fatalf("status %d: %s", code, body)
}
var got map[string]any
json.Unmarshal(f.got, &got)
if got["reasoning_effort"] != "xhigh" {
t.Errorf("sent %s", f.got)
}
}
// What reads and rewrites a Responses request's effort reads and rewrites
// the last update; OpenAI's own API and the ChatGPT backend get the items
// as Codex sent them.
func TestCodexEffortChangeReaders(t *testing.T) {
body := []byte(codexTurnAt("gpt-6.1-sol"))
if e := requestEffort(provider.Responses, body); e != "xhigh" {
t.Errorf("requestEffort %q", e)
}
if e := requestEffort(provider.Responses, []byte(`{"reasoning":{"effort":"low"},"input":[{"type":"message","role":"user","content":"configuration_update"}]}`)); e != "low" {
t.Errorf("a message naming the item: %q", e)
}
if q, err := parseResponses(body); err != nil || q.Effort != "xhigh" {
t.Errorf("parsed at %q (%v)", q.Effort, err)
}
for _, p := range []provider.Provider{
{Responses: "https://api.openai.com/v1"},
{Responses: "https://chatgpt.com/backend-api/codex", Account: &provider.Account{Agent: "codex"}},
} {
if got := forVendor(p, body, false); string(got) != string(body) {
t.Errorf("%s: %s", p.Responses, got)
}
}
// magpie's own pick goes where the last change went; the top stays
picked := withEffort(provider.Responses, body, "high")
var q struct {
Reasoning map[string]any `json:"reasoning"`
Input []map[string]any `json:"input"`
}
json.Unmarshal(picked, &q)
last, _ := q.Input[len(q.Input)-1]["reasoning"].(map[string]any)
first, _ := q.Input[1]["reasoning"].(map[string]any)
if q.Reasoning["effort"] != "medium" || last["effort"] != "high" || first["effort"] != "medium" || bodyEffort(provider.Responses, picked) != "high" {
t.Errorf("picked high: %s", picked)
}
fixed := withFixedEffort(provider.Responses, body, "low")
if e := requestEffort(provider.Responses, fixed); e != "low" {
t.Errorf("fixed at low reads %q: %s", e, fixed)
}
if b := withoutAnyReasoning(provider.Responses, body); strings.Contains(string(b), "configuration_update") || strings.Contains(string(b), `"reasoning"`) {
t.Errorf("reasonless: %s", b)
}
}