diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 8a323f025..87924b6b5 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -162,6 +162,7 @@ readings on both sides of detected boundaries. - The gateway and a magpie run from a terminal change the same files (#1674). `loginsMu` is a [`filelock.Mutex`](../../internal/filelock/filelock.go): besides the mutex it holds an OS lock on `logins.json.lock` (flock, `LockFileEx` on Windows), and taking it has `logins.json` read afresh (`filememo.Look`), so every read a change is made from sees what another magpie wrote, and a refresh the gateway wrote is never written back over. `savedTokenMu` holds `logins.json.renew.lock` the same way, so two magpies never spend one refresh token. `caller-keys.json` (`access`) and `mcp-signins.json` (`mcpauth`, with `mcp-signins.json.renew.lock` around a renewal) are changed under such locks too; `plugin-auth.json` already was, under `plugin-auth.json.lock`, which `host.js` takes too. A lock another magpie holds is waited for up to `filelock.Wait` (10s), then gone on without, as before there was one. `rememberLogins` writes nothing when only `Seen` would move on and the saved one is less than `seenEvery` (10 minutes) old, so a run that only lists accounts (`magpie ls`, `providers`, `sessions`, `usage`) leaves `logins.json` as it is. [`logins_lock_test.go`](../../internal/provider/logins_lock_test.go) covers both, the second with another test process writing between this one's read and write. - The account Codex or Claude Code is signed in to can be paused (`SetLoginOn` off, #263) only while another of its accounts is on. The gateway then sends it nothing: Codex's own-model turns go through routing, which passes over it (`OwnPaused`), and a native compaction (`/responses/compact`) goes to the first account on that isn't resting, signed as that account (`compactOn` in [codex_backend.go](../../internal/gateway/codex_backend.go)). The last other account off, the paused one is used again. A switched-off Codex provider is not a pause: Codex's own-model requests still relay on its sign-in as they came. - A switched-off provider (`Off`, #163) stays saved. The gateway says it is off instead of saying the model is unknown. +- A subscription switched off (`Off`) or whose account was removed from magpie (`Hidden`) is left alone in the background (`leftAlone` in [`left_alone.go`](../../internal/provider/left_alone.go); Riko on Discord, whose Claude switched off still ran `claude auth status --json` every minute). No CLI is asked who is signed in (`claudeIdentity`, `cliIdentity.get` for Cursor and Devin): what it said last, in memory or `cli-identity.json`, is served, so the account stays listed to switch on again. Nor is its allowance read (`fetchSubscriptionUsage`, `loginUsageAt`), a saved ChatGPT sign-in renewed (`RenewLogins`), the agent's account switched (`NextLogin`), a window warmed (`keepWarm`), its model list fetched (`newDue`), or a daily check-in made by the loop (`checkinNow` with `soon` false; a press still checks in). A Cursor switched off that was never asked who is signed in isn't listed until it is switched on. `TestLeftAloneRunsNoCLI` runs those paths with fake `claude`, `cursor-agent` and `devin` CLIs on PATH and checks none ran. Plugins' model lists (`KeepPluginsListed`) are asked of the plugin host all at once and aren't held back per provider. - A provider removed or switched off takes its models out of the catalog. [Agent wiring](agent-wiring.md)'s `Reseat` moves agents off them. - A preset marked `NoList` uses its preset model list instead of requesting `/models`, and ignores previously fetched lists, including their protocol and key restrictions, unless the user sets `ModelsURL` or chooses a region marked `Lists`. Each region can carry a different list. Volcengine Ark's Coding Plan and Agent Plan use separate preset lists. Both plans include their embedding model separately from agents' chat-model lists; Agent Plan additionally exposes its image- and video-generation models to Settings → Images; Ark itself refuses video generation on Small and Medium Agent Plans, which include it only in the Large and Max tiers. Models magpie does not yet serve (Agent Plan's speech models) are not advertised. Ark's pay-as-you-go region still fetches its own list. Coding's `/api/coding/v3/models` returns a general Ark catalog instead of the plan's model ids, while Agent's `/api/plan/v3/models` returns 404. [`presets.go`](../../internal/provider/presets.go) defines these choices; `List`, `fetch`, `live`, `planModels`, `PlanEmbeddings`, `PlanDrawers` and `PlanVideos` in [`models.go`](../../internal/provider/models.go) apply them when adding, refreshing and reading cached models. `TestVolcengineModelLists` checks that the plans make no list requests, ignore old cached lists and return their own preset models; pay-as-you-go and an explicit list URL still make requests. - A gateway key held to some accounts (#905) is held to those of the providers its list names: a provider it names no account of, the key uses as it always did. The list keeps an account by its stable id — `logins.json`'s `id`, set once written and kept through renames; the agents that keep no logins (and plugins) are known by a hash of the account's name, so an account renamed there drops out of a key's list, holding it closer, never wider. Storing an id for every agent is a larger change, not this one's. diff --git a/internal/provider/account.go b/internal/provider/account.go index 1159adc58..59084bf47 100644 --- a/internal/provider/account.go +++ b/internal/provider/account.go @@ -638,9 +638,13 @@ var claudeExecutable = claudecode.Find // still lying around (a keychain item logout left behind), so a signed-out // account stops showing up as a provider. func claudeIdentity() (user, plan string, signedOut bool) { + // switched off or removed, Claude Code isn't asked: what it said last + // is served (leftAlone) + quiet := leftAlone("claude") claudeStatusMu.Lock() defer claudeStatusMu.Unlock() switch { + case quiet: case claudeStatusAt.IsZero(): claudeStatusAt = time.Now() if u, p, out, ok := askClaudeStatus(); ok { diff --git a/internal/provider/checkin.go b/internal/provider/checkin.go index aa6760bb3..10fc258c4 100644 --- a/internal/provider/checkin.go +++ b/internal/provider/checkin.go @@ -19,10 +19,11 @@ import ( // checkinAcct is an account checked in each day. type checkinAcct struct { - User string - On bool - key string // its entry in the file; "" for one that can't be told apart - do func(context.Context) WorkBuddyCheckin + User string + On bool + key string // its entry in the file; "" for one that can't be told apart + provider string // the provider its card is under, which the user can switch off + do func(context.Context) WorkBuddyCheckin } // checkiner checks the accounts it lists in, keeping what came of it at @@ -71,6 +72,11 @@ func (c checkiner) checkinNow(ctx context.Context, soon bool) []WorkBuddyCheckin if !a.On || a.key == "" || asked[a.key] || off[a.key] { continue } + // nor, by the loop, one whose provider is switched off or removed + // (leftAlone); a press still checks it in + if !soon && leftAlone(a.provider) { + continue + } asked[a.key] = true prev, seen := st[a.key] settled := prev.settled(day, now, soon) diff --git a/internal/provider/cli_identity.go b/internal/provider/cli_identity.go index 6a4d275aa..2e5fa0d07 100644 --- a/internal/provider/cli_identity.go +++ b/internal/provider/cli_identity.go @@ -111,6 +111,11 @@ func (c *cliIdentity) get() (user, plan string, ok bool) { c.at = time.Unix(1, 0) } } + if leftAlone(c.name) { + // switched off or removed: the CLI isn't asked, what it said last + // is served + return c.user, c.plan, c.ok + } if c.at.IsZero() { // never answered: waited for, but only so long and only once — a // request looks several times, and a CLI that takes longer is diff --git a/internal/provider/codex_switch.go b/internal/provider/codex_switch.go index f87c16beb..d6b0d8ccf 100644 --- a/internal/provider/codex_switch.go +++ b/internal/provider/codex_switch.go @@ -142,8 +142,8 @@ func usedPast(q SubscriptionQuota, share float64, now time.Time) bool { // accounts that are on in magpie, in the order they were saved, whose // allowance is known and not spent. ok is false when the agent should stay. func NextLogin(ctx context.Context, agent string) (from, to string, back, ok bool) { - if accountRemoved(agent) { - return "", "", false, false // magpie has no say in its sign-in + if leftAlone(agent) { + return "", "", false, false // magpie has no say in its sign-in, or was told to leave it be } var spares []Login var first *Login diff --git a/internal/provider/codex_warmup.go b/internal/provider/codex_warmup.go index b96c4ba74..445d641ba 100644 --- a/internal/provider/codex_warmup.go +++ b/internal/provider/codex_warmup.go @@ -565,7 +565,7 @@ func keepWarm(ctx context.Context, name string, w codexWarmer, prefs func() (whi } // the wall clock, which goes on while the machine sleeps now := w.now().Round(0) - if which, at := prefs(); warmLook(which, at, w.owned(), now1, last, now) { + if which, at := prefs(); !leftAlone(name) && warmLook(which, at, w.owned(), now1, last, now) { last = now c, cancel := context.WithTimeout(ctx, 2*time.Minute) for _, r := range w.warmNow(c, which, at) { diff --git a/internal/provider/keepalive.go b/internal/provider/keepalive.go index 356866f32..3fef0673a 100644 --- a/internal/provider/keepalive.go +++ b/internal/provider/keepalive.go @@ -55,7 +55,7 @@ func RenewLogins(ctx context.Context, every time.Duration) []Renewal { loginsMu.Unlock() out := []Renewal{} for _, l := range ls { - if l.Agent != "codex" || strings.EqualFold(active[l.Agent], l.User) || accountRemoved(l.Agent) { + if l.Agent != "codex" || strings.EqualFold(active[l.Agent], l.User) || leftAlone(l.Agent) { continue } r := Renewal{Agent: l.Agent, User: l.User} diff --git a/internal/provider/left_alone.go b/internal/provider/left_alone.go new file mode 100644 index 000000000..2095f0345 --- /dev/null +++ b/internal/provider/left_alone.go @@ -0,0 +1,25 @@ +package provider + +// A provider the user switched off (Provider.Off) or whose account they +// removed from magpie (Provider.Hidden) is left alone in the background: +// no CLI is asked who is signed in (`claude auth status`, `cursor-agent +// about`, `devin auth status`), no allowance is read, no sign-in renewed, +// no window warmed, no account switched, no daily check-in made and no +// model list fetched. What was last known of it is still shown. Each of +// those ran every minute or so for a Claude switched off, and a request +// made just as a proxy came back up after a restart went out on the +// machine's own address (Riko on Discord). + +// leftAlone says whether magpie leaves provider id alone in the +// background: switched off, or its account removed from magpie. +func leftAlone(id string) bool { + if id == "" { + return false + } + for _, p := range load().Providers { + if p.ID == id && (p.Off || p.Hidden) { + return true + } + } + return false +} diff --git a/internal/provider/left_alone_test.go b/internal/provider/left_alone_test.go new file mode 100644 index 000000000..5a700e7fd --- /dev/null +++ b/internal/provider/left_alone_test.go @@ -0,0 +1,120 @@ +package provider + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/claudecode" + "github.com/yetone/magpie/internal/testenv" +) + +// A provider switched off, or whose account was removed from magpie, gets +// no request from magpie in the background: its CLI isn't asked who is +// signed in, its allowance isn't read, its sign-in isn't renewed or +// switched, its list isn't fetched (Riko on Discord: with Claude switched +// off, Surge showed `claude auth status --json` every minute). Fake +// claude, cursor-agent and devin CLIs on PATH log every run, and what the +// gateway's loops and the window's pages do is run with each of them +// stale, as minutes passing leave them. +func TestLeftAloneRunsNoCLI(t *testing.T) { + shellFakes(t) + findDevin := DevinExecutable + home := claudeHome(t) + claudeSignIn(t, home, time.Now().Add(24*time.Hour)) + writeFile(t, filepath.Join(home, ".claude.json"), map[string]any{"oauthAccount": map[string]any{"emailAddress": "me@example.com"}}) + + bin, log := t.TempDir(), filepath.Join(t.TempDir(), "runs") + for _, name := range []string{"claude", "cursor-agent", "devin"} { + testenv.Program(t, filepath.Join(bin, name), "#!/bin/sh\necho \""+name+" $*\" >> "+log+"\n"+ + "echo '{\"loggedIn\":true,\"email\":\"me@example.com\",\"subscriptionType\":\"max\"}'\n") + } + t.Setenv("PATH", bin+string(os.PathListSeparator)+"/usr/bin"+string(os.PathListSeparator)+"/bin") + // the real lookups, which find them on PATH + claudeExecutable, DevinExecutable = claudecode.Find, findDevin + forgetClaudeStatus() + forgetCursorStatus() + forgetDevinStatus() + t.Cleanup(func() { forgetClaudeStatus(); forgetCursorStatus(); forgetDevinStatus() }) + + runs := func() []string { + b, _ := os.ReadFile(log) + return strings.Fields(strings.ReplaceAll(strings.TrimSpace(string(b)), " ", "_")) + } + stale := func() { + claudeStatusMu.Lock() + if !claudeStatusAt.IsZero() { + claudeStatusAt = time.Now().Add(-time.Hour) + } + claudeStatusMu.Unlock() + for _, c := range cliIdentities() { + c.Lock() + if !c.at.IsZero() { + c.at = time.Now().Add(-time.Hour) + } + c.Unlock() + } + loginsMu.Lock() + loginsSeenAt = time.Time{} + loginsMu.Unlock() + } + loop := func() { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + for range 3 { + stale() + All() + Hidden() + fetchSubscriptionUsage(ctx) + for _, agent := range []string{"claude", "cursor", "devin"} { + LoginUsage(ctx, agent) + } + RenewLogins(ctx, 0) + SwitchWhenSpent(ctx, "claude") + FetchNew(time.Second) + } + } + + save := func(off, hidden bool) { + writeFile(t, Path(), map[string]any{"providers": []map[string]any{ + {"id": "claude", "off": off}, {"id": "cursor", "off": off}, {"id": "devin", "hidden": hidden}, + }}) + } + save(true, true) + loop() + if got := runs(); len(got) != 0 { + t.Fatalf("switched off or removed, the CLIs were run: %v", got) + } + // the account is still there to switch on again, its CLI never asked + if p, ok := find(All(), "claude"); !ok || !p.Off { + t.Fatalf("claude switched off: %+v %v", p, ok) + } + + // switched on, the same loop asks them: the fakes are the ones found + save(false, false) + loop() + got := strings.Join(runs(), " ") + for _, want := range []string{"claude_auth_status_--json", "cursor-agent_", "devin_auth_status"} { + if !strings.Contains(got, want) { + t.Errorf("switched on, no %s among %s", want, got) + } + } + // what was asked behind the look has answered before the test ends + for _, c := range cliIdentities() { + if pending, done := c.asking(); pending { + <-done + } + } + for { + claudeStatusMu.Lock() + busy := claudeStatusBusy + claudeStatusMu.Unlock() + if !busy { + break + } + time.Sleep(10 * time.Millisecond) + } +} diff --git a/internal/provider/login_usage.go b/internal/provider/login_usage.go index 52750b418..51230b62a 100644 --- a/internal/provider/login_usage.go +++ b/internal/provider/login_usage.go @@ -76,7 +76,8 @@ func LoginUsage(ctx context.Context, agent string) map[string]SubscriptionQuota // one taken from the cache is up to a minute old already, and Allowances // counts its own minute from then, not from when it asked (#1295). func loginUsageAt(ctx context.Context, agent string) (map[string]SubscriptionQuota, time.Time) { - if settings.AccountDiscoveryOff() { + // nor of a provider switched off or removed (leftAlone) + if settings.AccountDiscoveryOff() || leftAlone(agent) { return nil, time.Time{} } asked := time.Now() diff --git a/internal/provider/minimax_checkin.go b/internal/provider/minimax_checkin.go index 07049f26f..770e95f03 100644 --- a/internal/provider/minimax_checkin.go +++ b/internal/provider/minimax_checkin.go @@ -21,6 +21,7 @@ package provider // WorkBuddy's and Trae CN's are (checkin.go). import ( + "cmp" "context" "crypto/md5" "encoding/hex" @@ -131,7 +132,7 @@ func newMiniMaxCheckiner(accounts func() []miniMaxAccount) checkiner { return checkiner{path: miniMaxCheckinPath(), now: time.Now, mu: &miniMaxCheckinMu, by: "minimax", label: "minimax", accounts: func() []checkinAcct { var out []checkinAcct for _, a := range accounts() { - out = append(out, checkinAcct{User: a.User, On: a.On, key: miniMaxCheckinKey(a), do: func(ctx context.Context) WorkBuddyCheckin { return miniMaxCheckin(ctx, a) }}) + out = append(out, checkinAcct{User: a.User, On: a.On, key: miniMaxCheckinKey(a), provider: cmp.Or(a.card, a.siteID()), do: func(ctx context.Context) WorkBuddyCheckin { return miniMaxCheckin(ctx, a) }}) } return out }} diff --git a/internal/provider/models.go b/internal/provider/models.go index caac4a236..467bd1760 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -520,6 +520,11 @@ func newDue(ps []Provider) (due, skipped []newFetch) { for _, p := range ps { // a list of decision models fetched before magpie kept their // windows and input, or not fetched yet (ARNO on Discord) + // one switched off isn't asked (leftAlone): a signed-in + // agent's list asks its CLI or the vendor + if p.Off { + continue + } decide := p.decideListDue() if !decide && (p.Account == nil || !p.Ready()) { continue diff --git a/internal/provider/plugin_checkin.go b/internal/provider/plugin_checkin.go index 6fd14d354..41bae04c3 100644 --- a/internal/provider/plugin_checkin.go +++ b/internal/provider/plugin_checkin.go @@ -106,7 +106,7 @@ func (p pluginCheckinProvider) checkiner(now func() time.Time) checkiner { return checkiner{path: pluginCheckinPath(), now: now, mu: &pluginCheckinMu, by: pluginCheckinBy(p.ID), label: p.ID, accounts: func() []checkinAcct { var out []checkinAcct for _, a := range p.accounts { - out = append(out, checkinAcct{User: a.User, On: a.On, key: a.key, do: a.do}) + out = append(out, checkinAcct{User: a.User, On: a.On, key: a.key, provider: a.card, do: a.do}) } return out }} diff --git a/internal/provider/qoder_checkin.go b/internal/provider/qoder_checkin.go index 611ab62a4..898bb5b92 100644 --- a/internal/provider/qoder_checkin.go +++ b/internal/provider/qoder_checkin.go @@ -16,6 +16,7 @@ package provider // WorkBuddy's and Trae CN's are (checkin.go). import ( + "cmp" "context" "encoding/json" "errors" @@ -87,7 +88,7 @@ func newQoderCheckiner(accounts func() []qoderCheckinAcct, now func() time.Time) return checkiner{path: qoderCheckinPath(), now: now, mu: &qoderCheckinMu, by: "qoder", label: "qoder", recheck: true, accounts: func() []checkinAcct { var out []checkinAcct for _, a := range accounts() { - out = append(out, checkinAcct{User: a.User, On: a.On, key: qoderCheckinKey(a), do: func(ctx context.Context) WorkBuddyCheckin { return qoderCheckin(ctx, a, now()) }}) + out = append(out, checkinAcct{User: a.User, On: a.On, key: qoderCheckinKey(a), provider: cmp.Or(a.card, a.site), do: func(ctx context.Context) WorkBuddyCheckin { return qoderCheckin(ctx, a, now()) }}) } return out }} diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index 374554141..732d4e3df 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -402,22 +402,30 @@ func fetchSubscriptionUsage(ctx context.Context) []SubscriptionQuota { } return true } - if p, ok := claudeAccount(); ok && !hidden["claude"] { - // signed out, Claude Code's own allowance is none: the account in - // its place is a saved one, read as the others are - if ls := accountsOf("claude"); len(ls) > 1 || p.Account.standIn { - fetches = append(fetches, perLogin(via("claude"), ls, accountCard("claude"))...) - } else { - fetches = append(fetches, withUser(ctx, p.Account.User, func() SubscriptionQuota { - return claudeSubscriptionUsage(viaLogin("claude", p.Account.User), p.Account.User) - })) + // what is switched off or removed is looked at no further: finding + // the account asks its CLI who is signed in (leftAlone) + if !hidden["claude"] { + if p, ok := claudeAccount(); ok { + // signed out, Claude Code's own allowance is none: the account + // in its place is a saved one, read as the others are + if ls := accountsOf("claude"); len(ls) > 1 || p.Account.standIn { + fetches = append(fetches, perLogin(via("claude"), ls, accountCard("claude"))...) + } else { + fetches = append(fetches, withUser(ctx, p.Account.User, func() SubscriptionQuota { + return claudeSubscriptionUsage(viaLogin("claude", p.Account.User), p.Account.User) + })) + } } } - if user, plan, ok := cursorIdentity(); !moved("cursor") && ok && !hidden["cursor"] { - fetches = append(fetches, withUser(ctx, user, func() SubscriptionQuota { return cursorSubscriptionUsage(viaLogin("cursor", user), plan) })) + if !moved("cursor") && !hidden["cursor"] { + if user, plan, ok := cursorIdentity(); ok { + fetches = append(fetches, withUser(ctx, user, func() SubscriptionQuota { return cursorSubscriptionUsage(viaLogin("cursor", user), plan) })) + } } - if _, ok := grokAccount(); !moved("grok") && ok && !hidden["grok"] { - fetches = append(fetches, func() SubscriptionQuota { return keepReading(ctx, readNow(grokSubscriptionUsage(via("grok"))), "") }) + if !moved("grok") && !hidden["grok"] { + if _, ok := grokAccount(); ok { + fetches = append(fetches, func() SubscriptionQuota { return keepReading(ctx, readNow(grokSubscriptionUsage(via("grok"))), "") }) + } } if home, err := os.UserHomeDir(); err == nil { if p, ok := codexAccount(home); ok && !hidden["codex"] { diff --git a/internal/provider/trae_checkin.go b/internal/provider/trae_checkin.go index 3478777ea..1df55e2c4 100644 --- a/internal/provider/trae_checkin.go +++ b/internal/provider/trae_checkin.go @@ -23,6 +23,7 @@ package provider // account is told to check in in the Trae CN app. import ( + "cmp" "context" "encoding/json" "errors" @@ -86,7 +87,7 @@ func newTraeCheckiner(accounts func() []traeAccount) checkiner { return checkiner{path: traeCheckinPath(), now: time.Now, mu: &traeCheckinMu, by: "trae", label: "trae", accounts: func() []checkinAcct { var out []checkinAcct for _, a := range accounts() { - out = append(out, checkinAcct{User: a.User, On: a.On, key: traeCheckinKey(a), do: func(ctx context.Context) WorkBuddyCheckin { return traeCheckin(ctx, a) }}) + out = append(out, checkinAcct{User: a.User, On: a.On, key: traeCheckinKey(a), provider: cmp.Or(a.card, TraeCNID), do: func(ctx context.Context) WorkBuddyCheckin { return traeCheckin(ctx, a) }}) } return out }} diff --git a/internal/provider/workbuddy_checkin.go b/internal/provider/workbuddy_checkin.go index 159ac60b9..74ed08aa1 100644 --- a/internal/provider/workbuddy_checkin.go +++ b/internal/provider/workbuddy_checkin.go @@ -28,6 +28,7 @@ package provider // Only the Chinese build has the event: WorkBuddy AI ships with it off. import ( + "cmp" "context" "encoding/json" "errors" @@ -206,7 +207,7 @@ func (c wbCheckiner) checkiner() checkiner { if a.creds.UID != "" { key = wbCheckinKey(a) } - out = append(out, checkinAcct{User: a.User, On: a.On, key: key, do: func(ctx context.Context) WorkBuddyCheckin { return wbCheckin(ctx, a) }}) + out = append(out, checkinAcct{User: a.User, On: a.On, key: key, provider: cmp.Or(a.card, a.site.id), do: func(ctx context.Context) WorkBuddyCheckin { return wbCheckin(ctx, a) }}) } return out }}