Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

usage: a plugin window that doesn't say used is no reading (#3650)

yetone9733ed1b4aaf
diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md
index b707c455f..89a23874e 100644
--- a/docs/subsystems/provider-plugins.md
+++ b/docs/subsystems/provider-plugins.md
@@ -38,6 +38,10 @@ A plugin that learns a step's usage only after the step has ended reports it wit
The gateway parses the field into `Usage.Deferred` ([`cUsage`](../../internal/gateway/chat.go)) and adds it only where it bills: the usage records, the OTel attempt spans and route pricing, which prices it as a tier before the request's own ([`routeUsage`](../../internal/gateway/trace.go), [`Usage.billed`](../../internal/gateway/ir.go)). What a client is told stays the request's own, because agents read `prompt_tokens` as how full their context is: the passthrough forwards the plugin's bytes as they are, whose standard fields are the step's own, and a translated reply is encoded from the own count alone. `promptCounted` also reads the request's own. A reply without the field is handled as before. With an older magpie the field is ignored and the owed step goes unbilled in the ledger. [`deferred_usage_test.go`](../../internal/gateway/deferred_usage_test.go) covers the passthrough, the translated reply, the ledger, the OTel span and the pricing tiers.
+## A usage window that says no share
+
+A usage window's `used` (percent) may be left out when the plugin can't tell it: the Loomy plugins send only `display` ([#3650](https://github.com/yetone/magpie/issues/3650)). Left out is not 0. The host passes it on as `null` (`usageOf` in [`host.js`](../../internal/plugin/host.js)), `plugin.UsageWindow.Used` is a `*float64`, and [`quotaOfPlugin`](../../internal/provider/plugin_usage.go) makes such a window `Text` and `Aside`: the card shows its `display` (else "No allowance reported"), never a percentage or a meter (`quotaNoShare` in `app.js`), and `allowanceOf` leaves it out. An account whose windows all tell no share has no allowance, so routing counts it not known (`routedAllowance` in [`routing.go`](../../internal/provider/routing.go), for a fresh reading and the one kept on disk alike), as one never read, rather than as the one with all of it left. A window that says `used: 0` is a reading at 0, as before. [`plugin_usage_absent_test.go`](../../internal/provider/plugin_usage_absent_test.go) and `usage-no-reading.test.cjs` cover both.
+
## Cache a vendor doesn't count
A plugin whose vendor counts no cache tokens says so with `usage.magpie_cache_unknown: true` in its Anthropic usage, and leaves the cache fields out. Kiro does this: it caches on its side (a repeated prompt costs about half the credits), but its replies carry credits and a context share, never tokens (opencode-kiro-auth 0.1.16, zeewell on X). The gateway reads the field in [`aUsage`](../../internal/gateway/anthropic.go) into `Usage.cacheUnknown`, ORed across a reply's usage events. [`routeUsage`](../../internal/gateway/trace.go) then sets `RouteUsage.CacheUnknown` on a try that counted no cache read or write. The Routing page's `promptOf` (`plugins/routing/client.js`) leaves such a try out of the hit rate, so the request shows none, not 0%. The field is never told to a client: `Usage.anthropic()` leaves it out, and a passthrough forwards the plugin's bytes as they are. The usage ledger carries it too ([#3464](https://github.com/yetone/magpie/issues/3464)): the gateway records `usage.Record.CacheUnknown` on a call that counted no cache (`Usage.cacheNotCounted`), the ledger keeps it as row flag 8192 (`rowCacheUnknown`), and `usage.Totals` sums such calls' prompt into `cache_unknown` and their count into `cache_unknown_calls`. Every hit rate leaves that prompt out of its denominator: `Totals.HitRate`, and `cacheHitOf` in app.js, used by the tray panel's card, the Usage page's agent rows and cache tile, the requests' Cache hit rate card (which says how many it left out, `cacheLeftOut`) and each ranking row. One of only such calls shows no rate. A request row's cache cells show "—" and its details say the vendor doesn't count the cache. Calls kept before Kiro's plugin said so carry no flag, so a Kiro call (`kiro` or `kiro-plugin`) with no cache counted is read as one (`usage.CountsNoCache`): in the ledger's `rowChunk.row`, in `Totals.countCache`, and for Routing's history in `pricedRoutes` (`cacheCounted`, `internal/gui/trace.go`). The context view (`internal/gui/context.go`, `context.js`) shows no cache for such a call and doesn't score it as a miss. Not covered: hit rates read from agents' own session files (`sessions.Tokens`: the TUI and CLI session lists, the Sessions tab's totals), which carry Kiro's 0 as a miss. [`cache_unknown_test.go`](../../internal/gateway/cache_unknown_test.go) covers the passthrough and translated replies, both whole and streamed.
diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js
index d20ff72f6..f8f7bf36b 100644
--- a/internal/gui/assets/app.js
+++ b/internal/gui/assets/app.js
@@ -13317,7 +13317,7 @@ function accountQuota(data, user, capFor = () => 0, settable = null) {
fill.style.width = quotaFill(w) + "%";
track.append(fill);
capMark(track, w, capFor(w));
- m.append(el("span", "aq-n", t(w.name)), ...(w.text ? [] : [track]), el("b", "", quotaText(w)));
+ m.append(el("span", "aq-n", t(w.name)), ...(quotaNoShare(w) ? [] : [track]), el("b", "", quotaText(w)));
if (w.resetsAt) {
const at = new Date(w.resetsAt);
m.title = resetText(at, at.toLocaleString(intlLang()));
@@ -13354,7 +13354,7 @@ function poolLine(line, ws, q, capFor = () => 0, settable = null) {
capMark(track, w, capFor(w));
// each of a pool's windows is set apart: its own part of the meter
const part = el("span", "aq-win");
- part.append(el("span", "aq-k", w.window ? shortWindow(w.window) : ""), track, el("b", "", quotaText(w)));
+ part.append(el("span", "aq-k", w.window ? shortWindow(w.window) : ""), ...(quotaNoShare(w) ? [] : [track]), el("b", "", quotaText(w)));
m.append(settable ? settable(part, w) : part);
}
const w = p.ws[0];
@@ -13710,14 +13710,19 @@ async function refreshLanes() {
// own count, where it gives one, stands before the percentage.
let quotaLeft = false;
function to100(v) { return Math.max(0, Math.min(100, v)); }
+// quotaNoShare: the plugin didn't say how much of the window is used. Its
+// text is all there is, and no percentage may be read from it: 0 is a
+// reading, absent is not (#3650)
+function quotaNoShare(w) { return !!w.text || w.used == null; }
function tipLines(...a) { return a.filter(Boolean).join("\n"); }
function quotaFill(w) {
+ if (w.used == null) return 0;
const used = Math.round(to100(w.used));
return quotaLeft ? 100 - used : used;
}
function quotaText(w) {
if (w.unlimited) return t("Unlimited");
- if (w.text) return w.display;
+ if (quotaNoShare(w)) return w.display || t("No allowance reported");
const used = to100(w.used);
const n = quotaLeft ? 100 - used : used;
const pct = t(quotaLeft ? "{n} left" : "{n} used", { n: (Number.isInteger(n) ? n : n.toFixed(1)) + "%" });
@@ -13732,7 +13737,7 @@ function quotaText(w) {
// provider.WithWindowStarts). over says more is used than an even pace
// would have, whichever way the meter reads.
function quotaPace(w, now = Date.now()) {
- if (w.unlimited || w.historyMissing || !w.startsAt || !w.resetsAt) return null;
+ if (w.unlimited || quotaNoShare(w) || w.historyMissing || !w.startsAt || !w.resetsAt) return null;
const s = Date.parse(w.startsAt), e = Date.parse(w.resetsAt);
if (!(e > s) || now < s || now >= e) return null;
const d = to100(w.used) - (100 * (now - s)) / (e - s);
@@ -17071,8 +17076,8 @@ function panelQuotaCard(q) {
const balance = q.balance && balanceRow(q, "What is left on the account besides its windows", false);
// a pool's 5-hour and weekly rings, every pool's (a third pool once left
// Claude's out: 01huadalang on Discord), else three
- const fam = familyWindows(q.windows.filter((w) => !w.unlimited && !w.text));
- const tx = q.windows.filter((w) => w.text).map((w) => t(w.name) + " " + w.display).join(" · ");
+ const fam = familyWindows(q.windows.filter((w) => !w.unlimited && !quotaNoShare(w)));
+ const tx = q.windows.filter((w) => quotaNoShare(w)).map((w) => t(w.name) + " " + quotaText(w)).join(" · ");
if (!fam.length && (tx || q.windows.some((w) => w.unlimited))) {
card.append(pqLine(tx || t("Unlimited"), q));
if (balance) card.append(balance);
@@ -18065,7 +18070,7 @@ function quotaWindows(sub) {
if (w.historyMissing) track.style.visibility = "hidden";
track.append(fill);
quota.append(labels);
- if (!w.unlimited && !w.text) quota.append(track);
+ if (!w.unlimited && !quotaNoShare(w)) quota.append(track);
// when it starts again, on the clock and how long until then
let r = null;
if (w.resetsAt) {
diff --git a/internal/gui/tests/usage-no-reading.test.cjs b/internal/gui/tests/usage-no-reading.test.cjs
new file mode 100644
index 000000000..fc11975f8
--- /dev/null
+++ b/internal/gui/tests/usage-no-reading.test.cjs
@@ -0,0 +1,100 @@
+// Run with Node's test runner and Playwright on the module path; see README.md.
+// A plugin's usage window that leaves out used says nothing of how much of
+// it is spent — a 0% it never reported. The card shows what the plugin did
+// say (its display text, else "No allowance reported") and no percentage,
+// and no meter is drawn from it, rather than "100% left" (or NaN%) from a
+// 0 it was never told (#3650): neither as magpie's API sends such a window
+// (text, used 0) nor with used left out. A window that did say used:0
+// still shows its 0%, and its meter. Chromium and WebKit, every language,
+// used and left, at a narrow width; no backend, the API is faked here.
+// Contributed by skygunner.
+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(process.env.MAGPIE_ASSETS || path.join(__dirname, "../assets"));
+const langs = ["en", "zh", "zh-TW", "ja", "de"];
+const none = { en: "No allowance reported", zh: "暂无额度数据", "zh-TW": "暫無額度資料", ja: "利用枠の情報なし", de: "Kein Kontingent gemeldet" };
+
+const quotas = [
+ // the reporter's plugin: a count in its display, no used — as the API
+ // sends it (text) and as a page may be handed one (used left out)
+ { provider: "loomy-plugin", name: "Loomy", user: "[email protected]", windows: [
+ { name: "Credits", used: 0, text: true, display: "0 / 5000" },
+ { name: "Bonus", display: "12 / 300" },
+ { name: "Gift" },
+ ] },
+ { provider: "claude", name: "Claude", user: "[email protected]", windows: [
+ { name: "5 hours", used: 40 },
+ { name: "Weekly", used: 0 },
+ ] },
+];
+
+function serve(lang) {
+ return async (route) => {
+ const url = new URL(route.request().url());
+ const json = (data) => route.fulfill({ json: data });
+ 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: { lang, theme: "light" } });
+ if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
+ if (url.pathname === "/api/usage/quotas") return json(quotas);
+ 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: "" }); }
+ };
+}
+
+async function windows(card) {
+ return card.locator(".quota").evaluateAll((qs) => qs.map((q) => ({ n: q.querySelector(".quota-n")?.innerText ?? "", track: !!q.querySelector(".quota-track") })));
+}
+
+for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
+ test(`${engine}: a window that didn't say used shows its text, not a percentage`, async (t) => {
+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
+ t.after(() => browser.close());
+ for (const lang of langs) {
+ for (const width of [900, 390]) {
+ const page = await browser.newPage({ viewport: { width, height: 800 }, reducedMotion: "reduce" });
+ page.setDefaultTimeout(5000);
+ const errors = [];
+ page.on("pageerror", (e) => errors.push(e.message));
+ await page.route("**/*", serve(lang));
+ await page.goto("http://magpie.test/?view=usage");
+ const at = `${lang} ${width}px`;
+
+ const spent = page.locator(".subscription-card", { hasText: "Loomy" });
+ const fine = page.locator(".subscription-card", { hasText: "Claude" });
+ await spent.locator(".quota-n").first().waitFor();
+ await fine.locator(".quota-n").first().waitFor();
+ // as used, then as left: "100% left" was the reporter's reading
+ for (const side of ["used", "left"]) {
+ const s = await windows(spent);
+ assert.equal(s.length, 3, `${at} ${side}: ${JSON.stringify(s)}`);
+ assert.match(s[0].n, /^0 \/ 5000$/, `${at} ${side}: the plugin's own count`);
+ assert.match(s[1].n, /^12 \/ 300$/, `${at} ${side}: the plugin's own count`);
+ assert.equal(s[2].n, none[lang], `${at} ${side}: a window that said nothing`);
+ for (const w of s) {
+ assert.doesNotMatch(w.n, /NaN|%/, `${at} ${side}: no share from a used never sent: ${w.n}`);
+ assert.equal(w.track, false, `${at} ${side}: no meter from a share never sent: ${w.n}`);
+ }
+ // a window that did say its share keeps it, 0 too
+ const f = await windows(fine);
+ assert.match(f[0].n, side === "used" ? /40\s?%/ : /60\s?%/, `${at} ${side}: ${f[0].n}`);
+ assert.match(f[1].n, side === "used" ? /(^|\D)0\s?%/ : /100\s?%/, `${at} ${side}: a used of 0 that was said: ${f[1].n}`);
+ assert.ok(f.every((w) => w.track), `${at} ${side}: a window that said its share has its meter`);
+ if (side === "used") await fine.locator(".quota-n").first().click();
+ }
+ const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
+ assert.ok(overflow <= 0, `${at}: the page scrolls sideways by ${overflow}px`);
+ assert.deepEqual(errors, [], at);
+ await page.close();
+ }
+ }
+ });
+}
diff --git a/internal/plugin/host.js b/internal/plugin/host.js
index 9ac5337d9..6fafa0ab0 100644
--- a/internal/plugin/host.js
+++ b/internal/plugin/host.js
@@ -2371,7 +2371,8 @@ async function load({ provider, account, proxy }) {
// ms; none: it never runs out), window? ("fiveHour", "weekly") }]
// (every reset still to be used) } (the rate-limit resets the
// account may spend),
-// windows?: [{ name, used (percent, 0–100), resetsAt? (ISO or ms),
+// windows?: [{ name, used (percent, 0–100; left out: the plugin didn't
+// say, which is no share and not 0%), resetsAt? (ISO or ms),
// resetSecs?, display?, amount? / limit? / unit? (the window's own
// count, when it counts in amounts: amount of limit used, in unit,
// "credits"), span? (seconds the window runs), model? (a
@@ -2427,7 +2428,7 @@ async function usageOf(provider, account) {
: null,
windows: (Array.isArray(u.windows) ? u.windows : []).map((w) => ({
name: text(w?.name),
- used: Math.max(0, num(w?.used)), // past 100 when overspent
+ used: w?.used == null ? null : Math.max(0, num(w?.used)), // past 100 when overspent; null: not said
resetsAt: when(w?.resetsAt),
resetSecs: Math.max(0, Math.round(num(w?.resetSecs))),
display: text(w?.display),
diff --git a/internal/plugin/providers.go b/internal/plugin/providers.go
index 4aef959e7..a48e3758e 100644
--- a/internal/plugin/providers.go
+++ b/internal/plugin/providers.go
@@ -1072,7 +1072,7 @@ type UsageResets struct {
type UsageWindow struct {
Name string `json:"name"`
- Used float64 `json:"used"` // percent
+ Used *float64 `json:"used"` // percent; nil when the plugin didn't say
ResetsAt string `json:"resetsAt"` // RFC 3339
ResetSecs int64 `json:"resetSecs"`
Display string `json:"display"`
diff --git a/internal/provider/allowance_pooled_test.go b/internal/provider/allowance_pooled_test.go
index 72d74eac5..0ecdc1c5f 100644
--- a/internal/provider/allowance_pooled_test.go
+++ b/internal/provider/allowance_pooled_test.go
@@ -16,9 +16,9 @@ func TestAllowancePooled(t *testing.T) {
month := now.Add(20 * 24 * time.Hour)
pool := map[string]bool{"auto": true, "composer-2": true}
q := quotaOfPlugin(SubscriptionQuota{}, plugin.Usage{Windows: []plugin.UsageWindow{
- {Name: "Cursor Models", Used: 12, Models: []string{"auto", "composer-2"}},
- {Name: "Other Models", Used: 100, NotModels: []string{"auto", "composer-2"}},
- {Name: "Total", Used: 60, Aside: true},
+ {Name: "Cursor Models", Used: fptr(12), Models: []string{"auto", "composer-2"}},
+ {Name: "Other Models", Used: fptr(100), NotModels: []string{"auto", "composer-2"}},
+ {Name: "Total", Used: fptr(60), Aside: true},
}})
cursor := allowanceOf(q.Windows, now)
for _, m := range []string{"auto", "composer-2", "claude-4.6-sonnet", "gpt-5.5"} {
@@ -59,9 +59,9 @@ func TestPluginPoolCountsBareIDOfSizes(t *testing.T) {
now := time.Now()
pool := []string{"auto", "grok-4.7@256k", "grok-4.7@500k", "composer-2.5", "default"}
q := quotaOfPlugin(SubscriptionQuota{}, plugin.Usage{Windows: []plugin.UsageWindow{
- {Name: "Cursor Models", Used: 16, Models: pool},
- {Name: "Other Models", Used: 100, NotModels: pool},
- {Name: "Total", Used: 60, Aside: true},
+ {Name: "Cursor Models", Used: fptr(16), Models: pool},
+ {Name: "Other Models", Used: fptr(100), NotModels: pool},
+ {Name: "Total", Used: fptr(60), Aside: true},
}})
a := allowanceOf(q.Windows, now)
for m, want := range map[string]float64{
@@ -89,8 +89,8 @@ func TestPluginPoolCountsBareIDOfSizes(t *testing.T) {
// the other way: the pool lists a bare id (Cursor's autoBucketModels),
// and the model is asked for at a size
q = quotaOfPlugin(SubscriptionQuota{}, plugin.Usage{Windows: []plugin.UsageWindow{
- {Name: "Cursor Models", Used: 16, Models: []string{"auto", "grok-4.8"}},
- {Name: "Other Models", Used: 100, NotModels: []string{"auto", "grok-4.8"}},
+ {Name: "Cursor Models", Used: fptr(16), Models: []string{"auto", "grok-4.8"}},
+ {Name: "Other Models", Used: fptr(100), NotModels: []string{"auto", "grok-4.8"}},
}})
a = allowanceOf(q.Windows, now)
if used, _ := a.For("grok-4.8@1m", now); used != 16 {
diff --git a/internal/provider/plugin_usage.go b/internal/provider/plugin_usage.go
index f1f3bcdf8..8e47b025a 100644
--- a/internal/provider/plugin_usage.go
+++ b/internal/provider/plugin_usage.go
@@ -155,13 +155,20 @@ func quotaOfPlugin(q SubscriptionQuota, u plugin.Usage) SubscriptionQuota {
sortResetCards(q.Resets.Each)
}
for _, x := range u.Windows {
- w := QuotaWindow{Name: x.Name, Used: x.Used, ResetSecs: x.ResetSecs, Display: x.Display,
+ w := QuotaWindow{Name: x.Name, ResetSecs: x.ResetSecs, Display: x.Display,
Amount: x.Amount, Limit: x.Limit, Unit: x.Unit,
Span: time.Duration(x.Span * float64(time.Second)), Model: strings.ToLower(x.Model), Aside: x.Aside}
+ if x.Used != nil {
+ w.Used = *x.Used
+ } else if !x.Aside {
+ // the plugin didn't say how much of it is used: its text is all
+ // there is, and routing has no share to count (#3650)
+ w.Text, w.Aside = true, true
+ }
// a row set aside with text and nothing counted is that text: a
// window that counts nothing yet says 0 with a count, or with no
// text, and one that stops the account is a reading at 0
- w.Text = x.Aside && x.Display != "" && x.Used == 0 && x.Amount == 0 && x.Limit == 0
+ w.Text = w.Text || x.Aside && x.Display != "" && (x.Used == nil || *x.Used == 0) && x.Amount == 0 && x.Limit == 0
if t, err := time.Parse(time.RFC3339, x.ResetsAt); err == nil {
w.ResetsAt = &t
}
diff --git a/internal/provider/plugin_usage_absent_test.go b/internal/provider/plugin_usage_absent_test.go
new file mode 100644
index 000000000..97f1d7c69
--- /dev/null
+++ b/internal/provider/plugin_usage_absent_test.go
@@ -0,0 +1,134 @@
+package provider
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/plugin"
+ "github.com/yetone/magpie/internal/testenv"
+)
+
+// A plugin that leaves out used says nothing of how much of a window is
+// spent: a 0 is a reading, absent is not. The window goes as its text,
+// never "100% left" (QuotaWindow.Text), and has no share in the allowance
+// routing ranks on; an account whose windows all say nothing is unknown to
+// routing, not the account with the most left (#3650).
+func TestPluginWindowWithoutUsedIsNoReading(t *testing.T) {
+ now := time.Now()
+ q := quotaOfPlugin(SubscriptionQuota{Provider: "loomy-plugin", User: "u"}, plugin.Usage{Windows: []plugin.UsageWindow{
+ {Name: "Credits", Display: "0 / 5000"},
+ {Name: "Daily", Used: fptr(0), Display: "0 / 100", Limit: 100},
+ }})
+ if !q.Windows[0].Text || !q.Windows[0].Aside {
+ t.Errorf("not said: Text %v, Aside %v", q.Windows[0].Text, q.Windows[0].Aside)
+ }
+ if q.Windows[1].Text || q.Windows[1].Aside {
+ t.Errorf("a 0 that was said: Text %v, Aside %v", q.Windows[1].Text, q.Windows[1].Aside)
+ }
+ if a := allowanceOf(q.Windows, now); len(a) != 1 || a[0].Name != "Daily" || a[0].Used != 0 {
+ t.Errorf("the allowance routing ranks on: %+v", a)
+ }
+ only := quotaOfPlugin(SubscriptionQuota{Provider: "loomy-plugin", User: "v"}, plugin.Usage{Windows: []plugin.UsageWindow{
+ {Name: "Credits", Display: "0 / 5000"},
+ }})
+ if a := allowanceOf(only.Windows, now); len(a) != 0 {
+ t.Errorf("a window that said nothing is an allowance: %+v", a)
+ }
+}
+
+// A window that said nothing has no share in the allowance routing ranks
+// on, through the decode a plugin's reply takes: the window whose used was
+// never sent is absent from it, while one that said 0 is there (#3650).
+// This one compiles on the base too, so it is the regression that fails
+// before the fix.
+func TestAWindowWithoutUsedIsNoAllowance(t *testing.T) {
+ var u plugin.Usage
+ if err := json.Unmarshal([]byte(`{"windows":[{"name":"Credits","display":"0 / 5000"},{"name":"Daily","used":0,"limit":100,"display":"0 / 100"}]}`), &u); err != nil {
+ t.Fatal(err)
+ }
+ q := quotaOfPlugin(SubscriptionQuota{Provider: "loomy-plugin", User: "u"}, u)
+ if a := allowanceOf(q.Windows, time.Now()); len(a) != 1 || a[0].Name != "Daily" {
+ t.Fatalf("the allowance: %+v", a)
+ }
+}
+
+// Routing, from a fresh reading and from the one kept on disk alike
+// (Allowances, lastAllowances: routedAllowance), leaves an account whose
+// windows tell no share out, as not known, rather than ranking it as the
+// one with all of it left; one whose window said 0 is known (#3650).
+func TestRoutingKnowsNoAccountThatSaidNoShare(t *testing.T) {
+ var said, unsaid plugin.Usage
+ if err := json.Unmarshal([]byte(`{"windows":[{"name":"Credits","display":"0 / 5000","resetsAt":"2099-01-01T00:00:00Z"}]}`), &unsaid); err != nil {
+ t.Fatal(err)
+ }
+ if err := json.Unmarshal([]byte(`{"windows":[{"name":"Credits","used":0,"display":"0 / 5000","resetsAt":"2099-01-01T00:00:00Z"}]}`), &said); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ if a, ok := routedAllowance("plugin:loomy", "u", quotaOfPlugin(SubscriptionQuota{Provider: "loomy-plugin", User: "u"}, unsaid), now); ok {
+ t.Errorf("no share said, yet known: %+v", a)
+ }
+ a, ok := routedAllowance("plugin:loomy", "v", quotaOfPlugin(SubscriptionQuota{Provider: "loomy-plugin", User: "v"}, said), now)
+ if used, _ := a.For("", now); !ok || used != 0 {
+ t.Errorf("a used of 0 that was said: known %v, used %v", ok, used)
+ }
+}
+
+// Through the plugin host: a window the plugin sent without used reaches
+// magpie as no share (host.js's usageOf passes it on as null, not 0), so
+// the card tells its text and routing doesn't know the account, while a
+// window that said used 0 is a reading at 0 (#3650).
+func TestPluginHostPassesAnAbsentUsedOn(t *testing.T) {
+ bun := testenv.Bun(t)
+ claudeHome(t)
+ t.Setenv("MAGPIE_BUN", bun)
+ windows := filepath.Join(t.TempDir(), "windows.json")
+ if err := os.WriteFile(windows, []byte(`{
+ "a@fake": [{"name": "Credits", "display": "0 / 5000"}],
+ "full@fake": [{"name": "Credits", "used": 0, "display": "0 / 5000"}]
+ }`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("FAKE_WINDOWS", windows)
+ t.Cleanup(plugin.Settle)
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+ defer cancel()
+ abs, _ := filepath.Abs("../plugin/testdata/fake/index.js")
+ if _, err := plugin.Add(ctx, abs); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := plugin.Providers(ctx); err != nil {
+ t.Fatal(err)
+ }
+ for _, team := range []string{"a", "full"} {
+ st, err := StartPluginSignIn("fakeco", 1, map[string]string{"where": "work", "team": team})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := SubmitSignInCallback(st.ID, "good"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ u := LoginUsage(ctx, "plugin:fakeco")
+ unsaid, said := u["a@fake"], u["full@fake"]
+ if len(unsaid.Windows) != 1 || len(said.Windows) != 1 {
+ t.Fatalf("readings: %+v", u)
+ }
+ if w := unsaid.Windows[0]; !w.Text || !w.Aside || w.Display != "0 / 5000" {
+ t.Errorf("not said: %+v", w)
+ }
+ if w := said.Windows[0]; w.Text || w.Aside {
+ t.Errorf("a 0 that was said: %+v", w)
+ }
+ now := time.Now()
+ if a, ok := routedAllowance("plugin:fakeco", "a@fake", unsaid, now); ok {
+ t.Errorf("no share said, yet known: %+v", a)
+ }
+ if _, ok := routedAllowance("plugin:fakeco", "full@fake", said, now); !ok {
+ t.Error("a used of 0 that was said is not known")
+ }
+}
diff --git a/internal/provider/plugin_usage_test.go b/internal/provider/plugin_usage_test.go
index 47d377bac..44e538711 100644
--- a/internal/provider/plugin_usage_test.go
+++ b/internal/provider/plugin_usage_test.go
@@ -14,6 +14,9 @@ import (
"github.com/yetone/magpie/internal/testenv"
)
+// fptr is a plugin's window share, for the tests' literals.
+func fptr(v float64) *float64 { return &v }
+
// A plugin's accounts show their allowance as the built-ins' do: beside
// each account, on the usage page, and to the gateway, a window counting
// only some models holding back those alone.
diff --git a/internal/provider/plugin_usage_text_test.go b/internal/provider/plugin_usage_text_test.go
index 91cd3d0f0..a19cb5a81 100644
--- a/internal/provider/plugin_usage_text_test.go
+++ b/internal/provider/plugin_usage_text_test.go
@@ -18,9 +18,9 @@ import (
func TestPluginTextRowIsText(t *testing.T) {
q := quotaOfPlugin(SubscriptionQuota{Provider: "autoclaw-plugin", User: "u"}, plugin.Usage{Windows: []plugin.UsageWindow{
{Name: "积分余额", Display: "1,234 积分", Aside: true},
- {Name: "5 hours", Used: 40, Display: "40 / 100"},
+ {Name: "5 hours", Used: fptr(40), Display: "40 / 100"},
{Name: "Credits", Display: "0 / 50", Limit: 50, Aside: true},
- {Name: "On-demand", Display: "$0 / $20"},
+ {Name: "On-demand", Used: fptr(0), Display: "$0 / $20"},
{Name: "Bare", Aside: true},
}})
want := []bool{true, false, false, false, false}
diff --git a/internal/provider/quota_last.go b/internal/provider/quota_last.go
index bc8de38a5..408af10ed 100644
--- a/internal/provider/quota_last.go
+++ b/internal/provider/quota_last.go
@@ -202,8 +202,11 @@ func lastAllowances(agent string) map[string]Allowance {
c.load()
for _, l := range logins {
q, ok := c.reading(loginProvider(l) + "/" + strings.ToLower(l.User))
- if ok && len(q.Windows) > 0 {
- out[l.User] = allowanceOf(q.Windows, now).restartedBy(resetRunsOut(agent, l.User, q.Windows, q.Resets))
+ if !ok || len(q.Windows) == 0 {
+ continue
+ }
+ if a, ok := routedAllowance(agent, l.User, q, now); ok {
+ out[l.User] = a
}
}
return out
diff --git a/internal/provider/quotas_dedupe_test.go b/internal/provider/quotas_dedupe_test.go
index d7255fb22..65692fbf7 100644
--- a/internal/provider/quotas_dedupe_test.go
+++ b/internal/provider/quotas_dedupe_test.go
@@ -76,7 +76,7 @@ func TestGLMPlanMatchesZCodePlugin(t *testing.T) {
for _, id := range []string{"zcode", "zcode-plugin"} {
t.Run(id, func(t *testing.T) {
sub := quotaOfPlugin(SubscriptionQuota{Provider: id, User: "[email protected]"}, plugin.Usage{
- Windows: []plugin.UsageWindow{{Name: "Weekly", Span: 7 * 24 * 60 * 60, ResetsAt: reset.Format(time.RFC3339)}},
+ Windows: []plugin.UsageWindow{{Name: "Weekly", Used: fptr(0), Span: 7 * 24 * 60 * 60, ResetsAt: reset.Format(time.RFC3339)}},
})
for _, provider := range []string{"zhipu", "zai", "custom-glm"} {
plan := SubscriptionQuota{Provider: provider, glmPlan: true, User: "work key",
diff --git a/internal/provider/routing.go b/internal/provider/routing.go
index 3058c0d1a..eb547eb56 100644
--- a/internal/provider/routing.go
+++ b/internal/provider/routing.go
@@ -518,7 +518,9 @@ func Allowances(agent string) map[string]Allowance {
if q.Error != "" || len(q.Windows) == 0 {
continue
}
- all[user] = allowanceOf(q.Windows, time.Now()).restartedBy(resetRunsOut(agent, user, q.Windows, q.Resets))
+ if a, ok := routedAllowance(agent, user, q, time.Now()); ok {
+ all[user] = a
+ }
}
c.Lock()
now := time.Now()
@@ -724,6 +726,19 @@ func (a Allowance) restartedBy(runsOut time.Time) Allowance {
return a
}
+// routedAllowance is the allowance routing goes by from an account's
+// reading. ok is false when it tells no share at all — every window its
+// text or set aside, as a plugin's that doesn't say how much is used
+// (#3650): the account is then not known, as one never read, rather than
+// one with all of it left, ahead of the rest.
+func routedAllowance(agent, user string, q SubscriptionQuota, now time.Time) (Allowance, bool) {
+ a := allowanceOf(q.Windows, now)
+ if len(a) == 0 {
+ return nil, false
+ }
+ return a.restartedBy(resetRunsOut(agent, user, q.Windows, q.Resets)), true
+}
+
// allowanceOf keeps the windows that can stop an account.
func allowanceOf(ws []QuotaWindow, now time.Time) Allowance {
// Antigravity keeps the vendor's ids in its windows (and on disk),
@@ -749,7 +764,7 @@ func allowanceOf(ws []QuotaWindow, now time.Time) Allowance {
}
var a Allowance
for _, w := range ws {
- if w.Aside {
+ if w.Aside || w.Text {
continue
}
l := Limit{Used: w.Used, Span: w.Span, Model: w.Model, Amount: w.Amount, Of: w.Limit, Unit: w.Unit, matches: w.matches, partial: w.partial, Name: w.Name, Credits: w.Credits}
diff --git a/internal/provider/workbuddy_runs_out_test.go b/internal/provider/workbuddy_runs_out_test.go
index 0766a9dac..390d3c241 100644
--- a/internal/provider/workbuddy_runs_out_test.go
+++ b/internal/provider/workbuddy_runs_out_test.go
@@ -17,7 +17,7 @@ import (
func TestWorkBuddyCreditsRunOutForRouting(t *testing.T) {
now := time.Date(2026, 10, 11, 12, 0, 0, 0, time.UTC)
credits := func(runsOutAt string) plugin.Usage {
- return plugin.Usage{Plan: "Pro", Windows: []plugin.UsageWindow{{Name: "Credits", Used: 100 * 17.6 / 2250,
+ return plugin.Usage{Plan: "Pro", Windows: []plugin.UsageWindow{{Name: "Credits", Used: fptr(100 * 17.6 / 2250),
Display: "17.6 / 2250", Amount: 17.6, Limit: 2250, Unit: "credits", RunsOutAt: runsOutAt, RunsOut: 232.4}}}
}
q := quotaOfPlugin(SubscriptionQuota{}, credits("2026-10-12T16:39:27.000Z"))