diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 65370a94c..23fa2aee7 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -279,6 +279,7 @@ covers both response shapes, refreshes and the subsequent toggle. - The requests magpie makes by itself (a routing classifier's, a web search's, an image description's) are told apart from the agents' on the Usage page (#1839): magpie's row among the agents and its rows in the ledger carry a "magpie's own" mark (`ownBadge`), an account's, key's or model's row adds "{n} by magpie itself" from the summary's `own`, and an account's card says how many of the period's requests were magpie's own (`ownLine`, drawn again once the summary comes after the allowances). See `own-requests.test.cjs` and `TestSummaryCountsMagpiesOwnCallsApart`. - Opening the allowances is asking to see them (#1588, `quotasOpened` in `app.js`): the Usage page from the nav or its Overview tab picked, the window brought back to the front on the Overview, the tray panel's Allowances tab picked or the panel brought up on it, and a menu bar cell clicked each load `usage/quotas?asked=1`, as Refresh now does. An asked read makes the backend read every account again (`AskClaudeUsage`), so an opening within 30s (`QUOTAS_OPEN_GAP`) of the last asked read sends an ordinary read instead, which joins one on its way; Refresh now always asks. A panel page loaded while it is put away (hidden, or without focus) doesn't ask. The timed refresh is unchanged and never asks. See `allowance-open-read.test.cjs`. - The menu bar can show magpie's own totals beside the allowances (#1984): `usage:today` and `usage:7d` in `settings.TrayUsages`, offered after the cards in the same picker. `trayUsageCards` sums them with `usage.SummarizeTop(p, 0)` (the Overview's cached summary) and asks no vendor when only totals are picked; `trayTotalCard` makes the tokens (in and out, as `tokensOf`) over the cost in Settings' currency, `+` when some calls had no price, the cost row left out when none had one. The Mac draws them as plain cells, the bird beside them saying whose. A click opens the Overview at the period (`quotaView`, `?period=`) or the panel's Usage tab (`panelUseFocus`). No 3-day total: the Usage page has no such window. See `TestTrayTotals` and `tray-totals.test.cjs`. +- In Usage → Allowances, Trends → Cycle offers each account's own recorded cycle menu beside its curve (`quotaCurve`, `quotaRecordedCycles` in [`app.js`](../../internal/gui/assets/app.js)). The longest window (usually weekly) owns the menu; shorter windows are drawn over the selected dates with their own reset breaks. `/api/usage/quotas/history?days=45` supplies all retained readings, including remote cards. Completed cycles come from observed boundaries, not seven-day arithmetic; an early reset ends the previous cycle at the vendor's new start if it fits between readings, otherwise at the first new reading. Each menu option gives its observed duration, so an early reset is not labelled as a full seven days. The selected meters, plot, legend, tooltip and dashed pace use that cycle's last readings, never today's percentages. A window without a reading in the selected interval says so instead of showing a current value. Historical meters show the cycle end and sampling time; current account actions, balances and policies are left out until returning to the current view. Accounts are independent, and a selection survives card refreshes in the same page. Trends → 2 days temporarily shows recent readings; Off removes the curves; the tray always shows its current cycle. See `quota-curve.test.cjs` and the [history limits and reset inference](providers-accounts.md#constraints-and-failure-behavior). - The Usage page's cards are packed into columns, never all stretched to a row's height (`packUsage`, #860): each card in that order goes to the leftmost column that ends highest, on 1px grid rows, so short cards stack beside a tall one. The last card in each column then reaches down to where the tallest column ends (a `min-height`, cleared before the cards are measured again), so cards side by side in one row are as tall as each other and a stack ends with the tall card beside it (ikunbots on X); content stays at each card's top. The page's order (DOM, dragging, Alt+arrows) stays `UsageOrder`. The column count is the most 260px columns that fit, or one fewer when that leaves much less empty room; it is chosen again only when the cards change or the width fits another number of columns, so a card opened or folded stays where it is, even as the scrollbar comes in. See `usage-pack.test.cjs`. - The Providers page has a search box over its list (#1614, `findProviders` in [`app.js`](../../internal/gui/assets/app.js)): the words typed keep the rows, on and off, whose text or data say them all: name, id, preset, addresses, every model's id and name, the account's user and plan and each login's, account names and key names. The Turned off fold stays open while searching; Escape or clearing the box shows every row and the fold as it was. A row that is on reorders by dragging its logo, Alt+↑/↓, Alt+Shift+↑/↓ (top, bottom) or its right-click menu (`openProviderMenu`: Move to top, Move up, Move down, Move to bottom). While searching, a step or a drop moves it among the rows shown (it takes the place of the row it passes, `stepProvider`, `shownToOn`) and the hidden ones keep their order; Move to top and Move to bottom go to the ends of the whole list. Every move saves the whole order through `POST /api/providers/arrange`. See `provider-find.test.cjs` and `provider-order.test.cjs`. - A new user's Agents page (the window's first page and the panel's Agents tab) has a *Get started* card above the agents in the welcome's place (wangye1644294 on X, `guideCard` in [`app.js`](../../internal/gui/assets/app.js)). Its three steps are: add a model source; connect an agent, where the agents magpie found that can be connected are named and each is connected in one click (`agents/connect`); and, optional, a routing group, with the most harmless starter template that can be made from the user's models (`provider.Templates`, Never stuck first) added in one click through `POST /api/groups/template`. Every tick comes from the state: the models magpie serves (`served` in `/api/state`, groups left out), an agent wired, or a group that isn't automatic. None comes from the card having been seen. The card goes once the first two steps are done. Its close button saves `settings.GuideHidden` through `POST /api/settings/guide`, so the panel, the window and a reload agree, and the Settings save keeps it. See `getting-started.test.cjs`. diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 0056a5f3d..cc5c02fc5 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -131,6 +131,20 @@ listed models keep their `Available` names unchanged ## Constraints and failure behavior +Allowance readings are kept by provider, lowercased account and window in +`quota-history.json` ([`quota_history.go`](../../internal/provider/quota_history.go)), +for up to 45 days and 6000 points per window. Failed or stale readings add +nothing. `newCycle` preserves a boundary when the previous deadline passes, +appears/disappears, moves backward by more than five minutes or forward by +more than the elapsed sampling time plus five minutes. A refill of more +than five percentage points with a deadline unchanged within five minutes +is also a boundary: a manual or vendor reset need not change the deadline. +Smaller corrections and a rolling deadline advancing with time do not +split that window. These are observed boundaries, not a record of who reset +it; multiple resets between readings and refills hidden by subsequent +spending cannot be recovered. Sampling compression and sync merging keep +readings on both sides of detected boundaries. + - A successful Codex allowance reset invalidates an account's in-flight reading even when the read and reset have the same clock timestamp. `Allowances` snapshots `usedCache.generation` under its lock, and `forgetAllowance` advances the generation for that account; a reading from before the reset is dropped before routing can use it. [`routing.go`](../../internal/provider/routing.go), `TestResetAllowanceKnownAtOnce`. - Each refresh token has exactly one holder. Vendors rotate tokens on refresh, so two copies of one token would sign each other out. `savedTokenMu` stops two requests refreshing one saved account at once. - A Claude subscription account is used only for Claude Code, through the genuine Claude Code binary (see [Claude subscription bridge](claude-subscription-bridge.md)). diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 9bb1dc3a7..9ead2bdc4 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -846,6 +846,8 @@ body.window .field.solo { grid-column: auto; } .quota-curve { margin-top: 10px; } .quota-curve .qc-head { display: flex; justify-content: space-between; align-items: baseline; gap: 6px; font-size: 10.5px; color: var(--muted); } .quota-curve .qc-range { font-size: 10px; color: var(--faint); } +.quota-curve button.qc-range { display: inline-flex; align-items: center; gap: 3px; flex-shrink: 0; padding: 0; } +.quota-curve button.qc-range:disabled { opacity: 1; cursor: default; } .quota-curve .qc-plot { display: block; width: 100%; height: 52px; margin-top: 5px; overflow: hidden; } /* a click makes a curve larger, another back (TJHHHH on Discord) */ .quota-curve .qc-plot { cursor: zoom-in; transition: height .15s ease; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 46f439de4..222acde2d 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -14211,7 +14211,7 @@ function loadQuotas(asked, again) { if (!again) quotasTries = 0; let reading = false, same = false; const p = Promise.resolve(quotasLoading).catch(() => {}) - .then(() => Promise.all([api("usage/quotas" + (asked ? "?asked=1" : ""), undefined, (h) => { reading = h.get("X-Magpie-Reading") === "1"; }), api("usage/quotas/history?days=35").catch(() => null)])) + .then(() => Promise.all([api("usage/quotas" + (asked ? "?asked=1" : ""), undefined, (h) => { reading = h.get("X-Magpie-Reading") === "1"; }), api("usage/quotas/history?days=45").catch(() => null)])) .then(([q, h]) => { // an answer that isn't a list of cards is a read that failed: what // was read before stays, as it does when the read is refused @@ -14617,8 +14617,10 @@ function renderQuotas() { if (folded.has(sub)) continue; // "Every model" by the account, or the card's name: where the click // was, whichever way the meters under it grow or shrink - const [meters, every] = familyQuota(sub); const brief = several && !usageAcctOpen(sub, subs); + const history = !brief && quotaHistoryView(sub); + const shownSub = history ? quotaHistoryCard(sub, history) : sub; + const [meters, every] = history ? [quotaWindows(shownSub), null] : familyQuota(sub); if (sub.user) { const who = el("div", "subscription-account" + (brief ? " brief" : "")); who.dataset.card = trayCardID(sub); @@ -14637,31 +14639,31 @@ function renderQuotas() { if (brief) meters.classList.add("brief"); card.append(meters); // a remote magpie's gateway key: what its windows don't say (#1547) - const keyLine = !brief && keyLimitLine(sub); + const keyLine = !brief && !history && keyLimitLine(sub); if (keyLine) card.append(keyLine); // how many of the period's requests to it magpie made itself (#1839) - const own = !brief && ownLine(sub); + const own = !brief && !history && ownLine(sub); if (own) card.append(own); // WorkBuddy's, Trae CN's or MiniMax Code's daily check-in, how this account's went, // and the switch for it, on the card rather than only in Settings // (#694); the switch on the first card of each vendor's - if (sub.checkins) card.append(checkinRow(sub, sub === subs.find((x) => x.checkins && (x.checkinBy || "") === (sub.checkinBy || "")), subs)); + if (sub.checkins && !history) card.append(checkinRow(sub, sub === subs.find((x) => x.checkins && (x.checkinBy || "") === (sub.checkinBy || "")), subs)); // what was left over time, against an even burn (#651) const curve = !brief && !sub.error && quotaCurve(sub); if (curve) card.append(curve); // WorkBuddy's credits, day by day, as magpie counted them (#568) - if (!brief && sub.daily && !sub.error) card.append(creditDays(sub)); + if (!brief && !history && sub.daily && !sub.error) card.append(creditDays(sub)); // what is left besides the windows, under them - if (sub.balance && sub.windows?.length && !sub.error) card.append(balanceRow(sub, "What is left on the account besides its windows", false)); + if (!history && sub.balance && sub.windows?.length && !sub.error) card.append(balanceRow(sub, "What is left on the account besides its windows", false)); // the balance over time, and when it runs out at that pace - const spend = !brief && !sub.error && balanceCurve(sub); + const spend = !brief && !history && !sub.error && balanceCurve(sub); if (spend) card.append(spend); // when the windows were read: "Updated 3 min ago", or the time of // ones standing in for a reading that failed just now (#802; a // balance alone says it in its row) - const read = !brief && sub.windows?.length && !sub.error && readWhen(sub, true); + const read = !brief && sub.windows?.length && !sub.error && readWhen(shownSub, true); if (read) card.append(read); - if (!brief && sub.resets?.count) { + if (!brief && !history && sub.resets?.count) { const r = el("div", "quota-resets"); r.append(resetsWords(sub.resets, sub)); // only Codex's are spent from here: a GLM team's are spent on @@ -14675,10 +14677,10 @@ function renderQuotas() { card.append(r); } // the account's standing say on its resets, held or not (#719) - const policy = !brief && autoResetRow(sub, "quota-autoreset"); + const policy = !brief && !history && autoResetRow(sub, "quota-autoreset"); if (policy) card.append(policy); // and on its credits, when its windows run out - const credits = !brief && creditsRow(sub, "quota-credits"); + const credits = !brief && !history && creditsRow(sub, "quota-credits"); if (credits) card.append(credits); } // in the card's head, beside its name: no line of its own @@ -15073,6 +15075,7 @@ function creditDays(sub) { // a dashed line from the window's start to its reset is an even burn, and // a thin upright one is now. "2 days" is the last two days; "Cycle" the // current cycle of the account's longest window, its start to its reset; +// each account can pick an earlier recorded cycle beside its plot. // "Off" draws none, on the Usage page or on the tray's cards (ARNO on // Discord: 额度面板变得非常混乱和难以观看了). One pick in the allowances' // head turns every card, remembered, and the tray panel follows it. @@ -15131,8 +15134,74 @@ function quotaCycleBreak(a, b) { if (a.reset == null || b.reset == null) return true; if (a.reset <= b.at) return true; const moved = b.reset - a.reset, slack = 5 * 60e3; + const rolling = moved > 0 && Math.abs(moved - (b.at - a.at)) <= slack; + if (!rolling && Math.abs(moved) <= slack && b.left > a.left + 5) return true; return moved > b.at - a.at + slack || moved < -slack; } +// Recorded cycles, never weeks counted back from today's deadline. An +// early reset ends the preceding cycle at the first observed new reading +// unless the vendor's new start fits between those readings. +function quotaRecordedCycles(l) { + const cycles = []; + for (const p of l.points) { + let c = cycles[cycles.length - 1]; + const prev = c?.points[c.points.length - 1]; + if (!prev || quotaCycleBreak(prev, p)) { + let start = p.start ?? p.at; + if (prev && (prev.reset == null || prev.reset > p.at) && !(start > prev.at && start <= p.at)) start = p.at; + if (prev?.reset != null && prev.reset <= p.at) start = Math.max(start, prev.reset); + if (c) c.end = Math.min(c.end, start); + c = { id: String(p.at), start, end: p.reset ?? p.at, points: [] }; + cycles.push(c); + } + c.points.push(p); + c.end = p.reset ?? p.at; + } + return cycles; +} +// The longest recorded window owns the cycle picker (usually a week). +// Shorter windows still draw, with their own reset breaks, in that range. +function quotaPastCycles(lines, now) { + const longest = lines.reduce((a, b) => { + const span = (l) => Math.max(...l.points.map((p) => p.reset != null && p.start != null ? p.reset - p.start : 0)); + return span(b) > span(a) ? b : a; + }); + return { line: longest, cycles: quotaRecordedCycles(longest).filter((c, i, all) => i < all.length - 1 || c.end <= now).reverse() }; +} +const quotaCyclePicks = new Map(); // account -> recorded cycle's first reading +// One selection drives both the meters and the curve. A snapshot contains +// only the fields history actually kept, never today's counts or holds. +function quotaHistoryView(sub, lines = quotaLines(sub), now = Date.now()) { + if (quotaRange !== "cycle" || sub.error || !lines.length) return null; + const past = quotaPastCycles(lines, now); + const picked = past.cycles.find((c) => c.id === quotaCyclePicks.get(usageAcctKey(sub))); + if (!picked) return null; + const shown = lines.map((l) => { + const points = l === past.line ? picked.points : l.points.filter((p) => p.at >= picked.start && p.at < picked.end); + const last = points.at(-1); + return { ...l, points, cycle: l === past.line ? { start: picked.start, reset: picked.end } : last ? { start: last.start ?? points[0].at, reset: last.reset } : {} }; + }); + return { picked, shown }; +} +function quotaHistoryCard(sub, { picked, shown }) { + const windows = familyWindows(sub.windows).map((w) => { + const name = w.pool ? w.pool + " · " + w.name : w.name; + const last = shown.find((l) => l.name === name)?.points.at(-1); + const base = { name: w.name, pool: w.pool, historyMissing: !last }; + if (!last) return base; + return { ...base, used: 100 - last.left, recordedAt: last.at, + resetsAt: new Date(Math.min(last.reset ?? picked.end, picked.end)).toISOString() }; + }); + const at = Math.max(...windows.filter((w) => !w.historyMissing).map((w) => w.recordedAt)); + return { ...sub, windows, history: true, asOf: null, readAt: Number.isFinite(at) ? new Date(at).toISOString() : null }; +} +function quotaCycleLength(c) { + let minutes = Math.max(1, Math.round((c.end - c.start) / 60e3)); + const days = Math.floor(minutes / 1440); minutes %= 1440; + const hours = Math.floor(minutes / 60); minutes %= 60; + return [[days, "day"], [hours, "hour"], [minutes, "minute"]].filter(([n]) => n).map(([n, unit]) => + new Intl.NumberFormat(intlLang(), { style: "unit", unit, unitDisplay: "short" }).format(n)).join(" "); +} // the current cycle of a line: its start and its reset, the window's as // the card has it, else its last reading's function quotaCycle(l, now) { @@ -15144,6 +15213,7 @@ function quotaCycle(l, now) { while (i > 0 && !quotaCycleBreak(l.points[i - 1], l.points[i])) i--; start = l.points[i].at; } + if (reset === last.reset) start = Math.max(start, quotaRecordedCycles(l).at(-1).start); if (reset != null && reset <= now) reset = null; return { start: Math.min(start, now), reset }; } @@ -15183,6 +15253,11 @@ function quotaTimeText(at, now) { const time = d.toLocaleTimeString(lang, { hour: "2-digit", minute: "2-digit", hour12: false }); return sameDay ? time : d.toLocaleDateString(lang, { month: "short", day: "numeric" }) + " " + time; } +// A completed cycle can end today; still say both dates in its menu and +// axis, so a multi-day cycle doesn't read as two times on the first day. +function quotaCycleDate(at) { + return new Date(at).toLocaleString(intlLang(), { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", hour12: false }); +} // drawQuotaPlot puts lines' curves for [x0, x1] in svg, a w×h box: // the grid, the even burns, the lines, and now. function drawQuotaPlot(g, lines, x0, x1, w, h, now, thin) { @@ -15191,7 +15266,7 @@ function drawQuotaPlot(g, lines, x0, x1, w, h, now, thin) { const X = (t) => ((t - x0) / (x1 - x0)) * w; lines.forEach((l, i) => { const color = `var(--c${(i % 7) + 1})`; - const c = quotaCycle(l, now); + const c = l.cycle || quotaCycle(l, now); // a window far shorter than the span (a 5-hour one over a week) is // drawn faint, without its even burn, an all but upright dash const short = !thin && c.reset && c.reset - c.start < (x1 - x0) / 12; @@ -15214,7 +15289,9 @@ function quotaCurve(sub) { if (!lines.length) return null; const box = el("div", "quota-curve"); const head = el("div", "qc-head"); - const range = el("span", "qc-range"); + const range = el("button", "text qc-range"); + range.type = "button"; + const key = usageAcctKey(sub); head.append(el("span", "", t("Left over time")), range); // what the dashes are isn't plain from the plot (John on Discord asked) box.title = t("Solid: what was left. Dashed: an even pace, full at the cycle's start to empty at its reset; a line above its dashes lasts the cycle, one below runs out before the reset."); @@ -15223,24 +15300,46 @@ function quotaCurve(sub) { curveZoom(box, g); const axis = el("div", "qc-axis"); const legend = el("div", "qc-legend"); - lines.forEach((l, i) => { - const k = el("span", "qc-key"); - const sw = el("i"); - sw.style.background = `var(--c${(i % 7) + 1})`; - const last = l.points[l.points.length - 1]; - k.append(sw, el("span", "", l.label), el("b", "", Math.round(last.left) + "%")); - k.title = [t("{name}: {n} left, read {when}", { name: l.label, n: Math.round(last.left) + "%", when: quotaTimeText(last.at, Date.now()) }), - "", t("Latest readings:"), ...quotaReadings(l, Date.now())].join("\n"); - legend.append(k); - }); + const drawLegend = (shown, now) => { + legend.replaceChildren(); + shown.forEach((l, i) => { + const k = el("span", "qc-key"); + const sw = el("i"); + sw.style.background = `var(--c${(i % 7) + 1})`; + const last = l.points[l.points.length - 1]; + if (!last) return; + k.append(sw, el("span", "", l.label), el("b", "", Math.round(last.left) + "%")); + k.title = [t("{name}: {n} left, read {when}", { name: l.label, n: Math.round(last.left) + "%", when: quotaTimeText(last.at, now) }), + "", t("Latest readings:"), ...quotaReadings(l, now)].join("\n"); + legend.append(k); + }); + }; box.draw = () => { const now = Date.now(); - const [x0, x1] = quotaSpan(lines, quotaRange, now); - drawQuotaPlot(g, lines, x0, x1, W, H, now); - const r = t(quotaRange === "2d" ? "2 days" : "Cycle"); + const past = quotaPastCycles(lines, now); + const history = quotaHistoryView(sub, lines, now); + const picked = history?.picked; + const [x0, x1] = picked ? [picked.start, picked.end] : quotaSpan(lines, quotaRange, now); + // Keep only readings of the selected cycle. In particular, a refill + // at its end belongs to the next cycle, not this cycle's last figure. + const shown = history?.shown || lines; + drawQuotaPlot(g, shown, x0, Math.max(x0 + 1, x1), W, H, now); + const r = picked ? t("Past cycle") : t(quotaRange === "2d" ? "2 days" : "Cycle"); range.textContent = r; + range.disabled = quotaRange !== "cycle" || !past.cycles.length; + range.title = t("Choose a recorded cycle"); + range.setAttribute("aria-label", t("Choose a recorded cycle")); + if (!range.disabled) range.append(svg(CHEV, 9, 1.6)); + range.onclick = (e) => { + e.stopPropagation(); + if (range.classList.contains("open")) return closeProtoMenu(); + openProtoMenu(range, [{ v: "", name: "Cycle", note: "The current cycle, from the window's start to its reset" }, ...past.cycles.map((c) => ({ + v: c.id, name: quotaCycleDate(c.start) + " – " + quotaCycleDate(c.end), literalName: true, note: t("Recorded duration: {duration}", { duration: quotaCycleLength(c) }), + }))], picked?.id || "", (id) => { if (id) quotaCyclePicks.set(key, id); else quotaCyclePicks.delete(key); renderQuotas(); }, "Choose a recorded cycle", "sess-menu"); + }; g.setAttribute("aria-label", t("Left over time") + " · " + r); - axis.replaceChildren(el("span", "", quotaTimeText(x0, now)), el("span", "", quotaTimeText(x1, now))); + axis.replaceChildren(el("span", "", picked ? quotaCycleDate(x0) : quotaTimeText(x0, now)), el("span", "", picked ? quotaCycleDate(x1) : quotaTimeText(x1, now))); + drawLegend(shown, now); }; box.append(head, g, axis, legend); box.draw(); @@ -15248,8 +15347,7 @@ function quotaCurve(sub) { } // quotaReadings: a line's last eight readings, newest first, each what was // left and when it was read (#802), a line each, ↻ where the window -// started again; for its legend key's title, the card keeping no control -// of its own +// started again; for its legend key's title function quotaReadings(l, now) { const pts = l.points.slice(-8); return pts.map((p, i) => (i > 0 && quotaCycleBreak(pts[i - 1], p) ? "↻ " : "") + Math.round(p.left) + "% · " + quotaTimeText(p.at, now)).reverse(); @@ -15342,13 +15440,10 @@ function balanceCurve(sub) { } function setQuotaRange(id) { if (id === quotaRange) return; - const was = quotaRange; quotaRange = id; try { localStorage.setItem("magpie.quotaRange", id); } catch {} - // turned on or off, the cards are made again; a range redraws them - if (was === "off" || id === "off") return renderQuotas(); - renderQuotaTrend(); - for (const b of document.querySelectorAll(".quota-curve")) b.draw?.(); + // A range also restores today's meters when leaving a historical cycle. + renderQuotas(); } // quotaSpark: the tray card's thin line of a window's current cycle, the // even burn faint under it; none while the curves are off @@ -16627,7 +16722,9 @@ function balanceMeter(percent) { // refresh is left of it. function readWhen(q, refresh = false) { let s; - if (q.asOf) { + if (q.history && q.readAt) { + s = el("div", "quota-read", t("Last reading {when}", { when: quotaCycleDate(Date.parse(q.readAt)) })); + } else if (q.asOf) { s = el("div", "quota-read stale", asOfText(q)); s.title = asOfText(q); } else if (q.readAt) { @@ -16782,15 +16879,18 @@ function quotaWindows(sub) { // the count and its share in parts, so a count too long for its // window's width goes to a second line at the · rather than cut short const n = el("button", "quota-n"); - const [count, share] = quotaText(w).split(" · "); + const text = w.historyMissing ? t("No readings in this cycle") : quotaText(w); + const [count, share] = text.split(" · "); n.append(el("span", "", share ? count + " ·" : count)); if (share) n.append(" ", el("span", "", share)); - n.title = quotaText(w) + "\n" + t(quotaLeft ? "Show how much of each window is used" : "Show how much of each window is left"); + n.title = w.historyMissing ? text : text + "\n" + t(quotaLeft ? "Show how much of each window is used" : "Show how much of each window is left"); + n.disabled = !!w.historyMissing; n.onclick = () => setQuotaLeft(!quotaLeft); labels.append(el("span", "", t(w.name)), n); const track = el("div", "quota-track"); const fill = el("i"); - fill.style.width = `${quotaFill(w)}%`; + fill.style.width = w.historyMissing ? "0%" : `${quotaFill(w)}%`; + if (w.historyMissing) track.style.visibility = "hidden"; track.append(fill); quota.append(labels); if (!w.unlimited) quota.append(track); @@ -16799,10 +16899,10 @@ function quotaWindows(sub) { if (w.resetsAt) { const at = new Date(w.resetsAt); r = el("div", "quota-reset"); - r.append(el("span", "", resetText(at) + (at > Date.now() ? " ·" : ""))); - if (at > Date.now()) r.append(" ", el("span", "", untilText(at))); + r.append(el("span", "", sub.history ? t("Cycle ended {when}", { when: quotaCycleDate(+at) }) : resetText(at) + (at > Date.now() ? " ·" : ""))); + if (!sub.history && at > Date.now()) r.append(" ", el("span", "", untilText(at))); quota.append(r); - quota.title = resetText(at, at.toLocaleString(intlLang())); + quota.title = sub.history ? t("Last reading {when}", { when: quotaCycleDate(w.recordedAt) }) : resetText(at, at.toLocaleString(intlLang())); } // credits that run out before then, or with no reset at all const out = runsOutText(w); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 87a373715..98569aae1 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3138,6 +3138,12 @@ const I18N = { "Solid: what was left. Dashed: an even pace, full at the cycle's start to empty at its reset; a line above its dashes lasts the cycle, one below runs out before the reset.": "实线:剩余额度。虚线:匀速用量,周期开始时满、重置时用完;实线高于虚线则能撑到重置,低于则会在重置前用完。", "2 days": "2 天", "Cycle": "本周期", + "Recorded duration: {duration}": "已记录时长:{duration}", + "No readings in this cycle": "本周期无记录", + "Last reading {when}": "最后采样于 {when}", + "Cycle ended {when}": "周期结束于 {when}", + "Past cycle": "历史周期", + "Choose a recorded cycle": "选择已记录的周期", "The last two days": "最近两天", "The current cycle, from the window's start to its reset": "当前周期:从窗口开始到重置", "Trends: {range}": "走势:{range}", @@ -7846,6 +7852,12 @@ const I18N = { "Solid: what was left. Dashed: an even pace, full at the cycle's start to empty at its reset; a line above its dashes lasts the cycle, one below runs out before the reset.": "實線:剩餘額度。虛線:勻速用量,週期開始時滿、重置時用完;實線高於虛線則能撐到重置,低於則會在重置前用完。", "2 days": "2 天", "Cycle": "本週期", + "Recorded duration: {duration}": "已記錄時長:{duration}", + "No readings in this cycle": "此週期無記錄", + "Last reading {when}": "最後取樣於 {when}", + "Cycle ended {when}": "週期結束於 {when}", + "Past cycle": "歷史週期", + "Choose a recorded cycle": "選擇已記錄的週期", "The last two days": "最近兩天", "The current cycle, from the window's start to its reset": "目前週期:從時段開始到重置", "Trends: {range}": "走勢:{range}", @@ -12564,6 +12576,12 @@ const I18N = { "Solid: what was left. Dashed: an even pace, full at the cycle's start to empty at its reset; a line above its dashes lasts the cycle, one below runs out before the reset.": "実線:残量。破線:均等なペースで、サイクル開始時に満タン、リセット時に空になる線です。実線が破線より上ならサイクル終了まで持ち、下ならリセット前に使い切ります。", "2 days": "2 日", "Cycle": "サイクル", + "Recorded duration: {duration}": "記録された期間: {duration}", + "No readings in this cycle": "このサイクルの記録なし", + "Last reading {when}": "最終記録: {when}", + "Cycle ended {when}": "サイクル終了: {when}", + "Past cycle": "過去のサイクル", + "Choose a recorded cycle": "記録されたサイクルを選択", "The last two days": "直近 2 日間", "The current cycle, from the window's start to its reset": "現在のサイクル(ウィンドウ開始からリセットまで)", "Trends: {range}": "推移:{range}", @@ -17282,6 +17300,12 @@ const I18N = { "Solid: what was left. Dashed: an even pace, full at the cycle's start to empty at its reset; a line above its dashes lasts the cycle, one below runs out before the reset.": "Durchgezogen: der verbleibende Rest. Gestrichelt: ein gleichmäßiges Tempo, von voll zu Beginn des Zyklus bis leer beim Reset; eine Linie über ihrer gestrichelten reicht für den Zyklus, eine darunter ist vor dem Reset aufgebraucht.", "2 days": "2 Tage", "Cycle": "Zyklus", + "Recorded duration: {duration}": "Erfasste Dauer: {duration}", + "No readings in this cycle": "Keine Messwerte in diesem Zyklus", + "Last reading {when}": "Letzte Messung: {when}", + "Cycle ended {when}": "Zyklusende: {when}", + "Past cycle": "Vergangener Zyklus", + "Choose a recorded cycle": "Aufgezeichneten Zyklus wählen", "The last two days": "Die letzten zwei Tage", "The current cycle, from the window's start to its reset": "Der aktuelle Zyklus, vom Beginn des Zeitfensters bis zum Zurücksetzen", "Trends: {range}": "Verlauf: {range}", diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index 216005abd..148aa4ac5 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -2391,3 +2391,18 @@ and 50 once Plugins › Built-in sets it. Chromium and WebKit, every language, ```sh node --test internal/gui/tests/plugin-kernel.test.cjs internal/gui/tests/builtins.test.cjs ``` + +`quota-curve.test.cjs` also checks per-account historical cycle selection in +all five languages and both engines at 440px: natural expiry, an early +manual reset and an unscheduled refill with an unchanged deadline. The +historical legend and pace use the selected readings; other accounts stay +on their own cycle, missing short-window history is not invented, and +selecting a cycle does not scroll. `MAGPIE_QUOTA_ASSETS` selects an older +assets directory to verify the regression fails before the picker existed. + +Historical quota selections also update the 5-hour and weekly meters from +the last readings inside the selected interval. The cycle menu describes +observed duration rather than the nominal window name. Regression checks +cover missing windows, historical end and sampling dates, Used/Left, +restoring live values on 2 days/current cycle, and hiding live account +controls while inspecting history. diff --git a/internal/gui/tests/quota-curve.test.cjs b/internal/gui/tests/quota-curve.test.cjs index 6b8a48d3e..dddc5e163 100644 --- a/internal/gui/tests/quota-curve.test.cjs +++ b/internal/gui/tests/quota-curve.test.cjs @@ -5,7 +5,8 @@ // reset, and an upright line at now. One pick in the allowances' head, the // app's own menu, turns every card at once: "2 days" / "Cycle", or "Off" // (ARNO on Discord: the curves made the cards cluttered), which draws no -// curve on any card, the tray's thin line included; the pick is remembered +// curve on any card, the tray's thin line included; each account can pick +// an earlier recorded cycle in Cycle mode. The global pick is remembered // across a reload, and no click moves the page. Several accounts on a card // are set apart by a rule, a curve's legend before the next one too. An // account with no readings has no curve. The tray's card has a thin line of @@ -16,9 +17,10 @@ const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); const path = require("node:path"); const { test } = require("node:test"); +const vm = require("node:vm"); const { chromium, webkit } = require("playwright"); -const assets = path.resolve(__dirname, "../assets"); +const assets = process.env.MAGPIE_QUOTA_ASSETS || path.resolve(__dirname, "../assets"); const H = 3600e3; const iso = (ms) => new Date(ms).toISOString(); @@ -46,6 +48,141 @@ function fixtures(now) { return { quotas, history }; } +const cycleWords = { + en: { choose: "Choose a recorded cycle", past: "Past cycle", missing: "No readings in this cycle", duration: "Recorded duration:", reading: "Last reading", ended: "Cycle ended" }, + zh: { choose: "选择已记录的周期", past: "历史周期", missing: "本周期无记录", duration: "已记录时长:", reading: "最后采样于", ended: "周期结束于" }, + "zh-TW": { choose: "選擇已記錄的週期", past: "歷史週期", missing: "此週期無記錄", duration: "已記錄時長:", reading: "最後取樣於", ended: "週期結束於" }, + ja: { choose: "記録されたサイクルを選択", past: "過去のサイクル", missing: "このサイクルの記録なし", duration: "記録された期間:", reading: "最終記録:", ended: "サイクル終了:" }, + de: { choose: "Aufgezeichneten Zyklus wählen", past: "Vergangener Zyklus", missing: "Keine Messwerte in diesem Zyklus", duration: "Erfasste Dauer:", reading: "Letzte Messung:", ended: "Zyklusende:" }, +}; +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const [lang, w] of Object.entries(cycleWords)) { + test(`${engine} ${lang}: recorded quota cycles include manual and unscheduled resets`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const context = await browser.newContext({ viewport: { width: 440, height: 760 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const now = Date.now(), D = 24 * H; + const data = fixtures(now); + data.quotas[0].readAt = iso(now); + data.quotas[0].windows[1].holds = { tokens: 100000, cost: 12, priced: true, used: 30, routed: { calls: 10, tokens: 30000, cost: 3.6 } }; + const point = (day, left, reset) => ({ at: iso(now + day * D), left, start: iso(now + (reset - 7) * D), resetsAt: iso(now + reset * D) }); + // An early manual reset, an official refill with the SAME deadline, + // then an ordinary week. None is found by subtracting seven days + // from today's deadline. Only the manual cycle has old 5-hour data. + data.quotas[0].windows[1].resetsAt = iso(now + D); + data.history[0].lines[1].points = [ + point(-16, 90, -10), point(-14, 20, -10), + point(-13, 100, -6), point(-12, 70, -6), + point(-11, 100, -6), point(-9, 30, -6), + point(-5, 95, 1), point(-1 / 24, 65, 1), + ]; + const shortReset = now - 12 * D + H; + data.history[0].lines[0].points.unshift({ at: iso(now - 12 * D), left: 12, start: iso(shortReset - 5 * H), resetsAt: iso(shortReset) }); + const reads = []; + const handler = serve(lang, "light", false, data); + await page.route("**/*", (r) => { if (r.request().url().includes("/quotas/history")) reads.push(r.request().url()); return handler(r); }); + await page.goto("http://magpie.test/?view=usage"); + const card = page.locator('.subscription-card[data-key="codex"]'); + const curve = card.locator(".quota-curve").first(); + await curve.waitFor(); + assert.equal(await curve.locator("button.qc-range").count(), 1, "each account can choose a recorded cycle"); + assert.ok(reads.some((url) => new URL(url).searchParams.get("days") === "45"), "all retained history is requested"); + await card.locator(".quota-more").click(); + const other = card.locator(".quota-curve").nth(1); + const otherAxis = await other.locator(".qc-axis").textContent(); + const currentAxis = await curve.locator(".qc-axis").textContent(); + const currentLegend = await curve.locator(".qc-key").allTextContents(); + const meters = card.locator(".quota-windows").first(); + const currentMeters = await meters.locator(".quota-n").allTextContents(); + assert.equal(await meters.locator(".quota-holds").count(), 1, "the current view keeps upstream's whole-window estimate"); + const otherMeters = await card.locator(".quota-windows").nth(1).locator(".quota-n").allTextContents(); + const pick = curve.getByRole("button", { name: w.choose }); + for (const [index, left] of [[1, 30], [2, 70], [3, 20]]) { + const before = await page.locator("#view-usage").evaluate((v) => v.scrollTop); + await pick.click(); + const items = page.locator(".sess-menu .pm-item"); + assert.equal(await items.count(), 4, "current + three observed cycles"); + const notes = await items.locator(".pm-note").allTextContents(); + assert.ok(notes.slice(1).every((note) => note.startsWith(w.duration)), "menu describes the observed duration, not the window's nominal name"); + assert.notEqual(notes[1], notes[2], "a regular week and an early reset have different lengths"); + await items.nth(index).click(); + assert.equal(await pick.textContent(), w.past); + assert.equal(await meters.locator(".quota-holds").count(), 0, "today's whole-window estimate is not presented as a historical estimate"); + const hasShort = index === 2; + assert.deepEqual(await curve.locator(".qc-key b").allTextContents(), hasShort ? ["12%", left + "%"] : [left + "%"], "the historical legend uses that cycle's final reading"); + assert.match(await meters.locator(".quota-n").nth(1).textContent(), new RegExp((100 - left) + "%"), "the weekly meter follows the historical selection"); + if (hasShort) assert.match(await meters.locator(".quota-n").first().textContent(), /88%/, "the 5-hour meter uses its last reading inside that cycle"); + else assert.equal(await meters.locator(".quota-n").first().textContent(), w.missing, "missing history never shows today's meter"); + assert.ok((await meters.locator(".quota-reset").allTextContents()).every((text) => text.startsWith(w.ended)), "historical dates aren't current countdowns"); + assert.ok((await card.locator(".quota-read").first().textContent()).includes(w.reading)); + assert.equal(await card.locator(".quota-autoreset").count(), 1, "only the other account retains current controls"); + assert.equal(await curve.locator("line.qc-now").count(), 0, "now is outside a completed cycle"); + assert.equal(await curve.locator("line.qc-even").count(), hasShort ? 2 : 1, "the historical even pace belongs to the selected cycle"); + assert.equal(await curve.locator("path.qc-line").count(), hasShort ? 2 : 1, "no fabricated short-window readings"); + assert.notEqual(await curve.locator(".qc-axis").textContent(), currentAxis); + assert.equal(await other.locator(".qc-axis").textContent(), otherAxis, "another account stays on its own cycle"); + assert.deepEqual(await card.locator(".quota-windows").nth(1).locator(".quota-n").allTextContents(), otherMeters); + assert.equal(await page.locator("#view-usage").evaluate((v) => v.scrollTop), before, "choosing a cycle doesn't scroll"); + const coords = await curve.locator("path.qc-line").first().getAttribute("d"); + assert.ok(!/NaN|Infinity/.test(coords), coords); + } + await meters.locator(".quota-n").nth(1).click(); + assert.match(await meters.locator(".quota-n").nth(1).textContent(), /20%/, "Left is also the selected cycle's historical value"); + assert.equal(await meters.locator(".quota-n").first().textContent(), w.missing); + await meters.locator(".quota-n").nth(1).click(); + assert.match(await meters.locator(".quota-n").nth(1).textContent(), /80%/); + await page.locator("#quotaTrend").click(); + await page.locator(".sess-menu .pm-item").nth(1).click(); + assert.deepEqual(await meters.locator(".quota-n").allTextContents(), currentMeters, "2 days restores current meters"); + await page.locator("#quotaTrend").click(); + await page.locator(".sess-menu .pm-item").nth(2).click(); + assert.match(await meters.locator(".quota-n").nth(1).textContent(), /80%/, "Cycle resumes the account's selected historical period"); + await card.locator(".quota-refresh").first().click(); + await page.waitForFunction(() => !document.querySelector(".quota-refresh.busy")); + assert.equal(await pick.textContent(), w.past, "a refresh preserves the selected historical cycle"); + assert.deepEqual(await curve.locator(".qc-key b").allTextContents(), ["20%"]); + await pick.click(); + await page.locator(".sess-menu .pm-item").first().click(); + assert.equal(await curve.locator(".qc-axis").textContent(), currentAxis); + assert.deepEqual(await curve.locator(".qc-key").allTextContents(), currentLegend); + assert.deepEqual(await meters.locator(".quota-n").allTextContents(), currentMeters, "returning to this cycle restores today's meters"); + assert.equal(await meters.locator(".quota-holds").count(), 1, "returning to this cycle restores upstream's whole-window estimate"); + assert.deepEqual(await page.evaluate(() => ({ page: document.documentElement.scrollWidth > innerWidth, cards: [...document.querySelectorAll(".subscription-card")].some((c) => c.scrollWidth > c.clientWidth + 1) })), { page: false, cards: false }); + assert.deepEqual(errors, []); + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await pick.click(); + await page.locator(".sess-menu .pm-item").nth(2).click(); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-quota-history.png`) }); + } + }); + } +} + +test("quota curve distinguishes fixed refills, rolling recovery and clock rounding", async () => { + const source = await fs.readFile(path.join(assets, "app.js"), "utf8"); + const start = source.indexOf("function quotaCycleBreak(a, b) {"); + const end = source.indexOf("\n}\n", start); + const check = vm.runInNewContext(source.slice(start, end + 2) + "; quotaCycleBreak"); + const at = Date.UTC(2026, 9, 1), reset = at + 7 * 24 * H; + const a = { at, reset, left: 20 }; + for (const [name, gap, moved, left, want] of [ + ["fixed deadline refill", 60e3, 0, 100, true], + ["rounded fixed refill", 10 * 60e3, 60e3, 100, true], + ["manual restart", 60e3, 24 * H, 100, true], + ["earlier official restart", 60e3, -24 * H, 100, true], + ["normal expiry", 7 * 24 * H, 7 * 24 * H, 100, true], + ["small correction", 60e3, 0, 24, false], + ["clock rounding", 60e3, 60e3, 20, false], + ["rolling recovery", H, H, 80, false], + ["fast rolling recovery", 60e3, 60e3, 80, false], + ]) assert.equal(check(a, { at: at + gap, reset: reset + moved, left }), want, name); +}); + function serve(lang, theme, panel, data) { const settings = { theme, lang, tray: "panel", quotaLeft: false, currency: "usd" }; return async (route) => { @@ -55,9 +192,11 @@ function serve(lang, theme, panel, data) { 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/settings/quota-left") { settings.quotaLeft = route.request().postDataJSON().on; return json(settings); } if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); if (url.pathname === "/api/usage/quotas") return json(data.quotas); if (url.pathname === "/api/usage/quotas/history") return json(data.history); + if (url.pathname === "/api/usage") return json({ calls: 0, input: 0, output: 0, cost: 0, agents: [], accounts: [], models: [], series: [], days: [] }); if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); if (url.pathname === "/api/plugins") return json({ plugins: [] }); if (url.pathname.startsWith("/api/")) return json({}); @@ -107,7 +246,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // the range is picked once, in the allowances' head, not on every card const pick = page.locator("#quotaHead #quotaTrend"); assert.equal(await pick.textContent(), w.trend(w.cycle), "Cycle first"); - assert.equal(await page.locator(".quota-curve .segs, .quota-curve button, .quota-curve select").count(), 0, "no control on a card"); + assert.equal(await page.locator(".quota-curve .segs, .quota-curve button:not(.qc-range), .quota-curve select").count(), 0, "only the account's cycle picker on a card"); assert.equal(await curve.locator(".qc-range").textContent(), w.cycle); // a line a window, now; the 5-hour window, a comb over the week's // cycle, faint and without its upright even burn diff --git a/internal/gui/tests/quota-read-at.test.cjs b/internal/gui/tests/quota-read-at.test.cjs index 8c28333bc..b22d58bb2 100644 --- a/internal/gui/tests/quota-read-at.test.cjs +++ b/internal/gui/tests/quota-read-at.test.cjs @@ -91,7 +91,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const title = (await key.getAttribute("title")).split("\n"); assert.equal(title[2], w.latest, title.join(" | ")); assert.deepEqual(title.slice(3).map((l) => l.replace(/ · .*/, "")), ["72%", "↻ 100%", "35%"]); - assert.equal(await claude.locator(".quota-curve button").count(), 0, "no control on the card"); + assert.equal(await claude.locator(".quota-curve button:not(.qc-range)").count(), 0, "only the account's cycle picker on the card"); assert.deepEqual(errors, []); }); } diff --git a/internal/provider/quota_history.go b/internal/provider/quota_history.go index 0f9fdde6b..8ff59e64f 100644 --- a/internal/provider/quota_history.go +++ b/internal/provider/quota_history.go @@ -15,6 +15,7 @@ package provider // and a run of the same figure is its first and last point only. A cycle // ends where the window starts again: its reset passed, or moved further // than the time between two readings (a rolling window's moves with it). +// A fixed deadline's refill also starts a cycle, even if the reset stays. // Points older than quotaHistKept go, and a window keeps quotaHistMax. // // Other computers' points come in through the usage sync (davsync), merged @@ -149,6 +150,13 @@ func newCycle(a, b QuotaPoint) bool { return true } moved := b.ResetsAt.Sub(*a.ResetsAt) + // A manual or vendor reset can refill a fixed window without changing + // its deadline. Small corrections aren't a refill; a rolling deadline + // moving with the reading isn't a fixed window's reset either. + rolling := moved > 0 && (moved-b.At.Sub(a.At)).Abs() <= quotaHistSlack + if !rolling && moved.Abs() <= quotaHistSlack && b.Left > a.Left+5 { + return true + } return moved > b.At.Sub(a.At)+quotaHistSlack || moved < -quotaHistSlack } diff --git a/internal/provider/quota_history_test.go b/internal/provider/quota_history_test.go index 728b31c88..1f7f2b366 100644 --- a/internal/provider/quota_history_test.go +++ b/internal/provider/quota_history_test.go @@ -123,6 +123,41 @@ func TestQuotaHistoryCycles(t *testing.T) { } } +// A refill can leave the deadline alone, advance it or bring it forward. +// Preserve both readings even when they are too close for normal sampling. +func TestQuotaHistoryUnscheduledResets(t *testing.T) { + at := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC) + reset := at.Add(7 * 24 * time.Hour) + a := QuotaPoint{At: at, Left: 20, ResetsAt: &reset} + for _, tc := range []struct { + name string + gap, moved time.Duration + left float64 + want bool + }{ + {"refill with unchanged deadline", time.Minute, 0, 100, true}, + {"refill with rounded deadline", 10 * time.Minute, time.Minute, 100, true}, + {"manual restart", time.Minute, 24 * time.Hour, 100, true}, + {"official earlier restart", time.Minute, -24 * time.Hour, 100, true}, + {"ordinary reset", 7 * 24 * time.Hour, 7 * 24 * time.Hour, 100, true}, + {"small correction", time.Minute, 0, 24, false}, + {"deadline rounding", time.Minute, time.Minute, 20, false}, + {"rolling recovery", time.Hour, time.Hour, 80, false}, + {"fast rolling recovery", time.Minute, time.Minute, 80, false}, + } { + t.Run(tc.name, func(t *testing.T) { + r := reset.Add(tc.moved) + b := QuotaPoint{At: at.Add(tc.gap), Left: tc.left, ResetsAt: &r} + if got := newCycle(a, b); got != tc.want { + t.Fatalf("cycle break = %v, want %v", got, tc.want) + } + if tc.want && len(addPoint([]QuotaPoint{a}, b)) != 2 { + t.Fatal("reset folded into previous cycle") + } + }) + } +} + // TestMergeQuotaHistory: another computer's points join this one's: the // union, sorted, two within half a minute of each other the newer one, // and merging the same again changes nothing.