diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 7d0404632..af5dadee5 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -238,6 +238,13 @@ each place is drawn again once it is in. All three come from - an account whose reading failed is unknown, not 0, and is counted ("1 couldn't be read"); a window an `asOf` reading stands in for, whose reset has passed, is left out and counted in its tooltip; +- a window the account can't spend counts as used up: its `heldBy` + (`provider.WithHeldWindows`, set on `/api/usage/quotas`) names another + window that stops the account for every model, is used up and starts + again after it, as 7 days at 0% left holds 5 hours at 100% (#4791). + Not the other way: a week with room behind five hours used up keeps + it. The tooltip counts how many were held; each account's own card + still shows the vendor's figure; - only what two or more accounts have goes together; family and pool stay, so `familyWindows` folds the result as an account's. diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 4516fdc36..e1b1382ef 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3573,6 +3573,7 @@ const I18N = { "Unlimited on each of {n} accounts": "{n} 个账号都不限量", "Added up over {n} accounts": "{n} 个账号相加", "{n} more read before it started again: left out": "另有 {n} 个是重置前读到的,未计入", + "{n} of them can't spend theirs before a longer window used up starts again: counted as none left": "其中 {n} 个账号的更长周期已用完、重置前用不上这部分额度,按无剩余计", "The first of them starts again {when}": "最早的一个 {when} 重置", "{n} couldn't be read": "{n} 个读取失败", "An account whose reading failed isn't counted as empty or full: it is left out of these figures": "读取失败的账号不按用完或全满计算,而是不计入这些数字", @@ -7915,6 +7916,7 @@ const I18N = { "Unlimited on each of {n} accounts": "{n} 個帳號都不限量", "Added up over {n} accounts": "{n} 個帳號相加", "{n} more read before it started again: left out": "另有 {n} 個是重設前讀到的,未計入", + "{n} of them can't spend theirs before a longer window used up starts again: counted as none left": "其中 {n} 個帳號的更長週期已用完、重設前用不上這部分額度,按無剩餘計", "The first of them starts again {when}": "最早的一個 {when} 重設", "{n} couldn't be read": "{n} 個讀取失敗", "An account whose reading failed isn't counted as empty or full: it is left out of these figures": "讀取失敗的帳號不按用完或全滿計算,而是不計入這些數字", @@ -12272,6 +12274,7 @@ const I18N = { "Unlimited on each of {n} accounts": "{n} アカウントすべて無制限", "Added up over {n} accounts": "{n} アカウントの合計", "{n} more read before it started again: left out": "ほかに {n} 件はリセット前の読み取りのため除外", + "{n} of them can't spend theirs before a longer window used up starts again: counted as none left": "うち {n} 件は、より長い枠を使い切っており、そのリセットまで使えないため残りなしとして計上", "The first of them starts again {when}": "最も早いものは {when} にリセット", "{n} couldn't be read": "{n} 件は読み取れませんでした", "An account whose reading failed isn't counted as empty or full: it is left out of these figures": "読み取りに失敗したアカウントは空とも満杯とも数えず、これらの数字から除外します", @@ -16639,6 +16642,7 @@ const I18N = { "Unlimited on each of {n} accounts": "Unbegrenzt bei allen {n} Konten", "Added up over {n} accounts": "Summe über {n} Konten", "{n} more read before it started again: left out": "{n} weitere vor dem Neustart gelesen: nicht mitgezählt", + "{n} of them can't spend theirs before a longer window used up starts again: counted as none left": "{n} davon können ihren Rest erst nach dem Neustart eines aufgebrauchten längeren Fensters nutzen: als leer gezählt", "The first of them starts again {when}": "Das erste davon beginnt {when} neu", "{n} couldn't be read": "{n} nicht lesbar", "An account whose reading failed isn't counted as empty or full: it is left out of these figures": "Ein Konto, dessen Abfrage fehlschlug, zählt weder als leer noch als voll: Es fehlt in diesen Zahlen", diff --git a/internal/gui/assets/quotaall.js b/internal/gui/assets/quotaall.js index 1f8f3c7c1..554185944 100644 --- a/internal/gui/assets/quotaall.js +++ b/internal/gui/assets/quotaall.js @@ -13,7 +13,9 @@ // reading failed is not 0 but unknown: it is left out and counted as that; // so is a window an earlier reading (asOf) stands in for whose reset has // passed. A window only the vendor's text says has nothing to add up and is -// left out. Unlimited only where every account read says so, and one +// left out. A window the account can't spend, held by another used up that +// starts again after it (heldBy: 0% of 7 days left, 100% of 5 hours), has +// nothing left to count: it adds its whole as used (#4791). Unlimited only where every account read says so, and one // account's window alone is that account's, already below: only what two // or more have goes together (a Plus and a Pro account have no 5 hours in // common). The windows keep their family and pool, so familyWindows folds @@ -36,12 +38,14 @@ function mergeQuotas(subs, now = Date.now()) { if (!kind) continue; const k = JSON.stringify([w.name, w.family || "", w.pool || "", w.unit || "", kind]); let m = by.get(k); - if (!m) by.set(k, (m = { w, kind, plan: q.plan || "", n: 0, stale: 0, amount: 0, limit: 0, balance: 0, used: 0, soon: null })); + if (!m) by.set(k, (m = { w, kind, plan: q.plan || "", n: 0, stale: 0, held: 0, amount: 0, limit: 0, balance: 0, used: 0, soon: null })); if (q.asOf && w.resetsAt && Date.parse(w.resetsAt) <= now) { m.stale++; continue; } m.n++; - if (kind === "c") { m.amount += Math.max(0, w.amount || 0); m.limit += w.limit; } + const held = w.heldBy && kind !== "u" && kind !== "b"; + if (held) m.held++; + if (kind === "c") { m.amount += held ? w.limit : Math.max(0, w.amount || 0); m.limit += w.limit; } else if (kind === "b") m.balance += w.balance; - else if (kind !== "u") m.used += to100(w.used); + else if (kind !== "u") m.used += held ? 100 : to100(w.used); const at = w.resetsAt && Date.parse(w.resetsAt); if (at > now && (m.soon == null || at < m.soon)) m.soon = at; } @@ -51,7 +55,7 @@ function mergeQuotas(subs, now = Date.now()) { if (m.n < 2) continue; // one account's is already below if (m.kind === "u" && m.n < read.length) continue; const { w } = m; - const out = { name: w.name, family: w.family, pool: w.pool, unit: w.unit, accounts: m.n, unknown: m.stale, how: m.kind[0] }; + const out = { name: w.name, family: w.family, pool: w.pool, unit: w.unit, accounts: m.n, unknown: m.stale, held: m.held, how: m.kind[0] }; if (m.kind === "u") out.unlimited = true; else if (m.kind === "c") Object.assign(out, { amount: m.amount, limit: m.limit, used: (100 * m.amount) / m.limit }); else if (m.kind === "b") out.balance = m.balance; @@ -89,6 +93,7 @@ function quotaAll(subs, cls = "", max = Infinity) { name + " · " + quotaText(w), t(w.how === "p" ? "The mean of {n} accounts on one plan" : w.how === "u" ? "Unlimited on each of {n} accounts" : "Added up over {n} accounts", { n: w.accounts }), w.unknown && t("{n} more read before it started again: left out", { n: w.unknown }), + w.held && t("{n} of them can't spend theirs before a longer window used up starts again: counted as none left", { n: w.held }), w.firstReset && t("The first of them starts again {when}", { when: resetClock(new Date(w.firstReset)) }), w.tiers && "\n" + tiersText(w)); box.append(item); diff --git a/internal/gui/tests/usage-all-accounts.test.cjs b/internal/gui/tests/usage-all-accounts.test.cjs index f197613b4..89f3402cb 100644 --- a/internal/gui/tests/usage-all-accounts.test.cjs +++ b/internal/gui/tests/usage-all-accounts.test.cjs @@ -38,7 +38,7 @@ const groups = () => ({ models, pools: [], deciders: [], found: true, groups: [ { id: "glm", name: "GLM", members: ["workbuddy-ai/glm-5"], ready: true, memberInfo: [{ id: "workbuddy-ai/glm-5", ready: true, provider: "workbuddy-ai", name: "WorkBuddy AI", icon: "generic", model: "glm-5" }] }, ] }); -function serve(lang, theme, tray) { +function serve(lang, theme, tray, cards = quotas) { const settings = { theme, lang, tray, quotaLeft: false, currency: "usd" }; return async (route) => { const url = new URL(route.request().url()); @@ -48,7 +48,7 @@ function serve(lang, theme, tray) { 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, url: "http://127.0.0.1:3999" } }); - if (url.pathname === "/api/usage/quotas") return json(quotas()); + if (url.pathname === "/api/usage/quotas") return json(cards()); if (url.pathname === "/api/groups") return json(groups()); if (url.pathname === "/api/plugins") return json({ plugins: [] }); if (url.pathname === "/api/gateway/trace") { @@ -93,14 +93,14 @@ const shot = async (page, name) => { await page.screenshot({ path: path.join(process.env.SHOTS, name + ".png") }); }; -async function open(browser, lang, theme, tray, url, width = 440, height = 900) { +async function open(browser, lang, theme, tray, url, width = 440, height = 900, cards = quotas) { const context = await browser.newContext({ viewport: { width, height }, reducedMotion: "reduce", colorScheme: theme }); const page = await context.newPage(); page.setDefaultTimeout(8000); page.setDefaultNavigationTimeout(60000); const errors = []; page.on("pageerror", (e) => errors.push(e.message)); - await page.route("**/*", serve(lang, theme, tray)); + await page.route("**/*", serve(lang, theme, tray, cards)); await page.addInitScript(() => { try { if (!sessionStorage.getItem("set")) { localStorage.clear(); localStorage.setItem("magpie.quotaRange", "off"); sessionStorage.setItem("set", "1"); } } catch {} }); await page.goto(url); return { page, errors }; @@ -187,3 +187,67 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", } } } + +// #4791 (hayden4608 on Discord, handong66): three Codex accounts with 100% +// of 5 hours left and 0% of 7 days, one with 0% of 5 hours and 22% of 7 +// days. The server marks the three's 5 hours held by their week +// (provider.WithHeldWindows): they can't be spent before it starts again. +// The strip read 75% of 5 hours left; it says 0% left, its tooltip says +// three are held, and the week is 5.5% left as before. Each account's own +// card still shows the vendor's 100% left. +const heldWords = { + en: { held: "3 of them can't spend theirs before a longer window used up starts again: counted as none left", five: "0% left", week: "5.5% left" }, + zh: { held: "其中 3 个账号的更长周期已用完、重置前用不上这部分额度,按无剩余计" }, + "zh-TW": { held: "其中 3 個帳號的更長週期已用完、重設前用不上這部分額度,按無剩餘計" }, + ja: { held: "うち 3 件は、より長い枠を使い切っており、そのリセットまで使えないため残りなしとして計上" }, + de: { held: "3 davon können ihren Rest erst nach dem Neustart eines aufgebrauchten längeren Fensters nutzen: als leer gezählt" }, +}; +const pct = (s) => Number(/([\d.]+)%/.exec(s)?.[1]); +const heldCards = () => [["a", 0, 100, true], ["b", 0, 100, true], ["c", 0, 100, true], ["d", 100, 78, false]].map(([u, five, week, held]) => ({ + provider: "codex", name: "Codex", kind: "subscription", icon: "openai", plan: "Plus", user: u + "@example.com", readAt: iso(now), + windows: [{ name: "5 hours", used: five, resetsAt: iso(now + 4 * 3600e3), ...(held ? { heldBy: "7 days" } : {}) }, { name: "7 days", used: week, resetsAt: iso(now + 3 * 24 * 3600e3) }], +})); +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(heldWords)) { + test(`${engine} ${lang}: 5 hours an account can't spend before its week count as none left in all (#4791)`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const w = heldWords[lang]; + const check = async (page, strip) => { + await strip.first().waitFor(); + const ws = strip.locator(".quota-all-w"); + assert.equal(await ws.count(), 2); + const [five, week] = [ws.nth(0), ws.nth(1)]; + const fiveTip = await five.getAttribute("title"); + assert.ok(fiveTip.includes(w.held), fiveTip); + assert.ok(!(await week.getAttribute("title")).includes(w.held)); + return [await five.locator(".quota-all-n").textContent(), await week.locator(".quota-all-n").textContent()]; + }; + // the Usage page, left + const { page, errors } = await open(browser, lang, "light", "window", "http://magpie.test/?view=usage", 440, 900, heldCards); + const strip = page.locator('#subscriptionUsage > [data-key="codex"] .quota-all'); + await strip.waitFor(); + await page.locator("#quotaMode .opt").nth(1).click(); + await page.waitForFunction(() => /left|剩|残|übrig/i.test(document.querySelector('#subscriptionUsage > [data-key="codex"] .quota-all .quota-all-n')?.textContent || "")); + const [five, week] = await check(page, strip); + assert.equal(pct(five), 0, "no 5 hours left in all, not 75%: " + five); + assert.equal(pct(week), 5.5, week); + if (w.five) assert.equal(five, w.five); + if (w.week) assert.equal(week, w.week); + assert.deepEqual(await fits(page, ".quota-all"), []); + await shot(page, `held-usage-${engine}-${lang}`); + assert.deepEqual(errors, []); + // the tray panel + const panel = await open(browser, lang, "light", "panel", "http://magpie.test/?mode=panel", 360, 760, heldCards); + await panel.page.locator('#ptabs [data-ptab="usage"]').click(); + const pq = panel.page.locator("#panelQuota .pq-group .pq-all"); + const [pfive, pweek] = await check(panel.page, pq); + // the panel says what is used, as its settings have it + assert.equal(pct(pfive), 100, "every 5 hours used or held, not 25% used: " + pfive); + assert.equal(pct(pweek), 94.5, pweek); + assert.deepEqual(await fits(panel.page, ".pq-all"), []); + await shot(panel.page, `held-panel-${engine}-${lang}`); + assert.deepEqual(panel.errors, []); + }); + } +} diff --git a/internal/gui/tests/usage-merge.test.cjs b/internal/gui/tests/usage-merge.test.cjs index c3fe80b73..56bb107e7 100644 --- a/internal/gui/tests/usage-merge.test.cjs +++ b/internal/gui/tests/usage-merge.test.cjs @@ -116,3 +116,29 @@ test("windows keep their family and pool, apart by them", () => { ], now); assert.deepEqual(r.windows.map((w) => [w.pool, w.used]), [["Gemini", 20], ["Claude & GPT", 80]]); }); + +// #4791 (hayden4608 on Discord, handong66): three accounts with 100% of 5 +// hours left and 0% of 7 days, one with 0% of 5 hours and 22% of 7 days. +// The three can't spend their 5 hours before their week starts again: the +// server marks those windows heldBy "7 days", and the strip read 75% of 5 +// hours left in all. Held, they count as used up: 0% left; the week's +// figure is the mean as before, 5.5% left. +test("a window held by a longer one used up counts as nothing left", () => { + const codex = (user, five, week, fiveHeld) => ({ provider: "codex", name: "Codex", user, plan: "plus", windows: [ + { name: "5 hours", used: five, resetsAt: iso(now + 5 * H), ...(fiveHeld ? { heldBy: "7 days" } : {}) }, + { name: "7 days", used: week, resetsAt: iso(now + 72 * H) }, + ] }); + const r = merge([codex("a", 0, 100, true), codex("b", 0, 100, true), codex("c", 0, 100, true), codex("d", 100, 78, false)], now); + const [five] = by(r, "5 hours"), [week] = by(r, "7 days"); + assert.equal(five.used, 100, "no 5 hours to spend in all, not 75% left"); + assert.equal(five.held, 3); + assert.equal(five.accounts, 4); + assert.equal(week.used, 94.5, "5.5% of the week left, as before"); + assert.equal(week.held, 0); + // a counted window held so adds its whole as used + const c = merge([ + acct("a", [{ name: "Credits", amount: 0, limit: 500, unit: "credits", heldBy: "Monthly" }]), + acct("b", [{ name: "Credits", amount: 100, limit: 500, unit: "credits" }]), + ], now); + assert.deepEqual(by(c, "Credits").map((w) => [w.amount, w.limit, w.held]), [[600, 1000, 1]]); +}); diff --git a/internal/gui/usage.go b/internal/gui/usage.go index 89c49e6d5..e87be0bdc 100644 --- a/internal/gui/usage.go +++ b/internal/gui/usage.go @@ -270,6 +270,9 @@ func usageRoutes(mux *http.ServeMux, w Windows) { qs = usage.WithWindowHolds(qs, usage.Clock()) // and when each began, for its Pace number (fflake33) qs = provider.WithWindowStarts(qs, usage.Clock()) + // and which an account can't spend for another window used up, + // for the accounts' sum (#4791) + qs = provider.WithHeldWindows(qs, usage.Clock()) // and which the menu bar can show, by kind, for Settings to pick // among (settings.TrayWindows) qs = withTrayKinds(qs) @@ -292,7 +295,7 @@ func usageRoutes(mux *http.ServeMux, w Windows) { ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) defer cancel() provider.RefreshUsage(ctx, id, r.URL.Query().Get("user")) - writeJSON(rw, withTrayKinds(provider.WithWindowStarts(usage.WithWindowHolds(provider.InProviderOrder(provider.WithCheckins(provider.Quotas(ctx))), usage.Clock()), usage.Clock()))) + writeJSON(rw, withTrayKinds(provider.WithHeldWindows(provider.WithWindowStarts(usage.WithWindowHolds(provider.InProviderOrder(provider.WithCheckins(provider.Quotas(ctx))), usage.Clock()), usage.Clock()), usage.Clock()))) }) // WorkBuddy's daily check-in pressed now, from the Usage card, for // each account not in yet today, as `magpie accounts checkin` does; the diff --git a/internal/provider/quota_span_test.go b/internal/provider/quota_span_test.go index 2d7eea888..d872dffc5 100644 --- a/internal/provider/quota_span_test.go +++ b/internal/provider/quota_span_test.go @@ -64,6 +64,7 @@ func TestQuotaSpanCarriesEveryWindowField(t *testing.T) { "startsAt": "the GUI's Pace number (WithWindowStarts)", "trayKind": "the GUI's menu bar picker (gui.withTrayKinds)", "trayExtra": "the GUI's menu bar picker (gui.withTrayKinds)", + "heldBy": "the GUI's all-accounts sum (WithHeldWindows)", } names := func(t reflect.Type) map[string]bool { out := map[string]bool{} diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index 7b87e3de4..311efcd65 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -121,6 +121,12 @@ type QuotaWindow struct { // the menu bar shows only when picked (gui.trayChoices): money aside, // one model's window, Cursor's Grok Bot. TrayExtra bool `json:"trayExtra,omitempty"` + // HeldBy is, for the GUI only (WithHeldWindows), the name of another + // window of the account that is used up and stops it for every model + // ("7 days"): what is left of this one can't be used until that one + // starts again, so a sum over accounts counts it as nothing left + // (#4791). + HeldBy string `json:"heldBy,omitempty"` // matches further scopes pools whose membership isn't one model word. matches func(string) bool // partial is set on the windows of a reading that may leave some out: diff --git a/internal/provider/window_held.go b/internal/provider/window_held.go new file mode 100644 index 000000000..50d9644fb --- /dev/null +++ b/internal/provider/window_held.go @@ -0,0 +1,80 @@ +package provider + +import "time" + +// WithHeldWindows is qs with HeldBy set on each window whose remainder an +// account can't spend: another of its windows that stops it for every +// model (usedPast's rule: not aside, no model of its own, not past its +// reset) is used up and starts again only after this one does, so what +// this one has left is lost at its own reset, unspent. An account with 0% +// of its 7 days left and 100% of its 5 hours has no 5 hours to spend, and +// the Usage page's all-accounts strip, the tray panel's and the Routing +// groups' (mergeQuotas) count it as none left rather than as a full window +// (hayden4608, handong66: three such accounts and one with its 5 hours +// used up read 75% of 5 hours left in all, #4791). It isn't so the other +// way: a week with 22% left behind five hours used up still has that 22% +// once the five hours start again. A ChatGPT account that goes on on its +// credits isn't held. Another magpie's cards are as it sent them; qs and +// its windows, which the caches share, are left as they were. +func WithHeldWindows(qs []SubscriptionQuota, now time.Time) []SubscriptionQuota { + out := make([]SubscriptionQuota, len(qs)) + for i, q := range qs { + out[i] = q + if q.From != "" || q.Error != "" { + continue + } + var stops []int + for j, w := range q.Windows { + if stopsAll(q, w, now) { + stops = append(stops, j) + } + } + if len(stops) == 0 { + continue + } + ws := make([]QuotaWindow, len(q.Windows)) + for j, w := range q.Windows { + if !w.Unlimited && !w.Text && w.Balance == nil { + for _, s := range stops { + if s != j && outlasts(q.Windows[s], w, now) { + w.HeldBy = q.Windows[s].Name + break + } + } + } + ws[j] = w + } + out[i].Windows = ws + } + return out +} + +// stopsAll says whether w, one of q's windows, is used up at now and stops +// the account for every model while it is. +func stopsAll(q SubscriptionQuota, w QuotaWindow, now time.Time) bool { + if w.Aside || w.Text || w.Unlimited || w.Model != "" || w.matches != nil || w.Used < 100 || resetPassed(w, now) { + return false + } + return !w.Credits || !CodexCredits(q.User) // else the vendor spends the credits instead +} + +// outlasts says whether used-up window h starts again only after w does, +// by their resets where both are known, else by how long each runs. +func outlasts(h, w QuotaWindow, now time.Time) bool { + hr, wr := heldReset(h, now), heldReset(w, now) + if !hr.IsZero() && !wr.IsZero() { + return hr.After(wr) + } + return windowSpan(h) > windowSpan(w) +} + +// heldReset is when w starts again; zero when it doesn't say. +func heldReset(w QuotaWindow, now time.Time) 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{} +} diff --git a/internal/provider/window_held_test.go b/internal/provider/window_held_test.go new file mode 100644 index 000000000..c13ca853d --- /dev/null +++ b/internal/provider/window_held_test.go @@ -0,0 +1,86 @@ +package provider + +import ( + "encoding/json" + "testing" + "time" +) + +// #4791 (hayden4608 on Discord, handong66): four accounts of one plan, +// three with 100% of 5 hours left and 0% of 7 days, one with 0% of 5 hours +// and 22% of 7 days. The three can't spend their 5 hours until their week +// starts again, so their 5 hours are held by it; the fourth's week isn't +// held by its five hours, which start again first. +func TestHeldWindowsReportersCase(t *testing.T) { + now := time.Unix(1_793_620_800, 0) // 2026-11-02 12:00 UTC + // /wham/usage's rate_limit, as Codex reads it + codex := func(user string, fiveUsed, weekUsed float64, fiveIn, weekIn int64) SubscriptionQuota { + var u codexUsage + b := []byte(`{"plan_type":"plus","rate_limit":{"allowed":true,` + + `"primary_window":{"used_percent":` + jsonNum(fiveUsed) + `,"limit_window_seconds":18000,"reset_at":` + jsonNum(float64(now.Unix()+fiveIn)) + `},` + + `"secondary_window":{"used_percent":` + jsonNum(weekUsed) + `,"limit_window_seconds":604800,"reset_at":` + jsonNum(float64(now.Unix()+weekIn)) + `}}}`) + if err := json.Unmarshal(b, &u); err != nil { + t.Fatal(err) + } + return SubscriptionQuota{Provider: "codex", User: user, Plan: "plus", Windows: []QuotaWindow{u.RateLimit.Primary.window(), u.RateLimit.Secondary.window()}} + } + qs := []SubscriptionQuota{ + codex("a@example.com", 0, 100, 5*3600, 3*86400), + codex("b@example.com", 0, 100, 5*3600, 2*86400), + codex("c@example.com", 0, 100, 5*3600, 86400), + codex("d@example.com", 100, 78, 2*3600, 4*86400), + } + out := WithHeldWindows(qs, now) + for i := range 3 { + if got := out[i].Windows[0].HeldBy; got != "7 days" { + t.Errorf("%s: 5 hours held by %q, want 7 days", out[i].User, got) + } + if got := out[i].Windows[1].HeldBy; got != "" { + t.Errorf("%s: 7 days held by %q, want none", out[i].User, got) + } + } + for _, w := range out[3].Windows { + if w.HeldBy != "" { + t.Errorf("d: %s held by %q: a week behind five hours used up keeps its 22%% for after them", w.Name, w.HeldBy) + } + } + for _, q := range qs { + for _, w := range q.Windows { + if w.HeldBy != "" { + t.Fatalf("the cached cards were written: %s %s", q.User, w.Name) + } + } + } +} + +func TestHeldWindowsOnlyByWhatStopsTheAccount(t *testing.T) { + now := time.Unix(1_793_620_800, 0) + at := func(d time.Duration) *time.Time { t := now.Add(d); return &t } + five := QuotaWindow{Name: "5 hours", Used: 0, ResetsAt: at(time.Hour), Span: 5 * time.Hour} + for _, c := range []struct { + why string + week QuotaWindow + user string + held bool + }{ + {"a week used up", QuotaWindow{Name: "7 days", Used: 100, ResetsAt: at(48 * time.Hour), Span: 168 * time.Hour}, "", true}, + {"a week used up, its reset not told", QuotaWindow{Name: "7 days", Used: 100}, "", true}, + {"one model's week (Claude's Opus)", QuotaWindow{Name: "7 days Opus", Used: 100, ResetsAt: at(48 * time.Hour), Model: "opus"}, "", false}, + {"money aside", QuotaWindow{Name: "Extra usage", Used: 100, Aside: true}, "", false}, + {"a week whose reset has passed", QuotaWindow{Name: "7 days", Used: 100, ResetsAt: at(-time.Minute)}, "", false}, + {"a week that starts again first", QuotaWindow{Name: "7 days", Used: 100, ResetsAt: at(30 * time.Minute)}, "", false}, + {"a week with room", QuotaWindow{Name: "7 days", Used: 99, ResetsAt: at(48 * time.Hour)}, "", false}, + {"a ChatGPT account going on on its credits", QuotaWindow{Name: "7 days", Used: 100, ResetsAt: at(48 * time.Hour), Credits: true}, "e@example.com", false}, + } { + q := SubscriptionQuota{Provider: "codex", User: c.user, Windows: []QuotaWindow{five, c.week}} + got := WithHeldWindows([]SubscriptionQuota{q}, now)[0].Windows[0].HeldBy + if (got != "") != c.held { + t.Errorf("%s: 5 hours held by %q, want held %v", c.why, got, c.held) + } + } + // another magpie's card is as it sent it, a failed reading as it was + q := SubscriptionQuota{Provider: "codex", From: "studio", Windows: []QuotaWindow{five, {Name: "7 days", Used: 100}}} + if got := WithHeldWindows([]SubscriptionQuota{q}, now)[0].Windows[0].HeldBy; got != "" { + t.Errorf("another magpie's card held by %q", got) + } +}