Files
magpie/internal/provider/codex_app_server_test.go
T
yetone 8b0132b3d2 codex: the Codex app sends again on every system as soon as magpie takes a used-up ChatGPT account over, and gets it back at the reset
Ethereal499 and Isdavexxx on X, MasterYi on Discord, #540. The Codex app greys
Send for every model, magpie's too, while the ChatGPT account it is signed in
to is used up. Its composer's gate (ChatGPT.app 26.1013) reads authMethod
"chatgpt" plus rate limit allowed=false, and it asks account/read only when its
app-server starts. ef37b6fb7 (v0.1.1381) could fail in practice:
- (a) The reopen was macOS-only, ran once per time out, only from the GUI
  process. A Windows or Linux user, a magpie without its window, or a second
  time out stayed greyed.
- Switch-back: the app stayed on magpie (authMethod null, no cloud tasks or
  Log out) after the reset. Nothing restarted it.
- (c) Detection lag: the account was read every 5 minutes.
- The notice sat on the Providers page, not on Codex's Agents row.

Now:
- The gateway process (`provider.KeepCodexAppOnItsProvider`, every 3s, on
  every OS) ends the Codex app's own app-server each time `Agent.AppOut`
  flips, both ways. The app starts another at once and reads account/read
  afresh. Its window, threads and drafts stay.
- It never ends an app-server while a Codex request is in flight through
  magpie or ended in the last 10s (`Server.CodexBusy`, Codex's requests only),
  or while a session under the Codex home has a turn open (`codexTurnOpen`).
- It ends only the app's own app-server. That one runs on stdio; one another
  program starts with `--listen` is left alone (Miyi Helper runs one on this
  Mac). It must also run on magpie's Codex home (`proc.EnvOf`: ps -E on macOS,
  /proc on Linux; Windows can't tell).
- The exit is clean (`proc.End`: SIGTERM, or TerminateProcess with code 0 on
  Windows). The app shows any other exit as a crash.
- A listing that fails is taken up again at the next look. One that outlives
  3 ends, or is denied, makes the row say to quit and reopen.
- The active account is read every minute while it is held or a window is at
  90% or more (`codexLookEvery`).
- Codex's Agents row says "On magpie until <reset> · ChatGPT allowance used
  up". Hovering it, or opening the row, says what is off until then (cloud
  tasks, the usage meter, Log out) and that it all comes back on its own. In
  en, zh, zh-TW, ja and de.
- Removed: gui's keepCodexAppSending/codexAppOut, provider's episode
  bookkeeping, and the Providers-page notice.

Not changed, by design:
- A Codex own model that no magpie account serves stays as it is: magpie
  can't serve that turn.
- Account discovery off and "Only switch Codex's sign-in" (login=chatgpt) are
  the user's own choices, and are left alone.

Full suite green at cff1a9686 (on origin/main 6ce0f14b9), below. At
4541b3e97 (rebased on 430e3050d, which touched gateway.go, app.js and
i18n.js beside this) ran: gofmt -l, go build ./..., go vet on darwin,
linux (-tags nogui ./...) and windows; go test -run Codex ./internal/provider
./internal/agent ok; GUI codex-app-out (22 ok) and codex-app-stale (20 ok),
chromium and webkit. Pushed rebased on b92cb2f59 (two more commits,
neither in these files), built, not rerun.

Run at this commit (cff1a9686, on origin/main 6ce0f14b9), with a private
GOCACHE (another session ran go clean -cache mid-run):
- gofmt -l: clean. go build ./...: ok.
- go vet: darwin (touched packages); GOOS=linux -tags nogui ./...;
  GOOS=windows (touched packages).
