Skip to content

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

provider: Codex accounts are read one at a time and renewed every 8 days, not all at once

yetone6e55914b6d2b
diff --git a/internal/provider/codex_quiet_test.go b/internal/provider/codex_quiet_test.go
new file mode 100644
index 000000000..5dd68a7d5
--- /dev/null
+++ b/internal/provider/codex_quiet_test.go
@@ -0,0 +1,130 @@
+package provider
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// The background look at Codex's accounts (KeepOnAnAccountWithRoom) reads
+// the account Codex is on, and the others only once that one is spent.
+// It read every saved account at once every five minutes, a burst from one
+// address no official client makes, for a user holding several ChatGPT
+// accounts in magpie with no agent wired (owl on Discord).
+func TestCodexLookReadsTheActiveAccountOnly(t *testing.T) {
+ home := signIn(t) // [email protected], acct-1
+ rememberLogins(true)
+ codexSignIn(t, home, "[email protected]", "r-spare")
+ rememberLogins(true)
+ codexSignIn(t, home, "[email protected]", "r-work")
+ rememberLogins(true)
+ for _, u := range []string{"[email protected]", "[email protected]"} {
+ if err := SetLoginOn("codex", u, true); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var mu sync.Mutex
+ used := map[string]float64{"[email protected]": 20, "acct-1": 20, "[email protected]": 20}
+ hits := map[string]int{}
+ fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ id := r.Header.Get("chatgpt-account-id")
+ if strings.HasSuffix(r.URL.Path, "/wham/usage") {
+ hits[id]++
+ }
+ pct := used[id]
+ mu.Unlock()
+ json.NewEncoder(w).Encode(map[string]any{"plan_type": "plus", "rate_limit": map[string]any{
+ "primary_window": map[string]any{"used_percent": pct, "limit_window_seconds": 18000}}})
+ }))
+ defer fake.Close()
+ old := CodexBase
+ CodexBase = fake.URL + "/backend-api/codex"
+ t.Cleanup(func() { CodexBase = old })
+ look := func() (string, map[string]int) {
+ t.Helper()
+ loginUsageCache.Lock()
+ loginUsageCache.m = nil
+ loginUsageCache.Unlock()
+ mu.Lock()
+ hits = map[string]int{}
+ mu.Unlock()
+ to, err := SwitchWhenSpent(context.Background(), "codex")
+ if err != nil {
+ t.Fatal(err)
+ }
+ CodexUsedUp(context.Background())
+ mu.Lock()
+ defer mu.Unlock()
+ got := map[string]int{}
+ for k, v := range hits {
+ got[k] = v
+ }
+ return to, got
+ }
+
+ // work@ has room: only work@ is read, by both the switch and CodexUsedUp
+ // (the second from the minute's cache)
+ if to, got := look(); to != "" || len(got) != 1 || got["[email protected]"] != 1 {
+ t.Fatalf("with room: switched to %q, read %v", to, got)
+ }
+ // work@ spent: now the spares are read, and the first with room taken
+ mu.Lock()
+ used["[email protected]"] = 100
+ mu.Unlock()
+ to, got := look()
+ if to == "" || got["[email protected]"] != 1 || got["acct-1"]+got["[email protected]"] == 0 {
+ t.Fatalf("spent: switched to %q, read %v", to, got)
+ }
+ for id, n := range got {
+ if n > 1 {
+ t.Fatalf("%s read %d times in one look: %v", id, n, got)
+ }
+ }
+}
+
+// Saved sign-ins are renewed as often as Codex renews its own, and one a
+// look: renewing every idle account in the same hourly look kept them
+// renewed side by side, a burst of N refreshes from one address.
+func TestKeepAliveRenewsOneALook(t *testing.T) {
+ home := signIn(t)
+ rememberLogins(true) // me@ saved
+ codexSignIn(t, home, "[email protected]", "r-spare")
+ rememberLogins(true) // spare@ saved
+ codexSignIn(t, home, "[email protected]", "r-work")
+ rememberLogins(true) // codex on work@
+ if keepAliveEvery < 8*24*time.Hour {
+ t.Fatalf("saved sign-ins renewed every %v, more often than Codex's 8 days", keepAliveEvery)
+ }
+ var mu sync.Mutex
+ var got []string
+ fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body map[string]string
+ json.NewDecoder(r.Body).Decode(&body)
+ mu.Lock()
+ got = append(got, body["refresh_token"])
+ mu.Unlock()
+ json.NewEncoder(w).Encode(map[string]any{"access_token": fakeJWT(map[string]any{"exp": float64(time.Now().Add(time.Hour).Unix())}),
+ "refresh_token": body["refresh_token"] + "-2"})
+ }))
+ defer fake.Close()
+ old := codexTokenURL
+ codexTokenURL = fake.URL
+ t.Cleanup(func() { codexTokenURL = old })
+
+ rs := renewLogins(context.Background(), 0, keepAliveAtOnce)
+ renewed := 0
+ for _, r := range rs {
+ if r.Renewed {
+ renewed++
+ }
+ }
+ if len(rs) != 2 || renewed != 1 || len(got) != 1 {
+ t.Fatalf("one look renewed %d of %+v, refreshed %v", renewed, rs, got)
+ }
+}
diff --git a/internal/provider/codex_switch.go b/internal/provider/codex_switch.go
index 9335f4847..d4f915893 100644
--- a/internal/provider/codex_switch.go
+++ b/internal/provider/codex_switch.go
@@ -237,7 +237,14 @@ func NextLogin(ctx context.Context, agent string) (from, to string, back, ok boo
if keep && first != nil && first.On && first.Lapsed == "" {
return from, first.User, true, true
}
- u := LoginUsage(ctx, agent)
+ // the account it is on, and the one it goes back to, are read; the
+ // spares only once the one it is on is spent (below): every account
+ // read at once on each look was a burst no official client makes
+ var firstUser string
+ if first != nil {
+ firstUser = first.User
+ }
+ u := someLoginUsage(ctx, agent, from, firstUser)
now := time.Now()
// an account at its usage cap is spent as one at the share below
// (account_caps.go): it is moved off, and none is moved to or back to
@@ -262,6 +269,13 @@ func NextLogin(ctx context.Context, agent string) (from, to string, back, ok boo
if keep || !known || q.Error != "" || !q.Held && !usedPast(q, share, now) && !capped(from, q) {
return "", "", false, false
}
+ users := make([]string, 0, len(spares))
+ for _, l := range spares {
+ users = append(users, l.User)
+ }
+ for user, q := range someLoginUsage(ctx, agent, users...) {
+ u[user] = q
+ }
for _, l := range spares {
if q, known := u[l.User]; known && q.Error == "" && !q.Held && !usedPast(q, share, now) && !capped(l.User, q) {
return from, l.User, false, true
diff --git a/internal/provider/keepalive.go b/internal/provider/keepalive.go
index 3fef0673a..d5600096c 100644
--- a/internal/provider/keepalive.go
+++ b/internal/provider/keepalive.go
@@ -6,7 +6,8 @@ package provider
// routing leaves the accounts whose week resets later for days) could sit
// unused past its refresh token's life, and be found signed out just when
// it's needed. So whichever magpie runs the gateway renews each such
-// sign-in about once a day. The account the agent is signed in to is the
+// sign-in about as often as Codex renews its own: every eight days, one
+// account an hour, never all of them at once. The account the agent is signed in to is the
// agent's own to refresh, and is left to it. A Claude account is never
// refreshed by magpie: Claude Code refreshes it, whenever it runs on it
// (claude_dirs.go).
@@ -22,8 +23,17 @@ import (
"github.com/yetone/magpie/internal/settings"
)
-// keepAliveEvery is how long a saved sign-in goes before it is renewed.
-const keepAliveEvery = 24 * time.Hour
+// keepAliveEvery is how long a saved sign-in goes before it is renewed:
+// Codex's own TOKEN_REFRESH_INTERVAL (codex-rs login/src/auth/manager.rs,
+// 8 days). Once a day renewed every idle account eight times as often as
+// Codex does, each one in the same hourly look as the others: a burst of
+// N refreshes from one address every day (owl on Discord).
+const keepAliveEvery = 8 * 24 * time.Hour
+
+// keepAliveAtOnce is how many due sign-ins one look renews; the rest wait
+// for the next look, an hour on, so accounts saved together drift apart
+// instead of being renewed side by side for good.
+const keepAliveAtOnce = 1
// Renewal is what came of renewing one saved account.
type Renewal struct {
@@ -40,6 +50,13 @@ type Renewal struct {
// agent's hands that have gone every or longer without it; every 0 renews
// all of them.
func RenewLogins(ctx context.Context, every time.Duration) []Renewal {
+ return renewLogins(ctx, every, 0)
+}
+
+// renewLogins is RenewLogins renewing at most atOnce of the due sign-ins
+// (0: all of them); a due one past that is left for the next look and
+// reported as not renewed.
+func renewLogins(ctx context.Context, every time.Duration, atOnce int) []Renewal {
if settings.AccountDiscoveryOff() {
return nil
}
@@ -54,15 +71,17 @@ func RenewLogins(ctx context.Context, every time.Duration) []Renewal {
ls := readLogins()
loginsMu.Unlock()
out := []Renewal{}
+ tried := 0
for _, l := range ls {
if l.Agent != "codex" || strings.EqualFold(active[l.Agent], l.User) || leftAlone(l.Agent) {
continue
}
r := Renewal{Agent: l.Agent, User: l.User}
- if every > 0 && !renewalDue(l, every, time.Now()) {
+ if every > 0 && !renewalDue(l, every, time.Now()) || atOnce > 0 && tried >= atOnce {
out = append(out, r)
continue
}
+ tried++
if _, _, err := renewSavedLogin(ctx, l.Agent, l.User, true); err != nil {
r.Err = err.Error()
var refused refreshRefused
@@ -92,8 +111,8 @@ func renewalDue(l savedLogin, every time.Duration, now time.Time) bool {
return now.Sub(last) >= every
}
-// KeepLoginsAlive renews the saved sign-ins that are due, a minute after it
-// starts and every hour after that — a computer that slept through a day
+// KeepLoginsAlive renews a saved sign-in that is due, one a look, a minute
+// after it starts and every hour after that — a computer that slept through a day
// catches up within the hour of waking — until ctx ends.
func KeepLoginsAlive(ctx context.Context) {
t := time.NewTimer(time.Minute)
@@ -105,7 +124,7 @@ func KeepLoginsAlive(ctx context.Context) {
case <-t.C:
}
c, cancel := context.WithTimeout(ctx, 2*time.Minute)
- for _, r := range RenewLogins(c, keepAliveEvery) {
+ for _, r := range renewLogins(c, keepAliveEvery, keepAliveAtOnce) {
if r.Err != "" {
log.Printf("keeping %s account %s signed in: %s", r.Agent, r.User, r.Err)
}
diff --git a/internal/provider/keepalive_test.go b/internal/provider/keepalive_test.go
index 59e3a1359..58ee8bb1f 100644
--- a/internal/provider/keepalive_test.go
+++ b/internal/provider/keepalive_test.go
@@ -58,7 +58,7 @@ func TestRenewLogins(t *testing.T) {
t.Fatalf("refreshed with %v", got)
}
l := saved()
- if !strings.Contains(string(l.Auth), `"r-2"`) || time.Since(l.Renewed) > time.Minute || !renewalDue(l, keepAliveEvery, time.Now().Add(25*time.Hour)) {
+ if !strings.Contains(string(l.Auth), `"r-2"`) || time.Since(l.Renewed) > time.Minute || !renewalDue(l, keepAliveEvery, time.Now().Add(keepAliveEvery+time.Hour)) {
t.Fatalf("saved after renewal: %+v", l)
}
var live codexAuth
@@ -125,11 +125,14 @@ func TestRenewalDue(t *testing.T) {
l savedLogin
due bool
}{
- {"never renewed, seen long ago", savedLogin{Agent: "codex", Seen: now.Add(-48 * time.Hour)}, true},
+ {"never renewed, seen long ago", savedLogin{Agent: "codex", Seen: now.Add(-9 * 24 * time.Hour)}, true},
+ {"never renewed, seen two days ago", savedLogin{Agent: "codex", Seen: now.Add(-48 * time.Hour)}, false},
{"seen in the agent's hands today", savedLogin{Agent: "codex", Seen: now.Add(-time.Hour)}, false},
- {"renewed today", savedLogin{Agent: "codex", Seen: now.Add(-72 * time.Hour), Renewed: now.Add(-time.Hour)}, false},
+ {"renewed today", savedLogin{Agent: "codex", Seen: now.Add(-30 * 24 * time.Hour), Renewed: now.Add(-time.Hour)}, false},
{"codex refreshed itself lately", savedLogin{Agent: "codex", Seen: now.Add(-72 * time.Hour), Auth: codex(now.Add(-2 * time.Hour))}, false},
- {"codex a day since", savedLogin{Agent: "codex", Seen: now.Add(-72 * time.Hour), Auth: codex(now.Add(-25 * time.Hour))}, true},
+ {"codex a day since", savedLogin{Agent: "codex", Seen: now.Add(-72 * time.Hour), Auth: codex(now.Add(-25 * time.Hour))}, false},
+ {"codex a week since", savedLogin{Agent: "codex", Seen: now.Add(-30 * 24 * time.Hour), Auth: codex(now.Add(-7 * 24 * time.Hour))}, false},
+ {"codex eight days since", savedLogin{Agent: "codex", Seen: now.Add(-30 * 24 * time.Hour), Auth: codex(now.Add(-8*24*time.Hour - time.Minute))}, true},
} {
if got := renewalDue(c.l, keepAliveEvery, now); got != c.due {
t.Errorf("%s: due %v", c.name, got)
diff --git a/internal/provider/login_usage.go b/internal/provider/login_usage.go
index fa6d4a12c..45ef1b29a 100644
--- a/internal/provider/login_usage.go
+++ b/internal/provider/login_usage.go
@@ -106,13 +106,47 @@ func LoginUsage(ctx context.Context, agent string) map[string]SubscriptionQuota
// each account's reading's state: when it was last read well, and
// whether this try failed.
func loginUsageAt(ctx context.Context, agent string) (map[string]SubscriptionQuota, time.Time, map[string]readState) {
+ return loginUsageOf(ctx, agent, nil)
+}
+
+// someLoginUsage is LoginUsage of the named accounts alone. What a
+// background look needs is the account the agent is on, and the others
+// only once that one is spent: reading every account at once, every few
+// minutes from one address, is a pattern no single official client makes
+// (owl on Discord, accounts held in magpie with no agent wired).
+func someLoginUsage(ctx context.Context, agent string, users ...string) map[string]SubscriptionQuota {
+ want := map[string]bool{}
+ for _, u := range users {
+ if u != "" {
+ want[strings.ToLower(u)] = true
+ }
+ }
+ if len(want) == 0 {
+ return map[string]SubscriptionQuota{}
+ }
+ out, _, _ := loginUsageOf(ctx, agent, want)
+ return out
+}
+
+// loginUsageOf is loginUsageAt over the accounts whose lower-cased user
+// is in only, or over every account when only is nil.
+func loginUsageOf(ctx context.Context, agent string, only map[string]bool) (map[string]SubscriptionQuota, time.Time, map[string]readState) {
// nor of a provider switched off or removed (leftAlone)
if settings.AccountDiscoveryOff() || leftAlone(agent) {
return nil, time.Time{}, nil
}
asked := time.Now()
states := map[string]readState{}
- if out, ok := loginUsageStandIn(ctx, agent); ok {
+ if all, ok := loginUsageStandIn(ctx, agent); ok {
+ out := all
+ if only != nil {
+ out = map[string]SubscriptionQuota{} // the stand-in's map is its own
+ for user, q := range all {
+ if only[strings.ToLower(user)] {
+ out[user] = q
+ }
+ }
+ }
for user, q := range out {
states[user] = loginUsageEntry{at: asked, read: q}.state()
}
@@ -127,6 +161,9 @@ func loginUsageAt(ctx context.Context, agent string) (map[string]SubscriptionQuo
var wg sync.WaitGroup
oldest := asked
for _, l := range logins {
+ if only != nil && !only[strings.ToLower(l.User)] {
+ continue
+ }
wg.Add(1)
go func() {
defer wg.Done()
@@ -453,8 +490,15 @@ func CodexUsedUp(ctx context.Context) bool {
return codexReadingHeld(codexHoldReading(ctx))
}
// read as LoginUsage has it, fetched at most once a minute: the agent
- // package asks on every catalog sync
- return codexReadingHeld(LoginUsage(ctx, "codex"))
+ // package asks on every catalog sync. Only the account Codex is
+ // signed in to counts (codexReadingHeld), so only it is read
+ var active []string
+ for _, l := range Logins("codex") {
+ if l.Active {
+ active = append(active, l.User)
+ }
+ }
+ return codexReadingHeld(someLoginUsage(ctx, "codex", active...))
}
// CodexHoldMatters is set by the agent package: whether Codex is wired to