Files
magpie/internal/provider/codex_models_test.go
T
yetone 70ad7cf30f provider: an OpenAI key's GPT-6 Astra and Sol can go Ultrafast, on its Responses (OoopsHh on X)
OoopsHh on X: in Docker, an OpenAI API provider's GPT-6 Astra offered
Standard and Fast only, in the model's speed, in routing groups and in
the Agents settings. Every Ultrafast offer came from a Codex account's or
Codex CLI's list, which a Docker magpie with an API key has none of, and
buildResponses sent "ultrafast" to chatgpt.com alone.

OpenAI's Ultrafast mode guide
(developers.openai.com/api/docs/guides/ultrafast-mode) names GPT-6.2
Astra, GPT-6.2 Sol, GPT-6 Astra and GPT-6.1 Sol, with service_tier
"ultrafast" on the Responses API. provider.OpenAIUltra holds those four
(a dated snapshot too). UltraOn offers Ultrafast for them on an OpenAI
key's Responses, and on a provider added by its address (OwnFast) with no
Codex cache; the GUI's three speed controls read UltraOn
(providers.go canUltra, groups.go ultraOK, agent route UltraOK), so no
GUI asset changed. buildResponses sends the tier to api.openai.com for
those models only (any other goes priority, as before). OpenAI's Chat
Completions turns the tier away on every model, so a Chat request to
api.openai.com that would carry it, a client's own ask too, goes priority
(chatNoUltra, in the tierMate check). Another vendor's model is untouched.

