Files
magpie/internal/provider/keepalive.go
T
yetone 75cbc7e1e5 provider: a subscription switched off or removed makes no background requests, no claude auth status every minute (Riko on Discord)
Riko switched Claude off in Providers, and magpie still ran
`claude auth status --json` about every minute. Off only kept the
gateway from routing to it. Every page and request lists accounts,
which re-asked the CLI, and the background loops went on reading
allowances, renewing, switching, warming, checking in and fetching lists.
The same held for each sibling with a CLI or account check: Cursor
(`cursor-agent about`), Devin (`devin auth status`) and the rest.

What changed:
- left_alone.go: leftAlone(id), true for a provider that is Off or
  Hidden (account removed).
- account.go claudeIdentity and cli_identity.go get (Cursor, Devin): the
  CLI isn't asked; what it said last (memory or cli-identity.json) is
  served, so the account stays listed to switch on again.
- subscription_usage.go: claude, cursor and grok are checked as hidden
  before their account is looked up (the look-up ran the CLI).
- login_usage.go loginUsageAt, keepalive.go RenewLogins,
  codex_switch.go NextLogin, codex_warmup.go keepWarm: leftAlone where
  only accountRemoved (or nothing) was checked.
- models.go newDue: a provider that is off has no list fetched.
- checkin.go: each check-in account knows its card's provider; the loop
  skips one that is left alone, a press still checks it in (minimax,
  trae, qoder, workbuddy, plugin check-ins set it).
- docs/subsystems/providers-accounts.md says so.
Not covered: KeepPluginsListed lists every plugin at once in the host. A
Cursor switched off that was never asked who is signed in isn't listed
until switched on.

What was run:
- TestLeftAloneRunsNoCLI: fake claude, cursor-agent and devin on PATH log
  each run; with claude and cursor off and devin removed, All, Hidden,
  fetchSubscriptionUsage, LoginUsage, RenewLogins, SwitchWhenSpent and
  FetchNew run three times over stale caches and no CLI is run; switched
  back on, all three are asked again.
- Break check: with the source changes reverted it fails with
  "switched off or removed, the CLIs were run: [claude_auth_status_--json
  cursor-agent_about_--format_json devin_auth_status ...]"; with only the
  claude gate removed only claude is logged, with only cliIdentity's only
  cursor and devin.
- go test -tags nogui -timeout 45m ./internal/provider ./internal/gateway:
  ok (399s, 1271s).
- gofmt -l: clean. go vet (darwin), GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean, under set -o pipefail.
2026-10-14 08:28:08 +08:00

117 lines
3.4 KiB
Go

package provider
// Keeping saved accounts signed in. A ChatGPT account saved in magpie but
// not the one Codex is signed in to is refreshed only when it is used or
// its allowance looked at — and one waiting its turn (smart
// 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
// 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).
import (
"context"
"encoding/json"
"errors"
"log"
"strings"
"time"
"github.com/yetone/magpie/internal/settings"
)
// keepAliveEvery is how long a saved sign-in goes before it is renewed.
const keepAliveEvery = 24 * time.Hour
// Renewal is what came of renewing one saved account.
type Renewal struct {
Agent string `json:"agent"`
User string `json:"user"`
// Renewed is false when it wasn't due; Err is why it failed, and Lapsed
// whether the sign-in is gone (the vendor refused it) or may yet renew.
Renewed bool `json:"renewed"`
Err string `json:"error,omitempty"`
Lapsed bool `json:"lapsed,omitempty"`
}
// RenewLogins renews the saved ChatGPT sign-ins not in the
// 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 {
if settings.AccountDiscoveryOff() {
return nil
}
rememberLogins(false)
loginsMu.Lock()
active := map[string]string{}
for _, a := range loginAgents {
if l, ok := liveLogin(a); ok {
active[a] = l.User
}
}
ls := readLogins()
loginsMu.Unlock()
out := []Renewal{}
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()) {
out = append(out, r)
continue
}
if _, _, err := renewSavedLogin(ctx, l.Agent, l.User, true); err != nil {
r.Err = err.Error()
var refused refreshRefused
r.Lapsed = errors.As(err, &refused)
} else {
r.Renewed = true
}
out = append(out, r)
}
return out
}
// renewalDue says whether a saved sign-in has gone every without being
// renewed — since magpie last renewed it, or since it was last seen in the
// agent's hands, which kept it fresh — or its refresh token is near its end.
func renewalDue(l savedLogin, every time.Duration, now time.Time) bool {
last := l.Renewed
if l.Seen.After(last) {
last = l.Seen
}
var a struct {
LastRefresh time.Time `json:"last_refresh"`
}
if json.Unmarshal(l.Auth, &a) == nil && a.LastRefresh.After(last) {
last = a.LastRefresh
}
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
// catches up within the hour of waking — until ctx ends.
func KeepLoginsAlive(ctx context.Context) {
t := time.NewTimer(time.Minute)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
c, cancel := context.WithTimeout(ctx, 2*time.Minute)
for _, r := range RenewLogins(c, keepAliveEvery) {
if r.Err != "" {
log.Printf("keeping %s account %s signed in: %s", r.Agent, r.User, r.Err)
}
}
cancel()
t.Reset(time.Hour)
}
}