Skip to content

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

2.7 KB
Raw Blame
package agent

import (
	"encoding/base64"
	"encoding/json"
	"os"
	"path/filepath"
	"testing"
	"time"

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

// #1957 (parkavenue9639): Codex signed in to one account, another on in
// magpie. Claude Code's /model described every codex/gpt-* by the account
// Codex is signed in to, while magpie sent each request to the first in
// its own order: the other one when the signed-in one is paused, or when
// Codex is kept signed in to an account that isn't first. The note names
// the account a request goes to first.
func TestViaMagpieNamesTheAccountFirstInOrder(t *testing.T) {
	claims := func(m map[string]any) string {
		b, _ := json.Marshal(m)
		return "h." + base64.RawURLEncoding.EncodeToString(b) + ".s"
	}
	auth := func(email, acct string) map[string]any {
		return map[string]any{"auth_mode": "chatgpt", "tokens": map[string]any{
			"id_token":      claims(map[string]any{"email": email}),
			"access_token":  claims(map[string]any{"exp": time.Now().Add(time.Hour).Unix()}),
			"refresh_token": "r-" + acct, "account_id": acct}}
	}
	me, _ := json.Marshal(auth("[email protected]", "acct-1"))
	home, _ := codexHome(t, string(me), "model = \"gpt-5.5\"\n")
	os.WriteFile(filepath.Join(home, ".codex", "models_cache.json"), []byte(`{"models":[{"slug":"gpt-5.5","display_name":"GPT-5.5","priority":1}]}`), 0o644)
	b, _ := json.Marshal([]map[string]any{{"agent": "codex", "user": "[email protected]", "on": true,
		"seen": time.Now(), "auth": auth("[email protected]", "acct-2")}})
	os.MkdirAll(filepath.Dir(provider.Path()), 0o755)
	os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), b, 0o600)
	provider.ForgetAccounts()
	t.Cleanup(provider.ForgetAccounts)
	note := func() string {
		t.Helper()
		for _, o := range viaMagpie("claude", "") {
			if o.Value == "codex/gpt-5.5" {
				return o.Note
			}
		}
		t.Fatal("no codex/gpt-5.5 among Claude Code's models via magpie")
		return ""
	}
	if got := note(); got != "[email protected] · via magpie" {
		t.Fatalf("signed in to the first: %q", got)
	}
	// kept signed in to spare, me still first in the order
	if err := provider.SetKeepLoginAs("codex", "[email protected]"); err != nil {
		t.Fatal(err)
	}
	provider.ForgetAccounts()
	if got := note(); got != "[email protected] · via magpie" {
		t.Fatalf("kept signed in to spare, me first: %q", got)
	}
	// let go, Codex is on me again; me paused, spare takes its requests
	if err := provider.SetKeepLogin("codex", false); err != nil {
		t.Fatal(err)
	}
	if err := provider.SetLoginOn("codex", "[email protected]", false); err != nil {
		t.Fatal(err)
	}
	provider.ForgetAccounts()
	if got := note(); got != "[email protected] · via magpie" {
		t.Fatalf("signed in to me, paused: %q", got)
	}
}