The Codex subscription half (Docker asked the ChatGPT list as 0.159.0,
below the 0.166.0 that lists GPT-6.2 and Ultrafast) was fixed meanwhile
on main by e1c186cfe (0.169.1 and npm's latest);
TestCodexFallbackListsUltrafast keeps the fallback at or above 0.166.0.

Real requests (11-18, magpie's own keys, nothing printed):
- api.openai.com /v1/responses, service_tier ultrafast: gpt-6-astra,
  gpt-6.1-sol, gpt-6.2-astra, gpt-6.2-sol passed validation and stopped
  at 429 billing_not_active (the key's billing is off, so a served
  ultrafast reply was not seen); gpt-6-sol and gpt-6.1-terra answered 400
  "Invalid service_tier argument".
- /v1/chat/completions with ultrafast: 400 "Invalid service_tier
  argument" on every model; with priority, accepted up to billing.
- ChatGPT backend (a real Codex account), service_tier ultrafast:
  gpt-6.2-sol and gpt-6-astra as 0.170.0 answered 200 (the reply said
  service_tier default); as 0.159.0, gpt-6.2-sol was refused as not
  supported. Its models list as 0.166.0+ lists gpt-6.2-sol with
  priority and ultrafast; as 0.165.0 and before, no ultrafast anywhere.

Tests: TestOpenAIKeyUltrafast (Responses and Claude's API to an OpenAI
key's gpt-6-astra send ultrafast on /v1/responses; Chat goes priority;
gpt-6-sol can't be picked Ultrafast; another agent goes standard; an
Anthropic key's Claude has no Ultrafast and keeps speed "fast"),
TestCanUltraOwnProvider (OpenAI key and relay with no cache; gpt-6-sol,
gpt-6.1-mini, Claude false; OpenAIUltra's prefix, case and dated forms).

Broken by hand, each red: buildResponses without the api.openai.com
case (TestOpenAIKeyUltrafast sent priority); without chatNoUltra (Chat
sent ultrafast); UltraOn without the OpenAI branches
(TestCanUltraOwnProvider false for oa/gpt-6.1-sol).

Run on mica at 888847666 (this change on origin/main dc507aefd, after
e08dc0fe5 put api.openai.com's Responses on the WebSocket; pushed on
5cf1d3846, a sessions/GUI change after it, not run with this):
go test -count=1 -timeout 45m ./...: 101 packages ok, internal/gateway
included; red were internal/dirent's watch tests (#7031; dirent imports
only testenv, red alone on mica too) and TestGatewayModeListsNoOwnSessions
(#7064, ok run alone); the same at c7060224b. An earlier run at 2d1545833 (on d74754970) had
those plus TestImageMCPKeepsDrawingsOffTheHeap (#6890, ok alone).
Targeted internal/provider and internal/gateway Ultra/Fast/Tier runs on
mote: ok.
go vet on darwin, GOOS=linux and GOOS=windows for internal/provider and
internal/gateway: ok. gofmt -l: clean.

Not tried: a served ultrafast reply from api.openai.com (no key with
active billing), the Docker image itself, and the GUI suite (no asset
changed; the controls read the same canUltra/ultraOK fields their GUI
tests cover).
2026-11-18 21:20:35 +08:00

313 lines
12 KiB
Go

package provider
import (
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/testenv"
)
// A ChatGPT account lists the models of its own plan, asked with its own
// token; the cache Codex CLI keeps may be another account's.
func TestCodexModelsOfTheAccount(t *testing.T) {
signIn(t)
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/backend-api/codex/models" || r.Header.Get("chatgpt-account-id") != "acct-1" || r.URL.Query().Get("client_version") == "" {
w.WriteHeader(400)
return
}
w.Write([]byte(`{"models": [
{"slug": "gpt-5.6-luna", "display_name": "GPT-5.6 Luna", "visibility": "list", "priority": 2,
"supported_reasoning_levels": [{"effort": "low"}, {"effort": "medium"}]},
{"slug": "codex-auto-review", "visibility": "hide", "priority": 1}]}`))
}))
defer fake.Close()
old := CodexBase
CodexBase = fake.URL + "/backend-api/codex"
t.Cleanup(func() { CodexBase = old })
p, ok := find(All(), "codex")
if !ok {
t.Fatal("no codex account")
}
if ms := p.Available(); len(ms) != 1 || ms[0].ID != "gpt-5.5" {
t.Fatalf("before fetching, Codex CLI's cache: %+v", ms)
}
if _, err := p.Fetch(context.Background()); err != nil {
t.Fatal(err)
}
ms := p.Available()
if len(ms) != 1 || ms[0].ID != "gpt-5.6-luna" || len(ms[0].Efforts) != 2 {
t.Fatalf("after fetching: %+v", ms)
}
}
// The models list is asked for with the newest Codex known: the CLI
// installed over the version its cache was written with.
func TestCodexVersion(t *testing.T) {
shellFakes(t)
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
writeFile(t, filepath.Join(home, ".codex", "models_cache.json"), map[string]any{"client_version": "0.170.0"})
exe := filepath.Join(t.TempDir(), "codex")
testenv.Program(t, exe, "#!/bin/sh\necho codex-cli 0.171.1\n")
old := codexExecutable
t.Cleanup(func() { codexExecutable = old; codexVersionCache.at = time.Time{}; codexSeen = seenVersion{} })
codexSeen = seenVersion{}
for _, c := range []struct{ exe, want string }{{exe, "0.171.1"}, {"", "0.170.0"}} {
codexExecutable = func() string { return c.exe }
codexVersionCache.at = time.Time{}
if got := codexVersion(); got != c.want {
t.Errorf("with %q: %s, want %s", c.exe, got, c.want)
}
}
// Codex CLI's state under CODEX_HOME, when that is set
t.Setenv("CODEX_HOME", t.TempDir())
codexVersionCache.at = time.Time{}
if got := codexVersion(); got != codexClientVersion {
t.Errorf("CODEX_HOME with no cache: %s", got)
}
writeFile(t, filepath.Join(os.Getenv("CODEX_HOME"), "models_cache.json"), map[string]any{"client_version": "0.170.2"})
codexVersionCache.at = time.Time{}
if got := codexVersion(); got != "0.170.2" {
t.Errorf("CODEX_HOME's cache: %s", got)
}
}
// A Codex that came through the gateway newer than any magpie can find
// counts at once, the cached lookup notwithstanding: the account's model
// list is asked for as that Codex, and its turns say they are it. Only
// Codex's requests count, and never an older version.
func TestCodexVersionSeen(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", t.TempDir())
t.Setenv("CODEX_HOME", "")
old := codexExecutable
codexExecutable = func() string { return "" }
codexSeen = seenVersion{}
codexVersionCache.at = time.Time{}
t.Cleanup(func() { codexExecutable = old; codexVersionCache.at = time.Time{}; codexSeen = seenVersion{} })
if got := codexVersion(); got != codexClientVersion {
t.Fatalf("nothing seen: %s", got)
}
h := func(kv ...string) http.Header {
out := http.Header{}
for i := 0; i < len(kv); i += 2 {
out.Set(kv[i], kv[i+1])
}
return out
}
for _, c := range []struct {
h http.Header
want string
}{
{h("User-Agent", "claude-cli/2.1.300 (external, cli)"), codexClientVersion},
{h("User-Agent", "Mozilla/5.0", "version", "9.9.9"), codexClientVersion},
{h("User-Agent", "codex_cli_rs/0.170.0 (Mac OS 26.6.0; arm64) ghostty/1.2.0"), "0.170.0"},
{h("User-Agent", "Codex Desktop/0.172.3 (Windows 10.0.26100; x86_64) unknown", "originator", "Codex Desktop"), "0.172.3"},
{h("User-Agent", "codex_cli_rs/0.150.0", "version", "0.150.0"), "0.172.3"},
} {
SawCodexClient(c.h)
if got := codexVersion(); got != c.want {
t.Fatalf("after %v: %s, want %s", c.h, got, c.want)
}
}
var asked, ua, ver string
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
asked, ua, ver = r.URL.Query().Get("client_version"), r.Header.Get("User-Agent"), r.Header.Get("version")
w.Write([]byte(`{"models":[{"slug":"gpt-6.1-sol","visibility":"list"}]}`))
}))
defer fake.Close()
was := CodexBase
CodexBase = fake.URL + "/backend-api/codex"
t.Cleanup(func() { CodexBase = was })
sign := codexSign(func(context.Context) (string, string, error) { return "tok", "acct-1", nil })
if _, err := codexModels(context.Background(), sign); err != nil {
t.Fatal(err)
}
if asked != "0.172.3" || !strings.HasPrefix(ua, "codex_cli_rs/0.172.3 (") || ver != "0.172.3" {
t.Fatalf("models asked as client_version %q, User-Agent %q, version %q", asked, ua, ver)
}
}
// With no Codex CLI here, or an older one, the models list is still asked
// for as a Codex new enough for every model the account has: GPT-6.2 Sol
// and Astra, listed to 0.166.0 and later only, were never offered at the
// 0.159.0 magpie asked as (zzstar101 and m0eaki on X). npm's latest
// counts once read, and only a release version of it.
func TestCodexVersionPublished(t *testing.T) {
if compareClaudeVersion(codexClientVersion, "0.166.0") < 0 {
t.Fatalf("codexClientVersion %s is older than GPT-6.2's minimal_client_version 0.166.0", codexClientVersion)
}
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", t.TempDir())
t.Setenv("CODEX_HOME", "")
old, oldURL := codexExecutable, codexNpmLatest
codexExecutable = func() string { return "" }
reset := func() {
codexPublishedCache.Lock()
codexPublishedCache.v, codexPublishedCache.at = "", time.Time{}
codexPublishedCache.Unlock()
codexVersionCache.at = time.Time{}
codexSeen = seenVersion{}
}
t.Cleanup(func() { codexExecutable, codexNpmLatest = old, oldURL; reset() })
reset()
if got := codexVersion(); got != codexClientVersion {
t.Fatalf("a test binary asked npm: %s", got)
}
// a request an older Codex sent goes on saying the floor, in its
// version header and its User-Agent ("请求头版本太低了", zzstar101)
req := httptest.NewRequest(http.MethodPost, "https://chatgpt.com/backend-api/codex/responses", nil)
req.Header.Set("version", "0.159.0")
req.Header.Set("User-Agent", "codex_cli_rs/0.159.0 (Mac OS 26.2.0; arm64)")
sign := codexSign(func(context.Context) (string, string, error) { return "tok", "acct-1", nil })
if err := sign(context.Background(), req, []byte(`{}`)); err != nil {
t.Fatal(err)
}
if v, ua := req.Header.Get("version"), req.Header.Get("User-Agent"); v != codexClientVersion || !strings.Contains(ua, "/"+codexClientVersion+" (") {
t.Fatalf("an old Codex's request went as version %q, User-Agent %q", v, ua)
}
var answer string
var asks atomic.Int32
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
asks.Add(1)
w.Write([]byte(answer))
}))
defer fake.Close()
codexNpmLatest = fake.URL + "/@openai/codex/latest"
for _, c := range []struct{ answer, want string }{
{`{"name":"@openai/codex","version":"9.1.0"}`, "9.1.0"},
{`{"version":"9.2.0-alpha.3"}`, codexClientVersion},
{`{"version":"0.100.0"}`, codexClientVersion},
{`<html>`, codexClientVersion},
} {
reset()
answer = c.answer
asks.Store(0)
codexVersion() // asks in the background
deadline := time.Now().Add(10 * time.Second)
for {
codexPublishedCache.Lock()
done := !codexPublishedCache.at.IsZero() && !codexPublishedCache.asking
codexPublishedCache.Unlock()
if done {
break
}
if time.Now().After(deadline) {
t.Fatalf("%s: npm's answer was never read", c.answer)
}
time.Sleep(5 * time.Millisecond)
}
if got := codexVersion(); got != c.want {
t.Errorf("npm said %s: %s, want %s", c.answer, got, c.want)
}
if n := asks.Load(); n != 1 {
t.Errorf("npm said %s: asked %d times", c.answer, n)
}
}
}
// Codex CLI installed where a desktop app's PATH doesn't reach — under an
// nvm Node, or an npm prefix ~/.npmrc names — is found.
func TestCodexExecutableOffPath(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("unix install locations")
}
for name, dir := range map[string]string{
"nvm": ".nvm/versions/node/v22.3.0/bin",
"mise": ".local/share/mise/installs/node/24.14.0/bin",
"npm prefix": "custom-npm/bin",
} {
t.Run(name, func(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("PATH", "/usr/bin:/bin")
os.WriteFile(filepath.Join(home, ".npmrc"), []byte("registry=https://registry.npmjs.org/\nprefix = ~/custom-npm\n"), 0o644)
exe := filepath.Join(home, dir, "codex")
os.MkdirAll(filepath.Dir(exe), 0o755)
testenv.Program(t, exe, "#!/bin/sh\necho codex-cli 0.161.0\n")
if got := codexExecutable(); got != exe {
t.Fatalf("found %q, want %q", got, exe)
}
})
}
}
// A model that takes more than its window when asked keeps that most, so
// the context field can offer it: GPT-6's 872K over the 272K said.
func TestCodexModelsMaxContext(t *testing.T) {
ms := parseCodexModels([]byte(`{"models":[
{"slug":"gpt-6","context_window":272000,"max_context_window":872000},
{"slug":"gpt-5.5","context_window":272000,"max_context_window":272000}]}`))
if len(ms) != 2 || ms[0].Context != 272000 || ms[0].MaxContext != 872000 || ms[1].MaxContext != 0 {
t.Fatalf("%+v", ms)
}
}
// A codex CLI that fails to run — macOS stopping it as malware, with an
// alert each time (#864) — isn't run again every ten minutes, and an npm
// install's version is read from its package, not run.
func TestCodexVersionNotRerun(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("shell scripts")
}
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("CODEX_HOME", "")
dir := t.TempDir()
runs := filepath.Join(dir, "runs")
exe := filepath.Join(dir, "codex")
testenv.Program(t, exe, "#!/bin/sh\necho x >> '"+runs+"'\nexit 137\n")
old := codexExecutable
t.Cleanup(func() { codexExecutable = old; codexVersionCache.at = time.Time{}; codexSeen = seenVersion{} })
codexSeen = seenVersion{}
codexExecutable = func() string { return exe }
for range 3 { // ten minutes apart
codexVersionCache.at = time.Time{}
if got := codexVersion(); got != codexClientVersion {
t.Fatalf("got %s", got)
}
}
if b, _ := os.ReadFile(runs); strings.Count(string(b), "x") != 1 {
t.Fatalf("the failing codex was run %d times", strings.Count(string(b), "x"))
}
pkg := filepath.Join(dir, "node_modules", "@openai", "codex")
os.MkdirAll(filepath.Join(pkg, "bin"), 0o755)
os.WriteFile(filepath.Join(pkg, "package.json"), []byte(`{"version":"0.199.0"}`), 0o644)
testenv.Program(t, filepath.Join(pkg, "bin", "codex.js"), "#!/bin/sh\necho x >> '"+runs+"'\necho codex-cli 0.199.0\n")
link := filepath.Join(dir, "bin", "codex")
os.MkdirAll(filepath.Dir(link), 0o755)
os.Symlink(filepath.Join(pkg, "bin", "codex.js"), link)
codexExecutable = func() string { return link }
codexVersionCache.at = time.Time{}
if got := codexVersion(); got != "0.199.0" {
t.Fatalf("npm codex: %s", got)
}
if b, _ := os.ReadFile(runs); strings.Count(string(b), "x") != 1 {
t.Fatal("the npm codex was run")
}
}
// A magpie with no Codex to ask (in Docker: OoopsHh on X) asks for an
// account's models as a Codex the ChatGPT backend lists GPT-6.2 and
// Ultrafast to, which it does from 0.166.0 on.
func TestCodexFallbackListsUltrafast(t *testing.T) {
if newerVersion(codexClientVersion, "0.166.0") != codexClientVersion {
t.Fatalf("models asked for as Codex %s, which is listed no Ultrafast", codexClientVersion)
}
}