Files
magpie/internal/codexrelay/relay_test.go
T
yetone 4534561f6b codex: a thread open when magpie quits goes on through a relay, not a 503
idkatbro on X: a Codex session started while magpie was open keeps
failing after magpie quits with "unexpected status 503 Service
Unavailable: Unknown error, url:
http://127.0.0.1:3425/backend-api/codex/responses", until magpie is
opened again.

Cause: Codex signed in to ChatGPT, with more of its accounts on in
magpie, gets openai_base_url = the gateway's /backend-api/codex
(failover). At quit EndCodexFailover takes it out of config.toml, but
a thread already open, in the Codex app and its app-server above all,
keeps the base URL it started with. Every turn after went to a closed
port. With a system or env proxy in between, the proxy answers 503
with an empty body, which Codex shows as "Unknown error"; without one
Codex says "Connection refused" and reconnects. Reproduced on mote
with codex 0.162.1 and a proxy answering 503 for the closed port.
Masking plays no part: it runs only in the gateway, is opt-in, and its
own 503 carries a readable message.

Fix: when quit really ends failover (EndCodexFailover now says so),
the gateway is on loopback, and Codex processes run
(provider.CodexPIDs), magpie starts a detached `magpie codex-relay`
(internal/codexrelay). It waits up to 60s for the gateway's port, then
passes /backend-api/codex/* on to the ChatGPT backend with the same
transforms the gateway applies to Codex's own turns, signed by the
caller's own Authorization; it adds no credential
(gateway.CodexRelay).
- Refused with a readable 400 (Codex retries a 5xx five times over):
  a magpie model, a turn naming one of magpie's Codex accounts, and a
  turn masking would have masked, which is never sent unmasked.
- 403 for any Origin (null too) or a non-loopback Host, as corsGuard.
- Any other path gets 503 "magpie isn't running", never readable as
  magpie by ServedBy.
- It ends once every Codex process it was left for is gone and
  nothing is in flight.
- The next magpie (GUI or `magpie serve`) calls codexrelay.Leave
  first: a POST with the token from a 0600 state file. The relay
  closes its listener at once, so the port is free when Leave returns,
  and finishes its streams (up to 30 minutes). No running turn is cut.

Run (at 6df7dc287 on origin/main 4d9058a98, on mote):
- go vet of the six touched packages; gofmt -l clean.
- go test ./internal/codexrelay and the CodexRelay, CodexFailover,
  CodexProxy, RelayOpenCodex and CodexPIDs tests: ok.
- codexrelay tests on Windows (win-run) and Linux (wsl-run,
  magpie-desktop): ok.
- Windows smoke of the real binary (nogui build): `codex-relay`
  answers / with the readable 503, stays while its watched process
  lives, ends after it.
- Real codex 0.162.1 e2e on mote, sandbox CODEX_HOME, API-key sign-in,
  fake upstream: the relay waited out a port held 2s, then turn 1
  completed (RELAYED-OK); a turn on openrouter/kimi-k2 showed the
  refusal's message; turn 2 was mid-stream when Leave ran, the port
  was free at once, the turn completed, and the relay ended.
- GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... and a
  Windows build: ok.
- Full suite, go test -count=1 -timeout 45m ./... on mote: every
  package ok but internal/gui, where 10 real-window AppKit tests
  (dock, panel, tray, titlebar, covered window, plugin page) are
  killed at their 20-80s bars. The same 10 fail the same way at
  origin/main 4d9058a98 on mote, run alone: mote's AppKit hang, #4125
  (and #2645, #1936). None of them touches the quit path changed here.
- Rebased on origin/main 1198cff60 to push. Still running there when
  pushed: go vet ./..., Windows and Linux vet of the touched packages,
  and go test of codexrelay, gateway, agent, provider and cli. A red
  it shows gets its own issue.

Broken by hand, each red, then restored:
- Leave without ln.Close(), with a 1s delay before Shutdown injected:
  "the port isn't free after Leave" (with ln.Close: green).
- No pid watch: "relay outlived the Codex it was left for".
- Leave without the token check: an empty token got 204.
- No Origin/Host guard: Origin null got 200.
- No masking refusal, no magpie-model refusal: 200, sent upstream.
- An empty 503 at "/": TestCodexRelayIsNotMagpie red.
- RelayOpenCodex starting nothing: "no relay for the open Codex".
- EndCodexFailover never saying ended: TestCodexFailoverEndsWithMagpie.
- CodexPIDs missing "codex": the Codex app and CLI not found.

Not tried:
- the real Codex desktop app, and a real ChatGPT account. With a fake
  ChatGPT token codex 0.162.1 stops at its own "workspace routing
  discovery" against chatgpt.com before sending a turn, so the
  ChatGPT path is covered by unit tests only;
- a Codex in a WSL distro, and a connected (not failover) Codex: both
  left as they were;
- a magpie that ends without quitting (killed, crashed): still leaves
  failover in place and no relay;
- the relay's memory use as the full binary.
2026-10-29 17:13:05 +08:00

209 lines
5.5 KiB
Go

package codexrelay
import (
"context"
"io"
"net"
"net/http"
"os"
"runtime"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/proc"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/testenv"
)
// The tests run in a home of their own, never the user's real files.
func TestMain(m *testing.M) { testenv.Main(m) }
// freeAddr is a loopback address nothing listens on, held until the
// relay binds it: a port freed here could be handed to anything next.
func freeAddr(t *testing.T) (string, net.Listener) {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
return ln.Addr().String(), ln
}
// sleeper is a process of the test's own for the relay to watch, ended
// with the test.
func sleeper(t *testing.T) int {
t.Helper()
cmd := proc.Command("sleep", "600")
if runtime.GOOS == "windows" {
cmd = proc.Command("powershell", "-NoProfile", "-Command", "Start-Sleep 600")
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { cmd.Process.Kill(); cmd.Wait() })
return cmd.Process.Pid
}
func fast(t *testing.T) {
t.Helper()
wb, ww, wl := bindFor, watchEvery, leaveWait
bindFor, watchEvery, leaveWait = 10*time.Second, 50*time.Millisecond, 5*time.Second
t.Cleanup(func() { bindFor, watchEvery, leaveWait = wb, ww, wl })
}
func waitFor(t *testing.T, what string, ok func() bool) {
t.Helper()
end := time.Now().Add(20 * time.Second)
for !ok() {
if time.Now().After(end) {
t.Fatalf("never: %s", what)
}
time.Sleep(20 * time.Millisecond)
}
}
// The next magpie starting tells the relay to leave, and binds the port
// at once; the turn the relay is streaming then goes on to its end
// rather than being cut, and the relay ends after it.
func TestLeaveFreesPortAndFinishesStream(t *testing.T) {
fast(t)
addr, hold := freeAddr(t)
pid := sleeper(t)
release := make(chan struct{})
streaming := make(chan struct{})
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "first ")
w.(http.Flusher).Flush()
close(streaming)
<-release
io.WriteString(w, "last")
})
done := make(chan error, 1)
go func() { done <- Run(context.Background(), addr, []int{pid}, h) }()
// the relay waits for the port the quitting magpie still holds
time.Sleep(300 * time.Millisecond)
hold.Close()
waitFor(t, "state written", func() bool { _, ok := readState(); return ok })
type reply struct {
body string
err error
}
got := make(chan reply, 1)
go func() {
res, err := http.Get("http://" + addr + "/backend-api/codex/responses")
if err != nil {
got <- reply{err: err}
return
}
b, err := io.ReadAll(res.Body)
res.Body.Close()
got <- reply{string(b), err}
}()
<-streaming
Leave()
ln, err := net.Listen("tcp", addr)
if err != nil {
t.Fatalf("the port isn't free after Leave: %v", err)
}
ln.Close()
select {
case err := <-done:
t.Fatalf("relay ended with a turn still streaming: %v", err)
case <-time.After(200 * time.Millisecond):
}
close(release)
r := <-got
if r.err != nil || r.body != "first last" {
t.Fatalf("the streaming turn was cut: %q %v", r.body, r.err)
}
select {
case <-done:
case <-time.After(10 * time.Second):
t.Fatal("relay didn't end after its last turn")
}
if _, ok := readState(); ok {
t.Fatal("state left behind")
}
}
// With every Codex process it was left for gone, the relay ends of
// itself and gives the port back.
func TestEndsWhenCodexGone(t *testing.T) {
fast(t)
addr, hold := freeAddr(t)
hold.Close()
pid := sleeper(t)
done := make(chan error, 1)
go func() {
done <- Run(context.Background(), addr, []int{pid}, http.NotFoundHandler())
}()
waitFor(t, "state written", func() bool { _, ok := readState(); return ok })
select {
case <-done:
t.Fatal("ended while Codex runs")
case <-time.After(300 * time.Millisecond):
}
p, _ := os.FindProcess(pid)
p.Kill()
p.Wait()
select {
case <-done:
case <-time.After(10 * time.Second):
t.Fatal("relay outlived the Codex it was left for")
}
if _, ok := readState(); ok {
t.Fatal("state left behind")
}
}
// Leave asks only with the relay's token: a request without it, or from
// a page, doesn't move the relay off the port. A relay that is gone
// leaves no state for the next start to ask.
func TestLeaveNeedsToken(t *testing.T) {
fast(t)
addr, hold := freeAddr(t)
hold.Close()
pid := sleeper(t)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- Run(ctx, addr, []int{pid}, http.NotFoundHandler()) }()
waitFor(t, "state written", func() bool { _, ok := readState(); return ok })
st, _ := readState()
for _, c := range []struct{ token, origin string }{{"", ""}, {"wrong", ""}, {st.Token, "null"}} {
req, _ := http.NewRequest("POST", "http://"+addr+LeavePath, nil)
if c.token != "" {
req.Header.Set(TokenHeader, c.token)
}
if c.origin != "" {
req.Header.Set("Origin", c.origin)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
if res.StatusCode != 403 {
t.Fatalf("%+v: %d", c, res.StatusCode)
}
}
if _, err := net.Listen("tcp", addr); err == nil {
t.Fatal("the relay let go of the port without its token")
}
cancel()
<-done
// a state file whose relay is gone is removed, nothing asked
if err := writeState(state{Pid: 999999, Addr: addr, Token: "x"}); err != nil {
t.Fatal(err)
}
Leave()
if _, err := os.Stat(statePath()); !os.IsNotExist(err) {
t.Fatalf("dead relay's state kept: %v", err)
}
if !strings.HasPrefix(statePath(), settings.Dir()) {
t.Fatal("state outside magpie's folder")
}
}