diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 0cc48f1ba..30e87e0d1 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -2426,7 +2426,9 @@ type left struct { // fullest: when the window used is the share of renews // (Allowance.Fullest), zero when not known fullest time.Time - soon []time.Time // renews as Smart ranks them (Allowance.Renewal) + // fullestName: that window's name, when more than one counts the model + fullestName string + soon []time.Time // renews as Smart ranks them (Allowance.Renewal) // unreached: how many of soon's windows Smart passes over, as they // can't be used up before they renew any more (Allowance.Unreached) unreached int @@ -2550,7 +2552,7 @@ func weighRouted(p provider.Provider, cs []candidate, model string, from provide pc, due := a.Pace(c.model, now) amt, of, unit := a.Count(c.model, now) rs := a.Restarts(now) - l := left{used: u, renews: r, fullest: a.Fullest(c.model, now), soon: a.Renewal(c.model, now), unreached: a.Unreached(c.model, now), lapse: a.Lapse(c.model, now), lapsing: a.Lapsing(c.model, now), pace: pc, due: due, amount: amt, of: of, unit: unit, + l := left{used: u, renews: r, fullest: a.Fullest(c.model, now), fullestName: a.FullestName(c.model, now), soon: a.Renewal(c.model, now), unreached: a.Unreached(c.model, now), lapse: a.Lapse(c.model, now), lapsing: a.Lapsing(c.model, now), pace: pc, due: due, amount: amt, of: of, unit: unit, restarts: rs, dueRestart: !rs.IsZero() && due.Equal(rs), credits: spendsCredits(c.p, a)} // one not known counts as unused l.dueExpiry = !l.dueRestart && !l.lapse.IsZero() && due.Equal(l.lapse) l.weekLow = u >= lowShare && u < usedShare && a.CapUsed(c.model, now) < lowShare diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index 5907532ac..6260b5550 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -465,6 +465,10 @@ type Weighed struct { // from Renews' biggest first: a row says the two together, so of one // window, a Factory account's week and not its month (#1778) UsedRenews *time.Time `json:"usedRenews,omitempty"` + // UsedWindow: the name of the window Used is the share of, when more + // than one counts the model: the row says it with the share, so a + // week's 41% isn't read as the five hours' (Wing8Aqua on X) + UsedWindow string `json:"usedWindow,omitempty"` // Sunk: when it was rate limited with quota left, sending it to the // back of an order that sinks (sink.go); nil when it didn't, or the // order doesn't sink @@ -637,6 +641,7 @@ func weighed(c candidate, p provider.Provider, wg weighing, fallback bool, from ur := l.fullest w.UsedRenews = &ur } + w.UsedWindow = l.fullestName if l.of > 0 { w.Amount, w.Limit, w.Unit = l.amount, l.of, l.unit } diff --git a/internal/gateway/used_window_test.go b/internal/gateway/used_window_test.go index 2bf1d2f4c..cec487aef 100644 --- a/internal/gateway/used_window_test.go +++ b/internal/gateway/used_window_test.go @@ -60,4 +60,44 @@ func TestUsedRenewsWithItsOwnWindow(t *testing.T) { if d := weighed(got[0], dp, wg, false, provider.Anthropic); d.UsedRenews == nil || !d.UsedRenews.Equal(devinWeek) { t.Fatalf("Devin's: %+v", d) } + // the window the share is of, named, as more than one counts the + // model; Devin's one window needs no name (Wing8Aqua on X) + if w.UsedWindow != "7 days" { + t.Fatalf("Factory's 32%% is of %q, want its week", w.UsedWindow) + } + if d := weighed(got[0], dp, wg, false, provider.Anthropic); d.UsedWindow != "" { + t.Fatalf("Devin's one window named: %q", d.UsedWindow) + } +} + +// Wing8Aqua on X: two Claude Code accounts In turn, each at 0% of its +// five hours and some of its week. The share the row shows is the week's, +// the fullest, which sets an account aside under every routing; the trace +// names it so the row says "7d 41% used", not a bare 41% read as the +// five hours'. +func TestUsedWindowNamesTheWeekInTurn(t *testing.T) { + now := time.Now() + five, week := now.Add(5*time.Hour), now.Add(2*24*time.Hour) + claude := provider.Allowance{ + {Name: "5 hours", Used: 0, Resets: five, Span: 5 * time.Hour}, + {Name: "7 days", Used: 41, Resets: week, Span: 7 * 24 * time.Hour}, + } + old := allowances + t.Cleanup(func() { allowances = old }) + allowances = func(agent string) map[string]provider.Allowance { + if agent == "claude" { + return map[string]provider.Allowance{"a@example.com": claude, "b@example.com": claude} + } + return nil + } + a := provider.Provider{ID: "claude", Routing: provider.Rotate, Account: &provider.Account{Agent: "claude", User: "a@example.com"}} + b := provider.Provider{ID: "claude", Routing: provider.Rotate, Account: &provider.Account{Agent: "claude", User: "b@example.com"}} + cs := []candidate{{p: a, model: "claude-opus-5-5", rest: "claude@a"}, {p: b, model: "claude-opus-5-5", rest: "claude@b"}} + got, wg := weigh(provider.Provider{ID: "claude", Routing: provider.Rotate}, cs, "claude-opus-5-5", provider.Anthropic) + for _, c := range got { + w := weighed(c, c.p, wg, false, provider.Anthropic) + if !w.Known || w.Used != 41 || w.UsedWindow != "7 days" || w.UsedRenews == nil || !w.UsedRenews.Equal(week) { + t.Fatalf("%s: used %v of %q renewing %v, want 41 of its week", c.rest, w.Used, w.UsedWindow, w.UsedRenews) + } + } } diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index e95bfe3c0..f637535aa 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -611,8 +611,12 @@ function routingPage(part) { const out = x ? runsOutText(x) : ""; return out ? " · " + out : ""; }; + // the window the share is of before it, when the account has more than + // one (Weighed.UsedWindow): its fullest, which sets it aside under every + // routing, In turn's too: "7d 41% used", not a bare 41% read as its + // five hours (Wing8Aqua on X) const quota = (w, used, left, vars) => w.balance != null ? t(left, { n: balText(w), ...vars }) + lapses(w) - : (w.limit > 0 ? quotaCount(w) + " · " : "") + t(quotaLeft ? left : used, { n: pct(share(w)), ...vars }); + : (w.usedWindow ? shortWindow(w.usedWindow) + " " : "") + (w.limit > 0 ? quotaCount(w) + " · " : "") + t(quotaLeft ? left : used, { n: pct(share(w)), ...vars }); const fill = (w) => Math.max(0, Math.min(100, share(w))) + "%"; const FAIL = { rate: "rate limited", credit: "out of credit", quota: "quota used up", other: "failed", auth: "sign-in required", canceled: "canceled", foreign: "another account's reasoning", floor: "reply too short", verify: "needs verification", refused: "refused (safety filter)", shape: "request not understood", sight: "images not taken", proxy: "proxy not reachable", offline: "network down", overloaded: "servers overloaded", effort: "reasoning effort not in its plan", overflow: "too long for its model", room: "reply asked past the window left", slow: "slow to start", prompt: "agent's prompt turned away", restricted: "account restricted by the vendor" }; // a refusal the vendor called a rate limit, resting as out of quota diff --git a/internal/gui/tests/routing-used-window.test.cjs b/internal/gui/tests/routing-used-window.test.cjs new file mode 100644 index 000000000..768290583 --- /dev/null +++ b/internal/gui/tests/routing-used-window.test.cjs @@ -0,0 +1,99 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Wing8Aqua on X: two Claude Code accounts In turn, each at 0% of its five +// hours and 41% / 12% of its week. The rows said "41% used", read as the +// five hours. The share is the fullest window's, which sets an account +// aside under every routing, In turn's too; the row now names it ("7d 41% +// used"). An account with one window says its share as before. In every +// language, at a window's width and at 420px, in both engines. +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 now = Date.now(); +const iso = (ms) => new Date(ms).toISOString(); +const H = 3600e3; +const M = "deepseek-v4.1-flash"; + +// two Claude accounts with a 5 hours and a week, the share the week's +// (usedWindow), cc-0 the one that answered (its row says so), and a WorkBuddy one with a single window (no usedWindow) +const claude = (u, used) => ({ id: `claude#${u}`, provider: "claude", name: "Claude", who: `${u}@example.com`, kind: "account", agent: "claude", model: "claude-opus-5-5", + routing: "rotate", known: true, used, usedWindow: "7 days", renews: [iso(now + 48 * H), iso(now + 5 * H)], usedRenews: iso(now + 48 * H + 5 * 60e3) }); +const route = { + id: 3, seq: 3, time: iso(now - 2000), agent: "claude", model: "group/turns", provider: "claude", done: true, status: 200, ms: 900, tokens: 10, + group: { id: "turns", name: "Turns", routing: "rotate", members: ["claude/claude-opus-5-5"] }, + order: [claude("cc-0", 5), claude("cc-1", 41), claude("cc-2", 12), + { id: "wb#a1", provider: "wb", name: "WorkBuddy", who: "wb-1@example.com", kind: "account", model: "claude-opus-5-5", known: true, used: 30, renews: [iso(now + 10 * H)], usedRenews: iso(now + 10 * H) }], + tries: [{ id: "claude#cc-0", model: "claude-opus-5-5", start: iso(now - 1500), done: true, status: 200, ms: 900 }], +}; + +function serve(lang) { + const state = { agents: [{ id: "claude", name: "Claude Code", path: "/test/claude", fields: [] }], profiles: [], settings: { lang, theme: "light", quotaLeft: true } }; + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes + return json({ mine: true, now: new Date().toISOString(), seq: 3, totals: { requests: 1, rerouted: 0, errors: 0 }, routes: [route] }); + } + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/usage/quotas/history") return json([]); + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + 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)]; + await r.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: an account's share names its window when it has several`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [1100, 420]) { + await t.test(`${lang} at ${width}px`, async () => { + const ctx = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" }); + try { + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + await page.goto("http://magpie.test/?view=routing"); + // the request's order (.rt-accts) and the accounts' cards (.rt-act) + const texts = (who) => page.evaluate((who) => [ + ...[...document.querySelectorAll(".rt-accts > li")].filter((l) => l.textContent.includes(who)).map((l) => l.querySelector(".st, em")?.textContent || ""), + ...[...document.querySelectorAll(".rt-act")].filter((l) => l.textContent.includes(who)).map((l) => l.querySelector(".st")?.textContent || ""), + ], who); + await page.waitForFunction(() => document.querySelectorAll(".rt-act").length >= 4 && document.querySelectorAll(".rt-accts > li").length >= 4); + for (const [who, n] of [["cc-1@", "59%"], ["cc-2@", "88%"]]) { + const ts = await texts(who); + assert.equal(ts.length, 2, `${lang} ${width}: ${who} rows ${JSON.stringify(ts)}`); + for (const s of ts) { + assert.ok(s.startsWith("7d ") && s.includes(n), `${lang} ${width}: ${who} says "${s}", not its week's "7d … ${n}"`); + assert.equal(s.split("7d").length, 2, `${lang} ${width}: ${who} names it once: "${s}"`); + } + } + for (const s of await texts("wb-1@")) { + assert.ok(s.includes("70%") && !/\b\d+[hdw] /.test(s), `${lang} ${width}: one window, no name: "${s}"`); + } + const over = await page.evaluate(() => document.documentElement.scrollWidth - innerWidth); + assert.ok(over <= 1, `${lang} at ${width}: ${over}px past`); + assert.deepEqual(errors, []); + } finally { + await ctx.close(); + } + }); + } + } + }); +} diff --git a/internal/provider/allowance_fullest_test.go b/internal/provider/allowance_fullest_test.go index fb803b28e..85312f747 100644 --- a/internal/provider/allowance_fullest_test.go +++ b/internal/provider/allowance_fullest_test.go @@ -39,3 +39,24 @@ func TestFullestRenewsWithTheShare(t *testing.T) { t.Fatalf("a reset not known: %v", got) } } + +// FullestName names Fullest's window when more than one counts the model, +// so a share isn't read as another window's (Wing8Aqua on X); none for a +// lone window. +func TestFullestNameNamesTheShare(t *testing.T) { + now := time.Now() + a := Allowance{ + {Name: "5 hours", Used: 0, Resets: now.Add(5 * time.Hour), Span: 5 * time.Hour}, + {Name: "7 days", Used: 41, Resets: now.Add(48 * time.Hour), Span: 7 * 24 * time.Hour}, + } + if got := a.FullestName("claude-opus-5-5", now); got != "7 days" { + t.Fatalf("FullestName %q, want the week", got) + } + a[0].Used = 60 + if got := a.FullestName("claude-opus-5-5", now); got != "5 hours" { + t.Fatalf("five hours fuller: %q", got) + } + if got := a[1:].FullestName("m", now); got != "" { + t.Fatalf("one window named: %q", got) + } +} diff --git a/internal/provider/routing.go b/internal/provider/routing.go index c41b9ff5c..6e8f335e2 100644 --- a/internal/provider/routing.go +++ b/internal/provider/routing.go @@ -521,20 +521,39 @@ func (a Allowance) CapUsed(model string, now time.Time) float64 { // Zero when that window's reset isn't known, or has passed (it is empty // again then, its next reset not known). func (a Allowance) Fullest(model string, now time.Time) time.Time { + at, _ := a.fullest(model, now) + return at +} + +// FullestName is the name of the window For's share is of (Fullest's), +// when more than one window counts model: the share alone ("41% used") +// read as the five hours on the Routing page while it was the week's, +// the five hours at 0% (Wing8Aqua on X). Empty when one window, or none, +// counts it, or the vendor didn't name it. +func (a Allowance) FullestName(model string, now time.Time) string { + _, name := a.fullest(model, now) + return name +} + +func (a Allowance) fullest(model string, now time.Time) (time.Time, string) { model = strings.ToLower(model) - used, at := -1.0, time.Time{} + used, at, name, n := -1.0, time.Time{}, "", 0 for _, l := range a { if !l.applies(model) { continue } + n++ if !l.Resets.IsZero() && !l.Resets.After(now) { l.Used, l.Resets = 0, time.Time{} } if l.Used > used || l.Used == used && l.Resets.After(at) { - used, at = l.Used, l.Resets + used, at, name = l.Used, l.Resets, l.Name } } - return at + if n < 2 { + name = "" + } + return at, name } // Count is the count of the window For's share is of — the fullest that