diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 5060cbf58..e0e54b845 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -36,7 +36,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | A remote magpie's service tiers | A remote magpie's `/v1/models`, asked with `X-Magpie-Drawers` (`DrawersHeader`), gives each model the `service_tiers` its own Codex is offered on it (`codexTiers` → `codexcat.ServiceTiers`, from the same `CodexCatalog` and `codexcat.Entries` as its `/v1/codex/models`: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). The local keeps the ids (`catalog.Model.Tiers` → `Entry.Tiers`), `codexListed` hands them on for the remote's models, and `codexcat.Entries` offers them to the local Codex with Codex's own names (`namedTiers`). The gateway sends the tier Codex asks for to a remote magpie as it was asked (`Request.OwnTier`, as for a provider added by its address; dropped and not sent again if refused), and the remote serves it as its own Codex's turn (#1234). A remote from before this sends no tiers, and its models are offered none, as before. | [`codexcat.go`](../../internal/codexcat/codexcat.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`gateway.go`](../../internal/gateway/gateway.go), [`live.go`](../../internal/catalog/live.go) | | A membership's $0 catalog | models.dev lists every model of Kimi Code's plans (`kimi-code-plan-global`, `kimi-code-plan-cn`) at $0: what the membership charges per token, not what the model costs. `membershipCatalogs` are never read for a price (`priceCatalogs`, `makerPriceCatalogs`), so a Kimi Code provider's model is priced at the Kimi API model it is (`kimiCodeAPI`, from Kimi Code's docs: k3 and k3-256k are kimi-k3, kimi-for-coding-highspeed is kimi-k2.7-code-highspeed), and kimi-for-coding (K2.8 Preview, not on the API) is unpriced rather than free (#1370). The alias is Kimi Code's alone: a relay's own `k3` keeps its own price. The Requests list names the API model it was priced as (`PricedNameFor`). | [`models.go`](../../internal/provider/models.go) | | A key's own windows | A sub2api key given a spending limit per 5 hours, day or 7 days answers its `/v1/usage` with `rate_limits` and no `remaining` (`readSub2APIKeyLimits`). With the Balance URL set to it, the key's card shows them as the windows *5 hours*, *1 day*, *7 days*, in USD, beside a balance field the user wrote; *Check balance* and `magpie provider show` give what its fullest window has left (`Balance`). `KeyAllowance` gives routing the same windows: never waited for, read in the background at most once a minute, a failed read keeping the last, and seeded from the card's last reading (`quotas.json`) after a restart. A key bought as a plan (Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code: `planQuotaSourceOf`) gives routing its card's windows the same way (`planKeyWindows`, Zhipu's team quota behind a key with none of its own); the Usage page's read of its card is taken at once (`noteKeyAllowance`), and a key there that turns out pay-as-you-go, with no windows, is asked again only every 30 minutes (`keyNoWindowsAge`). StepFun's Step Plan is read through a sign-in, not the key, and isn't one of them. Nor are Volcengine Ark's Coding Plan and Agent Plan (#1427): their 5-hour, weekly and monthly windows are told only to the account's access key (`AccessKeyID`, `SecretAccessKey`), asked of `open.volcengineapi.com` (`GetCodingPlanUsage`, `GetAFPUsage`) and signed as Volcengine's own SDK signs (`volcSign`), so they are cards on the Usage page (`volcPlanQuotas` in `PlanQuotas`), never routing's windows. | [`sub2api_usage.go`](../../internal/provider/sub2api_usage.go), [`key_allowance.go`](../../internal/provider/key_allowance.go), [`volcengine_usage.go`](../../internal/provider/volcengine_usage.go) | -| Last served | `served.json` records when each account, plan or key last answered, shown as `lastServedAt` (#570) on `/v1/magpie/quotas` and on the Usage page's own cards (`Quotas` → `cardsServed`, this computer's cards only, the caches left alone). The Usage page and the tray panel show the last-answered account in full, and a menu bar card that follows the account in use (`codex|*`) takes the one that answered within the last hour, else `InUseLogin`'s guess (`trayInUseCard`; okingkee on X: A spent, B answering, the menu bar stayed on A). | [`served.go`](../../internal/provider/served.go), [`trayusage.go`](../../internal/gui/trayusage.go) | +| Last served | `served.json` records when each account, plan or key last answered, shown as `lastServedAt` (#570) on `/v1/magpie/quotas` and on the Usage page's own cards (`Quotas` → `cardsServed`, this computer's cards only, the caches left alone). The Usage page and the tray panel show the last-answered account in full, and a menu bar card that follows the account in use (`codex|*`) takes the one that answered within the last hour, else `InUseLogin`'s guess, else the one that answered last at all (a plugin's accounts, #1516) (`trayInUseCard`; okingkee on X: A spent, B answering, the menu bar stayed on A). `NoteServed` calls `OnServedMoved` when a provider's answers move to another account or key, and `SwitchLogin` after a switch, so the menu bar reads its cards again at once. | [`served.go`](../../internal/provider/served.go), [`trayusage.go`](../../internal/gui/trayusage.go) | | Partners | Services that pay to be listed first in the add sheet, under a heading of their own ("Partners · magpie's sponsors"). The list is `site/partners.js`, served at `usemagpie.ai/api/partners`: a change reaches users with a deploy, not a release. `Partners` never waits: it returns what was fetched last and fetches again behind the call every 6 hours (10 minutes after a failure), keeping the list in `partners.json` in the cache folder. Each entry is checked again on every read (`validPartners`): its own id, never a built-in preset's, a name, an endpoint, https only, at most 12; what only magpie's presets may set (a decision API, no key, a user endpoint) is cleared. Its logo is fetched through `FetchIcon` and kept as an uploaded icon. A partner is a preset to the rest of magpie (`Preset`, `FromPreset`, the editor), and one no longer listed still is to the providers added from it (`Seen`), without the sponsored mark. The window lists a partner in the languages it names (`langs`) only and shows its tagline in the page's language (`notes`, else `en`). `MAGPIE_PARTNERS` points it elsewhere, `off` lists none; tests list none unless they name a list. How often each listed partner was shown, opened (its row, its key page) and added is counted per UTC day (`CountPartner`, capped at 20 of each and 5 adds, kept in `partner-counts.json` in the cache folder) and sent with the next day's stats event as `magpie partner` events (`internal/stats`); nothing is counted with the stats or their usage part off. A listed partner the add sheet (or the TUI's, or `magpie providers presets`) hasn't shown yet is new (`NoticePartners` keeps those shown, as `noticed` in `partners.json`, whatever the stats); the window's add button carries a small dot for it, with its name in the title, until the sheet shows it. | [`partners.go`](../../internal/provider/partners.go), [`partner_events.go`](../../internal/provider/partner_events.go), [`site/partners.js`](../../site/partners.js) | | Protocol detection | Works out which of Chat, Responses, Anthropic Messages and Gemini generateContent a base URL speaks when a provider is added. Each is asked at the URL as it takes it (`DetectBase`); Gemini's at the `…/v1beta` beside a typed `…/v1` or bare host, a Gemini model from the list picked for it, with the key in `x-goog-api-key` (#1346). Detection, endpoint tests and model tests share `probe`, which adds `anthropic-version` only for Anthropic Messages; OpenAI probes omit that default so a relay that refuses it can answer. User-supplied headers still apply through `Sign`. | [`detect.go`](../../internal/provider/detect.go), [`test.go`](../../internal/provider/test.go) | diff --git a/internal/gui/trayusage.go b/internal/gui/trayusage.go index 5d63d22f2..897a225dc 100644 --- a/internal/gui/trayusage.go +++ b/internal/gui/trayusage.go @@ -180,8 +180,10 @@ var trayServedFresh = time.Hour // moves on from a spent account, and under Smart picks any, as soon as it // asks, which the account the agent is signed in to can lag (okingkee on // X: A used up, B answering, the menu bar still on A) — else the one -// InUseLogin reckons the gateway goes to first; the provider's first card -// when magpie can't tell (the account in use first among them). +// InUseLogin reckons the gateway goes to first; else the one that answered +// last at all (a plugin's accounts, which InUseLogin doesn't know); the +// provider's first card when magpie can't tell (the account in use first +// among them). func trayInUseCard(cards []provider.SubscriptionQuota, pid string, now time.Time) (provider.SubscriptionQuota, bool) { var mine []provider.SubscriptionQuota for _, q := range cards { @@ -196,17 +198,23 @@ func trayInUseCard(cards []provider.SubscriptionQuota, pid string, now time.Time if len(mine) > 1 { last := -1 for i, c := range mine { - if c.LastServedAt != nil && now.Sub(*c.LastServedAt) < trayServedFresh && - (last < 0 || c.LastServedAt.After(*mine[last].LastServedAt)) { + if c.LastServedAt != nil && (last < 0 || c.LastServedAt.After(*mine[last].LastServedAt)) { last = i } } - if last >= 0 { + in := -1 + if user := trayInUseAccount(pid); user != "" { + in = slices.IndexFunc(mine, func(q provider.SubscriptionQuota) bool { return strings.EqualFold(q.User, user) }) + } + switch { + case last >= 0 && now.Sub(*mine[last].LastServedAt) < trayServedFresh: + q = mine[last] + case in >= 0: + q = mine[in] + case last >= 0: + // a plugin's accounts are no sign-in InUseLogin knows (#1516): + // the one that answered last, however long ago, over the first q = mine[last] - } else if user := trayInUseAccount(pid); user != "" { - if i := slices.IndexFunc(mine, func(q provider.SubscriptionQuota) bool { return strings.EqualFold(q.User, user) }); i >= 0 { - q = mine[i] - } } } if q.User != "" { diff --git a/internal/gui/trayusage_inuse_test.go b/internal/gui/trayusage_inuse_test.go index 5343718bf..cffcf8792 100644 --- a/internal/gui/trayusage_inuse_test.go +++ b/internal/gui/trayusage_inuse_test.go @@ -87,3 +87,67 @@ func TestTrayInUseFollowsWhoAnswered(t *testing.T) { t.Errorf("one: %+v", got) } } + +// #1516, ikxlpz: a plugin's accounts (moved Kiro, Devin, ...) aren't +// sign-ins InUseLogin knows, so when none answered in the last hour the +// menu bar fell back to the first card, though the gateway had last gone +// to another. It shows the one that answered last, however long ago. +func TestTrayInUsePluginFollowsLastServed(t *testing.T) { + was := trayInUseAccount + trayInUseAccount = func(string) string { return "" } + t.Cleanup(func() { trayInUseAccount = was }) + now := time.Now() + at := func(d time.Duration) *time.Time { t := now.Add(-d); return &t } + cards := []provider.SubscriptionQuota{ + {Provider: "kiro", Name: "Kiro", User: "k1@x.y", Windows: []provider.QuotaWindow{{Name: "Month", Used: 5}}, LastServedAt: at(5 * time.Hour)}, + {Provider: "kiro", Name: "Kiro", User: "k2@x.y", Windows: []provider.QuotaWindow{{Name: "Month", Used: 90}}, LastServedAt: at(3 * time.Hour)}, + } + if got := trayPick(cards, []string{"kiro|*"}, now); len(got) != 1 || got[0].User != "k2@x.y" || got[0].Name != "Kiro · k2@x.y" { + t.Fatalf("plugin: %+v", got) + } + // none ever answered: the first, as before + cards[0].LastServedAt, cards[1].LastServedAt = nil, nil + if got := trayPick(cards, []string{"kiro|*"}, now); len(got) != 1 || got[0].User != "k1@x.y" { + t.Errorf("none served: %+v", got) + } +} + +// #1516: the menu bar reads its cards again when another account starts +// answering, not up to trayUsageEvery later. NoteServed tells OnServedMoved +// when a provider's answers move to another account, and only then. +func TestServedMovedWakesTheMenuBar(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + moved := make(chan struct{}, 8) + provider.OnServedMoved(func() { moved <- struct{}{} }) + t.Cleanup(func() { provider.OnServedMoved(nil) }) + told := func() bool { + select { + case <-moved: + return true + default: + return false + } + } + a := provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: "a@x.y"}} + b := provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: "b@x.y"}} + now := time.Now() + provider.NoteServed(a, now) + if !told() { + t.Error("the first answer told nobody") + } + provider.NoteServed(a, now.Add(time.Second)) + if told() { + t.Error("the same account again woke the menu bar") + } + provider.NoteServed(b, now.Add(2*time.Second)) + if !told() { + t.Error("b@ answering after a@ told nobody") + } + // and what was noted is what the menu bar's cards read + if at := provider.LastServed()["codex@b@x.y"]; !at.Equal(now.Add(2 * time.Second)) { + t.Errorf("served: %v", provider.LastServed()) + } +} diff --git a/internal/gui/trayusage_tray.go b/internal/gui/trayusage_tray.go index 30198f3f3..6a26e7e6d 100644 --- a/internal/gui/trayusage_tray.go +++ b/internal/gui/trayusage_tray.go @@ -27,6 +27,9 @@ func (h *host) watchTrayUsage() { // a card read while stale is refreshed behind it: read it again once // that lands, not a tick later, so the menu bar says what the panel does provider.OnSubscriptionUsage(onTrayUsage) + // another account answering, or the agent switched to another: a card + // following the account in use reads it at once (#1516) + provider.OnServedMoved(onTrayUsage) // Schedule native cell clicks on the application thread after startup. onTrayCellClick = func(id string) { h.whenReady(func() { application.InvokeAsync(func() { h.trayCellClick(id) }) }) diff --git a/internal/provider/logins.go b/internal/provider/logins.go index 5f95e886e..c75663a24 100644 --- a/internal/provider/logins.go +++ b/internal/provider/logins.go @@ -900,7 +900,11 @@ func SwitchLogin(agent, user string) error { if slices.Contains(loginAgents, agent) { setLoginReturn(agent, loginReturn{}) } - return switchLogin(agent, user) + if err := switchLogin(agent, user); err != nil { + return err + } + servedMoved() + return nil } func switchLogin(agent, user string) error { diff --git a/internal/provider/served.go b/internal/provider/served.go index 74a1985ab..bc26e92da 100644 --- a/internal/provider/served.go +++ b/internal/provider/served.go @@ -14,6 +14,7 @@ import ( "path/filepath" "strings" "sync" + "sync/atomic" "time" ) @@ -25,12 +26,46 @@ var servedAt = struct { sync.Mutex m map[string]time.Time // ServedID → when it last answered path string // the file m goes with: another (a test's HOME) starts afresh -}{m: map[string]time.Time{}} + // by: the ServedID that answered last for each provider (servedOf), + // to tell OnServedMoved when that is another one + by map[string]string +}{m: map[string]time.Time{}, by: map[string]string{}} + +// OnServedMoved sets what is told when a provider's requests are answered +// by another of its accounts or keys than the one that answered before, or +// when the user signs an agent in to another account (SwitchLogin): the +// menu bar following the account in use reads it again then, rather than +// minutes later (#1516). It is called after NoteServed lets go of its lock +// and must not block; nil tells nothing. +func OnServedMoved(f func()) { + if f == nil { + onServedMoved.Store(nil) + return + } + onServedMoved.Store(&f) +} + +var onServedMoved atomic.Pointer[func()] + +func servedMoved() { + if f := onServedMoved.Load(); f != nil { + (*f)() + } +} + +// servedOf is the provider a ServedID is of: "codex" for "codex@a@b.c", +// "deepseek" for "deepseek#k1a2b3c". +func servedOf(id string) string { + if i := strings.IndexAny(id, "@#"); i >= 0 { + return id[:i] + } + return id +} // ours is servedAt.m for the file at path. Called with servedAt held. func ours(path string) map[string]time.Time { if servedAt.path != path { - servedAt.path, servedAt.m = path, map[string]time.Time{} + servedAt.path, servedAt.m, servedAt.by = path, map[string]time.Time{}, map[string]string{} } return servedAt.m } @@ -55,12 +90,24 @@ func NoteServed(p Provider, at time.Time) { id := ServedID(p) path := servedPath() servedAt.Lock() - defer servedAt.Unlock() + moved := false + defer func() { + servedAt.Unlock() + if moved { + servedMoved() + } + }() mine := ours(path) if at.Before(mine[id]) { return } mine[id] = at + if of := servedOf(id); servedAt.by[of] != id { + // the first this process sees too: the menu bar may have taken + // another for the one in use until then + moved = true + servedAt.by[of] = id + } m := readServed(path) for k, t := range mine { if t.After(m[k]) {