quotas: a computer using another's magpie (remote-magpie) shows that magpie's quota cards (莫 on Discord: the second computer had the models and groups but /v1/magpie/quotas was empty, so Usage, the menu bar and magpie quota showed nothing) — each named with the remote ("Codex · Office", id office/codex, from: Office) and kept in its kind (subscription, plan, balance), on the Usage page, the tray, the TUI and magpie quota (which matches by the remote's id or name); their history comes with the local one. Only the computer holding the sign-ins asks vendors: it answers the new GET /v1/magpie/quotas/cards from what it has kept (CachedCards, never a read, whatever the age), asked here at most once in 30s; a card's refresh here POSTs /v1/magpie/quotas/refresh (that card, or every card from the remote's own card), which the remote does at most once in 30s per card. A remote keeps showing its last cards when it can't be reached; with none its one card says why (nothing read there yet, or a magpie too old to share — "update magpie there", zh/ja/de added). Cards from a third magpie aren't passed on, and the refresh path refuses them (400); a Codex reset or check-in isn't offered on a remote card. Same auth as /v1/magpie/quotas (loopback, or LAN with the key).
Verified: provider tests (fake remote: names/kinds, buttons stripped, third-magpie cards dropped, one ask per 30s, refresh paths, unreachable keeps last cards, 404 → update card, cache-only CachedCards, histories) and the gateway test (an in-process gateway with a fake balance vendor counting hits, asked through a remote-magpie provider: nothing read until a refresh, 5 card asks read nothing, two refreshes of a card read once, a remote card's refresh 400, another machine without the key refused) pass with -race -count=20; go test provider/gateway/gui/tui/root, vet, linux and windows builds pass. Two sandbox gateways (3481 with a fake balance vendor, 3482 with it as remote-magpie): magpie quota on the second showed the "nothing read" card with 0 vendor hits, then office/bal "Bal · Office" $12.00 after one refresh (1 hit), 10 more asks 0 hits, two card refreshes 1 hit. usage-remote-cards (names, translated remote errors, refresh ids) passes in Chromium and WebKit, en/zh/ja/de and fails without the app.js change; i18n-keys, gui-ja, gui-de, usage-card-refresh, usage-refresh, quota-reading-again pass. Not tried with a real second computer.
This commit is contained in:
@@ -201,6 +201,14 @@ Its list is the models the shared magpie's agents are shown, each named with
|
||||
its provider there (`Claude Sonnet 5 · Relay A · office`) — the ids stay ids
|
||||
(`office/relay-a/claude-sonnet-5`), only these labels carry the names — and its image
|
||||
models are listed under Settings → Images and draw through it.
|
||||
Its quotas show too: the Usage page, the menu bar and `magpie quota` list the
|
||||
shared magpie's cards named with it (`Codex · office`, id `office/codex`), as
|
||||
that magpie last read them — only the computer holding the sign-ins asks the
|
||||
vendors, and it answers from what it has kept (`GET /v1/magpie/quotas/cards`).
|
||||
A card's refresh here has it read that card once more
|
||||
(`POST /v1/magpie/quotas/refresh`, at most once in 30 seconds a card); until it
|
||||
has read anything, the remote's one card says so. Their history is shown with
|
||||
its own. A Codex reset or a check-in is pressed on that computer, not here.
|
||||
|
||||
Codex's native image tool first asks the provider that served its conversation
|
||||
turn for the requested image model. If that provider does not list the model,
|
||||
|
||||
@@ -27,7 +27,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| Sign-in in magpie | `StartSignIn` runs the vendor's own browser OAuth with its client and takes the tokens at a callback on this machine. A Claude account is signed in by Claude Code itself. | [`signin.go`](../../internal/provider/signin.go), [`claude_signin.go`](../../internal/provider/claude_signin.go) |
|
||||
| Used-up switch | When the account Codex or Claude Code is signed in to has used its allowance, the agent is signed in to the next account that is on and has room (#208). | [`codex_switch.go`](../../internal/provider/codex_switch.go) |
|
||||
| Routing groups | User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). Members are `provider/model[:effort]`. A group can nest another (`group/<id>`); `SaveGroup` refuses loops. `Match` takes a glob or `re:` pattern (#766). | [`group.go`](../../internal/provider/group.go) |
|
||||
| Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it. A single card can be read again on its own (#840). | [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go) |
|
||||
| Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it. A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). | [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go) |
|
||||
| Last served | `served.json` records when each account, plan or key last answered, shown as `lastServedAt` (#570). | [`served.go`](../../internal/provider/served.go) |
|
||||
| Protocol detection | Works out which APIs a base URL speaks when a provider is added. | [`detect.go`](../../internal/provider/detect.go) |
|
||||
|
||||
|
||||
@@ -478,6 +478,8 @@ func (s *Server) Handler() http.Handler {
|
||||
})
|
||||
mux.HandleFunc("GET /v1/magpie/quotas", s.quotas)
|
||||
mux.HandleFunc("GET /v1/magpie/quotas/history", s.quotasHistory)
|
||||
mux.HandleFunc("GET "+provider.RemoteCardsPath, s.quotaCards)
|
||||
mux.HandleFunc("POST "+provider.RemoteRefreshPath, s.quotaCardsRefresh)
|
||||
mux.HandleFunc("GET /v1/magpie/route", s.sessionRoute)
|
||||
mux.HandleFunc("GET /v1/magpie/concurrency", s.concurrency)
|
||||
mux.HandleFunc("GET /v1/magpie/limit", s.keyLimit)
|
||||
@@ -549,6 +551,60 @@ func (s *Server) quotasHistory(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]any{"object": "list", "data": provider.QuotaHistories(provider.QuotaHistorySince(q.Get("days"), time.Now()), q.Get("provider"), q.Get("user"))})
|
||||
}
|
||||
|
||||
// quotaCards is the Usage page's cards as this magpie last read them, for
|
||||
// another magpie that has this one as its provider (remote-magpie) to
|
||||
// show: its own cache, however old, and no vendor asked for it.
|
||||
func (s *Server) quotaCards(w http.ResponseWriter, r *http.Request) {
|
||||
if !local(r) && !sharedWith(r) {
|
||||
writeError(w, provider.Chat, http.StatusForbidden, "magpie's quotas are told to another machine only when magpie is shared on the local network (Settings → Share on local network) and the request carries its API key (Authorization: Bearer <key> or x-api-key: <key>)")
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"object": "list", "data": provider.CachedCards(time.Now())})
|
||||
}
|
||||
|
||||
// remoteRefreshes is when another magpie last had each card read again
|
||||
// here: one refreshed by hand is read at most once in remoteRefreshGap,
|
||||
// however often it is asked, so the vendor sees no more than this
|
||||
// computer's own refresh button would make it.
|
||||
var remoteRefreshes = struct {
|
||||
sync.Mutex
|
||||
at map[string]time.Time
|
||||
}{at: map[string]time.Time{}}
|
||||
|
||||
const remoteRefreshGap = 30 * time.Second
|
||||
|
||||
// quotaCardsRefresh is a card's refresh pressed on another magpie: the
|
||||
// card (?provider=, &user=) is read again here, or every card when none
|
||||
// is named, then the cards are answered as quotaCards answers them.
|
||||
func (s *Server) quotaCardsRefresh(w http.ResponseWriter, r *http.Request) {
|
||||
if !local(r) && !sharedWith(r) {
|
||||
writeError(w, provider.Chat, http.StatusForbidden, "magpie's quotas are told to another machine only when magpie is shared on the local network (Settings → Share on local network) and the request carries its API key (Authorization: Bearer <key> or x-api-key: <key>)")
|
||||
return
|
||||
}
|
||||
id, user := r.URL.Query().Get("provider"), r.URL.Query().Get("user")
|
||||
if strings.Contains(id, "/") || provider.IsRemoteCard(id) { // a card this magpie has from another: not passed on
|
||||
writeError(w, provider.Chat, http.StatusBadRequest, "this magpie reads only its own cards again")
|
||||
return
|
||||
}
|
||||
key := id + "|" + strings.ToLower(user)
|
||||
remoteRefreshes.Lock()
|
||||
due := time.Since(remoteRefreshes.at[key]) >= remoteRefreshGap
|
||||
if due {
|
||||
remoteRefreshes.at[key] = time.Now()
|
||||
}
|
||||
remoteRefreshes.Unlock()
|
||||
if due {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
if id == "" {
|
||||
provider.ReadAllCards(ctx)
|
||||
} else {
|
||||
provider.RefreshUsage(ctx, id, user)
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"object": "list", "data": provider.CachedCards(time.Now())})
|
||||
}
|
||||
|
||||
func modelObject(e provider.Entry) map[string]any {
|
||||
type reasoningLevel struct {
|
||||
Effort string `json:"effort"`
|
||||
|
||||
@@ -55,6 +55,10 @@ func fresh(t *testing.T) {
|
||||
levelled.m = map[string]levelling{}
|
||||
levelled.Unlock()
|
||||
provider.ForgetCopilotForTest()
|
||||
provider.ForgetRemoteCardsForTest()
|
||||
remoteRefreshes.Lock()
|
||||
remoteRefreshes.at = map[string]time.Time{}
|
||||
remoteRefreshes.Unlock()
|
||||
forgetRouting()
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A remote magpie's quotas (莫 on Discord), between a gateway and a
|
||||
// magpie that has it as its provider: the cards it is shown are the
|
||||
// gateway's as last read, and asking for them asks no vendor, however
|
||||
// often; a card's refresh reads it there once, and again no sooner than
|
||||
// remoteRefreshGap; a card the gateway has from a third magpie isn't read
|
||||
// for it; another machine without the gateway's key gets nothing.
|
||||
func TestRemoteMagpieQuotas(t *testing.T) {
|
||||
fresh(t)
|
||||
t.Setenv("MAGPIE_ADDR", "")
|
||||
provider.ForgetBalances()
|
||||
t.Cleanup(provider.ForgetBalances)
|
||||
var reads atomic.Int32
|
||||
vendor := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
reads.Add(1)
|
||||
w.Write([]byte(`{"data":{"total_available":6000000}}`))
|
||||
}))
|
||||
defer vendor.Close()
|
||||
if err := provider.Save(provider.Provider{ID: "bal", Name: "Bal", Key: "sk-bal", Chat: vendor.URL + "/v1",
|
||||
BalanceURL: vendor.URL + "/b", BalancePath: "$data.total_available / 500000"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gw := httptest.NewServer(lanGuard(New().Handler()))
|
||||
defer gw.Close()
|
||||
if err := provider.Save(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Key: "sk-magpie-office", Chat: gw.URL}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
// nothing read on the gateway yet: nothing is read for the remote
|
||||
cs := provider.RemoteCards(ctx)
|
||||
if len(cs) != 1 || cs[0].Provider != "office" || !strings.HasPrefix(cs[0].Error, "nothing read") {
|
||||
t.Fatalf("before any read: %+v", cs)
|
||||
}
|
||||
if n := reads.Load(); n != 0 {
|
||||
t.Fatalf("the remote's ask read the vendor %d times", n)
|
||||
}
|
||||
// its card's refresh has the gateway read every card
|
||||
provider.RefreshUsage(ctx, "office", "")
|
||||
if n := reads.Load(); n != 1 {
|
||||
t.Fatalf("refresh read the vendor %d times, want 1", n)
|
||||
}
|
||||
var bal *provider.SubscriptionQuota
|
||||
for _, q := range provider.RemoteCards(ctx) {
|
||||
if q.Provider == "office/bal" {
|
||||
bal = &q
|
||||
}
|
||||
}
|
||||
if bal == nil || bal.Balance != "$12.00" || bal.Name != "Bal · Office" || bal.Kind != "balance" {
|
||||
t.Fatalf("office/bal: %+v", bal)
|
||||
}
|
||||
// asked again and again, the gateway answers from what it has
|
||||
for range 5 {
|
||||
r, _ := http.NewRequest("GET", gw.URL+provider.RemoteCardsPath, nil)
|
||||
res, err := http.DefaultClient.Do(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res.Body.Close()
|
||||
}
|
||||
if n := reads.Load(); n != 1 {
|
||||
t.Fatalf("asking for the cards read the vendor: %d", n)
|
||||
}
|
||||
// the card's own refresh, pressed twice at once: read once
|
||||
provider.RefreshUsage(ctx, "office/bal", "")
|
||||
provider.RefreshUsage(ctx, "office/bal", "")
|
||||
if n := reads.Load(); n != 2 {
|
||||
t.Fatalf("two refreshes read the vendor %d times in all, want 2", n)
|
||||
}
|
||||
post := func(from, q, key string) int {
|
||||
r := httptest.NewRequest("POST", provider.RemoteRefreshPath+q, nil)
|
||||
r.RemoteAddr = from
|
||||
if key != "" {
|
||||
r.Header.Set("Authorization", "Bearer "+key)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
lanGuard(New().Handler()).ServeHTTP(w, r)
|
||||
return w.Code
|
||||
}
|
||||
if c := post("127.0.0.1:5000", "?provider=home/codex", ""); c != http.StatusBadRequest {
|
||||
t.Errorf("a third magpie's card: %d", c)
|
||||
}
|
||||
if c := post("127.0.0.1:5000", "?provider=office", ""); c != http.StatusBadRequest {
|
||||
t.Errorf("a remote magpie's own card: %d", c)
|
||||
}
|
||||
if c := post("192.168.1.9:5000", "?provider=bal", ""); c == http.StatusOK {
|
||||
t.Error("another machine without a key had a card read")
|
||||
}
|
||||
for _, path := range []string{provider.RemoteCardsPath} {
|
||||
r := httptest.NewRequest("GET", path, nil)
|
||||
r.RemoteAddr = "192.168.1.9:5000"
|
||||
w := httptest.NewRecorder()
|
||||
lanGuard(New().Handler()).ServeHTTP(w, r)
|
||||
if w.Code == http.StatusOK {
|
||||
t.Errorf("another machine without a key got %s", path)
|
||||
}
|
||||
}
|
||||
if n := reads.Load(); n != 2 {
|
||||
t.Errorf("refused requests read the vendor: %d", n)
|
||||
}
|
||||
}
|
||||
@@ -10625,6 +10625,9 @@ function quotaError(err) {
|
||||
if (/violation of Terms of Service/i.test(err)) return t("Google has suspended this account — hover for details");
|
||||
if (/access token is invalid or expired|didn't take the access token/.test(err)) return t("AiHubMix didn't take the access token — paste a new one in the provider's settings");
|
||||
if (/this key has no limit/.test(err)) return t("This key has no limit — add the account's access token in the provider's settings to see its balance");
|
||||
// a remote magpie's card (remote_quotas.go)
|
||||
if (/^nothing read on that magpie yet/.test(err)) return t("Nothing read on that computer yet — refresh this card to have it read");
|
||||
if (/^remote magpie doesn't share its quotas/.test(err)) return t("That computer's magpie doesn't share its quotas yet — update magpie there");
|
||||
return balanceError(err) || t("Allowance unavailable");
|
||||
}
|
||||
|
||||
|
||||
@@ -2081,6 +2081,8 @@ const I18N = {
|
||||
"Other Models": "其他模型",
|
||||
"Total": "合计",
|
||||
"Allowance unavailable": "暂时无法获取额度",
|
||||
"Nothing read on that computer yet — refresh this card to have it read": "那台电脑还没有读过额度 — 刷新这张卡片让它读取",
|
||||
"That computer's magpie doesn't share its quotas yet — update magpie there": "那台电脑的 magpie 还不能共享额度 — 请在那台电脑上更新 magpie",
|
||||
"As of {when} — couldn't be read just now": "截至 {when},暂时无法获取最新额度",
|
||||
"A cached window has expired; current allowance is unknown": "缓存中有窗口已过期,其当前额度未知",
|
||||
"As of {when}": "截至 {when}",
|
||||
@@ -5529,6 +5531,8 @@ const I18N = {
|
||||
"Other Models": "その他のモデル",
|
||||
"Total": "合計",
|
||||
"Allowance unavailable": "利用枠を取得できません",
|
||||
"Nothing read on that computer yet — refresh this card to have it read": "そのコンピューターではまだ読み取っていません — このカードを更新すると読み取ります",
|
||||
"That computer's magpie doesn't share its quotas yet — update magpie there": "そのコンピューターの magpie はまだ利用枠を共有できません — そちらの magpie を更新してください",
|
||||
"As of {when} — couldn't be read just now": "{when} 時点 — 現在は読み取れません",
|
||||
"A cached window has expired; current allowance is unknown": "キャッシュされた期間が期限切れです。現在の利用枠は不明です",
|
||||
"As of {when}": "{when} 時点",
|
||||
@@ -8975,6 +8979,8 @@ const I18N = {
|
||||
"Other Models": "Andere Modelle",
|
||||
"Total": "Gesamt",
|
||||
"Allowance unavailable": "Kontingent nicht verfügbar",
|
||||
"Nothing read on that computer yet — refresh this card to have it read": "Auf diesem Computer wurde noch nichts gelesen — diese Karte aktualisieren, um es lesen zu lassen",
|
||||
"That computer's magpie doesn't share its quotas yet — update magpie there": "Das magpie dieses Computers teilt seine Kontingente noch nicht — aktualisiere magpie dort",
|
||||
"As of {when} — couldn't be read just now": "Stand {when} — konnte gerade nicht gelesen werden",
|
||||
"A cached window has expired; current allowance is unknown": "Ein zwischengespeichertes Zeitfenster ist abgelaufen; das aktuelle Kontingent ist unbekannt",
|
||||
"As of {when}": "Stand {when}",
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Another computer's quotas (莫 on Discord): a computer whose provider is
|
||||
// another's magpie (remote-magpie) shows that magpie's cards, each named
|
||||
// with the computer ("Codex · Office"), without the buttons that would act
|
||||
// on this computer's accounts. The remote's own card says why it has none
|
||||
// (nothing read there yet, or a magpie too old to share) in the reader's
|
||||
// language, and its refresh asks for it by its id (?provider=office), the
|
||||
// remote's card by its own (?provider=office/codex). English, Chinese,
|
||||
// Japanese and German; no backend, the API is faked here.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const H = 3600e3, M = 60e3;
|
||||
const iso = (ms) => new Date(ms).toISOString();
|
||||
|
||||
function fixtures(now) {
|
||||
return [
|
||||
{ provider: "codex", name: "Codex", icon: "openai", plan: "Plus", user: "b@x.com", readAt: iso(now - 40 * M),
|
||||
windows: [{ name: "5 hours", used: 50, resetsAt: iso(now + 2 * H) }], resets: { count: 1 } },
|
||||
{ provider: "office/codex", name: "Codex · Office", icon: "openai", plan: "Pro", user: "a@x.com", from: "Office", kind: "subscription", readAt: iso(now - 40 * M),
|
||||
windows: [{ name: "5 hours", used: 30, resetsAt: iso(now + 2 * H) }] },
|
||||
{ provider: "home", name: "Home", icon: "magpie", from: "Home", kind: "subscription", windows: [],
|
||||
error: "nothing read on that magpie yet; refresh to have it read" },
|
||||
{ provider: "attic", name: "Attic", icon: "magpie", from: "Attic", kind: "subscription", windows: [],
|
||||
error: "remote magpie doesn't share its quotas; update magpie on that computer" },
|
||||
];
|
||||
}
|
||||
|
||||
function serve(lang, state) {
|
||||
const settings = { theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd" };
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (body) => route.fulfill({ json: body });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings });
|
||||
if (url.pathname === "/api/settings") return json(settings);
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
|
||||
if (url.pathname === "/api/usage/quotas") { state.gets++; return json(state.quotas); }
|
||||
if (url.pathname === "/api/usage/quotas/refresh") {
|
||||
assert.equal(route.request().method(), "POST");
|
||||
state.refreshes.push(url.search);
|
||||
await state.gate;
|
||||
const q = state.quotas.find((x) => x.provider === url.searchParams.get("provider") && (x.user || "") === (url.searchParams.get("user") || ""));
|
||||
if (q?.windows?.length) { q.windows[0].used = 61; q.readAt = iso(Date.now()); }
|
||||
if (q?.error) { state.quotas.push({ provider: q.provider + "/kimi", name: "Kimi · " + q.name, icon: "kimi-color", from: q.name, readAt: iso(Date.now()), windows: [{ name: "Week", used: 10 }] }); state.quotas.splice(state.quotas.indexOf(q), 1); }
|
||||
return json(state.quotas);
|
||||
}
|
||||
if (url.pathname === "/api/usage/quotas/history") return json([]);
|
||||
if (url.pathname === "/api/usage") return json({ calls: 0, cost: 0, days: [], agents: [], models: [], keys: [] });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
|
||||
};
|
||||
}
|
||||
|
||||
const words = {
|
||||
en: { none: "Nothing read on that computer yet — refresh this card to have it read", old: "That computer's magpie doesn't share its quotas yet — update magpie there" },
|
||||
zh: { none: "那台电脑还没有读过额度 — 刷新这张卡片让它读取", old: "那台电脑的 magpie 还不能共享额度 — 请在那台电脑上更新 magpie" },
|
||||
ja: { none: "そのコンピューターではまだ読み取っていません — このカードを更新すると読み取ります", old: "そのコンピューターの magpie はまだ利用枠を共有できません — そちらの magpie を更新してください" },
|
||||
de: { none: "Auf diesem Computer wurde noch nichts gelesen — diese Karte aktualisieren, um es lesen zu lassen", old: "Das magpie dieses Computers teilt seine Kontingente noch nicht — aktualisiere magpie dort" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh", "ja", "de"]) {
|
||||
const w = words[lang];
|
||||
test(`${engine} ${lang}: another computer's quota cards`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const errors = [];
|
||||
const page = await (await browser.newContext({ viewport: { width: 900, height: 700 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const state = { quotas: fixtures(Date.now()), gets: 0, refreshes: [], gate: Promise.resolve() };
|
||||
await page.route("**/*", serve(lang, state));
|
||||
await page.goto("http://magpie.test/?view=usage");
|
||||
|
||||
const office = page.locator(".subscription-card", { hasText: "Codex · Office" });
|
||||
await office.waitFor();
|
||||
assert.match(await office.locator(".quota-n").first().textContent(), /30%/);
|
||||
const home = page.locator(".subscription-card", { hasText: "Home" });
|
||||
assert.equal((await home.locator(".subscription-error").textContent()).trim(), w.none);
|
||||
const attic = page.locator(".subscription-card", { hasText: "Attic" });
|
||||
assert.equal((await attic.locator(".subscription-error").textContent()).trim(), w.old);
|
||||
|
||||
// the remote's card reads again over there, by its own id
|
||||
await office.hover();
|
||||
await office.locator("button.quota-refresh").click();
|
||||
await page.waitForFunction(() => !document.querySelector(".quota-refresh.busy"));
|
||||
// nothing read there yet: its refresh has the remote read every card
|
||||
await home.hover();
|
||||
await home.locator("button.quota-refresh").click();
|
||||
await page.locator(".subscription-card", { hasText: "Kimi · Home" }).waitFor();
|
||||
assert.deepEqual(state.refreshes, ["?provider=office%2Fcodex&user=a%40x.com", "?provider=home"]);
|
||||
assert.equal(await page.locator(".subscription-card", { hasText: "Home" }).locator(".subscription-error").count(), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -508,7 +508,12 @@ func usageRoutes(mux *http.ServeMux, w Windows) {
|
||||
// what was left of each window over time, for the quota cards' curves
|
||||
// (#651); ?days= back
|
||||
mux.HandleFunc("GET /api/usage/quotas/history", func(rw http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(rw, provider.QuotaHistories(provider.QuotaHistorySince(r.URL.Query().Get("days"), time.Now()), "", ""))
|
||||
days := r.URL.Query().Get("days")
|
||||
hs := provider.QuotaHistories(provider.QuotaHistorySince(days, time.Now()), "", "")
|
||||
// and a remote magpie's, for its cards (office/codex)
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
writeJSON(rw, append(hs, provider.RemoteQuotaHistories(ctx, days)...))
|
||||
})
|
||||
// spends one of a Codex account's rate-limit resets, which the page
|
||||
// has asked the user about first; what it did comes back
|
||||
|
||||
@@ -91,6 +91,11 @@ func forgetLoginReading(l Login) {
|
||||
// balance, and keeps it with the others, which aren't asked. The next
|
||||
// Quotas has it.
|
||||
func RefreshUsage(ctx context.Context, provider, user string) {
|
||||
// a remote magpie's card is read again there (remote_quotas.go)
|
||||
if p, card, ok := remoteOf(provider); ok {
|
||||
refreshRemote(ctx, p, card, user)
|
||||
return
|
||||
}
|
||||
r := cardRefresh{provider, user}
|
||||
ctx = context.WithValue(ctx, cardRefreshKey{}, r)
|
||||
ctx, seq := quotaReading(ctx)
|
||||
|
||||
@@ -27,10 +27,24 @@ func Allotted(ctx context.Context) []SubscriptionQuota {
|
||||
func quotas(ctx context.Context) (subs, plans, balances []SubscriptionQuota) {
|
||||
b := make(chan []SubscriptionQuota, 1)
|
||||
p := make(chan []SubscriptionQuota, 1)
|
||||
r := make(chan []SubscriptionQuota, 1)
|
||||
go func() { b <- KeyBalances(ctx) }()
|
||||
go func() { p <- PlanQuotas(ctx) }()
|
||||
go func() { r <- RemoteCards(ctx) }()
|
||||
subs = SubscriptionUsage(ctx)
|
||||
return subs, notShown(<-p, subs), <-b
|
||||
plans, balances = notShown(<-p, subs), <-b
|
||||
// a remote magpie's cards, each after this computer's of its kind
|
||||
for _, q := range <-r {
|
||||
switch q.Kind {
|
||||
case "plan":
|
||||
plans = append(plans, q)
|
||||
case "balance":
|
||||
balances = append(balances, q)
|
||||
default:
|
||||
subs = append(subs, q)
|
||||
}
|
||||
}
|
||||
return subs, plans, balances
|
||||
}
|
||||
|
||||
// notShown is the plans not already on a subscription's card: a GLM
|
||||
@@ -99,6 +113,9 @@ type Quota struct {
|
||||
// (served.go); Last is on the latest of them (#570).
|
||||
LastServedAt *time.Time `json:"lastServedAt,omitempty"`
|
||||
Last bool `json:"last,omitempty"`
|
||||
// From is the remote magpie whose account this is, by its name here
|
||||
// (remote_quotas.go); "" for this computer's own.
|
||||
From string `json:"from,omitempty"`
|
||||
}
|
||||
|
||||
// QuotaSpan is one window of an allowance: how much of it is used and
|
||||
@@ -133,7 +150,7 @@ func quotaReport(subs, plans, balances []SubscriptionQuota, now time.Time) []Quo
|
||||
}{{"subscription", subs}, {"plan", plans}, {"balance", balances}} {
|
||||
for _, q := range g.qs {
|
||||
r := Quota{Provider: q.Provider, Name: q.Name, Kind: g.kind, Plan: q.Plan, User: q.User, AsOf: q.AsOf, ReadAt: q.ReadAt,
|
||||
Windows: []QuotaSpan{}, Balance: q.Balance, Error: q.Error, Until: q.Until, Renew: q.Renew, Resets: q.Resets}
|
||||
Windows: []QuotaSpan{}, Balance: q.Balance, Error: q.Error, Until: q.Until, Renew: q.Renew, Resets: q.Resets, From: q.From}
|
||||
// a pool's own windows stand in for the models' drawing on it,
|
||||
// as the usage page shows them
|
||||
for _, w := range PooledWindows(q.Windows) {
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A remote magpie's quotas (莫 on Discord): a computer whose providers are
|
||||
// another's magpie (remote-magpie) has the accounts signed in there, not
|
||||
// here, so its Usage page, menu bar and magpie quota had nothing to show.
|
||||
// They now show the other magpie's cards as it last read them, each named
|
||||
// with that magpie ("Codex · office") and its provider id put after the
|
||||
// remote's ("office/codex"), so they never meet this computer's own.
|
||||
//
|
||||
// Only the magpie holding the sign-ins asks the vendors. It answers
|
||||
// RemoteCardsPath from what it has kept (CachedCards) and asks nobody;
|
||||
// a card's refresh here asks it to read that card again
|
||||
// (RemoteRefreshPath), which is the one time a vendor is asked for us.
|
||||
|
||||
// RemoteCardsPath is the gateway's answer of its kept cards.
|
||||
const RemoteCardsPath = "/v1/magpie/quotas/cards"
|
||||
|
||||
// RemoteRefreshPath has the gateway read a card (?provider=, &user=)
|
||||
// again, or every card when no provider is named, then answer as
|
||||
// RemoteCardsPath.
|
||||
const RemoteRefreshPath = "/v1/magpie/quotas/refresh"
|
||||
|
||||
// remoteCardsFor is how long another magpie's cards are kept here before
|
||||
// they are asked for again: reading its cache costs it nothing from the
|
||||
// vendors, but the menu bar and alerts ask often.
|
||||
const remoteCardsFor = 30 * time.Second
|
||||
|
||||
// errRemoteNothingRead is a remote magpie that has read no card since it
|
||||
// started: it is asked to only when a card is refreshed here.
|
||||
const errRemoteNothingRead = "nothing read on that magpie yet; refresh to have it read"
|
||||
|
||||
// errRemoteNoShare is a remote magpie too old to answer RemoteCardsPath.
|
||||
const errRemoteNoShare = "remote magpie doesn't share its quotas; update magpie on that computer"
|
||||
|
||||
// CachedCards is the Usage page's cards as this magpie last read them,
|
||||
// each with its kind, for another magpie to show: no vendor is asked,
|
||||
// whatever their age, and another magpie's cards shown here aren't
|
||||
// passed on.
|
||||
func CachedCards(now time.Time) []SubscriptionQuota {
|
||||
c := &subscriptionUsageCache
|
||||
c.Lock()
|
||||
data := c.data
|
||||
c.Unlock()
|
||||
subs := []SubscriptionQuota{}
|
||||
if data != nil {
|
||||
subs = withDailyCredits(visibleQuotas(data), now)
|
||||
}
|
||||
p := &planQuotaCache
|
||||
p.Lock()
|
||||
plans := slices.Clone(p.data)
|
||||
p.Unlock()
|
||||
b := &keyBalanceCache
|
||||
b.Lock()
|
||||
balances := slices.Clone(b.data)
|
||||
b.Unlock()
|
||||
out := []SubscriptionQuota{}
|
||||
for _, g := range []struct {
|
||||
kind string
|
||||
qs []SubscriptionQuota
|
||||
}{{"subscription", subs}, {"plan", notShown(plans, subs)}, {"balance", balances}} {
|
||||
for _, q := range g.qs {
|
||||
if q.From == "" {
|
||||
q.Kind = g.kind
|
||||
out = append(out, q)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ReadAllCards has every card read again, the page's Refresh asked by
|
||||
// another magpie whose card of this one's said nothing was read yet.
|
||||
func ReadAllCards(ctx context.Context) {
|
||||
AskUsage()
|
||||
ForgetBalances()
|
||||
forgetPlanQuotas()
|
||||
Quotas(ctx)
|
||||
}
|
||||
|
||||
var remoteCardCache struct {
|
||||
sync.Mutex
|
||||
m map[string]remoteCardsRead
|
||||
}
|
||||
|
||||
type remoteCardsRead struct {
|
||||
at time.Time
|
||||
cards []SubscriptionQuota // as the remote has them, not yet named
|
||||
err string
|
||||
}
|
||||
|
||||
// ForgetRemoteCardsForTest drops the remote magpies' cards kept here, for
|
||||
// a test run again (-count) to ask its own fake remote afresh.
|
||||
func ForgetRemoteCardsForTest() {
|
||||
c := &remoteCardCache
|
||||
c.Lock()
|
||||
c.m = nil
|
||||
c.Unlock()
|
||||
}
|
||||
|
||||
// remoteMagpies are the remote magpies this magpie uses.
|
||||
func remoteMagpies() []Provider {
|
||||
var out []Provider
|
||||
for _, p := range All() {
|
||||
if p.IsRemoteMagpie() && !p.Hidden && !p.Off && p.Key != "" && p.Anthropic != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// RemoteCards is every remote magpie's cards, named for this computer.
|
||||
func RemoteCards(ctx context.Context) []SubscriptionQuota {
|
||||
ps := remoteMagpies()
|
||||
got := make([][]SubscriptionQuota, len(ps))
|
||||
var wg sync.WaitGroup
|
||||
for i, p := range ps {
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); got[i] = remoteCards(ctx, p, false) }()
|
||||
}
|
||||
wg.Wait()
|
||||
return slices.Concat(got...)
|
||||
}
|
||||
|
||||
// remoteCards is p's cards, from what was kept here when it is recent and
|
||||
// fresh isn't asked. A remote that can't be asked keeps showing its last
|
||||
// cards, as old as they are; with none, one card says why.
|
||||
func remoteCards(ctx context.Context, p Provider, fresh bool) []SubscriptionQuota {
|
||||
c := &remoteCardCache
|
||||
c.Lock()
|
||||
r, ok := c.m[p.ID]
|
||||
c.Unlock()
|
||||
if !ok || fresh || time.Since(r.at) >= remoteCardsFor {
|
||||
cards, err := askRemote(ctx, p, http.MethodGet, RemoteCardsPath)
|
||||
r.at = time.Now()
|
||||
if err != nil {
|
||||
r.err = err.Error()
|
||||
} else {
|
||||
r.cards, r.err = cards, ""
|
||||
}
|
||||
c.Lock()
|
||||
if c.m == nil {
|
||||
c.m = map[string]remoteCardsRead{}
|
||||
}
|
||||
c.m[p.ID] = r
|
||||
c.Unlock()
|
||||
}
|
||||
name := remoteName(p)
|
||||
if len(r.cards) == 0 {
|
||||
msg := r.err
|
||||
if msg == "" {
|
||||
msg = errRemoteNothingRead
|
||||
}
|
||||
return []SubscriptionQuota{{Provider: p.ID, Name: name, Icon: "magpie", Kind: "subscription", From: name, Windows: []QuotaWindow{}, Error: msg}}
|
||||
}
|
||||
out := make([]SubscriptionQuota, 0, len(r.cards))
|
||||
for _, q := range r.cards {
|
||||
if q.From != "" || q.Provider == "" {
|
||||
continue
|
||||
}
|
||||
q.Provider = p.ID + "/" + q.Provider
|
||||
q.Name += " · " + name
|
||||
q.From = name
|
||||
// what is pressed on a card acts on this computer's accounts:
|
||||
// a Codex reset or a check-in is the other magpie's to do
|
||||
q.Resets, q.Checkins, q.CheckinBy, q.Checkin = nil, false, "", nil
|
||||
if q.Windows == nil {
|
||||
q.Windows = []QuotaWindow{}
|
||||
}
|
||||
out = append(out, q)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func remoteName(p Provider) string {
|
||||
if p.Name != "" {
|
||||
return p.Name
|
||||
}
|
||||
return p.ID
|
||||
}
|
||||
|
||||
// remoteOf is the remote magpie a card's provider id names, and the id of
|
||||
// the card there ("" for the card that stands for the remote itself).
|
||||
func remoteOf(id string) (Provider, string, bool) {
|
||||
rid, card, _ := strings.Cut(id, "/")
|
||||
for _, p := range remoteMagpies() {
|
||||
if p.ID == rid {
|
||||
return p, card, true
|
||||
}
|
||||
}
|
||||
return Provider{}, "", false
|
||||
}
|
||||
|
||||
// IsRemoteCard is whether id is a card this magpie has from a remote
|
||||
// magpie, or the card standing for the remote itself.
|
||||
func IsRemoteCard(id string) bool {
|
||||
_, _, ok := remoteOf(id)
|
||||
return ok
|
||||
}
|
||||
|
||||
// refreshRemote has the remote magpie read its card again (every card,
|
||||
// for the remote's own), then keeps what it now has.
|
||||
func refreshRemote(ctx context.Context, p Provider, card, user string) {
|
||||
q := url.Values{}
|
||||
if card != "" {
|
||||
q.Set("provider", card)
|
||||
if user != "" {
|
||||
q.Set("user", user)
|
||||
}
|
||||
}
|
||||
path := RemoteRefreshPath
|
||||
if len(q) > 0 {
|
||||
path += "?" + q.Encode()
|
||||
}
|
||||
if _, err := askRemote(ctx, p, http.MethodPost, path); err != nil {
|
||||
c := &remoteCardCache
|
||||
c.Lock()
|
||||
if r, ok := c.m[p.ID]; ok {
|
||||
r.err = err.Error()
|
||||
c.m[p.ID] = r
|
||||
}
|
||||
c.Unlock()
|
||||
}
|
||||
remoteCards(ctx, p, true)
|
||||
}
|
||||
|
||||
// RemoteQuotaHistories is every remote magpie's quota history since days
|
||||
// ago, as its own GET /v1/magpie/quotas/history has it (read from its
|
||||
// disk, no vendor asked), the providers named as RemoteCards names them.
|
||||
func RemoteQuotaHistories(ctx context.Context, days string) []QuotaHistory {
|
||||
ps := remoteMagpies()
|
||||
got := make([][]QuotaHistory, len(ps))
|
||||
var wg sync.WaitGroup
|
||||
for i, p := range ps {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
var hs []QuotaHistory
|
||||
if err := remoteJSON(ctx, p, http.MethodGet, "/v1/magpie/quotas/history?days="+url.QueryEscape(days), &hs); err != nil {
|
||||
return
|
||||
}
|
||||
for j := range hs {
|
||||
hs[j].Provider = p.ID + "/" + hs[j].Provider
|
||||
}
|
||||
got[i] = hs
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return slices.Concat(got...)
|
||||
}
|
||||
|
||||
func askRemote(ctx context.Context, p Provider, method, path string) ([]SubscriptionQuota, error) {
|
||||
var cards []SubscriptionQuota
|
||||
if err := remoteJSON(ctx, p, method, path, &cards); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cards, nil
|
||||
}
|
||||
|
||||
// remoteJSON asks p's gateway, with its key, for a {"data": …} list.
|
||||
func remoteJSON(ctx context.Context, p Provider, method, path string, dst any) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, method, p.Anthropic+path, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+p.Key)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := p.Do(http.DefaultClient, req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("couldn't reach %s: %w", remoteName(p), err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
b, _ := io.ReadAll(io.LimitReader(res.Body, 8<<20))
|
||||
switch {
|
||||
case res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusMethodNotAllowed:
|
||||
return fmt.Errorf("%s", errRemoteNoShare)
|
||||
case res.StatusCode < 200 || res.StatusCode >= 300:
|
||||
var e struct {
|
||||
Error struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if json.Unmarshal(b, &e) == nil && e.Error.Message != "" {
|
||||
return fmt.Errorf("%s: %s", remoteName(p), e.Error.Message)
|
||||
}
|
||||
return fmt.Errorf("%s answered %s", remoteName(p), res.Status)
|
||||
}
|
||||
var list struct {
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &list); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(list.Data) == 0 {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(list.Data, dst)
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// fakePeer is another magpie's gateway as RemoteCards asks it: its kept
|
||||
// cards at RemoteCardsPath, a card read again at RemoteRefreshPath.
|
||||
type fakePeer struct {
|
||||
sync.Mutex
|
||||
cards []SubscriptionQuota
|
||||
status int
|
||||
gets int
|
||||
refreshes []string // provider|user of each refresh asked
|
||||
}
|
||||
|
||||
func (f *fakePeer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
f.Lock()
|
||||
defer f.Unlock()
|
||||
if r.Header.Get("Authorization") != "Bearer sk-magpie-office" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if f.status != 0 {
|
||||
w.WriteHeader(f.status)
|
||||
return
|
||||
}
|
||||
switch r.Method + " " + r.URL.Path {
|
||||
case "GET " + RemoteCardsPath:
|
||||
f.gets++
|
||||
case "POST " + RemoteRefreshPath:
|
||||
f.refreshes = append(f.refreshes, r.URL.Query().Get("provider")+"|"+r.URL.Query().Get("user"))
|
||||
case "GET /v1/magpie/quotas/history":
|
||||
json.NewEncoder(w).Encode(map[string]any{"object": "list", "data": []QuotaHistory{{Provider: "codex", User: "a@x.com", Lines: []QuotaLine{{Name: "5h"}}}}})
|
||||
return
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]any{"object": "list", "data": f.cards})
|
||||
}
|
||||
|
||||
func remoteQuotaHome(t *testing.T, peer http.Handler) {
|
||||
t.Helper()
|
||||
azureHome(t)
|
||||
srv := httptest.NewServer(peer)
|
||||
t.Cleanup(srv.Close)
|
||||
if err := Save(Provider{ID: "office", Name: "Office", Preset: RemoteMagpiePreset, Key: "sk-magpie-office", Chat: srv.URL}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ForgetRemoteCardsForTest()
|
||||
t.Cleanup(ForgetRemoteCardsForTest)
|
||||
}
|
||||
|
||||
// 莫 on Discord: a computer whose providers are another's magpie showed
|
||||
// no quota at all. It now shows the other magpie's cards, named with it
|
||||
// and kept apart from its own by id, in their kinds; what a card's
|
||||
// buttons would do to this computer's accounts is left off, and a card
|
||||
// the other magpie has from a third isn't passed on.
|
||||
func TestRemoteMagpieCards(t *testing.T) {
|
||||
peer := &fakePeer{cards: []SubscriptionQuota{
|
||||
{Provider: "codex", Name: "Codex", Icon: "codex", User: "a@x.com", Kind: "subscription", Windows: []QuotaWindow{{Name: "5h", Used: 40}},
|
||||
Resets: &ResetCredits{Count: 1}, Checkins: true},
|
||||
{Provider: "zhipu", Name: "GLM Coding", Kind: "plan", Windows: []QuotaWindow{{Name: "5h", Used: 10}}},
|
||||
{Provider: "deepseek", Name: "DeepSeek", Kind: "balance", Balance: "¥12.00"},
|
||||
{Provider: "home/codex", Name: "Codex · Home", Kind: "subscription", From: "Home"},
|
||||
}}
|
||||
remoteQuotaHome(t, peer)
|
||||
ctx := context.Background()
|
||||
subs, plans, balances := quotas(ctx)
|
||||
find := func(qs []SubscriptionQuota, id string) *SubscriptionQuota {
|
||||
for i := range qs {
|
||||
if qs[i].Provider == id {
|
||||
return &qs[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
c := find(subs, "office/codex")
|
||||
if c == nil || c.Name != "Codex · Office" || c.From != "Office" || c.User != "a@x.com" || c.Icon != "codex" || len(c.Windows) != 1 || c.Windows[0].Used != 40 {
|
||||
t.Fatalf("subscription card: %+v", c)
|
||||
}
|
||||
if c.Resets != nil || c.Checkins {
|
||||
t.Errorf("a remote card's buttons are kept: %+v", c)
|
||||
}
|
||||
if p := find(plans, "office/zhipu"); p == nil || p.Name != "GLM Coding · Office" {
|
||||
t.Errorf("plan: %+v", plans)
|
||||
}
|
||||
if b := find(balances, "office/deepseek"); b == nil || b.Balance != "¥12.00" {
|
||||
t.Errorf("balance: %+v", balances)
|
||||
}
|
||||
for _, qs := range [][]SubscriptionQuota{subs, plans, balances} {
|
||||
for _, q := range qs {
|
||||
if strings.Contains(q.Provider, "home") {
|
||||
t.Errorf("a third magpie's card passed on: %+v", q)
|
||||
}
|
||||
}
|
||||
}
|
||||
// the menu bar and alerts ask often; the other magpie is asked once in
|
||||
// remoteCardsFor
|
||||
Quotas(ctx)
|
||||
RemoteCards(ctx)
|
||||
if peer.gets != 1 {
|
||||
t.Errorf("asked %d times, want 1", peer.gets)
|
||||
}
|
||||
// magpie quota names it too
|
||||
var found bool
|
||||
for _, q := range QuotaReport(ctx, time.Now()) {
|
||||
if q.Provider == "office/codex" {
|
||||
found = q.From == "Office" && q.Kind == "subscription"
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Error("QuotaReport has no office/codex from Office")
|
||||
}
|
||||
}
|
||||
|
||||
// A remote card's refresh asks the other magpie to read that card again,
|
||||
// and then what it has now; the remote's own card (nothing read there
|
||||
// yet) asks it to read every card.
|
||||
func TestRemoteMagpieCardRefresh(t *testing.T) {
|
||||
peer := &fakePeer{}
|
||||
remoteQuotaHome(t, peer)
|
||||
ctx := context.Background()
|
||||
cs := RemoteCards(ctx)
|
||||
if len(cs) != 1 || cs[0].Provider != "office" || cs[0].Error != errRemoteNothingRead || cs[0].Icon != "magpie" {
|
||||
t.Fatalf("nothing read there: %+v", cs)
|
||||
}
|
||||
peer.Lock()
|
||||
peer.cards = []SubscriptionQuota{{Provider: "codex", Name: "Codex", User: "a@x.com", Windows: []QuotaWindow{{Name: "5h", Used: 70}}}}
|
||||
peer.Unlock()
|
||||
RefreshUsage(ctx, "office", "")
|
||||
RefreshUsage(ctx, "office/codex", "a@x.com")
|
||||
if got := strings.Join(peer.refreshes, ","); got != "|,codex|a@x.com" {
|
||||
t.Errorf("refreshes asked: %q", got)
|
||||
}
|
||||
cs = RemoteCards(ctx)
|
||||
if len(cs) != 1 || cs[0].Provider != "office/codex" || cs[0].Windows[0].Used != 70 {
|
||||
t.Errorf("after refresh: %+v", cs)
|
||||
}
|
||||
if peer.gets != 3 {
|
||||
t.Errorf("cards asked %d times, want 3 (once, then after each refresh)", peer.gets)
|
||||
}
|
||||
// a card of this computer's own isn't sent there
|
||||
RefreshUsage(ctx, "codex", "")
|
||||
if len(peer.refreshes) != 2 {
|
||||
t.Errorf("a local refresh went to the remote: %v", peer.refreshes)
|
||||
}
|
||||
}
|
||||
|
||||
// A remote that can't be asked keeps its last cards, as old as they are;
|
||||
// with none, its card says why, and a magpie too old to share its quotas
|
||||
// is told to be updated.
|
||||
func TestRemoteMagpieUnreachable(t *testing.T) {
|
||||
peer := &fakePeer{cards: []SubscriptionQuota{{Provider: "codex", Name: "Codex", Windows: []QuotaWindow{{Name: "5h", Used: 5}}}}}
|
||||
remoteQuotaHome(t, peer)
|
||||
ctx := context.Background()
|
||||
RemoteCards(ctx)
|
||||
peer.Lock()
|
||||
peer.status = http.StatusBadGateway
|
||||
peer.Unlock()
|
||||
if cs := remoteCards(ctx, remoteMagpies()[0], true); len(cs) != 1 || cs[0].Provider != "office/codex" || cs[0].Error != "" {
|
||||
t.Errorf("last cards not kept: %+v", cs)
|
||||
}
|
||||
ForgetRemoteCardsForTest()
|
||||
peer.Lock()
|
||||
peer.status = http.StatusNotFound
|
||||
peer.Unlock()
|
||||
if cs := RemoteCards(ctx); len(cs) != 1 || cs[0].Error != errRemoteNoShare {
|
||||
t.Errorf("an old magpie: %+v", cs)
|
||||
}
|
||||
}
|
||||
|
||||
// The cards told to another magpie are this one's as last read: nothing
|
||||
// is read for it, however old they are, and another magpie's aren't
|
||||
// passed on.
|
||||
func TestCachedCardsAskNobody(t *testing.T) {
|
||||
azureHome(t)
|
||||
c := &subscriptionUsageCache
|
||||
c.Lock()
|
||||
keep, keepAt := c.data, c.at
|
||||
c.data = []SubscriptionQuota{{Provider: "codex", Name: "Codex", User: "a@x.com", Windows: []QuotaWindow{{Name: "5h", Used: 1}}}}
|
||||
c.at = time.Now().Add(-time.Hour)
|
||||
c.Unlock()
|
||||
t.Cleanup(func() {
|
||||
c.Lock()
|
||||
c.data, c.at = keep, keepAt
|
||||
c.Unlock()
|
||||
})
|
||||
cs := CachedCards(time.Now())
|
||||
if len(cs) != 1 || cs[0].Provider != "codex" || cs[0].Kind != "subscription" {
|
||||
t.Errorf("cards: %+v", cs)
|
||||
}
|
||||
if SubscriptionUsageReading() {
|
||||
t.Error("telling the cards started a read")
|
||||
}
|
||||
c.Lock()
|
||||
at := c.at
|
||||
c.Unlock()
|
||||
if time.Since(at) < 30*time.Minute {
|
||||
t.Error("the cache was read again")
|
||||
}
|
||||
}
|
||||
|
||||
// A remote magpie's history comes with its cards' ids.
|
||||
func TestRemoteQuotaHistories(t *testing.T) {
|
||||
remoteQuotaHome(t, &fakePeer{})
|
||||
hs := RemoteQuotaHistories(context.Background(), "7")
|
||||
if len(hs) != 1 || hs[0].Provider != "office/codex" || hs[0].User != "a@x.com" {
|
||||
t.Errorf("%+v", hs)
|
||||
}
|
||||
}
|
||||
@@ -117,6 +117,12 @@ type SubscriptionQuota struct {
|
||||
Checkins bool `json:"checkins,omitempty"`
|
||||
CheckinBy string `json:"checkinBy,omitempty"`
|
||||
Checkin *WorkBuddyCheckin `json:"checkin,omitempty"`
|
||||
// Kind is the card's kind as another magpie is told it (CachedCards):
|
||||
// subscription, plan or balance; "" here.
|
||||
Kind string `json:"kind,omitempty"`
|
||||
// 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"`
|
||||
// In-process read order, separate from the vendor's ReadAt and never
|
||||
// persisted: restarting starts a new sequence.
|
||||
readSeq uint64
|
||||
|
||||
+14
-2
@@ -357,6 +357,12 @@ func quotaMatches(q provider.Quota, only []string) bool {
|
||||
if strings.EqualFold(q.Provider, o) || strings.EqualFold(q.Name, o) || strings.EqualFold(q.Kind, o) {
|
||||
return true
|
||||
}
|
||||
// a remote magpie's card: by the remote ("office", or its name)
|
||||
// or by the provider there ("codex" is office/codex too)
|
||||
if rid, there, ok := strings.Cut(q.Provider, "/"); ok && q.From != "" &&
|
||||
(strings.EqualFold(rid, o) || strings.EqualFold(q.From, o) || strings.EqualFold(there, o)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -408,9 +414,15 @@ func quotaHistoryCmd(args []string) error {
|
||||
}
|
||||
now := time.Now()
|
||||
hs := []provider.QuotaHistory{}
|
||||
for _, h := range provider.QuotaHistories(provider.QuotaHistorySince(days, now), "", "") {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
all := provider.QuotaHistories(provider.QuotaHistorySince(days, now), "", "")
|
||||
// and each remote magpie's, as it keeps them (office/codex)
|
||||
all = append(all, provider.RemoteQuotaHistories(ctx, days)...)
|
||||
for _, h := range all {
|
||||
rid, there, _ := strings.Cut(h.Provider, "/")
|
||||
if len(only) == 0 || slices.ContainsFunc(only, func(o string) bool {
|
||||
return o == h.Provider || o == h.User || o == h.Provider+"/"+h.User
|
||||
return o == h.Provider || o == h.User || o == h.Provider+"/"+h.User || there != "" && (o == rid || o == there || o == there+"/"+h.User)
|
||||
}) {
|
||||
hs = append(hs, h)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user