From 2a90ed10305fa162cffc77d5449d1aaa4ab49228 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 24 Sep 2026 12:49:51 +0800 Subject: [PATCH] =?UTF-8?q?usage:=20the=20page=20no=20longer=20waits=20on?= =?UTF-8?q?=20subscription=20quotas=20=E2=80=94=20they=20load=20on=20their?= =?UTF-8?q?=20own,=20in=20parallel,=20stale-while-revalidate=20(#6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gui/assets/app.js | 84 ++++++++++++-------- internal/gui/usage.go | 22 ++--- internal/provider/subscription_usage.go | 84 ++++++++++++++++---- internal/provider/subscription_usage_test.go | 50 +++++++++++- 4 files changed, 183 insertions(+), 57 deletions(-) diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 82d8be99d..d19723cec 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -1559,12 +1559,26 @@ $("#addProvider").onclick = () => { adding = true; editing = null; draft = null; const PERIODS = [["today", "Today"], ["7d", "7 days"], ["30d", "30 days"], ["all", "All"]]; +// The subscriptions' quotas come from the vendors and can take a while (or +// never come without a proxy), so they load on their own and the local log +// never waits for them. They don't depend on the period either. +let quotas = null; async function loadUsage() { renderUsageLoading(); + loadQuotas(); usage = await api("usage?period=" + period); renderUsage(); } +let quotasLoading = null; +function loadQuotas() { + if (quotasLoading) return quotasLoading; + quotasLoading = api("usage/quotas") + .then((q) => { quotas = q || []; }, () => { quotas = quotas || []; }) + .finally(() => { quotasLoading = null; renderQuotas(); }); + return quotasLoading; +} + function renderUsageLoading() { const view = $("#view-usage"); view.classList.add("loading"); @@ -1578,14 +1592,7 @@ function renderUsageLoading() { } slide(seg, "period"); $("#usageCost").replaceChildren(el("span", "skeleton sk-cost")); - const subscriptions = $("#subscriptionUsage"); - subscriptions.hidden = false; - subscriptions.replaceChildren(); - for (let i = 0; i < 2; i++) { - const card = el("div", "subscription-card skeleton-card"); - card.append(el("span", "skeleton sk-title"), el("span", "skeleton sk-line"), el("span", "skeleton sk-line short")); - subscriptions.append(card); - } + renderQuotas(); const stats = $("#stats"); stats.classList.remove("empty"); stats.replaceChildren(); @@ -1616,33 +1623,20 @@ function fmtCost(t) { } const tokensOf = (t) => t.input + t.output; -function renderUsage() { - const u = usage; - const view = $("#view-usage"); - view.classList.remove("loading"); - view.removeAttribute("aria-busy"); - const seg = $("#period"); - seg.replaceChildren(); - for (const [id, name] of PERIODS) { - const b = el("button", "opt" + (id === period ? " on" : ""), t(name)); - b.onclick = () => { for (const x of seg.querySelectorAll(".opt")) x.classList.toggle("on", x === b); slide(seg, "period"); period = id; loadUsage().catch((e) => status(e.message, "err")); }; - seg.append(b); - } - slide(seg, "period"); - const cost = $("#usageCost"); - cost.replaceChildren(); - const c = fmtCost(u); - if (c) { - cost.append(el("b", "", "≈" + c), el("span", "", t("list price"))); - cost.title = u.unpriced ? t(u.unpriced === 1 ? "{n} call had no known price and is not counted" : "{n} calls had no known price and are not counted", { n: u.unpriced }) : t("At each model's list price on models.dev"); - } else if (u.calls) { - cost.append(el("span", "", t("no price for these models"))); - } - +function renderQuotas() { const subscriptions = $("#subscriptionUsage"); subscriptions.replaceChildren(); - subscriptions.hidden = !u.subscriptions?.length; - for (const sub of u.subscriptions || []) { + if (!quotas) { + subscriptions.hidden = false; + for (let i = 0; i < 2; i++) { + const card = el("div", "subscription-card skeleton-card"); + card.append(el("span", "skeleton sk-title"), el("span", "skeleton sk-line"), el("span", "skeleton sk-line short")); + subscriptions.append(card); + } + return; + } + subscriptions.hidden = !quotas.length; + for (const sub of quotas) { const card = el("div", "subscription-card"); const head = el("div", "subscription-head"); head.append(icon(sub.icon), el("b", "", sub.name)); @@ -1669,6 +1663,30 @@ function renderUsage() { } subscriptions.append(card); } +} + +function renderUsage() { + const u = usage; + const view = $("#view-usage"); + view.classList.remove("loading"); + view.removeAttribute("aria-busy"); + const seg = $("#period"); + seg.replaceChildren(); + for (const [id, name] of PERIODS) { + const b = el("button", "opt" + (id === period ? " on" : ""), t(name)); + b.onclick = () => { for (const x of seg.querySelectorAll(".opt")) x.classList.toggle("on", x === b); slide(seg, "period"); period = id; loadUsage().catch((e) => status(e.message, "err")); }; + seg.append(b); + } + slide(seg, "period"); + const cost = $("#usageCost"); + cost.replaceChildren(); + const c = fmtCost(u); + if (c) { + cost.append(el("b", "", "≈" + c), el("span", "", t("list price"))); + cost.title = u.unpriced ? t(u.unpriced === 1 ? "{n} call had no known price and is not counted" : "{n} calls had no known price and are not counted", { n: u.unpriced }) : t("At each model's list price on models.dev"); + } else if (u.calls) { + cost.append(el("span", "", t("no price for these models"))); + } const stats = $("#stats"); stats.replaceChildren(); diff --git a/internal/gui/usage.go b/internal/gui/usage.go index 00441a8e3..0e2d502eb 100644 --- a/internal/gui/usage.go +++ b/internal/gui/usage.go @@ -20,17 +20,14 @@ type usageGroup struct { type usageJSON struct { usage.Summary - Agents []usageGroup `json:"agents"` - Models []usageGroup `json:"models"` - Path string `json:"path"` - Subscriptions []provider.SubscriptionQuota `json:"subscriptions"` + Agents []usageGroup `json:"agents"` + Models []usageGroup `json:"models"` + Path string `json:"path"` } -func usageState(ctx context.Context, p usage.Period) usageJSON { +func usageState(p usage.Period) usageJSON { s := usage.Summarize(p) - quotaCtx, cancel := context.WithTimeout(ctx, 8*time.Second) - defer cancel() - out := usageJSON{Summary: s, Agents: []usageGroup{}, Models: []usageGroup{}, Path: tilde(usage.Path()), Subscriptions: provider.SubscriptionUsage(quotaCtx)} + out := usageJSON{Summary: s, Agents: []usageGroup{}, Models: []usageGroup{}, Path: tilde(usage.Path())} agents := map[string]*agent.Agent{} for _, a := range agent.All() { agents[a.ID] = a @@ -67,6 +64,13 @@ func usageRoutes(mux *http.ServeMux) { default: p = usage.Month } - writeJSON(rw, usageState(r.Context(), p)) + writeJSON(rw, usageState(p)) + }) + // The subscriptions' quotas come from the vendors, which can be slow or + // unreachable, so the page asks for them apart from the local log. + mux.HandleFunc("GET /api/usage/quotas", func(rw http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second) + defer cancel() + writeJSON(rw, provider.SubscriptionUsage(ctx)) }) } diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index c71943f3c..c5c1a7b3e 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -35,41 +35,97 @@ type SubscriptionQuota struct { var subscriptionUsageCache struct { sync.Mutex - at time.Time - data []SubscriptionQuota + at time.Time + data []SubscriptionQuota + pending chan struct{} // closed when the refresh in flight is done } +// subscriptionTimeout bounds one refresh; the vendors' endpoints can be +// unreachable without a proxy, and then each fetch would hang to it. +var subscriptionTimeout = 10 * time.Second + // SubscriptionUsage returns rolling quotas for signed-in first-party agents. // Results are cached because these private account endpoints are aggressively -// rate limited when several CLI sessions are active. +// rate limited when several CLI sessions are active. Once there is something +// cached it comes back at once, and a stale copy is refreshed in the +// background; only the very first call waits, for as long as ctx allows. func SubscriptionUsage(ctx context.Context) []SubscriptionQuota { - subscriptionUsageCache.Lock() - defer subscriptionUsageCache.Unlock() - if time.Since(subscriptionUsageCache.at) < time.Minute && subscriptionUsageCache.data != nil { - return append([]SubscriptionQuota(nil), subscriptionUsageCache.data...) + c := &subscriptionUsageCache + c.Lock() + have, fresh := c.data != nil, time.Since(c.at) < time.Minute + if !fresh && c.pending == nil { + done := make(chan struct{}) + c.pending = done + go func() { + out := fetchSubscriptionUsage() + c.Lock() + c.at, c.data, c.pending = time.Now(), out, nil + c.Unlock() + close(done) + }() } - var out []SubscriptionQuota + pending := c.pending + c.Unlock() + if !have && pending != nil { + select { + case <-pending: + case <-ctx.Done(): + return nil + } + } + c.Lock() + defer c.Unlock() + return visibleQuotas(c.data) +} + +// visibleQuotas drops accounts removed from magpie since the last refresh. +func visibleQuotas(all []SubscriptionQuota) []SubscriptionQuota { hidden := map[string]bool{} for _, p := range load().Providers { hidden[p.ID] = p.Hidden } + out := []SubscriptionQuota{} + for _, q := range all { + if !hidden[q.Provider] { + out = append(out, q) + } + } + return out +} + +// fetchSubscriptionUsage asks every signed-in vendor at once. +func fetchSubscriptionUsage() []SubscriptionQuota { + ctx, cancel := context.WithTimeout(context.Background(), subscriptionTimeout) + defer cancel() + hidden := map[string]bool{} + for _, p := range load().Providers { + hidden[p.ID] = p.Hidden + } + var fetches []func() SubscriptionQuota if _, ok := claudeAccount(); ok && !hidden["claude"] { - out = append(out, claudeSubscriptionUsage(ctx)) + fetches = append(fetches, func() SubscriptionQuota { return claudeSubscriptionUsage(ctx) }) } if home, err := os.UserHomeDir(); err == nil { - if p, ok := codexAccount(home); ok && !hidden[p.ID] { - out = append(out, codexSubscriptionUsage(ctx, filepath.Join(home, ".codex", "auth.json"))) + if _, ok := codexAccount(home); ok && !hidden["codex"] { + auth := filepath.Join(home, ".codex", "auth.json") + fetches = append(fetches, func() SubscriptionQuota { return codexSubscriptionUsage(ctx, auth) }) } cfg := os.Getenv("XDG_CONFIG_HOME") if cfg == "" { cfg = filepath.Join(home, ".config") } if app, ok := copilotLogin(cfg); ok && !hidden["copilot"] { - out = append(out, copilotSubscriptionUsage(ctx, app.Token)) + fetches = append(fetches, func() SubscriptionQuota { return copilotSubscriptionUsage(ctx, app.Token) }) } } - subscriptionUsageCache.at, subscriptionUsageCache.data = time.Now(), out - return append([]SubscriptionQuota(nil), out...) + out := make([]SubscriptionQuota, len(fetches)) + var wg sync.WaitGroup + for i, f := range fetches { + wg.Add(1) + go func() { defer wg.Done(); out[i] = f() }() + } + wg.Wait() + return out } func accountJSON(ctx context.Context, url, token string, headers map[string]string, dst any) error { diff --git a/internal/provider/subscription_usage_test.go b/internal/provider/subscription_usage_test.go index b1032d9a9..1ca3e9f5e 100644 --- a/internal/provider/subscription_usage_test.go +++ b/internal/provider/subscription_usage_test.go @@ -1,6 +1,10 @@ package provider -import "testing" +import ( + "context" + "testing" + "time" +) func TestCodexQuotaUsesProviderWindowDuration(t *testing.T) { for _, tt := range []struct { @@ -28,3 +32,47 @@ func TestCompactQuotaNumber(t *testing.T) { } } } + +// A stale copy comes back at once while it refreshes, and accounts removed +// from magpie in the meantime are left out of it. +func TestSubscriptionUsageServesStale(t *testing.T) { + signIn(t) + if err := Delete("codex"); err != nil { + t.Fatal(err) + } + c := &subscriptionUsageCache + c.Lock() + c.at, c.pending = time.Now().Add(-time.Hour), nil + c.data = []SubscriptionQuota{{Provider: "claude", Name: "Claude Code"}, {Provider: "codex", Name: "Codex"}} + c.Unlock() + t.Cleanup(func() { + for { + c.Lock() + p := c.pending + if p == nil { + c.data, c.at = nil, time.Time{} + c.Unlock() + return + } + c.Unlock() + <-p + } + }) + + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + start := time.Now() + got := SubscriptionUsage(ctx) + if time.Since(start) > 40*time.Millisecond { + t.Fatalf("waited %v for a stale copy", time.Since(start)) + } + if len(got) != 1 || got[0].Provider != "claude" { + t.Fatalf("got %+v, want only claude", got) + } + c.Lock() + refreshing := c.pending != nil || time.Since(c.at) < time.Minute + c.Unlock() + if !refreshing { + t.Fatal("a stale copy did not start a refresh") + } +}