usage: credits a day for every credit-based subscription, pool by pool (#3321)
The Usage page's credits a day (#568) counted WorkBuddy alone: its allow-list named the provider, and it read one "Credits" window's display. moxuanchen asked for it on every subscription that sells credits, and tnt1223 asked again on Discord. A window is now counted by what it is, not whose it is: a meter whose unit or name says credits (credits, 积分, 積分, 点数) or money (usd/$, cny/¥, eur/€), with a used and a total, read from the plugin's amount/limit, or else from its display ("x / y", units, currency signs, thousands separators, compact k/M/万, e-notation, a trailing "· note" cut). A share alone, a text row, an unlimited, family or aside window (when the card has another), a card with an error or an old reading is not counted; of several same-unit windows over a span (OpenDesign's 5 hours and Week) the longest is. Each window keeps its own ledger, keyed provider|user|window, so Qoder's Credits and Add-on credits don't mix; the card carries daily (the first) and moreDaily (the rest), each with its window and, for money, its unit. WorkBuddy's ledger under the old provider|user key still shows, and moves to its Credits window's key on the next reading. A total that drops counts nothing that day, never a negative. GUI: a card shows a row per pool, named after the window when it has several; money says "Spent per day" in the unit's currency. Strings in zh, zh-TW, ja and de. Not changed: API-key plan cards (PlanQuotas) aren't passed through the ledger; ZCode's buckets carry no unit, so only one named "Credits" counts. Run: - go test ./internal/gui ./internal/usageapi (-timeout 45m): ok. ./internal/provider dies in TestUnreadLoginsWriteErrorsKeepCredentials with "close of synctest channel from outside bubble" (#3632, red on origin/main, filememo.Forget); with that test skipped: ok. New TestCreditWindowShapes (22 plugin window shapes from the plugins repo's packages, plus Copilot's premium requests not counted), TestDailyCreditsEveryVendor (Trae CN with no display, Qoder's two pools, CodeArts' aside buckets, OpenDesign's spans, resets, errors, Command Code's dollars), TestDailyCreditsKeptBefore (an old WorkBuddy ledger shown before and after a reading, then moved). - GUI credit-days.test.cjs, chromium and webkit: the WorkBuddy cases and a new one at 360px in en, zh, zh-TW, ja, de (Trae CN, Qoder's two pools named, Cursor's On-demand spent in $, no sideways scroll); i18n-keys, gui-zh-tw, gui-ja, gui-de, quota-pools, quota-credits, plan-credits, usage-accounts, panel-usage, quota-name-translated, credits-run-out: 57/57 ok. - gofmt -l clean; go vet darwin, GOOS=linux/windows -tags nogui ok. - Real use: magpie built from this tree in a sandbox HOME, the fake plugin (a copy of internal/plugin/testdata/fake) signed in with a key, two windows read from a file: Credits 100/1000 then 137.5/1000, and Add-on credits "5 / 50 credits" then "9 / 50 credits". The card showed "37.5 today" and "4 today", one row per pool, at 900px and 360px; credits-daily.json held fakeco|api key|Credits and fakeco|api key|Add-on credits. Credits then dropped to 2/1000: the day stayed 37.5. Broken by hand: with origin/main's credits_daily.go the three new Go tests and TestDailyCredits fail (14 shapes "counted false", [null] days, the old key not moved); with origin/main's app.js the new GUI case fails in all five languages. Not tried: a real account of any vendor other than the fake plugin; Windows and Linux GUIs. Reported by moxuanchen.
This commit is contained in:
+17
-11
@@ -15545,8 +15545,12 @@ function renderQuotas(lazy) {
|
||||
// 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 && !history && sub.daily && !sub.error) card.append(creditDays(sub));
|
||||
// the account's credits, day by day, as magpie counted them (#568):
|
||||
// each pool on its own, named when there are several (#3321)
|
||||
if (!brief && !history && sub.daily && !sub.error) {
|
||||
const pools = [sub.daily, ...(sub.moreDaily || [])];
|
||||
for (const d of pools) card.append(creditDays(d, pools.length > 1));
|
||||
}
|
||||
// what is left besides the windows, under them
|
||||
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
|
||||
@@ -15943,13 +15947,15 @@ async function moveUsage(key, to) {
|
||||
}
|
||||
}
|
||||
|
||||
// creditDays: the credits an account used each day of the period, as
|
||||
// magpie counted them from its readings of the vendor's meter, which tells
|
||||
// only what the cycle has used so far — a bar a day, and the period's sum;
|
||||
// a day before magpie first read it is not known rather than nothing.
|
||||
function creditDays(sub) {
|
||||
// creditDays: the credits (or money, in its unit's currency) one of an
|
||||
// account's windows used each day of the period, as magpie counted them
|
||||
// from its readings of the vendor's meter, which tells only what the cycle
|
||||
// has used so far — a bar a day, and the period's sum; a day before magpie
|
||||
// first read it is not known rather than nothing. named: the window's name
|
||||
// beside the head, for a card with several.
|
||||
function creditDays(daily, named) {
|
||||
const box = el("div", "credit-days");
|
||||
const { since, days } = sub.daily;
|
||||
const { since, days, window: pool, unit } = daily;
|
||||
const by = new Map(days.map((d) => [d.day, d.used]));
|
||||
const key = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
||||
const today = new Date();
|
||||
@@ -15967,11 +15973,11 @@ function creditDays(sub) {
|
||||
d.setDate(d.getDate() - i);
|
||||
list.push({ day: key(d), date: d, used: by.get(key(d)) || 0, known: key(d) >= since });
|
||||
}
|
||||
const num = (v) => (Math.round(v * 100) / 100).toLocaleString(intlLang());
|
||||
const num = (v) => { try { if (unit) return new Intl.NumberFormat(intlLang(), { style: "currency", currency: unit.toUpperCase() }).format(v); } catch {} return (Math.round(v * 100) / 100).toLocaleString(intlLang()); };
|
||||
const dayName = (d) => d.toLocaleDateString(intlLang(), { month: "short", day: "numeric" });
|
||||
const sum = list.reduce((a, d) => a + d.used, 0);
|
||||
const head = el("div", "cd-head");
|
||||
const name = el("span", "", t("Credits used per day"));
|
||||
const name = el("span", "", t(unit ? "Spent per day" : "Credits used per day") + (named && pool ? " · " + t(pool) : ""));
|
||||
name.title = t("Counted from magpie's readings of the vendor's meter, since {date}: what is used while magpie isn't reading it is counted on the day it next does", { date: dayName(new Date(since + "T12:00:00")) });
|
||||
head.append(name, el("b", "", n > 1 ? t("{n} in {days} days", { n: num(sum), days: n }) : range && range.to !== key(today) ? t("{n} on {date}", { n: num(sum), date: dayName(last) }) : t("{n} today", { n: num(sum) })));
|
||||
box.append(head);
|
||||
@@ -15983,7 +15989,7 @@ function creditDays(sub) {
|
||||
const fill = el("i");
|
||||
fill.style.height = d.known && peak ? Math.max(d.used ? 6 : 0, 100 * d.used / peak).toFixed(1) + "%" : "0%";
|
||||
b.append(fill);
|
||||
b.title = d.known ? t("{date}: {n} credits", { date: dayName(d.date), n: num(d.used) }) : t("{date}: not counted — magpie began counting on {since}", { date: dayName(d.date), since: dayName(new Date(since + "T12:00:00")) });
|
||||
b.title = d.known ? t(unit ? "{date}: {n} spent" : "{date}: {n} credits", { date: dayName(d.date), n: num(d.used) }) : t("{date}: not counted — magpie began counting on {since}", { date: dayName(d.date), since: dayName(new Date(since + "T12:00:00")) });
|
||||
bars.append(b);
|
||||
}
|
||||
box.append(bars);
|
||||
|
||||
@@ -3127,6 +3127,8 @@ const I18N = {
|
||||
// Gateway: routing, live
|
||||
"Hide accounts": "账号打码",
|
||||
"Credits used per day": "每天用掉的积分",
|
||||
"Spent per day": "每天花掉的金额",
|
||||
"{date}: {n} spent": "{date}:花掉 {n}",
|
||||
"Left over time": "剩余额度走势",
|
||||
"Balance over time": "余额走势",
|
||||
"Runs out {in} at this pace": "按此速度,预计 {in}用完",
|
||||
@@ -7106,6 +7108,8 @@ const I18N = {
|
||||
"Saved": "已儲存",
|
||||
"Hide accounts": "帳號打碼",
|
||||
"Credits used per day": "每天用掉的積分",
|
||||
"Spent per day": "每天花掉的金額",
|
||||
"{date}: {n} spent": "{date}:花掉 {n}",
|
||||
"Left over time": "剩餘額度走勢",
|
||||
"Balance over time": "餘額走勢",
|
||||
"Runs out {in} at this pace": "按此速度,預計 {in}用完",
|
||||
@@ -11098,6 +11102,8 @@ const I18N = {
|
||||
"Saved": "保存しました",
|
||||
"Hide accounts": "アカウントを隠す",
|
||||
"Credits used per day": "1 日あたりのクレジット使用量",
|
||||
"Spent per day": "1 日あたりの支出",
|
||||
"{date}: {n} spent": "{date}:{n} 使用",
|
||||
"Left over time": "残量の推移",
|
||||
"Balance over time": "残高の推移",
|
||||
"Runs out {in} at this pace": "このペースだと {in}に尽きる見込み",
|
||||
@@ -15100,6 +15106,8 @@ const I18N = {
|
||||
"Saved": "Gespeichert",
|
||||
"Hide accounts": "Konten verbergen",
|
||||
"Credits used per day": "Verbrauchte Credits pro Tag",
|
||||
"Spent per day": "Ausgaben pro Tag",
|
||||
"{date}: {n} spent": "{date}: {n} ausgegeben",
|
||||
"Left over time": "Rest im Zeitverlauf",
|
||||
"Balance over time": "Guthaben im Zeitverlauf",
|
||||
"Runs out {in} at this pace": "Bei diesem Tempo leer {in}",
|
||||
|
||||
@@ -96,3 +96,58 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Every credit-based provider (#3321), not WorkBuddy alone: a plugin's card
|
||||
// (Trae CN) gets the same bars; a card with two pools (Qoder's Credits and
|
||||
// Add-on credits) shows each on its own, named; a meter in money (Cursor's
|
||||
// On-demand) is spent, in its currency, not credits. Every language, at a
|
||||
// phone's width.
|
||||
const pools = () => [
|
||||
{ provider: "trae-cn", name: "Trae CN", plan: "Pro", user: "trae@x", windows: [{ name: "Credits", used: 10, amount: 100, limit: 1000, unit: "credits" }],
|
||||
daily: { since: dayKey(2), days: [{ day: dayKey(0), used: 7 }], window: "Credits" } },
|
||||
{ provider: "qoder", name: "Qoder", plan: "Pro", user: "q@x", windows: [{ name: "Credits", used: 10, display: "300 / 3000 credits" }, { name: "Add-on credits", used: 50, display: "50 / 100 credits" }],
|
||||
daily: { since: dayKey(2), days: [{ day: dayKey(0), used: 4 }], window: "Credits" },
|
||||
moreDaily: [{ since: dayKey(2), days: [{ day: dayKey(0), used: 9 }], window: "Add-on credits" }] },
|
||||
{ provider: "cursor", name: "Cursor", plan: "Pro", user: "c@x", windows: [{ name: "On-demand", used: 25, display: "$5 / $20" }],
|
||||
daily: { since: dayKey(2), days: [{ day: dayKey(0), used: 2.5 }], window: "On-demand", unit: "usd" } },
|
||||
];
|
||||
const poolWords = {
|
||||
en: { head: "Credits used per day", spent: "Spent per day", day1: "Today" },
|
||||
zh: { head: "每天用掉的积分", spent: "每天花掉的金额", day1: "今天" },
|
||||
"zh-TW": { head: "每天用掉的積分", spent: "每天花掉的金額", day1: "今天" },
|
||||
ja: { head: "1 日あたりのクレジット使用量", spent: "1 日あたりの支出", day1: "今日" },
|
||||
de: { head: "Verbrauchte Credits pro Tag", spent: "Ausgaben pro Tag", day1: "Heute" },
|
||||
};
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of Object.keys(poolWords)) {
|
||||
const w = poolWords[lang];
|
||||
test(`${engine} ${lang}: every provider's credits a day, pool by pool`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await (await browser.newContext({ viewport: { width: 360, height: 760 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", async (route) => {
|
||||
if (new URL(route.request().url()).pathname === "/api/usage/quotas") return route.fulfill({ json: pools() });
|
||||
return serve(lang)(route);
|
||||
});
|
||||
await page.goto("http://magpie.test/?view=usage");
|
||||
const today = page.locator("#period .opt").filter({ hasText: new RegExp("^" + w.day1 + "$") });
|
||||
if (await today.count()) await today.first().click();
|
||||
const heads = (name) => page.locator(".subscription-card", { hasText: name }).locator(".credit-days .cd-head span").allTextContents();
|
||||
await page.locator(".subscription-card", { hasText: "Cursor" }).locator(".credit-days").waitFor();
|
||||
assert.deepEqual(await heads("Trae CN"), [w.head]);
|
||||
const q = await heads("Qoder");
|
||||
assert.equal(q.length, 2);
|
||||
assert.ok(q[0].startsWith(w.head + " · ") && q[1].startsWith(w.head + " · ") && q[0] !== q[1], q.join(" | "));
|
||||
assert.deepEqual(await heads("Cursor"), [w.spent]);
|
||||
const spent = await page.locator(".subscription-card", { hasText: "Cursor" }).locator(".credit-days .cd-head b").textContent();
|
||||
assert.match(spent, /2[.,]50/);
|
||||
assert.match(spent, /\$/);
|
||||
const wide = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
|
||||
assert.ok(wide <= 0, `no page scroll sideways (${wide}px)`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,35 @@
|
||||
package provider
|
||||
|
||||
// How many of its credits a WorkBuddy account used each day (#568).
|
||||
// WorkBuddy's meter tells only what the cycle has used so far against what
|
||||
// it grants ("500.52 / 5600"), the built-in's and its plugin's card alike,
|
||||
// so each reading of it is kept beside the one before, and what was used
|
||||
// in between is counted on the day of the later one. That is the whole of
|
||||
// it while magpie reads the meter (whenever the Usage page, the tray or
|
||||
// routing asks, a minute apart at most); what is used while it doesn't is
|
||||
// counted on the day it next does.
|
||||
// How many of its credits an account used each day (#568, #3321). A
|
||||
// vendor's meter tells only what the cycle has used so far against what it
|
||||
// grants ("500.52 / 5600"), so each reading of it is kept beside the one
|
||||
// before, and what was used in between is counted on the day of the later
|
||||
// one. That is the whole of it while magpie reads the meter (whenever the
|
||||
// Usage page, the tray or routing asks, a minute apart at most); what is
|
||||
// used while it doesn't is counted on the day it next does.
|
||||
//
|
||||
// Which windows are credits is told by their shape, not by the vendor: a
|
||||
// count of used against granted (amount of limit, or a display "x / y")
|
||||
// in credits (積分, credits) or money ($, usd, ¥), from its unit, the
|
||||
// display's own word or symbol, or else its name. A share alone, tokens,
|
||||
// requests or a balance with nothing granted count nothing. Each such
|
||||
// window is counted on its own, by provider, account and window name, so
|
||||
// a card's several pools (Qoder's Add-on credits, Kiro's Free trial) never
|
||||
// mix. A pool's breakdown set aside (CodeArts' buckets under its total)
|
||||
// counts only when the card has nothing else, and of one allowance seen
|
||||
// over several spans (Open Design's 5 hours and week) only the longest.
|
||||
//
|
||||
// A reading that has used less than the one before is a cycle started
|
||||
// again or a credit pack gone: what was used between the two can't be
|
||||
// told apart from what went, so nothing is counted for it and the new
|
||||
// reading is where counting goes on from. A pack added (a check-in's
|
||||
// credits, one bought) only grows what is granted, which counts nothing.
|
||||
// A reading that failed, or one kept from before, is no reading.
|
||||
//
|
||||
// Kept in credits-daily.json, by provider and account name, the readings
|
||||
// and the days' sums only — no token, nothing of the vendor's but the two
|
||||
// figures.
|
||||
// Kept in credits-daily.json, by provider, account and window name, the
|
||||
// readings and the days' sums only — no token, nothing of the vendor's but
|
||||
// the two figures. WorkBuddy's, kept by provider and account alone before
|
||||
// #3321, are its Credits window's.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
@@ -35,7 +47,8 @@ import (
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
)
|
||||
|
||||
// DailyCredits is what an account's credits went to day by day.
|
||||
// DailyCredits is what one of an account's credits windows went to day
|
||||
// by day.
|
||||
type DailyCredits struct {
|
||||
// Since is the day magpie first read the account's credits: the days
|
||||
// before it aren't known, not unused.
|
||||
@@ -43,6 +56,11 @@ type DailyCredits struct {
|
||||
// Days are the days of the last creditsShown with credits used, oldest
|
||||
// first.
|
||||
Days []DayCredits `json:"days"`
|
||||
// Window is the card's window they are of ("Credits", "Add-on
|
||||
// credits"), and Unit a currency's code when it counts money ("usd"),
|
||||
// "" when credits.
|
||||
Window string `json:"window,omitempty"`
|
||||
Unit string `json:"unit,omitempty"`
|
||||
}
|
||||
|
||||
// DayCredits is one day's credits used ("2006-01-02", the local day).
|
||||
@@ -82,43 +100,179 @@ func parseCredits(b []byte) (map[string]*creditsAccount, error) {
|
||||
return accts, nil
|
||||
}
|
||||
|
||||
// creditsCounted says whether q's credits are counted by the day:
|
||||
// WorkBuddy's, either build, built-in or its plugin's.
|
||||
func creditsCounted(q SubscriptionQuota) bool {
|
||||
return q.Provider == wbCN.id || q.Provider == wbAI.id || strings.HasPrefix(q.Provider, wbCN.id+"-")
|
||||
// creditWindow is a window of a card that counts credits (or money):
|
||||
// used of total, in unit ("credits", or a currency's code in lower case).
|
||||
type creditWindow struct {
|
||||
name, unit string
|
||||
used, total float64
|
||||
aside bool
|
||||
span time.Duration
|
||||
}
|
||||
|
||||
func creditsKey(q SubscriptionQuota) string {
|
||||
// creditUnit is what a window's unit, or a display's word or symbol, says
|
||||
// it counts: "credits", a currency ("usd", "cny", "eur"), or "" for
|
||||
// anything else (tokens, requests, ACUs) and nothing said.
|
||||
func creditUnit(s string) string {
|
||||
s = strings.ToLower(strings.TrimSpace(s))
|
||||
switch s {
|
||||
case "":
|
||||
return ""
|
||||
case "$", "usd", "us$", "dollar", "dollars":
|
||||
return "usd"
|
||||
case "¥", "¥", "cny", "rmb", "元", "yuan":
|
||||
return "cny"
|
||||
case "€", "eur", "euro", "euros":
|
||||
return "eur"
|
||||
}
|
||||
if strings.Contains(s, "credit") || strings.Contains(s, "积分") || strings.Contains(s, "積分") || strings.Contains(s, "点数") {
|
||||
return "credits"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// creditsDisplay is "used / total" with what vendors put about it: a
|
||||
// currency sign, thousands' commas, a compact K/M/B/万/亿, an exponent
|
||||
// (Qoder's 1.5e+06), and a unit word after; a note after a " · " (CodeArts'
|
||||
// "· 300 即将过期", JoyCode's "· 剩余 …") is cut before it is read.
|
||||
var creditsDisplay = regexp.MustCompile(`(?i)^\s*([$¥¥€])?\s*([\d.,]*\d(?:e[+-]?\d+)?)\s*([kmb]\b|万|亿)?\s*/\s*([$¥¥€])?\s*([\d.,]*\d(?:e[+-]?\d+)?)\s*([kmb]\b|万|亿)?\s*(.*?)\s*$`)
|
||||
|
||||
func creditsNumber(n, scale string) (float64, bool) {
|
||||
if strings.Count(n, ".") > 1 {
|
||||
return 0, false
|
||||
}
|
||||
v, err := strconv.ParseFloat(strings.ReplaceAll(n, ",", ""), 64)
|
||||
if err != nil || math.IsNaN(v) || math.IsInf(v, 0) {
|
||||
return 0, false
|
||||
}
|
||||
switch strings.ToLower(scale) {
|
||||
case "k":
|
||||
v *= 1e3
|
||||
case "m":
|
||||
v *= 1e6
|
||||
case "b":
|
||||
v *= 1e9
|
||||
case "万":
|
||||
v *= 1e4
|
||||
case "亿":
|
||||
v *= 1e8
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
|
||||
// displayCredits reads a display "used / total": the two figures and the
|
||||
// unit its symbol or word names ("" when it names none).
|
||||
func displayCredits(d string) (used, total float64, unit string, ok bool) {
|
||||
if i := strings.Index(d, "·"); i >= 0 {
|
||||
d = d[:i]
|
||||
}
|
||||
m := creditsDisplay.FindStringSubmatch(d)
|
||||
if m == nil {
|
||||
return 0, 0, "", false
|
||||
}
|
||||
u, ok1 := creditsNumber(m[2], m[3])
|
||||
t, ok2 := creditsNumber(m[5], m[6])
|
||||
if !ok1 || !ok2 {
|
||||
return 0, 0, "", false
|
||||
}
|
||||
sign := m[1]
|
||||
if sign == "" {
|
||||
sign = m[4]
|
||||
}
|
||||
if sign != "" {
|
||||
unit = creditUnit(sign)
|
||||
} else if m[7] != "" {
|
||||
unit = creditUnit(m[7])
|
||||
if unit == "" {
|
||||
unit = "-" // a word, and not credits: tokens, requests
|
||||
}
|
||||
}
|
||||
return u, t, unit, true
|
||||
}
|
||||
|
||||
// creditOf is w as a credits window, when it is one: a count of used
|
||||
// against granted, in credits or money.
|
||||
func creditOf(w QuotaWindow) (creditWindow, bool) {
|
||||
if w.Unlimited || w.Text || w.Family != "" {
|
||||
return creditWindow{}, false
|
||||
}
|
||||
c := creditWindow{name: w.Name, aside: w.Aside, span: w.Span}
|
||||
shown := ""
|
||||
if w.Limit > 0 {
|
||||
c.used, c.total = w.Amount, w.Limit
|
||||
} else {
|
||||
u, t, unit, ok := displayCredits(w.Display)
|
||||
if !ok {
|
||||
return creditWindow{}, false // a share alone
|
||||
}
|
||||
c.used, c.total, shown = u, t, unit
|
||||
}
|
||||
switch {
|
||||
case w.Unit != "":
|
||||
c.unit = creditUnit(w.Unit)
|
||||
case shown == "" && w.Limit > 0:
|
||||
// amount of limit and no unit: the display may still say it
|
||||
if _, _, unit, ok := displayCredits(w.Display); ok {
|
||||
shown = unit
|
||||
}
|
||||
fallthrough
|
||||
default:
|
||||
if shown == "-" {
|
||||
return creditWindow{}, false
|
||||
}
|
||||
c.unit = shown
|
||||
if c.unit == "" {
|
||||
c.unit = creditUnit(w.Name)
|
||||
}
|
||||
}
|
||||
if c.unit == "" || c.total <= 0 || c.used < 0 || math.IsNaN(c.used) || math.IsInf(c.used, 0) || math.IsInf(c.total, 0) {
|
||||
return creditWindow{}, false
|
||||
}
|
||||
return c, true
|
||||
}
|
||||
|
||||
// creditWindows are q's windows counted by the day, from a reading just
|
||||
// made: none of a card that failed or one kept from before.
|
||||
func creditWindows(q SubscriptionQuota) []creditWindow {
|
||||
if q.Error != "" || q.AsOf != nil {
|
||||
return nil // a reading kept from before isn't a new one
|
||||
}
|
||||
var all []creditWindow
|
||||
for _, w := range q.Windows {
|
||||
if c, ok := creditOf(w); ok && !slices.ContainsFunc(all, func(x creditWindow) bool { return x.name == c.name }) {
|
||||
all = append(all, c)
|
||||
}
|
||||
}
|
||||
// a pool's breakdown set aside counts only when nothing else does:
|
||||
// CodeArts' buckets are its total's credits again
|
||||
if slices.ContainsFunc(all, func(c creditWindow) bool { return !c.aside }) {
|
||||
all = slices.DeleteFunc(all, func(c creditWindow) bool { return c.aside })
|
||||
}
|
||||
// one allowance over several spans (5 hours, a week): the longest's
|
||||
// count alone, which a rolling short one's drops don't cut into
|
||||
for i := 0; i < len(all); i++ {
|
||||
for j := range all {
|
||||
if j != i && all[i].span > 0 && all[j].unit == all[i].unit && all[j].span > all[i].span {
|
||||
all = slices.Delete(all, i, i+1)
|
||||
i--
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return all
|
||||
}
|
||||
|
||||
func creditsKey(q SubscriptionQuota, window string) string {
|
||||
return q.Provider + "|" + strings.ToLower(q.User) + "|" + window
|
||||
}
|
||||
|
||||
// creditsOldKey is where an account's credits were kept before #3321,
|
||||
// WorkBuddy's alone, its one Credits window's.
|
||||
func creditsOldKey(q SubscriptionQuota) string {
|
||||
return q.Provider + "|" + strings.ToLower(q.User)
|
||||
}
|
||||
|
||||
var creditsDisplay = regexp.MustCompile(`^\s*([\d.,]+)\s*/\s*([\d.,]+)\s*$`)
|
||||
|
||||
// creditsOf is what q's credits window says: used and granted.
|
||||
func creditsOf(q SubscriptionQuota) (used, total float64, ok bool) {
|
||||
if q.Error != "" || q.AsOf != nil {
|
||||
return 0, 0, false // a reading kept from before isn't a new one
|
||||
}
|
||||
for _, w := range q.Windows {
|
||||
if w.Name != "Credits" {
|
||||
continue
|
||||
}
|
||||
m := creditsDisplay.FindStringSubmatch(w.Display)
|
||||
if m == nil {
|
||||
return 0, 0, false
|
||||
}
|
||||
u, err1 := strconv.ParseFloat(strings.ReplaceAll(m[1], ",", ""), 64)
|
||||
t, err2 := strconv.ParseFloat(strings.ReplaceAll(m[2], ",", ""), 64)
|
||||
if err1 != nil || err2 != nil || t <= 0 {
|
||||
return 0, 0, false
|
||||
}
|
||||
return u, t, true
|
||||
}
|
||||
return 0, 0, false
|
||||
}
|
||||
|
||||
// noteDailyCredits keeps the WorkBuddy accounts' readings among qs, made
|
||||
// at now, and counts what each used since its last.
|
||||
// noteDailyCredits keeps the readings of the credits windows among qs,
|
||||
// made at now, and counts what each used since its last.
|
||||
func noteDailyCredits(qs []SubscriptionQuota, now time.Time) {
|
||||
creditsMu.Lock()
|
||||
defer creditsMu.Unlock()
|
||||
@@ -130,33 +284,34 @@ func noteDailyCredits(qs []SubscriptionQuota, now time.Time) {
|
||||
day := now.Local().Format("2006-01-02")
|
||||
changed := false
|
||||
for _, q := range qs {
|
||||
if !creditsCounted(q) {
|
||||
continue
|
||||
}
|
||||
used, total, ok := creditsOf(q)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
key := creditsKey(q)
|
||||
a := accts[key]
|
||||
if a == nil {
|
||||
a = &creditsAccount{Since: day}
|
||||
accts[key] = a
|
||||
a.Last = creditsReading{Used: used, Total: total, At: now}
|
||||
changed = true
|
||||
continue
|
||||
}
|
||||
if used == a.Last.Used && total == a.Last.Total {
|
||||
continue
|
||||
}
|
||||
if d := used - a.Last.Used; d > 0 {
|
||||
if a.Days == nil {
|
||||
a.Days = map[string]float64{}
|
||||
for _, c := range creditWindows(q) {
|
||||
key := creditsKey(q, c.name)
|
||||
a := accts[key]
|
||||
if old := accts[creditsOldKey(q)]; a == nil && old != nil && c.name == "Credits" {
|
||||
a = old // kept before the window was named: carried over
|
||||
accts[key] = a
|
||||
delete(accts, creditsOldKey(q))
|
||||
changed = true
|
||||
}
|
||||
a.Days[day] = math.Round((a.Days[day]+d)*100) / 100
|
||||
if a == nil {
|
||||
a = &creditsAccount{Since: day}
|
||||
accts[key] = a
|
||||
a.Last = creditsReading{Used: c.used, Total: c.total, At: now}
|
||||
changed = true
|
||||
continue
|
||||
}
|
||||
if c.used == a.Last.Used && c.total == a.Last.Total {
|
||||
continue
|
||||
}
|
||||
if d := c.used - a.Last.Used; d > 0 {
|
||||
if a.Days == nil {
|
||||
a.Days = map[string]float64{}
|
||||
}
|
||||
a.Days[day] = math.Round((a.Days[day]+d)*100) / 100
|
||||
}
|
||||
a.Last = creditsReading{Used: c.used, Total: c.total, At: now}
|
||||
changed = true
|
||||
}
|
||||
a.Last = creditsReading{Used: used, Total: total, At: now}
|
||||
changed = true
|
||||
}
|
||||
if !changed {
|
||||
return
|
||||
@@ -182,9 +337,10 @@ func noteDailyCredits(qs []SubscriptionQuota, now time.Time) {
|
||||
_ = writeFileAtomic(path, b)
|
||||
}
|
||||
|
||||
// withDailyCredits gives each WorkBuddy card in qs its days, as kept.
|
||||
// withDailyCredits gives each card in qs the days of its credits windows,
|
||||
// as kept: Daily the first's, MoreDaily the rest's.
|
||||
func withDailyCredits(qs []SubscriptionQuota, now time.Time) []SubscriptionQuota {
|
||||
if !slices.ContainsFunc(qs, creditsCounted) {
|
||||
if !slices.ContainsFunc(qs, func(q SubscriptionQuota) bool { return slices.ContainsFunc(q.Windows, isCreditWindow) }) {
|
||||
return qs
|
||||
}
|
||||
// read only: the parse is shared until the file changes
|
||||
@@ -195,18 +351,39 @@ func withDailyCredits(qs []SubscriptionQuota, now time.Time) []SubscriptionQuota
|
||||
cut := now.Local().AddDate(0, 0, -creditsShown).Format("2006-01-02")
|
||||
out := slices.Clone(qs)
|
||||
for i, q := range out {
|
||||
a := accts[creditsKey(q)]
|
||||
if !creditsCounted(q) || a == nil {
|
||||
continue
|
||||
}
|
||||
d := &DailyCredits{Since: a.Since, Days: []DayCredits{}}
|
||||
for day, used := range a.Days {
|
||||
if day >= cut && used > 0 {
|
||||
d.Days = append(d.Days, DayCredits{Day: day, Used: used})
|
||||
var all []*DailyCredits
|
||||
for _, w := range q.Windows {
|
||||
c, ok := creditOf(w)
|
||||
if !ok || slices.ContainsFunc(all, func(d *DailyCredits) bool { return d.Window == c.name }) {
|
||||
continue
|
||||
}
|
||||
a := accts[creditsKey(q, c.name)]
|
||||
if a == nil && c.name == "Credits" {
|
||||
a = accts[creditsOldKey(q)] // not yet carried over
|
||||
}
|
||||
if a == nil {
|
||||
continue
|
||||
}
|
||||
d := &DailyCredits{Since: a.Since, Days: []DayCredits{}, Window: c.name}
|
||||
if c.unit != "credits" {
|
||||
d.Unit = c.unit
|
||||
}
|
||||
for day, used := range a.Days {
|
||||
if day >= cut && used > 0 {
|
||||
d.Days = append(d.Days, DayCredits{Day: day, Used: used})
|
||||
}
|
||||
}
|
||||
slices.SortFunc(d.Days, func(x, y DayCredits) int { return strings.Compare(x.Day, y.Day) })
|
||||
all = append(all, d)
|
||||
}
|
||||
if len(all) > 0 {
|
||||
out[i].Daily = all[0]
|
||||
}
|
||||
if len(all) > 1 {
|
||||
out[i].MoreDaily = all[1:]
|
||||
}
|
||||
slices.SortFunc(d.Days, func(x, y DayCredits) int { return strings.Compare(x.Day, y.Day) })
|
||||
out[i].Daily = d
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func isCreditWindow(w QuotaWindow) bool { _, ok := creditOf(w); return ok }
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// pluginWindowsCard is a card as quotaOfPlugin makes it from a plugin's usage,
|
||||
// the windows given as the plugin's own JSON.
|
||||
func pluginWindowsCard(t *testing.T, provider, user, windows string) SubscriptionQuota {
|
||||
t.Helper()
|
||||
var u plugin.Usage
|
||||
if err := json.Unmarshal([]byte(`{"windows":`+windows+`}`), &u); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return quotaOfPlugin(SubscriptionQuota{Provider: provider, User: user}, u)
|
||||
}
|
||||
|
||||
// TestCreditWindowShapes: a window is counted by the day by its shape,
|
||||
// whoever sends it: a count of used against granted in credits or money,
|
||||
// from amount of limit or a display "x / y" with what vendors write about
|
||||
// it, and never a share alone, tokens, requests, ACUs or a balance (#3321).
|
||||
// Each window is as its plugin (magpie-community/plugins) makes it.
|
||||
func TestCreditWindowShapes(t *testing.T) {
|
||||
cases := []struct {
|
||||
who, window string
|
||||
ok bool
|
||||
used, total float64
|
||||
unit string
|
||||
}{
|
||||
// workbuddy: display and amount of limit
|
||||
{"WorkBuddy", `{"name":"Credits","used":8.94,"display":"500.52 / 5600","amount":500.52,"limit":5600,"unit":"credits"}`, true, 500.52, 5600, "credits"},
|
||||
// trae (CN): amount of limit, no display
|
||||
{"Trae CN", `{"name":"Credits","used":71.43,"amount":4678.52,"limit":6550,"unit":"credits"}`, true, 4678.52, 6550, "credits"},
|
||||
// qoder: display alone, its unit in it
|
||||
{"Qoder", `{"name":"Credits","used":41.15,"display":"1234.5 / 3000 credits"}`, true, 1234.5, 3000, "credits"},
|
||||
{"Qoder, a big pool", `{"name":"Shared credits","used":75,"display":"1.5e+06 / 2e+06 credits"}`, true, 1.5e6, 2e6, "credits"},
|
||||
// opendesign: display alone
|
||||
{"Open Design", `{"name":"Week","used":12,"span":604800,"display":"120 / 1000 credits"}`, true, 120, 1000, "credits"},
|
||||
// mimo: display alone, compact
|
||||
{"MiMo", `{"name":"Token Plan","used":12.3,"display":"12.3M / 100M credits"}`, true, 12.3e6, 100e6, "credits"},
|
||||
// commandcode: dollars in the display, named Credits
|
||||
{"Command Code", `{"name":"Credits","used":24.68,"display":"$12.34 / $50.00"}`, true, 12.34, 50, "usd"},
|
||||
// codearts: compact display with a note, amount of limit exact
|
||||
{"CodeArts", `{"name":"总积分","used":40,"display":"1.2万 / 3万 · 300 即将过期","amount":12000,"limit":30000,"unit":"credits"}`, true, 12000, 30000, "credits"},
|
||||
{"a display with a note alone", `{"name":"Credits","used":24.68,"display":"1,234 / 5,000 · 300 即将过期"}`, true, 1234, 5000, "credits"},
|
||||
// joycode: 积分, and the rest after a ·
|
||||
{"JoyCode", `{"name":"通用积分","used":12,"amount":120,"limit":1000,"unit":"积分","display":"120 / 1,000 · 剩余 880"}`, true, 120, 1000, "credits"},
|
||||
// kiro, minimax, raccoon: amount of limit in credits
|
||||
{"Kiro", `{"name":"Credits","used":10,"display":"5.5 / 55","amount":5.5,"limit":55,"unit":"credits","span":2592000}`, true, 5.5, 55, "credits"},
|
||||
{"MiniMax", `{"name":"Credits","used":20,"display":"200 / 1000","amount":200,"limit":1000,"unit":"credits"}`, true, 200, 1000, "credits"},
|
||||
// cline: amount of limit, no unit, named Credits
|
||||
{"Cline", `{"name":"Credits","used":25,"limit":40,"amount":10,"display":"10 / 40"}`, true, 10, 40, "credits"},
|
||||
// trae (global): dollars by its unit
|
||||
{"Trae", `{"name":"Dollar Usage","used":30,"amount":6,"limit":20,"unit":"usd"}`, true, 6, 20, "usd"},
|
||||
// not credits
|
||||
{"Devin's ACUs", `{"name":"ACUs","used":5,"display":"12.5 / 250 ACUs"}`, false, 0, 0, ""},
|
||||
{"a share alone", `{"name":"Cursor Models","used":40}`, false, 0, 0, ""},
|
||||
{"CodeArts' free tokens", `{"name":"免费额度","used":10,"display":"10万 / 100万","amount":100000,"limit":1000000,"unit":"tokens","aside":true}`, false, 0, 0, ""},
|
||||
{"ZCode's prompts", `{"name":"5 hours","used":10,"amount":20,"limit":200,"display":"20 / 200","span":18000}`, false, 0, 0, ""},
|
||||
{"AutoClaw's balance", `{"name":"积分余额","used":0,"aside":true,"display":"1200"}`, false, 0, 0, ""},
|
||||
{"Cline's credits used", `{"name":"Credits","used":0,"aside":true,"display":"12 credits used"}`, false, 0, 0, ""},
|
||||
{"no figures", `{"name":"Credits","used":100,"display":"no credits left"}`, false, 0, 0, ""},
|
||||
{"nothing granted", `{"name":"Credits","used":0,"display":"0 / 0"}`, false, 0, 0, ""},
|
||||
}
|
||||
testenv.SetHome(t, t.TempDir())
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
now := time.Now()
|
||||
check := func(who string, q SubscriptionQuota, ok bool, used, total float64, unit string) {
|
||||
t.Helper()
|
||||
noteDailyCredits([]SubscriptionQuota{q}, now)
|
||||
b, _ := os.ReadFile(creditsPath())
|
||||
accts, _ := parseCredits(b)
|
||||
a := accts[q.Provider+"|u|"+q.Windows[0].Name]
|
||||
if (a != nil) != ok {
|
||||
t.Errorf("%s: counted %v, want %v", who, a != nil, ok)
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if a.Last.Used != used || a.Last.Total != total {
|
||||
t.Errorf("%s: read %v / %v, want %v / %v", who, a.Last.Used, a.Last.Total, used, total)
|
||||
}
|
||||
if unit == "credits" {
|
||||
unit = ""
|
||||
}
|
||||
if d := withDailyCredits([]SubscriptionQuota{q}, now)[0].Daily; d == nil || d.Unit != unit || d.Window != q.Windows[0].Name {
|
||||
t.Errorf("%s: the card's days %+v, want in %q", who, d, unit)
|
||||
}
|
||||
}
|
||||
for i, c := range cases {
|
||||
check(c.who, pluginWindowsCard(t, fmt.Sprintf("p%d", i), "u", "["+c.window+"]"), c.ok, c.used, c.total, c.unit)
|
||||
}
|
||||
// copilot's built-in premium requests: a count, of requests
|
||||
check("Copilot", SubscriptionQuota{Provider: "copilot", User: "u", Windows: []QuotaWindow{{Name: "Premium requests", Used: 40, Display: "120 / 300"}}}, false, 0, 0, "")
|
||||
}
|
||||
|
||||
// TestDailyCreditsEveryVendor: any card with a credits window has its
|
||||
// days, a plugin's without a display too (Trae CN, #3321); each pool of a
|
||||
// card is counted on its own, a breakdown set aside and the shorter spans
|
||||
// of one allowance aren't, and a total started again counts nothing.
|
||||
func TestDailyCreditsEveryVendor(t *testing.T) {
|
||||
testenv.SetHome(t, t.TempDir())
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
day := func(d, h int) time.Time { return time.Date(2026, 10, d, h, 0, 0, 0, time.Local) }
|
||||
trae := func(used float64) SubscriptionQuota {
|
||||
return pluginWindowsCard(t, "trae-cn", "Moxuan", `[{"name":"Credits","used":10,"amount":`+jsonNum(used)+`,"limit":6550,"unit":"credits"}]`)
|
||||
}
|
||||
qoder := func(main, addon float64) SubscriptionQuota {
|
||||
return pluginWindowsCard(t, "qoder", "me@x.com", `[{"name":"Credits","used":10,"display":"`+jsonNum(main)+` / 3000 credits"},{"name":"Add-on credits","used":10,"display":"`+jsonNum(addon)+` / 1000 credits"}]`)
|
||||
}
|
||||
codearts := func(total, basic float64) SubscriptionQuota {
|
||||
return pluginWindowsCard(t, "codearts", "hw", `[{"name":"总积分","used":10,"amount":`+jsonNum(total)+`,"limit":30000,"unit":"credits","display":"x"},{"name":"基础积分","used":10,"amount":`+jsonNum(basic)+`,"limit":10000,"unit":"credits","aside":true}]`)
|
||||
}
|
||||
design := func(hours, week float64) SubscriptionQuota {
|
||||
return pluginWindowsCard(t, "opendesign", "d", `[{"name":"5 hours","used":1,"span":18000,"display":"`+jsonNum(hours)+` / 100 credits"},{"name":"Week","used":1,"span":604800,"display":"`+jsonNum(week)+` / 1000 credits"}]`)
|
||||
}
|
||||
read := func(at time.Time, qs ...SubscriptionQuota) { noteDailyCredits(qs, at) }
|
||||
read(day(1, 9), trae(4600), qoder(100, 0), codearts(1000, 500), design(10, 200))
|
||||
read(day(1, 12), trae(4678.52), qoder(130, 20), codearts(1300, 700), design(30, 220))
|
||||
// a new month: Trae's total started again, CodeArts' too
|
||||
read(day(2, 1), trae(5), qoder(130, 20), codearts(0, 0), design(0, 220))
|
||||
read(day(2, 9), trae(40), qoder(160, 20), codearts(50, 50), design(15, 235))
|
||||
// an error and a reading kept from before count nothing
|
||||
errd := trae(6000)
|
||||
errd.Error = "Trae: 401"
|
||||
kept := trae(6000)
|
||||
asOf := day(2, 9)
|
||||
kept.AsOf = &asOf
|
||||
read(day(2, 10), errd, kept)
|
||||
|
||||
got := withDailyCredits([]SubscriptionQuota{trae(40), qoder(160, 20), codearts(50, 50), design(15, 235)}, day(2, 12))
|
||||
want := map[string][]*DailyCredits{
|
||||
"Moxuan": {{Since: "2026-10-01", Days: []DayCredits{{"2026-10-01", 78.52}, {"2026-10-02", 35}}, Window: "Credits"}},
|
||||
"me@x.com": {{Since: "2026-10-01", Days: []DayCredits{{"2026-10-01", 30}, {"2026-10-02", 30}}, Window: "Credits"}, {Since: "2026-10-01", Days: []DayCredits{{"2026-10-01", 20}}, Window: "Add-on credits"}},
|
||||
"hw": {{Since: "2026-10-01", Days: []DayCredits{{"2026-10-01", 300}, {"2026-10-02", 50}}, Window: "总积分"}},
|
||||
"d": {{Since: "2026-10-01", Days: []DayCredits{{"2026-10-01", 20}, {"2026-10-02", 15}}, Window: "Week"}},
|
||||
}
|
||||
for _, q := range got {
|
||||
all := append([]*DailyCredits{q.Daily}, q.MoreDaily...)
|
||||
if !reflect.DeepEqual(all, want[q.User]) {
|
||||
b, _ := json.Marshal(all)
|
||||
w, _ := json.Marshal(want[q.User])
|
||||
t.Errorf("%s's days: %s, want %s", q.Provider, b, w)
|
||||
}
|
||||
}
|
||||
// money's days say their currency
|
||||
cc := pluginWindowsCard(t, "commandcode", "c", `[{"name":"Credits","used":1,"display":"$1.00 / $50.00"}]`)
|
||||
read(day(3, 9), cc)
|
||||
cc2 := pluginWindowsCard(t, "commandcode", "c", `[{"name":"Credits","used":1,"display":"$3.50 / $50.00"}]`)
|
||||
read(day(3, 10), cc2)
|
||||
if d := withDailyCredits([]SubscriptionQuota{cc2}, day(3, 11))[0].Daily; d == nil || d.Unit != "usd" || len(d.Days) != 1 || d.Days[0].Used != 2.5 {
|
||||
t.Errorf("Command Code's days: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func jsonNum(f float64) string { b, _ := json.Marshal(f); return string(b) }
|
||||
|
||||
// TestDailyCreditsKeptBefore: WorkBuddy's days, kept by provider and
|
||||
// account alone before #3321, are still its card's, and counting goes on
|
||||
// from its last reading under the window's own name.
|
||||
func TestDailyCreditsKeptBefore(t *testing.T) {
|
||||
testenv.SetHome(t, t.TempDir())
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
day := func(d, h int) time.Time { return time.Date(2026, 10, d, h, 0, 0, 0, time.Local) }
|
||||
old := `{
|
||||
"workbuddy|李雷": {
|
||||
"since": "2026-09-20",
|
||||
"last": {"used": 130.25, "total": 5600, "at": "2026-10-01T23:00:00+08:00"},
|
||||
"days": {"2026-09-20": 12.5, "2026-10-01": 30.25}
|
||||
}
|
||||
}`
|
||||
if err := os.MkdirAll(filepath.Dir(creditsPath()), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(creditsPath(), []byte(old), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
card := wbCard("workbuddy", "李雷", 130.25, 5600)
|
||||
want := &DailyCredits{Since: "2026-09-20", Days: []DayCredits{{"2026-09-20", 12.5}, {"2026-10-01", 30.25}}, Window: "Credits"}
|
||||
if d := withDailyCredits([]SubscriptionQuota{card}, day(2, 9))[0].Daily; !reflect.DeepEqual(d, want) {
|
||||
t.Errorf("before a new reading: %+v, want %+v", d, want)
|
||||
}
|
||||
noteDailyCredits([]SubscriptionQuota{wbCard("workbuddy", "李雷", 140.25, 5600)}, day(2, 10))
|
||||
want.Days = append(want.Days, DayCredits{"2026-10-02", 10})
|
||||
if d := withDailyCredits([]SubscriptionQuota{card}, day(2, 11))[0].Daily; !reflect.DeepEqual(d, want) {
|
||||
t.Errorf("after: %+v, want %+v", d, want)
|
||||
}
|
||||
b, _ := os.ReadFile(creditsPath())
|
||||
var kept map[string]json.RawMessage
|
||||
if err := json.Unmarshal(b, &kept); err != nil || len(kept) != 1 || kept["workbuddy|李雷|Credits"] == nil {
|
||||
t.Errorf("the file: %s", b)
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,12 @@ func wbCard(provider, user string, used, total float64) SubscriptionQuota {
|
||||
Windows: []QuotaWindow{{Name: "Credits", Used: 100 * used / total, Display: compactNumber(used) + " / " + compactNumber(total)}}}
|
||||
}
|
||||
|
||||
// shareCard is a card whose one window tells a share alone (Cursor's,
|
||||
// Grok's): no count, nothing to count by the day.
|
||||
func shareCard(provider, user string, used float64) SubscriptionQuota {
|
||||
return SubscriptionQuota{Provider: provider, User: user, Windows: []QuotaWindow{{Name: "Cursor Models", Used: used}}}
|
||||
}
|
||||
|
||||
func dailyOf(t *testing.T, qs []SubscriptionQuota, user string) *DailyCredits {
|
||||
t.Helper()
|
||||
for _, q := range qs {
|
||||
@@ -53,7 +59,8 @@ func TestDailyCredits(t *testing.T) {
|
||||
noteDailyCredits([]SubscriptionQuota{wbCard("workbuddy", "李雷", s.used, s.tot)}, s.at)
|
||||
}
|
||||
// another account, the AI build's through its plugin; an error and a
|
||||
// card kept from before count nothing; another vendor isn't counted
|
||||
// card kept from before count nothing; a window telling a share alone
|
||||
// isn't counted
|
||||
noteDailyCredits([]SubscriptionQuota{wbCard("workbuddy-ai", "138****5678", 10, 3000)}, day(4, 9))
|
||||
noteDailyCredits([]SubscriptionQuota{wbCard("workbuddy-ai", "138****5678", 15, 3000)}, day(4, 10))
|
||||
errd := wbCard("workbuddy-ai", "138****5678", 999, 3000)
|
||||
@@ -61,21 +68,21 @@ func TestDailyCredits(t *testing.T) {
|
||||
asOf := day(4, 11)
|
||||
kept := wbCard("workbuddy-ai", "138****5678", 900, 3000)
|
||||
kept.AsOf = &asOf
|
||||
noteDailyCredits([]SubscriptionQuota{errd, kept, wbCard("cursor", "x", 5, 10)}, day(4, 12))
|
||||
noteDailyCredits([]SubscriptionQuota{errd, kept, shareCard("cursor", "x", 50)}, day(4, 12))
|
||||
noteDailyCredits([]SubscriptionQuota{wbCard("workbuddy-ai", "138****5678", 18, 3000)}, day(4, 13))
|
||||
|
||||
cards := []SubscriptionQuota{wbCard("workbuddy", "李雷", 70, 5600), wbCard("workbuddy-ai", "138****5678", 18, 3000), wbCard("cursor", "x", 5, 10)}
|
||||
cards := []SubscriptionQuota{wbCard("workbuddy", "李雷", 70, 5600), wbCard("workbuddy-ai", "138****5678", 18, 3000), shareCard("cursor", "x", 50)}
|
||||
got := withDailyCredits(cards, day(5, 13))
|
||||
want := &DailyCredits{Since: "2026-10-01", Days: []DayCredits{{"2026-10-01", 30.25}, {"2026-10-02", 30}, {"2026-10-03", 6}, {"2026-10-05", 60}}}
|
||||
want := &DailyCredits{Since: "2026-10-01", Days: []DayCredits{{"2026-10-01", 30.25}, {"2026-10-02", 30}, {"2026-10-03", 6}, {"2026-10-05", 60}}, Window: "Credits"}
|
||||
if d := dailyOf(t, got, "李雷"); !reflect.DeepEqual(d, want) {
|
||||
t.Errorf("WorkBuddy's days: %+v, want %+v", d, want)
|
||||
}
|
||||
want = &DailyCredits{Since: "2026-10-04", Days: []DayCredits{{"2026-10-04", 8}}}
|
||||
want = &DailyCredits{Since: "2026-10-04", Days: []DayCredits{{"2026-10-04", 8}}, Window: "Credits"}
|
||||
if d := dailyOf(t, got, "138****5678"); !reflect.DeepEqual(d, want) {
|
||||
t.Errorf("WorkBuddy AI's days: %+v, want %+v", d, want)
|
||||
}
|
||||
if d := dailyOf(t, got, "x"); d != nil {
|
||||
t.Errorf("another vendor's card has days: %+v", d)
|
||||
t.Errorf("a share alone has days: %+v", d)
|
||||
}
|
||||
if cards[0].Daily != nil {
|
||||
t.Error("the cards given were changed")
|
||||
|
||||
@@ -174,9 +174,11 @@ type SubscriptionQuota struct {
|
||||
// now (codexHeld): not on a window at 100% alone, which credits get
|
||||
// past.
|
||||
Held bool `json:"held,omitempty"`
|
||||
// Daily is a WorkBuddy account's credits used day by day, as magpie
|
||||
// counted them from its readings (credits_daily.go).
|
||||
Daily *DailyCredits `json:"daily,omitempty"`
|
||||
// Daily is the account's credits used day by day, as magpie counted
|
||||
// them from its readings (credits_daily.go): its first credits
|
||||
// window's, and MoreDaily its other pools', each apart.
|
||||
Daily *DailyCredits `json:"daily,omitempty"`
|
||||
MoreDaily []*DailyCredits `json:"moreDaily,omitempty"`
|
||||
// Checkins is set on a WorkBuddy (China) or Trae CN account whose
|
||||
// daily check-in is pressed for, CheckinBy whose ("" WorkBuddy's,
|
||||
// "trae" Trae CN's), and Checkin is how its last one went, nil before
|
||||
|
||||
Reference in New Issue
Block a user