Files
magpie/internal/agent/codex_app_test.go
T
yetone cc81ad4ea1 codex: a Windows Codex app that starts no app-server after a switch is reopened (蛋仔 on Discord)
After magpie switched Codex's account, the Windows Codex app answered
every send with "Codex app-server process is not available" until it
was quit and opened again. The report said the app doesn't reconnect
after a clean exit. That is half right. The app (MSIX OpenAI.Codex
26.1021, an Electron ChatGPT.exe that spawns codex.exe app-server over
stdio) does start another, but only once the old one's stdout reaches
EOF and its exit has fired. On Windows a child of the app-server (an MCP
server, a tool command) inherits that pipe handle. A child left running
keeps the pipe open, so the app never sees the close, starts none, and
its send() throws. Reproduced on the Windows box with the real codex.exe
0.164 app-server plus an MCP server: stdout ended only when the MCP
server did, and at once when the tree was ended.

magpie took "the old pid is gone" as done in each place it restarts the
app-server. None of them checked that a new one came:
- codexAppStep (the switch watcher) now records the pids it ended and
  waits codexAppBackWait (30s) for another app-server. If none comes and
  the app still runs (CodexAppOpen), it quits and opens the app as the
  Agents row's Restart does (CodexAppReopen: restartWin by the
  OpenAI.Codex_2p2nqsd0c76g0!App AUMID, Windows only). Where it can't,
  the row says to (CodexAppStuck).
- RestartCodexApp (macOS Restart), RestartCodexAppWhenIdle (uninstall)
  and the switch notice's Restart (RestartSwitchedCodexApp, 46aa7e6b8)
  wait for a new app-server too, and reopen or say so the same way.
  RestartSwitchedCodexApp's own 20s codexAppBackWait went into the
  shared 30s one.
- recheckLeft no longer clears the "still on the old account" record
  while the app is open with no app-server.
