Files
magpie/internal/provider/switch_next_test.go
T
yetone 15b83901ac accounts: switch to the next account with room, or the one with the most left (#4532)
StringKe (#4532), comparing magpie with cswap 0.29.0: there was no "switch
to the next account", and when every account was past its line the
automatic switch stayed on the spent one, where cswap moves to the account
with the most room left.

- `magpie accounts switch <claude|codex> next` (provider.NextInOrder) takes
  the other accounts that are on in magpie, from the one after the account
  the agent is on, wrapping round: the first whose allowance is known and
  has room, else the one with the most room left, and says it is past its
  line. A saved Claude account not read yet is read first (readSpare), as
  the automatic switch's spares are. With no reading of any it refuses
  rather than guess; for any other agent it asks for the account by name.
- NextLogin (shared by Codex and Claude Code): when the account the agent
  is on is spent and every spare is past its line too, it moves to the
  spare with the most room left (roomLeft: the fullest stopping window's
  distance below the switch share, or the account's own cap when lower),
  when that has at least roomMargin (1 point) more than the one it is on,
  so two all but even accounts don't trade the agent each look. A held,
  failed or unknown reading is never moved to. One model's own window
  still counts for nothing, as before.
- docs: reference.md (the automatic switch and `next`; its "a Claude
  account magpie knows nothing of is not moved to" was stale since
  readSpare), providers-accounts.md's Used-up switch row, the en/zh/ja
  start pages' command table, `magpie help`.

Run (on mote, sandbox HOME through the packages' TestMain):
- go test -timeout 45m -count=1 ./internal/provider ./internal/cli: ok
  (144s, 44s), at this change's tree before the next commit's edits.
- TestNextLoginTakesTheMostRoomWhenAllArePast and TestNextInOrder, each
  over codex and claude with three accounts: green; red with the fallback
  taken out of NextLogin (the two "most room" cases, both agents) and with
  NextInOrder not starting after the signed-in account ("the one after
  it", both agents). The "none has more by the margin" case fails without
  roomMargin.
- Built the nogui binary and ran in a fresh sandbox HOME on mote:
  `accounts switch claude next --help` (prints the accounts help),
  `switch claude next` and `switch codex next` with no accounts ("has no
  other account that is on"), `switch gemini next` (asks for a name),
  `switch claude nxt` (no such account), `switch claude` (usage).
- gofmt -l clean. Cross-OS vet: run at the head of this stack.

Not tried: a real switch between real Claude or Codex accounts; the CLI
`next` with real saved accounts (the provider tests cover the choice).
2026-10-31 18:18:37 +08:00

147 lines
5.1 KiB
Go

package provider
import (
"context"
"slices"
"strings"
"testing"
"time"
)
// threeAccounts signs agent in to three accounts in a sandbox HOME, all on
// in magpie, and answers them as `next` takes them: the two the agent
// isn't on, from the one after the account it is on in their order,
// wrapping round, then that account.
func threeAccounts(t *testing.T, agent string) []string {
t.Helper()
if agent == "codex" {
home := signIn(t) // me@example.com
rememberLogins(true)
codexSignIn(t, home, "work@example.com", "r-work")
rememberLogins(true)
codexSignIn(t, home, "third@example.com", "r-third")
rememberLogins(true)
} else {
claudeThree(t)
}
ls := Logins(agent)
at := slices.IndexFunc(ls, func(l Login) bool { return l.Active })
if len(ls) != 3 || at < 0 {
t.Fatalf("not three accounts, one signed in: %+v", ls)
}
if at == 2 {
t.Fatalf("the one signed in is the last, so nothing wraps round: %+v", ls)
}
var users []string
for i := range ls {
l := ls[(at+1+i)%3]
if err := SetLoginOn(agent, l.User, true); err != nil {
t.Fatal(err)
}
users = append(users, l.User)
}
return users
}
func usedAt(agent string, used map[string]float64) func(context.Context, string) map[string]SubscriptionQuota {
at := time.Now().Add(time.Hour)
return func(context.Context, string) map[string]SubscriptionQuota {
out := map[string]SubscriptionQuota{}
for u, v := range used {
out[u] = SubscriptionQuota{Provider: agent, User: u, Windows: []QuotaWindow{
{Name: "5 hours", Used: v, ResetsAt: &at, Span: 5 * time.Hour},
{Name: "Fable", Used: 100, Model: "fable", ResetsAt: &at}, // one model's own: never counted
}}
}
return out
}
}
// StringKe (#4532): when the account the agent is on is spent and every
// other is past its line too, the switch moves to the one with the most
// room left, as cswap does, and stays when none has more than the one it
// is on by roomMargin. Codex shares the switch, so it is held to it too.
func TestNextLoginTakesTheMostRoomWhenAllArePast(t *testing.T) {
for _, agent := range []string{"codex", "claude"} {
t.Run(agent, func(t *testing.T) {
u := threeAccounts(t, agent)
on := u[2]
t.Cleanup(func() { LoginUsageVia(nil) })
for _, c := range []struct {
name string
used []float64 // u[0], u[1], on
to string
}{
{"the first has room", []float64{50, 99, 100}, u[0]},
{"the second has the most room", []float64{99.5, 98.5, 100}, u[1]},
{"the first has the most room", []float64{98.2, 99.9, 100}, u[0]},
{"none has more by the margin", []float64{99.5, 99.5, 100}, ""},
{"the one it is on has the most", []float64{100, 100, 99}, ""},
} {
LoginUsageVia(usedAt(agent, map[string]float64{u[0]: c.used[0], u[1]: c.used[1], on: c.used[2]}))
from, to, back, ok := NextLogin(context.Background(), agent)
if c.to == "" {
if ok {
t.Errorf("%s: moved %q→%q, want it to stay", c.name, from, to)
}
continue
}
if !ok || back || from != on || to != c.to {
t.Errorf("%s: got %q→%q back=%v ok=%v, want %q→%q", c.name, from, to, back, ok, on, c.to)
}
}
})
}
}
// `magpie accounts switch <agent> next` takes the accounts in order from
// the one after the account the agent is on, wrapping round: the first
// with room, else the one with the most room left, said to be past its
// line; one off in magpie is never taken.
func TestNextInOrder(t *testing.T) {
for _, agent := range []string{"codex", "claude"} {
t.Run(agent, func(t *testing.T) {
u := threeAccounts(t, agent)
on := u[2]
t.Cleanup(func() { LoginUsageVia(nil) })
for _, c := range []struct {
name string
used []float64
off int // 1-based index of an account turned off, 0 none
to string
over bool
}{
{"the one after it", []float64{10, 10, 10}, 0, u[0], false},
{"the first spent, the second has room", []float64{99, 10, 10}, 0, u[1], false},
{"every one past, the second has the most", []float64{99.5, 98.5, 10}, 0, u[1], true},
{"every one past, the first has the most", []float64{98.5, 100, 10}, 0, u[0], true},
{"the first off", []float64{10, 10, 10}, 1, u[1], false},
} {
LoginUsageVia(usedAt(agent, map[string]float64{u[0]: c.used[0], u[1]: c.used[1], on: c.used[2]}))
if c.off > 0 {
if err := SetLoginOn(agent, u[c.off-1], false); err != nil {
t.Fatal(err)
}
}
to, over, err := NextInOrder(context.Background(), agent)
if err != nil || !strings.EqualFold(to, c.to) || over != c.over {
t.Errorf("%s: got %q over=%v err=%v, want %q over=%v", c.name, to, over, err, c.to, c.over)
}
if c.off > 0 {
if err := SetLoginOn(agent, u[c.off-1], true); err != nil {
t.Fatal(err)
}
}
}
// none read: magpie says so rather than guess
LoginUsageVia(func(context.Context, string) map[string]SubscriptionQuota { return map[string]SubscriptionQuota{} })
if to, _, err := NextInOrder(context.Background(), agent); err == nil {
t.Errorf("no readings: got %q, want an error", to)
}
})
}
if _, _, err := NextInOrder(context.Background(), "gemini"); err == nil {
t.Error("next for Gemini CLI: want an error")
}
}