diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index f286a33f4..01c847eff 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). | [`served.go`](../../internal/provider/served.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) | | 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 ae27c6019..5d63d22f2 100644 --- a/internal/gui/trayusage.go +++ b/internal/gui/trayusage.go @@ -142,14 +142,14 @@ func trayUsageCards(ctx context.Context, ids []string) []provider.SubscriptionQu if len(ids) == 0 { return nil } - return trayPick(provider.Quotas(ctx), ids) + return trayPick(provider.Quotas(ctx), ids, time.Now()) } -func trayPick(cards []provider.SubscriptionQuota, ids []string) []provider.SubscriptionQuota { +func trayPick(cards []provider.SubscriptionQuota, ids []string, now time.Time) []provider.SubscriptionQuota { var out []provider.SubscriptionQuota for _, id := range ids { if pid, ok := strings.CutSuffix(id, trayInUse); ok { - if q, ok := trayInUseCard(cards, pid); ok { + if q, ok := trayInUseCard(cards, pid, now); ok { out = append(out, q) } continue @@ -163,17 +163,26 @@ func trayPick(cards []provider.SubscriptionQuota, ids []string) []provider.Subsc // trayInUse ends a card id that follows a subscription's account in use // ("claude|*") rather than naming one: with several accounts, the one the -// gateway goes to first is the one worth watching, whichever it is now. +// gateway is sending to is the one worth watching, whichever it is now. const trayInUse = "|*" // trayInUseAccount is the account of an agent's the gateway goes to first; // a var for tests. var trayInUseAccount = provider.InUseLogin +// trayServedFresh is how lately an account must have answered through the +// gateway for the menu bar to take it as the one in use; a var for tests. +var trayServedFresh = time.Hour + // trayInUseCard is the card of the provider's account in use, named with -// the account so the tooltip says which it is; the provider's first card +// the account so the tooltip says which it is: the one that answered a +// request through the gateway last, within trayServedFresh — the gateway +// 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). -func trayInUseCard(cards []provider.SubscriptionQuota, pid string) (provider.SubscriptionQuota, bool) { +func trayInUseCard(cards []provider.SubscriptionQuota, pid string, now time.Time) (provider.SubscriptionQuota, bool) { var mine []provider.SubscriptionQuota for _, q := range cards { if q.Provider == pid { @@ -185,7 +194,16 @@ func trayInUseCard(cards []provider.SubscriptionQuota, pid string) (provider.Sub } q := mine[0] if len(mine) > 1 { - if user := trayInUseAccount(pid); user != "" { + last := -1 + for i, c := range mine { + if c.LastServedAt != nil && now.Sub(*c.LastServedAt) < trayServedFresh && + (last < 0 || c.LastServedAt.After(*mine[last].LastServedAt)) { + last = i + } + } + if last >= 0 { + 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] } diff --git a/internal/gui/trayusage_cells_test.go b/internal/gui/trayusage_cells_test.go index 508481c77..5a669d08b 100644 --- a/internal/gui/trayusage_cells_test.go +++ b/internal/gui/trayusage_cells_test.go @@ -30,14 +30,14 @@ func TestTrayUsageCells(t *testing.T) { cards := trayCards() // the ticked ones in the order ticked; one no longer there is left out - picked := trayPick(cards, []string{"codex|x@y.z", "gone|who", "claude|a@b.c"}) + picked := trayPick(cards, []string{"codex|x@y.z", "gone|who", "claude|a@b.c"}, time.Now()) if len(picked) != 2 || picked[0].Provider != "codex" || picked[1].Provider != "claude" { t.Fatalf("picked %+v", picked) } - if got := trayPick(cards, nil); got != nil { + if got := trayPick(cards, nil, time.Now()); got != nil { t.Fatalf("none ticked: %+v", got) } - if got := trayPick(cards, []string{"claude"}); got != nil { + if got := trayPick(cards, []string{"claude"}, time.Now()); got != nil { t.Fatalf("the vendor without the account: %+v", got) } @@ -52,7 +52,7 @@ func TestTrayUsageCells(t *testing.T) { {[]string{"claude|a@b.c", "codex|x@y.z", "copilot", "deepseek"}, [][]string{{"42%", "18%"}, {"8%", "100%"}, {"63%"}, {"¥12.30"}}, "42% · 18% | 8% · 100% | 63% | ¥12.30"}, } { - cells, label, tip := trayUsageView(trayPick(cards, tc.ids), now, false) + cells, label, tip := trayUsageView(trayPick(cards, tc.ids, now), now, false) if label != tc.label { t.Errorf("%v: label %q, want %q", tc.ids, label, tc.label) } diff --git a/internal/gui/trayusage_inuse_test.go b/internal/gui/trayusage_inuse_test.go index cf2c279ae..5343718bf 100644 --- a/internal/gui/trayusage_inuse_test.go +++ b/internal/gui/trayusage_inuse_test.go @@ -26,7 +26,7 @@ func TestTrayInUse(t *testing.T) { {Provider: "zcode", Name: "ZCode", User: "z@x.y", Windows: []provider.QuotaWindow{{Name: "5 小时", Used: 5}}}, {Provider: "deepseek", Name: "DeepSeek", Balance: "¥1.00"}, } - got := trayPick(cards, []string{"claude|*", "zcode|*", "deepseek", "claude|a@x.y", "gone|*"}) + got := trayPick(cards, []string{"claude|*", "zcode|*", "deepseek", "claude|a@x.y", "gone|*"}, time.Now()) if len(got) != 4 { t.Fatalf("cards: %+v", got) } @@ -44,12 +44,46 @@ func TestTrayInUse(t *testing.T) { } // switched: the card follows inUse = "a@x.y" - if got = trayPick(cards, []string{"claude|*"}); len(got) != 1 || got[0].User != "a@x.y" { + if got = trayPick(cards, []string{"claude|*"}, time.Now()); len(got) != 1 || got[0].User != "a@x.y" { t.Errorf("after a switch: %+v", got) } // can't tell: the first, the one in use first among them inUse = "" - if got = trayPick(cards, []string{"claude|*"}); len(got) != 1 || got[0].User != "a@x.y" { + if got = trayPick(cards, []string{"claude|*"}, time.Now()); len(got) != 1 || got[0].User != "a@x.y" { t.Errorf("unknown: %+v", got) } } + +// okingkee on X: three Codex accounts, the menu bar on "account in use". +// A used its allowance up and the gateway went on to B, but the menu bar +// stayed on A: it asked whom the agent is signed in to. It follows the +// account that answered last, while that is lately; else, as before, the +// one InUseLogin reckons the gateway goes to first. +func TestTrayInUseFollowsWhoAnswered(t *testing.T) { + was := trayInUseAccount + trayInUseAccount = func(string) string { return "a@x.y" } + 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: "codex", Name: "Codex", User: "a@x.y", Windows: []provider.QuotaWindow{{Name: "5-hour", Used: 100}}, LastServedAt: at(40 * time.Minute)}, + {Provider: "codex", Name: "Codex", User: "b@x.y", Windows: []provider.QuotaWindow{{Name: "5-hour", Used: 12}}, LastServedAt: at(time.Minute)}, + {Provider: "codex", Name: "Codex", User: "c@x.y", Windows: []provider.QuotaWindow{{Name: "5-hour", Used: 0}}}, + } + got := trayPick(cards, []string{"codex|*"}, now) + if len(got) != 1 || got[0].User != "b@x.y" || got[0].Name != "Codex · b@x.y" { + t.Fatalf("in use: %+v", got) + } + if label, _ := trayUsageText(got[0], now, false); label != "12%" { + t.Errorf("label %q", label) + } + // nothing answered lately: whom the gateway goes to first + cards[0].LastServedAt, cards[1].LastServedAt = at(3*time.Hour), at(2*time.Hour) + if got = trayPick(cards, []string{"codex|*"}, now); len(got) != 1 || got[0].User != "a@x.y" { + t.Errorf("stale answers: %+v", got) + } + // one account alone is the one, whoever answered + if got = trayPick(cards[2:], []string{"codex|*"}, now); len(got) != 1 || got[0].User != "c@x.y" { + t.Errorf("one: %+v", got) + } +} diff --git a/internal/provider/quotas.go b/internal/provider/quotas.go index cb51cc259..af7ce594a 100644 --- a/internal/provider/quotas.go +++ b/internal/provider/quotas.go @@ -13,7 +13,7 @@ import ( // what doesn't answer before ctx ends comes back with an error. func Quotas(ctx context.Context) []SubscriptionQuota { subs, plans, balances := quotas(ctx) - return append(append(subs, plans...), balances...) + return cardsServed(subs, plans, balances, LastServed()) } // Allotted is Quotas without the keys' balances: the accounts and plans diff --git a/internal/provider/served.go b/internal/provider/served.go index 8ea0f6c52..74a1985ab 100644 --- a/internal/provider/served.go +++ b/internal/provider/served.go @@ -114,43 +114,11 @@ func withServed(qs []Quota, served map[string]time.Time) []Quota { if len(served) == 0 { return qs } - var keys map[string][]KeyInfo // provider → its keys, read once + by := servedBy{served: served} var latest time.Time for i := range qs { q := &qs[i] - var at time.Time - latestOf := func(id string) { - if t, ok := served[id]; ok && t.After(at) { - at = t - } - } - user := strings.ToLower(q.User) - switch { - case q.Kind == "subscription" && user != "": - latestOf(q.Provider + "@" + user) - case q.User == "": - // the one account or key it has, or any of them: a balance - // one account has whichever key asks - for id, t := range served { - if (id == q.Provider || strings.HasPrefix(id, q.Provider+"@") || strings.HasPrefix(id, q.Provider+"#")) && t.After(at) { - at = t - } - } - default: - // a plan's or balance's key, by the name or mask it is told by - if keys == nil { - keys = map[string][]KeyInfo{} - for _, p := range All() { - keys[p.ID] = p.KeyList() - } - } - for _, k := range keys[q.Provider] { - if k.Name == q.User || k.Name == "" && k.Masked == q.User { - latestOf(q.Provider + "#" + k.ID) - } - } - } - if !at.IsZero() { + if at := by.at(q.Provider, q.Kind, q.User); !at.IsZero() { t := at.UTC() q.LastServedAt = &t if at.After(latest) { @@ -165,3 +133,73 @@ func withServed(qs []Quota, served map[string]time.Time) []Quota { } return qs } + +// servedBy finds when a card's account, plan or key last answered, in +// served (LastServed's map). +type servedBy struct { + served map[string]time.Time + keys map[string][]KeyInfo // provider → its keys, read once, when a plan or balance asks +} + +// at is when the card of provider's kind ("subscription", "plan" or +// "balance") told by user last answered; zero when it hasn't. +func (s *servedBy) at(provider, kind, user string) time.Time { + var at time.Time + latestOf := func(id string) { + if t, ok := s.served[id]; ok && t.After(at) { + at = t + } + } + switch { + case kind == "subscription" && user != "": + latestOf(provider + "@" + strings.ToLower(user)) + case user == "": + // the one account or key it has, or any of them: a balance + // one account has whichever key asks + for id, t := range s.served { + if (id == provider || strings.HasPrefix(id, provider+"@") || strings.HasPrefix(id, provider+"#")) && t.After(at) { + at = t + } + } + default: + // a plan's or balance's key, by the name or mask it is told by + if s.keys == nil { + s.keys = map[string][]KeyInfo{} + for _, p := range All() { + s.keys[p.ID] = p.KeyList() + } + } + for _, k := range s.keys[provider] { + if k.Name == user || k.Name == "" && k.Masked == user { + latestOf(provider + "#" + k.ID) + } + } + } + return at +} + +// cardsServed sets LastServedAt on the Usage page's cards, this +// computer's own (a remote magpie's answer there, not here), as +// withServed does on the gateway's: what the Usage page and the tray +// panel show in full, and what the menu bar's "account in use" follows, +// is the account that answered last. Each is a copy; the caches the +// cards come from are left as they were. +func cardsServed(subs, plans, balances []SubscriptionQuota, served map[string]time.Time) []SubscriptionQuota { + out := make([]SubscriptionQuota, 0, len(subs)+len(plans)+len(balances)) + by := servedBy{served: served} + for _, g := range []struct { + kind string + qs []SubscriptionQuota + }{{"subscription", subs}, {"plan", plans}, {"balance", balances}} { + for _, q := range g.qs { + if q.From == "" && len(served) > 0 { + if at := by.at(q.Provider, g.kind, q.User); !at.IsZero() { + t := at.UTC() + q.LastServedAt = &t + } + } + out = append(out, q) + } + } + return out +} diff --git a/internal/provider/served_test.go b/internal/provider/served_test.go index 44a3bdbad..b93c12d62 100644 --- a/internal/provider/served_test.go +++ b/internal/provider/served_test.go @@ -59,3 +59,39 @@ func TestQuotasLastServed(t *testing.T) { } func ptr(t time.Time) *time.Time { return &t } + +// The Usage page's cards are told it too (okingkee on X): the page and the +// tray panel show the account that answered last in full, and the menu +// bar's "account in use" follows it. A remote magpie's card is that one's, +// and the cache the cards are read from keeps none of it. +func TestCardsLastServed(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + now := time.Now().Truncate(time.Second) + NoteServed(Provider{ID: "codex", Account: &Account{Agent: "codex", User: "B@x.com"}}, now.Add(-time.Minute)) + NoteServed(Provider{ID: "solo", Key: "sk-solo"}, now.Add(-2*time.Hour)) + subs := []SubscriptionQuota{ + {Provider: "codex", User: "a@x.com"}, + {Provider: "codex", User: "b@x.com"}, + {Provider: "codex", User: "b@x.com", From: "studio"}, + } + balances := []SubscriptionQuota{{Provider: "solo"}} + got := cardsServed(subs, nil, balances, LastServed()) + if len(got) != 4 { + t.Fatalf("cards: %+v", got) + } + want := []*time.Time{nil, ptr(now.Add(-time.Minute)), nil, ptr(now.Add(-2 * time.Hour))} + for i, q := range got { + if (q.LastServedAt == nil) != (want[i] == nil) || q.LastServedAt != nil && !q.LastServedAt.Equal(*want[i]) { + t.Errorf("%d %s %q from %q: lastServedAt %v, want %v", i, q.Provider, q.User, q.From, q.LastServedAt, want[i]) + } + } + if subs[1].LastServedAt != nil || balances[0].LastServedAt != nil { + t.Error("the cards read from were written to") + } + if b, _ := json.Marshal(got[1]); !strings.Contains(string(b), `"lastServedAt":"`) { + t.Errorf("json %s", b) + } +} diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index 60ea61fa6..f38cb8147 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -136,6 +136,10 @@ type SubscriptionQuota struct { // From is the remote magpie a card is that one's (remote_quotas.go), // by its name here; "" for this computer's own. From string `json:"from,omitempty"` + // LastServedAt is when the account, plan or key last answered a + // request through this computer's gateway, nil when it hasn't in the + // last 30 days (served.go); set by Quotas, never cached. + LastServedAt *time.Time `json:"lastServedAt,omitempty"` // In-process read order, separate from the vendor's ReadAt and never // persisted: restarting starts a new sequence. readSeq uint64