diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index dd8b746fb..d1354f432 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -332,7 +332,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`. - `GOOGLE_APPLICATION_CREDENTIALS` and `CLOUDSDK_CONFIG` are in `agentenv.Vars`. The desktop app takes them from the login shell when it wasn't started with them (`proc.UserPath`, macOS and Linux), and `testenv` clears both. Vertex AI reads them as set (`vertexEnvPath`), not through `appdir.Getenv`, which takes a relative value as unset: a `~/` that starts one is the home, and one that still isn't a full path is refused, naming the variable. Passed over, it would have the request signed from gcloud's own file, which may be another account's (a person's, where the variable named a service account's key). - The Vertex AI preset's `HeaderHints` are Google's Priority PayGo and Flex PayGo headers, `X-Vertex-AI-LLM-Request-Type` and `X-Vertex-AI-LLM-Shared-Request-Type`: the editor offers to add them, the values are the user's, and they go as `Headers` do. Priority PayGo couldn't be confirmed: on the project it was tried on, Vertex AI answered with `trafficType` `ON_DEMAND`. - An account's weight under `weight` routing is kept per account too (`AccountWeights`, by the account in lower case, 2–1000; one not in it weighs 1, and nothing sets one from the plan), as a key's is (`KeyAccount.Weight`), so a Max and a Pro account can share requests by how much more one allows (rubbzha on X). `SetAccountWeight` (GUI `provider/accountweight`, the chip beside each account in use in the editor while the routing is By weight; `magpie provider account-weight [account [n|default]]`) sets it, `moveAccountSettings` carries it through a Copilot rename, and `withPicks` puts it on the accounts `All` gives, so the gateway's `keyWeight` reads it with no file read (`Provider.AccountWeight`). -- A usage cap is kept per account (`AccountCaps`, 1–99) and, beside it, per window (`AccountWindowCaps`, by the account and the window's `capId`, its name in lower case: `WindowCapID`). A window's own share wins over the account's; 100 is no cap on that window. `CapsOf` gives both (`WindowCaps`), `CapHeld` and `capReached` judge each window by its own, and `SetWindowCap` (GUI `provider/windowcap`, `magpie provider account-cap --window `) sets one. A config without window caps reads as before. How a pool ends at its caps is kept with the provider (plugins#349): `CapStop` answers 429 rather than going on to the fallbacks once every account in use is at its cap, and `CapCareful` reads usage again near a cap and holds an account whose usage can't be told (both off by default; `SetCapStop`, `SetCapCareful`, GUI `provider/capstop` and `provider/capcareful`, ticks under the account list once an account has a cap). `UsageRead` says when an account's usage was last read well and whether the last try failed (a failed try keeps the good reading's time), and `ReadUsageNow` reads it again. `magpie provider pool [--accounts a,b,…] [--cap percent|off] [--stop on|off] [--careful on|off]` shows and sets the whole pool in one command: which accounts are on and in what order, each one's cap, and both settings, and names the accounts in use with no cap. +- A usage cap is kept per account (`AccountCaps`, 1–99) and, beside it, per window (`AccountWindowCaps`, by the account and the window's `capId`, its name in lower case: `WindowCapID`). A window's own share wins over the account's; 100 is no cap on that window. `CapsOf` gives both (`WindowCaps`), `CapHeld` and `capReached` judge each window by its own, and `SetWindowCap` (GUI `provider/windowcap`, `magpie provider account-cap --window `) sets one; `SetWindowCaps` sets several at once, as the GUI's meter for a family of models (Antigravity's Gemini 3.1 Pro, High and Low) posts its models' windows in `windows`. An Antigravity pool's own windows ("Gemini · 7 days") are set aside for routing but capped (`WithCapped`, `capId` the pool's name and its own, as `LineName`): `allowanceOf` hangs each on its members' windows (`Limit.pool`), and `CapHeld` and `NearCap` count them through `capLimits`, so a cap on one holds that pool's models only (pluviophile714 on Discord, `TestPoolWindowCapHeld`). A config without window caps reads as before. How a pool ends at its caps is kept with the provider (plugins#349): `CapStop` answers 429 rather than going on to the fallbacks once every account in use is at its cap, and `CapCareful` reads usage again near a cap and holds an account whose usage can't be told (both off by default; `SetCapStop`, `SetCapCareful`, GUI `provider/capstop` and `provider/capcareful`, ticks under the account list once an account has a cap). `UsageRead` says when an account's usage was last read well and whether the last try failed (a failed try keeps the good reading's time), and `ReadUsageNow` reads it again. `magpie provider pool [--accounts a,b,…] [--cap percent|off] [--stop on|off] [--careful on|off]` shows and sets the whole pool in one command: which accounts are on and in what order, each one's cap, and both settings, and names the accounts in use with no cap. - A window whose reset time has passed has started again, whatever share it was read at (`resetPassed`). That holds for a reading kept from before (`AsOf`) and for a fresh one: Claude Code's `/usage` gives a reset to the minute and can lag it, so a run just after a reset can still say 100% with that reset. `claudeWindows` hands such a window back empty on every path, and `usedPast`, `usedUp`, `BackAt` and `capReached` leave it out when they judge an account spent, for Codex, Claude Code and `magpie quota wait` alike. A card can still show a kept reading as it was read (`reported`, for a Claude card while `/usage` is unavailable); that changes what it shows, never which account is used. A reset `/usage` gives as a time alone ("resets 3pm") can be read as its next one, a day on (`claudeResetTime`), and is then not seen as passed here. - A restart to update can run two magpies for up to the old one's drain ([GUI shell](gui-shell.md#a-restart-to-update-hands-the-gateway-over)), each diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index be50c168a..e2125be59 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -13805,12 +13805,8 @@ function poolLine(line, ws, q, capFor = () => 0, settable = null) { return line; } -// An account's usage cap (provider.AccountCaps): the share of each of its -// windows it is used to at most — a new account kept to 70% of its five -// hours and its week. At it, routing takes the account for used up and -// goes on to the others until the window renews. The pill on its row says -// the cap and opens the app's menu of shares; a mark on each meter the cap -// counts shows where it is, and a note says when it holds the account. +// An account's usage cap (provider.AccountCaps): the share of each window +// it is used to at most; past it routing goes on to the others. const CAP_SHARES = [50, 60, 70, 80, 90]; // An account's name of the user's own (#1515), kept by magpie // (provider.AccountNames), never in a sign-in; accountSeatOf, the key plan @@ -13876,11 +13872,8 @@ function addRow(say, go) { return b; } function accountCapOf(p, user) { return p?.accountCaps?.[String(user).toLowerCase()] || 0; } -// A window's own cap (provider.AccountWindowCaps, willz on Discord): a -// friend's account stops at 50% of its five hours while its week may go to -// 40%. Kept by the account and the window's capId, 1–99, or 100 for no cap -// on that window; a window with none of its own takes the account's cap. -// windowOwnCapOf is the window's own, 0 when it follows the account's. +// A window's own cap (provider.AccountWindowCaps, willz on Discord), by +// capId: 1–99, 100 for none, 0 when it follows the account's. function windowOwnCapOf(p, user, w) { return (w?.capId && p?.accountWindowCaps?.[String(user).toLowerCase()]?.[w.capId]) || 0; } @@ -13910,7 +13903,8 @@ function capHeldOf(q, capFor) { const h = w.capsSome ? some : all; h.n++; if (w.used >= h.used) { h.used = w.used; h.cap = cap; } - if (w.capsSome && !some.names.includes(w.name)) some.names.push(w.name); + const nm = w.pool && !w.family ? w.pool + " · " + t(w.name) : w.name; + if (w.capsSome && !some.names.includes(nm)) some.names.push(nm); if (!r) h.unknown = true; else h.back = Math.max(h.back, r); } const h = all.n ? all : some.n ? some : null; @@ -13978,10 +13972,11 @@ function pillNumber(at, val, ph, cls, label, parse, bad, own, set) { } // windowCapMeter: a window's meter on an account's row as the button that -// sets the window's own cap; not a family's (tiers) or on-demand's. +// sets the window's own cap, a family's its models' (tiers); not on-demand's. function windowCapMeter(m, p, user, w) { - if (!w.capId || w.tiers) return m; - const own = windowOwnCapOf(p, user, w), cap = accountCapOf(p, user); + const ids = (w.tiers || [w]).map((x) => x.capId), owns = ids.map((capId) => windowOwnCapOf(p, user, { capId })); + if (!ids.every(Boolean)) return m; + const own = new Set(owns).size > 1 ? 0 : owns[0], cap = accountCapOf(p, user); const name = t(w.name); const b = spanBtn(el("span", m.className + " aq-set" + (own ? " own" : ""))); b.append(...m.childNodes); @@ -13992,7 +13987,7 @@ function windowCapMeter(m, p, user, w) { : t("Click to give {window} a cap of its own, apart from this account's", { window: name })].filter(Boolean).join("\n"); b.setAttribute("aria-haspopup", "menu"); b.setAttribute("aria-expanded", "false"); - const set = (v) => accountAction("provider/windowcap", { id: p.id, account: user, window: w.capId, cap: v }, + const set = (v) => accountAction("provider/windowcap", { id: p.id, account: user, window: w.capId, ...w.tiers && { windows: ids }, cap: v }, v === 0 ? t("{window} of {who} follows the account's cap", { window: name, who: user }) : v >= 100 ? t("{window} of {who} has no cap", { window: name, who: user }) : t("{who} stops at {n}% of {window}", { who: user, n: v, window: name })); diff --git a/internal/gui/providers.go b/internal/gui/providers.go index cebea5072..ebf8ded04 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -1463,6 +1463,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // it follow the account's cap Cap int `json:"cap"` Window string `json:"window"` + // Windows, for windowcap, in place of Window: a family's + // windows, which the GUI shows as one meter + Windows []string `json:"windows"` // Weight, for accountweight: the account's share under By // weight routing, 1 to provider.MaxKeyWeight (0 or 1: none) Weight int `json:"weight"` @@ -2068,7 +2071,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) { return } case "windowcap": - if err := provider.SetWindowCap(in.ID, req.Account, req.Window, req.Cap); err != nil { + if len(req.Windows) == 0 { + req.Windows = []string{req.Window} + } + if err := provider.SetWindowCaps(in.ID, req.Account, req.Windows, req.Cap); err != nil { fail(rw, err) return } diff --git a/internal/gui/tests/window-cap-pool.test.cjs b/internal/gui/tests/window-cap-pool.test.cjs new file mode 100644 index 000000000..3b4559f16 --- /dev/null +++ b/internal/gui/tests/window-cap-pool.test.cjs @@ -0,0 +1,157 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// An Antigravity account's meters set their own caps too (pluviophile714 on +// Discord: the row's 上限 90% said 每个窗口可单独设上限:点击下方它的用量条, +// and a click on 剩余 97.8% · 7d did nothing). Each pool's 5 hours and 7 +// days is a button that posts its pool's window ("gemini · 7 days": both +// pools have a "7 days"); a family's meter, its models shown as one (the +// pool read without its summary), posts every model's window at once. The +// menu is the app's own, the click moves nothing. Chromium and WebKit, +// narrow and wide, in every language the menu is in; the API is faked. +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 at = (h) => new Date(Date.now() + h * 36e5 + 60e3).toISOString(); +const USER = "pluvio@example.com"; +// as /api/login/usage sends them, WithCapped's marks on +const model = (name, id, family, pool, used) => ({ name, model: id, family, pool, used, resetsAt: at(3), capId: name.toLowerCase(), capped: true, capsSome: true }); +const own = (pool, name, used, h) => ({ name, pool, used, resetsAt: at(h), capId: `${pool} · ${name}`.toLowerCase(), capped: true, capsSome: true }); +const models = (pool) => [ + model("Gemini 3.1 Pro (High)", "gemini-3.1-pro-high", "Gemini", pool && "Gemini", 1), + model("Gemini 3.1 Pro (Low)", "gemini-3.1-pro-low", "Gemini", pool && "Gemini", 1), + model("Claude Sonnet 4.6", "claude-sonnet-4-6", "Claude", pool && "Claude & GPT", 0), +]; +// the reporter's: 2.2% of the Gemini week used, 97.8% left +const pooled = () => [...models(true), own("Gemini", "5 hours", 1, 3), own("Gemini", "7 days", 2.2, 100), own("Claude & GPT", "5 hours", 0, 3), own("Claude & GPT", "7 days", 0, 90)]; + +function serve(lang, posts, windows) { + const settings = { lang, theme: "light", quotaLeft: true }; + const antigravity = { + id: "antigravity", name: "Antigravity", icon: "antigravity-color", chat: "", responses: "", anthropic: "", catalog: "", + models: [{ id: "gemini-3.1-pro-high", name: "Gemini 3.1 Pro (High)", on: true }], agents: [], fallback: [], headers: {}, keyList: [], + account: { agent: "antigravity", agentName: "Antigravity", user: USER, plan: "Google AI Pro", logins: [{ user: USER, plan: "Google AI Pro", active: true, on: true }] }, + accountCaps: { [USER]: 90 }, + }; + const providers = { providers: [antigravity], presets: [], excluded: [], gateway: { running: true, window: true } }; + 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 }); + if (url.pathname === "/api/settings") return json(settings); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/login/usage") return json(url.searchParams.get("agent") === "antigravity" ? { [USER]: { provider: "antigravity", plan: "Google AI Pro", windows: windows() } } : {}); + if (url.pathname === "/api/provider/windowcap" && route.request().method() === "POST") { + const body = route.request().postDataJSON(); + posts.push(body); + const caps = { ...antigravity.accountWindowCaps?.[USER] }; + for (const w of body.windows || [body.window]) { + if (body.cap) caps[w] = body.cap; else delete caps[w]; + } + antigravity.accountWindowCaps = { [USER]: caps }; + return json(providers); + } + 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: "" }); } + }; +} + +// the menu's head names the window: the pool's, or the family's +const words = { + en: { week: "Cap for Gemini · 7 days", fam: "Cap for Gemini", left: "97.8% left", cap: "Cap 50%" }, + zh: { week: "Gemini · 7 天的上限", fam: "Gemini的上限", left: "剩余 97.8%", cap: "上限 50%" }, + "zh-TW": { week: null, fam: null, left: null, cap: "上限 50%" }, + ja: { week: null, fam: null, left: null, cap: null }, + de: { week: null, fam: null, left: null, cap: null }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const width of [420, 1100]) { + for (const lang of Object.keys(words)) { + const w = words[lang]; + const open = async (t, name, windows) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${width}-${lang}-${name}-window-cap-pool.png`) }); + } + await browser.close(); + }); + const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], posts = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, posts, windows)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: "Antigravity" }).first().click(); + await page.locator(".editor .accts .acc .aq-w").first().waitFor(); + return { page, errors, posts }; + }; + const row = (page) => page.locator(`.editor .accts .acc[data-account-id="${USER}"]`); + const meters = (page) => row(page).locator('.aq-set[role="button"]'); + const menu = (page) => page.locator(".proto-menu"); + const pick = (page, name) => menu(page).locator(".pm-item", { has: page.locator(".pm-name", { hasText: new RegExp(`^${name}$`) }) }).click(); + const posted = async (posts, n) => { + for (let i = 0; i < 60 && posts.length === n; i++) await new Promise((r) => setTimeout(r, 50)); + return posts.at(-1); + }; + const still = async (page, b) => { + await b.scrollIntoViewIfNeeded(); + await page.waitForTimeout(150); + const top = () => row(page).evaluate((e) => Math.round(e.getBoundingClientRect().top)); + const before = await top(); + await b.click(); + await menu(page).waitFor(); + assert.equal(await top(), before, "the row moved"); + }; + const label = `${engine} ${width} ${lang}`; + + test(`${label}: each pool's 5 hours and 7 days sets its own cap`, async (t) => { + const { page, errors, posts } = await open(t, "pool", pooled); + // Gemini 5h, Gemini 7d, Claude & GPT 5h, 7d: every meter a button + assert.equal(await row(page).locator(".aq-win").count(), 4); + assert.equal(await meters(page).count(), 4); + const week = meters(page).nth(1); + if (w.left) assert.match(await week.textContent(), new RegExp(w.left.replace(".", "\\."))); + // the account's 90% marks the pool's meters too + assert.equal(await row(page).locator(".aq-cap").count(), 4); + await still(page, week); + if (w.week) assert.equal(await menu(page).locator(".pm-head").textContent(), w.week); + assert.equal(await page.locator("select").count(), 0, "no native select"); + const n = posts.length; + await pick(page, "50%"); + assert.deepEqual(await posted(posts, n), { id: "antigravity", account: USER, window: "gemini · 7 days", cap: 50 }); + await row(page).locator(".aq-own").first().waitFor(); + assert.equal(await row(page).locator(".aq-own").count(), 1); + if (w.cap) assert.equal(await meters(page).nth(1).locator(".aq-own").textContent(), w.cap); + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), "no page scroll sideways"); + assert.deepEqual(errors, []); + }); + + test(`${label}: a family's meter sets each of its models' windows`, async (t) => { + const { page, errors, posts } = await open(t, "family", () => models(false)); + assert.equal(await meters(page).count(), 2); + const gemini = meters(page).first(); + await still(page, gemini); + if (w.fam) assert.equal(await menu(page).locator(".pm-head").textContent(), w.fam); + const n = posts.length; + await pick(page, "60%"); + const body = await posted(posts, n); + assert.deepEqual({ ...body, windows: [...body.windows].sort() }, { id: "antigravity", account: USER, window: body.window, windows: ["gemini 3.1 pro (high)", "gemini 3.1 pro (low)"], cap: 60 }); + await row(page).locator(".aq-own").first().waitFor(); + assert.equal(await row(page).locator(".aq-own").count(), 1); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/provider/account_caps.go b/internal/provider/account_caps.go index 577205615..45c235024 100644 --- a/internal/provider/account_caps.go +++ b/internal/provider/account_caps.go @@ -29,6 +29,7 @@ package provider import ( "fmt" "maps" + "slices" "strconv" "strings" "time" @@ -134,11 +135,24 @@ func AccountCapsOf(id, user string) WindowCaps { // of the subscription id: 1–99, 100 for no cap on that window whatever the // account's cap, or 0 to have it follow the account's cap again. func SetWindowCap(id, ref, window string, cap int) error { + return SetWindowCaps(id, ref, []string{window}, cap) +} + +// SetWindowCaps is SetWindowCap of several windows at once: a family's +// models' own (Antigravity's Gemini 3.1 Pro (High) and (Low)), which the +// GUI shows as one meter. +func SetWindowCaps(id, ref string, windows []string, cap int) error { if cap != 0 && (cap < MinCap || cap > 100) { return fmt.Errorf("a window's cap is a share from %d%% to %d%%, or 100%% for none on it, not %d%%", MinCap, MaxCap, cap) } - w := WindowCapID(window) - if w == "" { + var ws []string + for _, w := range windows { + if w = WindowCapID(w); w == "" { + return fmt.Errorf("name the usage window to cap") + } + ws = append(ws, w) + } + if len(ws) == 0 { return fmt.Errorf("name the usage window to cap") } p, err := Find(id) @@ -153,7 +167,7 @@ func SetWindowCap(id, ref, window string, cap int) error { return fmt.Errorf("%s has no account %q", p.Name, ref) } k := accountKey(r) - if p.AccountWindowCaps[k][w] == cap { + if !slices.ContainsFunc(ws, func(w string) bool { return p.AccountWindowCaps[k][w] != cap }) { return nil } all := map[string]map[string]int{} @@ -163,10 +177,12 @@ func SetWindowCap(id, ref, window string, cap int) error { if all[k] == nil { all[k] = map[string]int{} } - if cap == 0 { - delete(all[k], w) - } else { - all[k][w] = cap + for _, w := range ws { + if cap == 0 { + delete(all[k], w) + } else { + all[k][w] = cap + } } if len(all[k]) == 0 { delete(all, k) @@ -285,9 +301,9 @@ func (a Allowance) CapHeld(model string, caps WindowCaps, now time.Time) *CapHol model = strings.ToLower(model) var h *CapHold unknown, byCap := false, false - for _, l := range a { + for _, l := range a.capLimits(model) { share, credits := caps.Of(l.Name) - if share <= 0 || !l.applies(model) || l.Used < float64(share) { + if share <= 0 || l.Used < float64(share) { continue } if !l.Resets.IsZero() && !l.Resets.After(now) { @@ -326,9 +342,9 @@ func (a Allowance) NearCap(model string, caps WindowCaps, points float64, now ti return false } model = strings.ToLower(model) - for _, l := range a { + for _, l := range a.capLimits(model) { share, _ := caps.Of(l.Name) - if share <= 0 || !l.applies(model) || l.Used < float64(share)-points { + if share <= 0 || l.Used < float64(share)-points { continue } if !l.Resets.IsZero() && !l.Resets.After(now) { @@ -367,11 +383,16 @@ func WithCapped(m map[string]SubscriptionQuota) map[string]SubscriptionQuota { for u, q := range m { ws := make([]QuotaWindow, len(q.Windows)) for i, w := range q.Windows { - w.Capped = !w.Aside && !w.Unlimited - w.CapsSome = w.Capped && (w.Model != "" || w.matches != nil) + // a pool's own window holds its models (allowanceOf) + pool := w.PoolWindow() && len(PoolMembers(q.Windows, w)) > 0 + w.Capped = (!w.Aside || pool) && !w.Unlimited + w.CapsSome = w.Capped && (w.Model != "" || w.matches != nil || pool) if w.Capped { w.CapID = WindowCapID(w.Name) } + if pool { + w.CapID = WindowCapID(w.LineName()) + } ws[i] = w } if q.Windows != nil { diff --git a/internal/provider/account_caps_test.go b/internal/provider/account_caps_test.go index 12ab25068..a27c891f0 100644 --- a/internal/provider/account_caps_test.go +++ b/internal/provider/account_caps_test.go @@ -318,3 +318,80 @@ func TestCodexSwitchedAtCap(t *testing.T) { t.Fatal("a cap set on an account it hasn't") } } + +// An Antigravity account's pools each have a 5-hour and a 7-day window +// of their own, set aside for routing, which reads the models' windows +// (pluviophile714 on Discord: the Gemini 7 days' meter, clicked, did +// nothing, though the cap's pill said a window can have its own). Each is +// marked capped, by its pool's name and its own, as both pools have a "7 +// days"; a cap on it holds the pool's models only, and the account's cap +// counts it like any window. +func TestPoolWindowCapHeld(t *testing.T) { + now := time.Now() + five, week := now.Add(2*time.Hour), now.Add(4*24*time.Hour) + ws := []QuotaWindow{ + {Name: "Gemini 3.1 Pro (High)", Model: "gemini-3.1-pro-high", Family: "Gemini", Pool: "Gemini", Used: 10, ResetsAt: &five}, + {Name: "Gemini 3.1 Pro (Low)", Model: "gemini-3.1-pro-low", Family: "Gemini", Pool: "Gemini", Used: 10, ResetsAt: &five}, + {Name: "Claude Sonnet 4.6", Model: "claude-sonnet-4-6", Family: "Claude", Pool: "Claude & GPT", Used: 5, ResetsAt: &five}, + {Name: "7 days", Pool: "Gemini", Used: 60, ResetsAt: &week, Aside: true, Span: 7 * 24 * time.Hour}, + {Name: "5 hours", Pool: "Gemini", Used: 10, ResetsAt: &five, Aside: true, Span: 5 * time.Hour}, + {Name: "7 days", Pool: "Claude & GPT", Used: 2, ResetsAt: &week, Aside: true, Span: 7 * 24 * time.Hour}, + } + got := WithCapped(map[string]SubscriptionQuota{"me@example.com": {Windows: ws}})["me@example.com"].Windows + if w := got[3]; !w.Capped || !w.CapsSome || w.CapID != "gemini · 7 days" { + t.Fatalf("the Gemini pool's week: capped %v, some %v, id %q", w.Capped, w.CapsSome, w.CapID) + } + if got[5].CapID != "claude & gpt · 7 days" { + t.Fatalf("the other pool's week: %q", got[5].CapID) + } + if got[0].CapID != "gemini 3.1 pro (high)" { + t.Fatalf("a model's own window's id changed: %q", got[0].CapID) + } + a := allowanceOf(ws, now) + if used, _ := a.For("gemini-3.1-pro-high", now); used != 10 { + t.Fatalf("routing went by the pool's window, set aside for it: %v", used) + } + gem := WindowCaps{Windows: map[string]int{"gemini · 7 days": 50}} + if h := a.CapHeld("gemini-3.1-pro-high", gem, now); h == nil || h.Used != 60 || h.Cap != 50 || !h.Back.Equal(week) { + t.Fatalf("the Gemini week at 60%% of 50%%: %+v", h) + } + if h := a.CapHeld("claude-sonnet-4-6", gem, now); h != nil { + t.Fatalf("the Gemini pool's cap held Claude: %+v", h) + } + if h := a.CapHeld("gemini-3.1-pro-high", WindowCaps{Windows: map[string]int{"gemini · 7 days": 70}}, now); h != nil { + t.Fatalf("held under its own 70%%: %+v", h) + } + if !a.NearCap("gemini-3.1-pro-high", gem, 15, now) { + t.Fatal("the Gemini week is not near its cap") + } + if h := a.CapHeld("gemini-3.1-pro-low", WindowCaps{All: 55}, now); h == nil || h.Cap != 55 { + t.Fatalf("the account's 55%% left the pool's week out: %+v", h) + } +} + +// A family's meter (Antigravity's Gemini 3.1 Pro, High and Low) sets each +// of its models' windows at once. +func TestSetWindowCaps(t *testing.T) { + signIn(t) // me@example.com on codex + if err := SetWindowCaps("codex", "me@example.com", []string{"Gemini 3.1 Pro (High)", "gemini 3.1 pro (low)"}, 60); err != nil { + t.Fatal(err) + } + c := AccountCapsOf("codex", "me@example.com") + if a, _ := c.Of("gemini 3.1 pro (high)"); a != 60 { + t.Fatalf("high: %+v", c) + } + if b, _ := c.Of("Gemini 3.1 Pro (Low)"); b != 60 { + t.Fatalf("low: %+v", c) + } + for _, bad := range [][]string{nil, {"x", " "}} { + if err := SetWindowCaps("codex", "me@example.com", bad, 60); err == nil { + t.Errorf("%q taken", bad) + } + } + if err := SetWindowCaps("codex", "me@example.com", []string{"gemini 3.1 pro (high)", "gemini 3.1 pro (low)"}, 0); err != nil { + t.Fatal(err) + } + if c := AccountCapsOf("codex", "me@example.com"); c.Windows != nil { + t.Fatalf("cleared, still %+v", c) + } +} diff --git a/internal/provider/routing.go b/internal/provider/routing.go index 795909ff2..58b0e0a30 100644 --- a/internal/provider/routing.go +++ b/internal/provider/routing.go @@ -250,6 +250,10 @@ type Limit struct { matches func(string) bool partial bool // of a reading that may leave windows out (QuotaWindow.partial) Name string // QuotaWindow.Name: which window it is, one reading to the next (WindowCapID) + // pool is the windows of the pool a model's own window draws on + // (Antigravity's "Gemini · 7 days"), which hold the account at its + // caps only (capLimits): routing goes on by the model's own window + pool []Limit // ResetRunsOut is when the reset the account spends by itself before // it runs out does (resetRunsOut): spent then, it starts this window // again — at Restarts, which routing takes for the window's renewal @@ -1008,21 +1012,28 @@ func allowanceOf(ws []QuotaWindow, now time.Time) Allowance { } } } + resets := func(w QuotaWindow) time.Time { + switch { + case w.ResetsAt != nil: + return *w.ResetsAt + case w.ResetSecs > 0: + return now.Add(time.Duration(w.ResetSecs) * time.Second) + } + return time.Time{} + } var a Allowance + at := map[string]int{} // a model's own window, by its model for _, w := range ws { 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} + 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, Resets: resets(w)} if ids := families[w.Model]; ids != nil && w.Family != "" && w.matches == nil { l.Model = "" l.matches = func(model string) bool { return ids[model] } } - switch { - case w.ResetsAt != nil: - l.Resets = *w.ResetsAt - case w.ResetSecs > 0: - l.Resets = now.Add(time.Duration(w.ResetSecs) * time.Second) + if w.Family != "" && w.Model != "" { + at[w.Model] = len(a) } if w.RunsOutAt != nil { l.RunsOut, l.RunsOutLeft = *w.RunsOutAt, w.RunsOut @@ -1038,5 +1049,30 @@ func allowanceOf(ws []QuotaWindow, now time.Time) Allowance { } a = append(a, l) } + // a pool's own windows, set aside for routing, hold its models at + // their caps (pluviophile714 on Discord), under their LineName + for _, w := range ws { + if !w.PoolWindow() || w.Text { + continue + } + pl := Limit{Used: w.Used, Span: w.Span, Name: w.LineName(), Resets: resets(w)} + for _, m := range PoolMembers(ws, w) { + if i, ok := at[m.Model]; ok { + a[i].pool = append(a[i].pool, pl) + } + } + } return a } + +// capLimits are the windows of a that count model, each with the windows +// of the pool it draws on, which hold it at caps only. +func (a Allowance) capLimits(model string) []Limit { + var out []Limit + for _, l := range a { + if l.applies(model) { + out = append(append(out, l), l.pool...) + } + } + return out +}