- go test -count=1 -timeout 45m: internal/proc, internal/provider,
  internal/agent, internal/gateway, internal/gui all ok, skipping four
  tests red on main without this change, each already filed:
  TestUnreadLoginsWriteErrorsKeepCredentials (#3632, a synctest crash
  since 091153bf) and TestFetchAsksOneListOnceForTwoBasesOfIt,
  TestFetchUnionsProtocolListsWithoutChat, TestFetchAsksASharedBaseOnce
  (#3854, since 6eb510f78). All three of the latter fail the same at
  origin/main 6ce0f14b9 and at 353519f55 without this commit.
- GUI at cff1a9686, chromium and webkit, 231 cases ok: codex-app-out (5 languages, 980 and 440px),
  i18n-keys, gui-de/ja/zh-tw, codex-app-stale, codex-accounts-via,
  agent-stale-copies, agent-app-restart, agent-failover, agent-connect,
  agent-layout, agent-expand-steady, agent-connected-unfolded,
  agent-notice-lang and codex-signin-always.
- Windows box (cross-built test binaries): proc and provider's Codex app
  tests pass. TestEndExitsClean passes there and goes red with exit code 1.
- Broken by hand, each went red:
  - Codex-only busy: TestCodexBusy.
  - The 90% cadence: TestCodexLookEvery.
  - The retry after a failed listing: TestCodexAppServerUnknown.
  - The turn guard: TestCodexAppServerRestartedEachWay.
  - The --listen exclusion: TestCodexAppOwnServer.
  - Code 0 on Windows: TestEndExitsClean.
  - The row's notice: codex-app-out.test.cjs, 4 of 4.
- Real app: ChatGPT.app 26.1013 in a sandbox HOME/CODEX_HOME, with this
  build serving on 3492/3493. Codex was put on magpie as Sync does for a held
  account (model_provider = "magpie", codex.out in stash.json). OpenAI's usage
  reading to the app was never faked.
  - The first listing ran out at load ~200, so the timeout is now 30s. The
    next look ended the app-server, and the app started another 12s later.
    Its profile went from "Pro · Usage · Log out" to "magpie" with no reopen,
    and /api/state carried appOut.
  - Undoing it ended the app-server again, and the profile came back to Pro,
    Usage and Log out.
  - The owner's own ChatGPT app (its app-server on ~/.codex) was never
    touched.
- One webkit codex-app-out run at load 291 had one red subtest, name lost.
  It passed 3 of 3 alone and in two full webkit runs.

Not tried:
- The Windows Store app (not installed on the box), and a real Codex app
  on Linux.
- A real used-up account.
- A turn running in the real app while the switch happens (unit-tested
  only).
2026-10-27 15:57:41 +08:00

347 lines
12 KiB
Go

package provider
import (
"context"
"errors"
"os"
"path/filepath"
"runtime"
"slices"
"testing"
"time"
"github.com/yetone/magpie/internal/proc"
)
// codexAppStub stands in for Codex's provider, the running app-servers
// and their ends, for codexAppStep.
type codexAppStub struct {
on, known bool
running []int
listErr error
endErr error
turnOpen bool
ended []int
// next: the app-server the app starts after one is ended
next int
}
func stubCodexApp(t *testing.T) *codexAppStub {
t.Helper()
s := &codexAppStub{known: true, next: 100}
oldOn, oldList, oldEnd, oldTurn := CodexAppOnMagpie, codexAppServersOn, endCodexAppServer, codexTurnRunning
t.Cleanup(func() {
CodexAppOnMagpie, codexAppServersOn, endCodexAppServer, codexTurnRunning = oldOn, oldList, oldEnd, oldTurn
codexApp.Lock()
codexApp.seen, codexApp.on, codexApp.stale, codexApp.stuck = false, false, nil, false
codexApp.Unlock()
})
codexApp.Lock()
codexApp.seen, codexApp.on, codexApp.stale, codexApp.stuck = false, false, nil, false
codexApp.Unlock()
CodexAppOnMagpie = func() (bool, bool) { return s.on, s.known }
codexAppServersOn = func(context.Context, string) ([]int, error) {
if s.listErr != nil {
return nil, s.listErr
}
return slices.Clone(s.running), nil
}
endCodexAppServer = func(pid int) error {
if s.endErr != nil {
return s.endErr
}
s.ended = append(s.ended, pid)
// the app starts another app-server, which reads the provider anew
if i := slices.Index(s.running, pid); i >= 0 {
s.running[i] = s.next
s.next++
}
return nil
}
codexTurnRunning = func(string, time.Time) bool { return s.turnOpen }
return s
}
// When magpie becomes Codex's provider for its used-up ChatGPT account the
// Codex app's own app-server is restarted, so the app reads its account
// again and lifts the grey on Send (Ethereal499, MasterYi), and again when
// magpie puts Codex back on the account at its reset, so the app's ChatGPT
// side comes back. Never while a Codex turn runs: one in flight through
// magpie, one ended under codexAppIdle ago (a tool between two requests),
// or one open in Codex's sessions.
func TestCodexAppServerRestartedEachWay(t *testing.T) {
signIn(t)
s := stubCodexApp(t)
now := time.Now()
idle := func() (int, time.Time) { return 0, now.Add(-time.Minute) }
step := func(busy func() (int, time.Time)) []int { return codexAppStep(context.Background(), now, busy) }
s.running = []int{60}
if got := step(idle); got != nil {
t.Fatalf("on its account with room: ended %v", got)
}
s.on = true
if got := step(func() (int, time.Time) { return 1, now.Add(-time.Minute) }); got != nil {
t.Fatalf("a Codex request in flight: ended %v", got)
}
if got := step(func() (int, time.Time) { return 0, now.Add(-codexAppIdle / 2) }); got != nil {
t.Fatalf("Codex's last request just ended: ended %v", got)
}
s.turnOpen = true
if got := step(idle); got != nil {
t.Fatalf("a turn open in Codex's sessions: ended %v", got)
}
s.turnOpen = false
if got := step(idle); !slices.Equal(got, []int{60}) {
t.Fatalf("on magpie, idle: ended %v, want [60]", got)
}
if got := step(idle); got != nil {
t.Fatalf("the new app-server read magpie as it started: ended %v", got)
}
s.on = false // the reset: back on the account
if got := step(idle); !slices.Equal(got, []int{100}) {
t.Fatalf("back on the account: ended %v, want [100]", got)
}
if got := step(idle); got != nil || CodexAppStuck() {
t.Fatalf("after: ended %v, stuck %v", got, CodexAppStuck())
}
}
// A magpie started while it is Codex's provider for a used-up account
// restarts the app-servers it finds: they may have started before.
// Started with Codex on its account, it leaves them be.
func TestCodexAppServerFirstLook(t *testing.T) {
signIn(t)
s := stubCodexApp(t)
now := time.Now()
idle := func() (int, time.Time) { return 0, time.Time{} }
s.running = []int{60}
s.on = true
if got := codexAppStep(context.Background(), now, idle); !slices.Equal(got, []int{60}) {
t.Fatalf("first look on magpie: ended %v", got)
}
s2 := stubCodexApp(t)
s2.running = []int{70}
if got := codexAppStep(context.Background(), now, idle); got != nil {
t.Fatalf("first look on the account: ended %v", got)
}
}
// Codex's provider not known (its config unreadable) changes nothing, and
// app-servers that can't be listed as the provider changes are listed at
// the next look.
func TestCodexAppServerUnknown(t *testing.T) {
signIn(t)
s := stubCodexApp(t)
now := time.Now()
idle := func() (int, time.Time) { return 0, time.Time{} }
s.running = []int{60}
s.known = false
s.on = true
if got := codexAppStep(context.Background(), now, idle); got != nil {
t.Fatalf("not known: ended %v", got)
}
s.known = true
s.listErr = errors.New("ps failed")
if got := codexAppStep(context.Background(), now, idle); got != nil {
t.Fatalf("not listed: ended %v", got)
}
s.listErr = nil
if got := codexAppStep(context.Background(), now, idle); !slices.Equal(got, []int{60}) {
t.Fatalf("listed at the next look: ended %v", got)
}
}
// An app-server that outlives codexAppTries ends, or that magpie may not
// end, is left to the user: CodexAppStuck says so for the Agents row.
func TestCodexAppServerStuck(t *testing.T) {
signIn(t)
s := stubCodexApp(t)
now := time.Now()
idle := func() (int, time.Time) { return 0, time.Time{} }
s.running = []int{60}
s.on = true
oldEnd := endCodexAppServer
tries := 0
endCodexAppServer = func(int) error { tries++; return nil } // it doesn't end
for range codexAppTries + 2 {
codexAppStep(context.Background(), now, idle)
}
if tries != codexAppTries || !CodexAppStuck() {
t.Fatalf("tries %d (want %d), stuck %v", tries, codexAppTries, CodexAppStuck())
}
endCodexAppServer = oldEnd
s.on = false // a change starts afresh
codexAppStep(context.Background(), now, idle)
if CodexAppStuck() {
t.Fatal("still stuck after the provider changed")
}
s.on = true
s.endErr = proc.ErrDenied
codexAppStep(context.Background(), now, idle)
if !CodexAppStuck() {
t.Fatal("denied: not stuck")
}
}
// TestCodexAppHomeHelper is TestCodexAppServersOnHome's app-server: it
// waits to be ended (a system binary's environment is kept from ps).
func TestCodexAppHomeHelper(t *testing.T) {
if os.Getenv("MAGPIE_CODEX_HOME_HELPER") != "1" {
return
}
time.Sleep(30 * time.Second)
}
// Only the app-servers on magpie's Codex home are restarted: one under
// another HOME or CODEX_HOME (a sandbox, another user) is left be.
func TestCodexAppServersOnHome(t *testing.T) {
if runtime.GOOS != "darwin" && runtime.GOOS != "linux" {
t.Skip("no environment to tell homes by here: every app-server counts")
}
start := func(env ...string) int {
ctx, cancel := context.WithCancel(context.Background())
cmd := proc.CommandContext(ctx, os.Args[0], "-test.run=^TestCodexAppHomeHelper$")
cmd.Env = append([]string{"MAGPIE_CODEX_HOME_HELPER=1"}, env...)
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { cancel(); _ = cmd.Wait() })
return cmd.Process.Pid
}
ctx := context.Background()
a, b := t.TempDir(), t.TempDir()
onHome := start("HOME=" + a)
if !codexAppHomeIs(ctx, onHome, filepath.Join(a, ".codex")) {
t.Fatal("HOME's .codex: not counted")
}
if codexAppHomeIs(ctx, onHome, filepath.Join(b, ".codex")) {
t.Fatal("another HOME's: counted")
}
onCodexHome := start("HOME="+a, "CODEX_HOME="+b)
if !codexAppHomeIs(ctx, onCodexHome, b) {
t.Fatal("CODEX_HOME: not counted")
}
if codexAppHomeIs(ctx, onCodexHome, filepath.Join(a, ".codex")) {
t.Fatal("HOME's .codex under another CODEX_HOME: counted")
}
if codexAppHomeIs(ctx, 1<<30, b) {
t.Fatal("a process that isn't there counted")
}
}
// A turn is open in Codex's sessions when the newest task event of a file
// written to lately is task_started.
func TestCodexTurnOpen(t *testing.T) {
home := t.TempDir()
dir := filepath.Join(home, "sessions", "2026", "10", "27")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
now := time.Now()
write := func(name, body string, at time.Time) {
p := filepath.Join(dir, name)
if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
t.Fatal(err)
}
if err := os.Chtimes(p, at, at); err != nil {
t.Fatal(err)
}
}
started := `{"type":"event_msg","payload":{"type":"task_started","turn_id":"1"}}` + "\n"
done := `{"type":"event_msg","payload":{"type":"task_complete","turn_id":"1"}}` + "\n"
aborted := `{"type":"event_msg","payload":{"type":"turn_aborted","turn_id":"1"}}` + "\n"
if codexTurnOpen(home, now) {
t.Fatal("no sessions: open")
}
write("rollout-a.jsonl", started+done, now)
if codexTurnOpen(home, now) {
t.Fatal("turn complete: open")
}
write("rollout-b.jsonl", started+aborted, now)
if codexTurnOpen(home, now) {
t.Fatal("turn aborted: open")
}
write("rollout-c.jsonl", started+done+started, now.Add(-codexTurnWindow-time.Minute))
if codexTurnOpen(home, now) {
t.Fatal("a turn left open long ago: open")
}
write("rollout-d.jsonl", started+done+started, now)
if !codexTurnOpen(home, now) {
t.Fatal("a turn running: not open")
}
}
// While the account Codex is on is near out, or out, it is read every
// minute, not five: the app greys Send on its own reading, and magpie
// takes over only on its own (Ethereal499). At the reset, as soon.
func TestCodexLookEvery(t *testing.T) {
signIn(t) // me@example.com, active
rememberLogins(true)
at := func(used float64, held bool) map[string]SubscriptionQuota {
return map[string]SubscriptionQuota{"me@example.com": {Held: held, Windows: []QuotaWindow{{Name: "5h", Used: 20}, {Name: "week", Used: used}}}}
}
if got := codexLookEvery(at(50, false)); got != loginSwitchEvery {
t.Fatalf("half used: %v", got)
}
if got := codexLookEvery(at(91, false)); got != codexNearOutEvery {
t.Fatalf("near out: %v", got)
}
if got := codexLookEvery(at(0, true)); got != codexNearOutEvery {
t.Fatalf("out: %v", got)
}
if got := codexLookEvery(map[string]SubscriptionQuota{"other@example.com": {Held: true}}); got != loginSwitchEvery {
t.Fatalf("another account out: %v", got)
}
if got := codexLookEvery(map[string]SubscriptionQuota{"me@example.com": {Held: true, Error: "x"}}); got != loginSwitchEvery {
t.Fatalf("a failed read: %v", got)
}
}
// The Agents row says until when Codex is on magpie: the latest reset of
// the windows used up.
func TestCodexOutUntil(t *testing.T) {
signIn(t)
rememberLogins(true)
soon, later := time.Now().Add(time.Hour), time.Now().Add(48*time.Hour)
u := map[string]SubscriptionQuota{"me@example.com": {Held: true, Windows: []QuotaWindow{
{Name: "5h", Used: 100, ResetsAt: &soon},
{Name: "week", Used: 100, ResetsAt: &later},
}}}
if got := codexOutUntil(u); !got.Equal(later) {
t.Fatalf("both used up: %v, want %v", got, later)
}
u["me@example.com"].Windows[1].Used = 40
if got := codexOutUntil(u); !got.Equal(soon) {
t.Fatalf("5h used up: %v, want %v", got, soon)
}
q := u["me@example.com"]
q.Held = false
u["me@example.com"] = q
if got := codexOutUntil(u); !got.IsZero() {
t.Fatalf("not out: %v", got)
}
}
// Only the app's own app-server is restarted: another program's, started
// from the app's bundled codex with --listen (Miyi Helper's, seen on the
// owner's Mac), is that program's.
func TestCodexAppOwnServer(t *testing.T) {
own := "/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex -c features.code_mode_host=true app-server --analytics-default-enabled -c plugins.codex-app-tools@openai-bundled.mcp_servers.codex_app.enabled=true"
if !isCodexAppOwnServer(own) {
t.Fatalf("the app's own app-server not taken: %s", own)
}
for _, other := range []string{
"/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex app-server --listen stdio://",
"/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex app-server --listen=ws://127.0.0.1:4500",
"/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex -c forced_login_method=\"chatgpt\" exec-server --remote https://codex-cloud-environments.chatgpt.com/api",
"/usr/local/bin/codex app-server",
} {
if isCodexAppOwnServer(other) {
t.Errorf("taken for the app's own app-server: %s", other)
}
}
}