Files
magpie/internal/gateway/codex_desktop_test.go
T
yetone fb2e11e288 agent: a Codex sign-in OpenAI refused to refresh for good counts as none (#4308)
jjt on Discord: Codex's ChatGPT sign-in was revoked, and magpie's
models were gone from Codex until they signed in again.

Cause: Codex keeps a revoked sign-in's auth.json as it was and remembers
the permanent refresh failure in memory alone (codex-rs
login/src/auth/manager.rs). magpie read auth.json alone
(codexChatGPTKnown), counted the sign-in and wired Codex beside it
(openai_base_url, requires_openai_auth). There, Codex's /models went to
the gateway, which passed OpenAI's 401 token_revoked through, so the
picker had no magpie model; and every turn, magpie's models too, failed
at Codex 0.162.1's workspace routing discovery
(/backend-api/wham/accounts/check, 401).

Change:
- provider: codexRefresh tells a refusal Codex takes as permanent
  (request_chatgpt_token_refresh: refresh_token_expired, _reused or
  _invalidated, a 400 invalid_grant, or a 401 - here only a 401 that
  carries an error code, read as oauth/error.rs reads it). When magpie's
  own refresh of Codex's sign-in (codexTokenRenewing, from the usage read
  that KeepOnAnAccountWithRoom runs) is refused that way, and the store
  still holds that refresh token, codex-signin-gone.json keeps the Codex
  home -> sha256 of the refused refresh token (no token stored). A
  successful refresh forgets it. Writes Touch the catalog so the agents
  resync; the loop's noteCodexGoneNow notices a sign-in made again
  elsewhere within minutes.
- agent: codexChatGPTKnown reads such a sign-in as none
  (provider.CodexSignInGone), as v0.1.2087 did for forced_login_method =
  "api": magpie is Codex's provider without requires_openai_auth, the
  user's auth.json stays. A record that can't be read is unknown (as
  magpie last wired it). Signing in again gives another refresh token,
  which the record doesn't name: Sync writes requires_openai_auth back.
- gateway: codexModels doesn't pass a revoked /models answer
  (provider.SignInRevoked) through: it lists Codex's cached models and
  magpie's. The desk file does the same while the live list says revoked
  (CodexListRevoked). Any other refusal (token_expired, 5xx) is as before.
- docs: agent-wiring and gateway-routing.

