Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

4.8 KB
Raw Blame
package gateway

import (
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	"github.com/yetone/magpie/internal/provider"
)

// twoAccounts stands in for the ChatGPT backend with Codex signed in to
// [email protected] (acct-1) and [email protected] (acct-2) on beside it;
// each answers with its own account id, and the requests are noted.
func twoAccounts(t *testing.T) *[]http.Header {
	t.Helper()
	codexSignedIn(t, "[email protected]")
	var heads []http.Header
	up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		io.ReadAll(r.Body)
		heads = append(heads, r.Header.Clone())
		io.WriteString(w, sse(
			`data: {"type":"response.created","response":{"id":"r1","model":"gpt-5.5"}}`,
			`data: {"type":"response.output_text.delta","delta":"from `+r.Header.Get("chatgpt-account-id")+`"}`,
			`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":7,"output_tokens":1}}}`))
	}))
	t.Cleanup(up.Close)
	was := provider.CodexBase
	provider.CodexBase = up.URL + "/backend-api/codex"
	t.Cleanup(func() { provider.CodexBase = was })
	return &heads
}

// pinnedPost asks for model at path, magpie's /v1/responses or Codex's
// own endpoint, pinned to account.
func pinnedPost(t *testing.T, s *Server, path, model, account string) (int, string) {
	t.Helper()
	rec := httptest.NewRecorder()
	req := httptest.NewRequest("POST", path, strings.NewReader(`{"model":"`+model+`","stream":true,"input":"ping"}`))
	req.Header.Set("Authorization", "Bearer magpie")
	if path != "/v1/responses" {
		req.Header.Set("Authorization", "Bearer chatgpt-token")
		req.Header.Set("chatgpt-account-id", "acct-1")
	}
	req.Header.Set(AccountHeader, account)
	s.Handler().ServeHTTP(rec, req)
	return rec.Code, rec.Body.String()
}

var pinPaths = map[string]string{"/v1/responses": "codex/gpt-5.5", CodexPath + "/responses": "gpt-5.5"}

// X-Magpie-Account names the account that answers, over the one routing
// would pick first (acct-1, Codex's own), on magpie's endpoint and on
// Codex's; the header isn't sent on, and the trace says it was pinned.
func TestAccountPinned(t *testing.T) {
	heads := twoAccounts(t)
	s := New()
	for path, model := range pinPaths {
		*heads = nil
		code, body := pinnedPost(t, s, path, model, "[email protected]")
		if code != 200 || !strings.Contains(body, "from acct-2") {
			t.Fatalf("%s: %d %s", path, code, body)
		}
		if len(*heads) != 1 || (*heads)[0].Get("chatgpt-account-id") != "acct-2" {
			t.Fatalf("%s: upstream %v", path, *heads)
		}
		if (*heads)[0].Get(AccountHeader) != "" {
			t.Errorf("%s: %s went upstream", path, AccountHeader)
		}
		r := s.trace.routes[len(s.trace.routes)-1]
		if r.Pinned != "[email protected]" || len(r.Order) != 1 || r.Order[0].Who != "[email protected]" {
			t.Errorf("%s: route pinned %q order %+v", path, r.Pinned, r.Order)
		}
	}
	// the first account, by its user, is pinned as well
	*heads = nil
	if code, body := pinnedPost(t, s, "/v1/responses", "codex/gpt-5.5", "[email protected]"); code != 200 || !strings.Contains(body, "from acct-1") {
		t.Fatalf("own account: %d %s", code, body)
	}
}

// An account magpie doesn't have is an error, not another account's reply.
func TestAccountPinnedUnknown(t *testing.T) {
	heads := twoAccounts(t)
	s := New()
	for path, model := range pinPaths {
		code, body := pinnedPost(t, s, path, model, "[email protected]")
		if code != 404 || !strings.Contains(body, "[email protected]") || !strings.Contains(body, "[email protected]") {
			t.Fatalf("%s: %d %s", path, code, body)
		}
	}
	if len(*heads) != 0 {
		t.Fatalf("asked upstream: %v", *heads)
	}
}

// A resting account pinned is an error saying so, with the other account,
// ready, not asked in its place.
func TestAccountPinnedResting(t *testing.T) {
	heads := twoAccounts(t)
	restingUntil.Lock()
	restingUntil.m["codex@[email protected]"] = time.Now().Add(time.Hour)
	restingUntil.note["codex@[email protected]"] = Rest{Why: failQuota}
	restingUntil.Unlock()
	t.Cleanup(func() {
		restingUntil.Lock()
		delete(restingUntil.m, "codex@[email protected]")
		delete(restingUntil.note, "codex@[email protected]")
		restingUntil.Unlock()
	})
	s := New()
	for path, model := range pinPaths {
		code, body := pinnedPost(t, s, path, model, "[email protected]")
		if code != 429 || !strings.Contains(body, "rests until") {
			t.Fatalf("%s: %d %s", path, code, body)
		}
	}
	if len(*heads) != 0 {
		t.Fatalf("asked upstream: %v", *heads)
	}
	// unpinned, the other one answers
	rec := httptest.NewRecorder()
	req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(`{"model":"codex/gpt-5.5","stream":true,"input":"ping"}`))
	req.Header.Set("Authorization", "Bearer magpie")
	s.Handler().ServeHTTP(rec, req)
	if rec.Code != 200 || !strings.Contains(rec.Body.String(), "from acct-2") {
		t.Fatalf("unpinned: %d %s", rec.Code, rec.Body.String())
	}
}