usage: an account whose longer window is used up adds no headroom to the all-accounts sum (#4791)
hayden4608 (Discord) and handong66 (#4791) have four Codex accounts. Three show 5 hours 100% left with 7 days 0% left, and one shows 5 hours 0% left with 7 days 22% left. The All accounts strip read "5 hours 75% left", but none of those three can spend its 5 hours until its week starts again. The right figure is 0%. mergeQuotas (quotaall.js) is the one place that sums windows across accounts. It feeds the Usage page's strip, the tray panel's strip and the Routing groups' line. The native menu-bar tray, the TUI, the CLI and /v1/magpie/quotas show one account at a time and are unchanged. The GUI's JSON doesn't carry Aside, Model or the matches, so the call is made in Go. provider.WithHeldWindows marks a window heldBy another window of the same account when that other window: - stops the account for every model, by routing's rule: not aside, no model, no matches, used >= 100, reset not passed, and not Codex credits that go on; and - starts again after this one (by reset times, else by span). So 7 days used up holds 5 hours, but 5 hours used up doesn't hold a week with 22% left. /api/usage/quotas and its refresh apply it. mergeQuotas counts a held share window as 100 used and a held counted one as its limit, and the strip's tooltip says how many were counted that way (en/zh/zh-TW/ja/de). The account cards still show the vendor's own figure. Run on mote (macOS) at this head's parent tree: - go vet for darwin, linux (nogui) and windows: ok; gofmt -l: none. - go test -count=1 ./internal/provider ./internal/gui, before the quota_span leftOut line and an i18n comment fix. The provider package's only red was TestQuotaSpanCarriesEveryWindowField, which wanted heldBy named, and it is now named. internal/gui's only red was TestMainWindowCorners/macOS_26_SDK, which is #3949. - GUI, chromium and webkit, every language, 440px and 360px: quota-*, usage-* (all-accounts, merge, accounts, fold, refresh and more), panel-usage/quota/switch-accounts/balance-order, routing-quota-left, routing-group, tray-usage, i18n-keys, gui-de/ja/zh-tw, old-webkit: 704 of 707. The reds were i18n-keys (a quoted "All accounts" in window_held.go's comment, fixed here) and usage-fold's "17 subscriptions and 29 accounts" in both engines, which is #4790 and is red at origin/main too (see below). At the pushed head, rebased oneb3b9376e, on mote: gofmt none, vet ok. internal/provider ok. internal/gui is red only on TestMainWindowCorners (#3949). GUI usage-merge, usage-all-accounts, i18n-keys and usage-fold, both engines: 44 of 46. The 2 reds are usage-fold's 29 accounts, which fail the same at origin/maineb3b9376eon mote (noted on #4790). Broken by hand, each red, then restored (cmp): - Go, no HeldBy set: both TestHeldWindows tests red (a, b, c not held). - Go, outlasts always true: red on d and on "a week that starts again first". - JS, held forced false: usage-merge plus all 5 languages of usage-all-accounts red in chromium, showing the reporter's "5 hours · 75% left". Not tried: real accounts. The issue names no provider; Codex is assumed from the cards' 5 hours / 7 days. Not done: marking a card as held by its week, the reporter's optional second ask. Not written: a handler-level test that /api/usage/quotas carries heldBy. Not run on Linux or Windows.
This commit is contained in:
@@ -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.
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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]]);
|
||||
});
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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{}
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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{}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user