- A turn stuck open when quota ran out mid-task (蛋仔's follow-up) held
  the restart for up to codexTurnWindow (30m), since an open turn in
  Codex's sessions meant "a task runs". A switch off a used-up account
  (SwitchWhenSpent) now marks it spent (codexAppSpentSwitch). After such
  a switch, a turn that has written no session file and sent nothing
  through magpie for codexTurnStuckAfter (2m) counts as stuck, and the
  app-server is restarted past it. Its next request would be refused on
  that account anyway. A tool still running in that turn is ended with
  it. A switch for any other reason waits for the turn as before.
macOS is never reopened unasked (a reopen opens a new window,
yoshi037070, 10-27). WSL needs nothing: WSL Codex has no desktop app, and
the Windows app's app-server runs on the Windows side.

Run (at this head unless said):
- mote: go test -timeout 45m ./... at 4cf444bc4, this change on
  origin/main 807048470. It was rebased on dca3e2d71 after (5 commits,
  none in codex_app*/codex_switch/codex_daemon), and the -run below was
  run again at the pushed head. Result: every package ok except gateway and gui, whose reds aren't this
  change's (it touches neither package). gateway: TestAntigravityTurn*
  x4 and TestCodexSpentGrokFailingIsTold, red the same on origin/main
  46aa7e6b8 (#4362), and TestUnroutedUnknownHoldAnsweredSooner, which
  passes alone 3 of 3 at this head (filed #4377). gui:
  TestMainWindowCorners (#3949).
- mote: provider and agent -run 'CodexApp|CodexDaemon|RestartCodex|
  RestartSwitched|CodexSwitched|CodexSessionsQuiet|Switch' ok; gofmt -l clean; GOOS=windows, linux,
  darwin go vet ./internal/agent ./internal/provider ok.
- win-run, the same -run: everything of mine passes. Two tests are red,
  TestCodexDaemonEnvIsTheTerminals and TestWorkBuddyRestartOnMac, the
  same on origin/main (#4115).
- Broken by hand, each red, then restored: the step's no-app-server
  branch, RestartCodexApp's not-back check, uninstall's reopen,
  recheckLeft's open check (4 provider tests); RestartSwitchedCodexApp
  without the reopen (TestRestartSwitchedCodexApp "reopened 0"); the
  codexWinApp matcher widened to \WindowsApps\OpenAI.
  (TestCodexAppReopenedOnWindows). The stuck-turn bypass taken out
  ("a turn stuck on the used-up account: ended []"), the spent mark not
  set (TestCodexSwitchedWhenUsedUp), and the bypass without its spent
  and quiet checks ("a turn open after a switch not for spend: ended
  [60]").
- Real Codex app on Windows (xiaomi-gpu, OpenAI.Codex 26.1021.3705.0,
  from a throwaway test, not committed, run as a scheduled task in the
  console session):
  - RestartCodexAppWhenIdle ended the real app-server, and the app
    started another within ~0.6s. codexAppBack saw it (left false).
  - codexAppReopen quit ChatGPT.exe 43832 and opened the app by its
    AUMID in 3.7s (main now 70060). A new app-server came 9.6s after.

Not tried:
- The stuck state itself in the real app: an MCP child really holding
  the app-server's stdout inside the Codex app. It was reproduced with
  codex.exe outside the app, and the reopen was run on a working app.
- A signed-in real account switch on Windows.
- The quota-mid-task hang with a real used-up account. Why the app sat
  on the turn wasn't reproduced. A plain usage_limit_reached refusal
  closes the turn (task_complete, as dd9828f2b found), so this covers a
  turn that stays open, whatever holds it.
- Whether a reopen loses an unsent draft.
- The macOS path with a real stuck app (it says to quit and reopen;
  nothing is reopened there).
2026-10-30 13:42:48 +08:00

158 lines
5.9 KiB
Go

package agent
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// The Codex app's Restart restarts only the app-server of the app the row
// lists as left on the old list. It never quits the app and opens it
// again, which opened a new window (yoshi037070, 10-27).
func TestCodexAppReopen(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip(staleOnWindows)
}
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
t.Setenv("CODEX_HOME", "")
dir := filepath.Join(home, ".codex")
os.MkdirAll(dir, 0o755)
os.WriteFile(filepath.Join(dir, "config.toml"), []byte("model_provider = \"magpie\"\n"), 0o600)
const bundle = "/Applications/Codex.app"
wasRunning, wasQuit, wasOpen, wasRestart := running, appQuit, appOpen, restartAppServer
t.Cleanup(func() { running, appQuit, appOpen, restartAppServer = wasRunning, wasQuit, wasOpen, wasRestart })
running = func(pat string) []runningProc {
ps := []runningProc{
{3 * time.Hour, bundle + "/Contents/MacOS/Codex"},
{3 * time.Hour, bundle + "/Contents/Resources/codex app-server"},
}
var out []runningProc
for _, p := range ps {
if strings.Contains(pat, "codex") && strings.Contains(p.cmd, "codex ") || strings.Contains(pat, `Codex\.app/Contents/`) {
out = append(out, p)
}
}
return out
}
var did []string
appQuit = func(_ context.Context, b string) error { did = append(did, "quit "+b); return nil }
appOpen = func(_ context.Context, b string) error { did = append(did, "open "+b); return nil }
restartAppServer = func(_ context.Context, b string) error { did = append(did, "restart "+b); return nil }
a := codex(home)
if err := reopenApp(context.Background(), a, "/Applications/Other.app"); err == nil || len(did) > 0 {
t.Fatalf("an app not listed: %v, did %v", err, did)
}
if err := reopenApp(context.Background(), a, bundle); err != nil {
t.Fatal(err)
}
if got := strings.Join(did, ", "); got != "restart "+bundle {
t.Fatalf("did %q, want only its app-server restarted", got)
}
// a restart that fails is said
did = nil
restartAppServer = func(context.Context, string) error { return errors.New("didn't end") }
if err := reopenApp(context.Background(), a, bundle); err == nil || len(did) > 0 {
t.Fatalf("failed restart: %v, did %v", err, did)
}
}
// The Restart on Codex's "the Codex app is still signed in as" notice says
// what went wrong in a notice the GUI translates, and an error it doesn't
// know (a failed listing) is "couldn't tell", never success.
func TestRestartSwitchedCodexAppSays(t *testing.T) {
old := restartSwitchedApp
t.Cleanup(func() { restartSwitchedApp = old })
for _, c := range []struct {
err error
want notice
}{
{provider.ErrCodexAppGone, noticeSwitchAppGone},
{provider.ErrCodexAppNoEnd, noticeSwitchAppNoEnd},
{provider.ErrCodexAppNotBack, noticeSwitchAppNotBack},
{errors.New("ps: timed out"), noticeSwitchAppUnknown},
} {
restartSwitchedApp = func(context.Context) error { return c.err }
err := RestartSwitchedCodexApp(context.Background())
if err == nil || err.Error() != c.want.say("agent", "Codex") {
t.Errorf("%v: said %v, want %q", c.err, err, c.want.say("agent", "Codex"))
}
}
restartSwitchedApp = func(context.Context) error { return nil }
if err := RestartSwitchedCodexApp(context.Background()); err != nil {
t.Fatal(err)
}
}
// When the Windows Codex app starts no app-server in place of the one
// magpie ended (its stdout held open by a process that one started), it
// can't send till it is quit and opened again (蛋仔 on Discord, 10-30):
// magpie does that, to the OpenAI.Codex package's ChatGPT.exe only, by
// its AppUserModelID. macOS isn't reopened unasked.
func TestCodexAppReopenedOnWindows(t *testing.T) {
restartSandbox(t)
restartOnWindows = true
appCloseWait, appBackWait, appTrayGrace = time.Second, time.Second, 10*time.Millisecond
const image = `C:\Program Files\WindowsApps\OpenAI.Codex_26.1021.3705.0_x64__2p2nqsd0c76g0\app\ChatGPT.exe`
start := time.Now().Add(-time.Hour)
alive := true
winProcs = func(name string) []winProc {
if !strings.EqualFold(name, "ChatGPT.exe") {
return nil
}
// the ChatGPT chat app beside it, always running
ps := []winProc{{pid: 50, parent: 4, image: `C:\Program Files\WindowsApps\OpenAI.ChatGPT-Desktop_1.2025.1.0_x64__2p2nqsd0c76g0\app\ChatGPT.exe`, start: start}}
if alive {
ps = append(ps,
winProc{pid: 10, parent: 4, image: image, start: start, aumid: "OpenAI.Codex_2p2nqsd0c76g0!App"},
winProc{pid: 11, parent: 10, image: image, start: start.Add(time.Second)})
}
return ps
}
winShown = func([]int) bool { return false } // in the tray
var did []string
winClose = func(pids []int) error { did = append(did, fmt.Sprint("close ", pids)); return nil }
winEnd = func(pid int) error { did = append(did, fmt.Sprint("end ", pid)); alive = false; return nil }
winLaunch = func(p winProc) error { did = append(did, "open "+p.aumid); alive = true; return nil }
if open, known := codexAppOpen(context.Background()); !open || !known {
t.Fatalf("open %v, known %v", open, known)
}
if err := codexAppReopen(context.Background()); err != nil {
t.Fatal(err)
}
if want := []string{"close [10 11]", "end 10", "open OpenAI.Codex_2p2nqsd0c76g0!App"}; !slices.Equal(did, want) {
t.Fatalf("did %q, want %q", did, want)
}
// quit meanwhile: nothing to do, it starts one as it opens
alive, did = false, nil
if open, known := codexAppOpen(context.Background()); open || !known {
t.Fatalf("quit: open %v, known %v", open, known)
}
if err := codexAppReopen(context.Background()); err != nil || did != nil {
t.Fatalf("quit: %v, did %q", err, did)
}
restartOnWindows = false
alive = true
if err := codexAppReopen(context.Background()); err == nil || did != nil {
t.Fatalf("not Windows: %v, did %q", err, did)
}
}