Run:
- real codex 0.162.1 (app-server over stdio, and exec) on mote, sandbox
  HOME/CODEX_HOME, fake OpenAI (chatgpt_base_url,
  CODEX_REFRESH_TOKEN_URL_OVERRIDE, provider.CodexBase) answering 401
  token_revoked and refresh_token_invalidated; no real network.
  - Old wiring beside the dead sign-in, old gateway: model/list had no
    magpie model (jjt's case). With the gateway change: fake/m1 listed,
    but exec -m fake/m1 fails at workspace routing discovery (401), and
    account/read errors too - why the wiring change is needed.
  - Uncommitted e2e in the agent package with magpie's own written
    config: Set("fake/m1") wrote it beside the sign-in; magpie's
    LoginUsage("codex") then heard the refresh refused, Sync rewrote it
    to model_provider = "magpie", model_catalog_json, no
    requires_openai_auth. account/read: {"account":null,
    "requiresOpenaiAuth":false}; model/list: fake/m1 plus Codex's
    models; exec -m fake/m1 answered "hi from magpie"; auth.json byte
    for byte the same.
- Red on the old code (broken by hand): without the codexChatGPTKnown
  check TestCodexGoneSignInIsNoChatGPT is red; without the
  noteCodexSignInGone call TestCodexSignInGoneWhenRefusedForGood is red;
  with codexRefreshGone true for every failure TestCodexRefreshGoneRule
  is red; TestCodexModelListRevokedSignIn and
  TestCodexDesktopCatalogRevokedSignIn are red on the old gateway.
  Taking out the store re-check in noteCodexSignInGone leaves the tests
  green: a token Codex rotated meanwhile is already held by the hash
  comparison, and the re-check only saves a needless record, log line
  and resync. Not guarded on its own.
- via mote-run, at this commit rebased on origin/main 1f03d7546:
  gofmt -l clean; go vet ./internal/provider ./internal/agent
  ./internal/gateway for darwin, linux (-tags nogui) and windows ok;
  go test -timeout 45m -p 1 of the three: provider ok (92.3s), agent ok
  (192.1s), gateway ok (530.9s). The first full run had the new provider
  test red: run after the other Codex tests it read their cached logins
  and listed none; it now has the resetRevoked/rememberLogins setup its
  siblings use.
  Rebased after the run onto 05a6087e1 (access: key model scope) and
  8cbd0a9c9 (GUI loading bird); neither touches the Codex paths, and
  this push wasn't run again on them.

Not tried: the real Codex desktop app (ChatGPT.app); signing in again
with the real binary (the unit test writes a new auth.json); the
keychain credential store; magpie's left-alone mode, where magpie
doesn't refresh Codex's sign-in, so nothing is recorded there;
Codex homes on Windows and in WSL.
2026-10-30 01:40:48 +08:00

125 lines
3.5 KiB
Go

package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// codexDeskReset forgets the backend's list for the Codex app, before the
// test and after it.
func codexDeskReset(t *testing.T) {
t.Helper()
reset := func() {
codexDesk.Lock()
done := codexDesk.done
codexDesk.Unlock()
if done != nil {
<-done
}
codexDesk.Lock()
codexDesk.body, codexDesk.got, codexDesk.tried, codexDesk.asking, codexDesk.done, codexDesk.revoked = nil, time.Time{}, time.Time{}, false, nil, false
codexDesk.Unlock()
}
reset()
t.Cleanup(reset)
was := CodexDesktopChanged
t.Cleanup(func() { CodexDesktopChanged = was })
}
// codexDeskAsked waits for the ask CodexDesktopCatalog started.
func codexDeskAsked(t *testing.T) {
t.Helper()
codexDesk.Lock()
done := codexDesk.done
codexDesk.Unlock()
if done == nil {
t.Fatal("the backend was never asked")
}
<-done
}
// The list the Codex app reads from a file beside the ChatGPT sign-in
// (laddieyao on Discord): the backend's entries as it sent them, its
// base_instructions untouched, asked for with Codex's own sign-in, and
// magpie's models after them. Not known until the backend has answered,
// and a failed ask after that keeps the last list it gave: unknown, never
// an empty list.
func TestCodexDesktopCatalog(t *testing.T) {
codexSignedIn(t)
codexDeskReset(t)
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Anthropic: "http://127.0.0.1:1",
Models: []string{"claude-opus-5.5"}}); err != nil {
t.Fatal(err)
}
var fail atomic.Bool
var auth atomic.Value
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
auth.Store(r.Header.Get("Authorization"))
if fail.Load() {
http.Error(w, "down", http.StatusBadGateway)
return
}
io.WriteString(w, `{"models":[{"slug":"gpt-5.5","priority":1,"base_instructions":"You are Codex, based on GPT-5.","visibility":"list"}]}`)
}))
defer up.Close()
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
defer func() { provider.CodexBase = was }()
var changed atomic.Int32
CodexDesktopChanged = func() { changed.Add(1) }
if b, ok := CodexDesktopCatalog(); ok || b != nil {
t.Fatalf("known before the backend answered: %s", b)
}
codexDeskAsked(t)
if changed.Load() != 1 {
t.Fatalf("changed told %d times", changed.Load())
}
if a, _ := auth.Load().(string); a == "" {
t.Fatal("asked without Codex's sign-in")
}
b, ok := CodexDesktopCatalog()
if !ok {
t.Fatal("not known after the backend answered")
}
var got struct {
Models []map[string]any `json:"models"`
}
if err := json.Unmarshal(b, &got); err != nil {
t.Fatal(err)
}
slugs := map[string]map[string]any{}
for _, m := range got.Models {
slugs[m["slug"].(string)] = m
}
if m := slugs["gpt-5.5"]; m == nil || m["base_instructions"] != "You are Codex, based on GPT-5." {
t.Fatalf("the backend's entry: %v", m)
}
if slugs["relay/claude-opus-5.5"] == nil {
t.Fatalf("magpie's models missing: %s", b)
}
// an ask that fails keeps the list the backend gave last
fail.Store(true)
codexDesk.Lock()
codexDesk.got, codexDesk.tried = time.Time{}, time.Time{}
codexDesk.Unlock()
if _, ok := CodexDesktopCatalog(); !ok {
t.Fatal("the last list forgotten as the backend is asked again")
}
codexDeskAsked(t)
if b2, ok := CodexDesktopCatalog(); !ok || string(b2) != string(b) {
t.Fatalf("after a failed ask: %v\n%s", ok, b2)
}
if changed.Load() != 1 {
t.Fatalf("a failed ask told as a change")
}
}