diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index f857cca09..1e45402e7 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -693,7 +693,7 @@ function renderUsage() { const hit = u.cache_read && hitRate !== null ? t("hit rate {p}", { p: Math.round(100 * hitRate) + "%" }) : ""; tile(fmtN(u.cache_read), t("cache read"), hit, u.cache_write ? t("{n} written", { n: fmtN(u.cache_write) }) + cacheTTLs(u, fmtN) : ""); tile(fmtN(u.reasoning), t("reasoning"), t("inside output")); - tile(String(u.calls), t(u.calls === 1 ? "call" : "calls"), [u.errors ? t("{n} failed", { n: u.errors }) : "", u.retried ? t("{n} answered on a retry", { n: u.retried }) : "", u.unpriced ? t("{n} unpriced", { n: u.unpriced }) : ""].filter(Boolean).join(" · "), u.unpriced ? unpricedCallsWhy(u.unpriced) : ""); + tile(String(u.calls), t(u.calls === 1 ? "call" : "calls"), [u.credited ? ledCredits(u).textContent : "", u.errors ? t("{n} failed", { n: u.errors }) : "", u.retried ? t("{n} answered on a retry", { n: u.retried }) : "", u.unpriced ? t("{n} unpriced", { n: u.unpriced }) : ""].filter(Boolean).join(" · "), u.unpriced ? unpricedCallsWhy(u.unpriced) : ""); // the timeline: one bar per hour, day or week; output sits on top of input const chart = $("#chart"); @@ -734,6 +734,10 @@ function renderUsage() { const sub = []; if (g.sub) sub.push(g.sub); sub.push(t(g.calls === 1 ? "{n} call" : "{n} calls", { n: g.calls })); + // what the calls cost in their plan's credits, as the replies said + // (WorkBuddy's 积分): an account's, a model's, an agent's (lcyksp + // on Discord), not only their tokens + if (g.credited) sub.push(ledCredits(g).textContent); // magpie's own calls apart from the agents' (#1839): magpie's row // says it is, and a model's, a key's or an account's how many of // its calls were diff --git a/internal/gui/tests/plan-credits.test.cjs b/internal/gui/tests/plan-credits.test.cjs index 5a6d87da0..c5e87ab62 100644 --- a/internal/gui/tests/plan-credits.test.cjs +++ b/internal/gui/tests/plan-credits.test.cjs @@ -49,7 +49,15 @@ const SESSION = { via: [{ provider: "workbuddy-ai", model: "gemini-3.5-flash", calls: 70, tokens: 1470, credits: 0.7000000000000005, credited: 70 }, { provider: "zai", model: "glm-5.2", calls: 3, tokens: 10 }], }; -function server(lang) { +// the Overview's summary: two WorkBuddy accounts whose replies said +// credits, and one Codex account's that said none (lcyksp on Discord: the +// 积分 each account spent, not only its tokens) +const acct = (id, provider, sub, calls, credits, credited) => ({ id: provider + "@" + id, provider, account: id, name: id, sub, icon: "generic", calls, errors: 0, input: 900 * calls, output: 100 * calls, cache_read: 0, cache_write: 0, cost: 0, ...(credited ? { credits, credited } : {}) }); +const ACCOUNTS = [acct("a@x.com", "workbuddy", "WorkBuddy", 70, 35, 70), acct("b@x.com", "workbuddy", "WorkBuddy", 2, 2.25, 1), acct("c@x.com", "codex", "Codex", 5)]; +const OVERVIEW = { calls: 77, errors: 0, input: 69300, output: 7700, reasoning: 0, unpriced: 77, cost: 0, cache_read: 0, cache_write: 0, credits: 37.25, credited: 71, bucket: "day", series: [], agents: [], models: [], accounts: ACCOUNTS, callerKeys: [], path: "~/.config/magpie/usage.jsonl" }; +const EMPTY = { calls: 0, errors: 0, input: 0, output: 0, reasoning: 0, unpriced: 0, cost: 0, bucket: "day", series: [], agents: [], models: [], path: "" }; + +function server(lang, usage = EMPTY) { return async (route) => { const url = new URL(route.request().url()); const json = (data) => route.fulfill({ json: data }); @@ -58,7 +66,7 @@ function server(lang) { if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); if (url.pathname === "/api/usage/requests") return json(ledger(url.searchParams.get("period"))); if (url.pathname === "/api/usage/quotas") return json([]); - if (url.pathname === "/api/usage") return json({ calls: 0, errors: 0, input: 0, output: 0, reasoning: 0, unpriced: 0, cost: 0, bucket: "day", series: [], agents: [], models: [], path: "" }); + if (url.pathname === "/api/usage") return json(usage); if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], models: [], gateway: { running: false } }); if (url.pathname === "/api/sessions") return json({ sessions: [SESSION], terminal: true, dirs: ["~/.codex/sessions"] }); if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} }); @@ -83,6 +91,54 @@ const L = { de: ["0,7 Credits", "0 Credits", /Credits/], }; +// each language's 35, 2.25 and 37.25 credits +const A = { + en: ["35 credits", "2.25 credits", "37.25 credits"], + zh: ["35 积分", "2.25 积分", "37.25 积分"], + "zh-TW": ["35 積分", "2.25 積分", "37.25 積分"], + ja: ["35 クレジット", "2.25 クレジット", "37.25 クレジット"], + de: ["35 Credits", "2,25 Credits", "37,25 Credits"], +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": the Overview says each account's credits and the period's", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const [lang, [a, b, all]] of Object.entries(A)) { + await t.test(lang, async () => { + const errors = []; + const ctx = await browser.newContext({ viewport: { width: 1100, height: 800 }, reducedMotion: "reduce" }); + const p = await ctx.newPage(); + p.setDefaultTimeout(5000); + p.setDefaultNavigationTimeout(60000); + p.on("pageerror", (e) => errors.push(e.message)); + await p.route("**/*", server(lang, OVERVIEW)); + await p.goto("http://magpie.test/?view=usage"); + await p.locator("#usageAccounts .row").first().waitFor(); + const subs = await p.locator("#usageAccounts .sub").allTextContents(); + assert.equal(subs.length, 3, subs.join(" | ")); + assert(subs[0].includes(a), "a@x.com's line: " + subs[0]); + assert(subs[1].includes(b), "b@x.com's line: " + subs[1]); + assert(!/credit|积分|積分|クレジット/i.test(subs[2]), "an account no reply said credits for: " + subs[2]); + const kpi = (await p.locator("#stats .kpi").nth(3).textContent()).trim(); + assert(kpi.includes(all), "the calls tile: " + kpi); + assert.equal(await p.locator("#stats .kpi").count(), 4, "no tile is added"); + // a narrow window keeps each line inside its row + await p.setViewportSize({ width: 420, height: 800 }); + await p.waitForTimeout(150); + const fits = await p.locator("#usageAccounts .row").evaluateAll((rs) => rs.every((r) => r.scrollWidth <= r.clientWidth + 1)); + assert(fits, "the accounts' rows fit a 420px window"); + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await p.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-account-credits.png`), fullPage: true }); + } + assert.deepEqual(errors, []); + await ctx.close(); + }); + } + }); +} + for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { test(engine + ": the credits WorkBuddy's replies said, by model and by session", async (t) => { const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); diff --git a/internal/usage/plan_credits_test.go b/internal/usage/plan_credits_test.go index 84ae1c539..ef1473fcd 100644 --- a/internal/usage/plan_credits_test.go +++ b/internal/usage/plan_credits_test.go @@ -124,3 +124,34 @@ func TestPlanCreditsPacked(t *testing.T) { } } } + +// Each account's credits are its own on the Usage page's Accounts list +// (lcyksp on Discord: WorkBuddy's 积分 spent, per account, not only +// tokens), through the summary and the Requests page's account groups. +func TestPlanCreditsByAccount(t *testing.T) { + resetUsageTest(t) + at := Clock().Add(-time.Hour) + credit := func(v float64) *float64 { return &v } + for i := 0; i < 70; i++ { + Append(Record{Time: at.Add(time.Duration(i) * time.Second), Agent: "codex", Provider: "workbuddy", ProviderAccount: "a@x", Model: "glm-5.3", Input: 9, Output: 12, Status: 200, Credits: credit(0.5)}) + } + Append(Record{Time: at.Add(2 * time.Minute), Agent: "codex", Provider: "workbuddy", ProviderAccount: "b@x", Model: "glm-5.3", Input: 9, Output: 1, Status: 200, Credits: credit(2.25)}) + Append(Record{Time: at.Add(3 * time.Minute), Agent: "codex", Provider: "workbuddy", ProviderAccount: "b@x", Model: "glm-5.3", Input: 9, Output: 1, Status: 200}) + + near := func(a, b float64) bool { return math.Abs(a-b) < 1e-9 } + want := map[string]Totals{"a@x": {Credits: 35, Credited: 70}, "b@x": {Credits: 2.25, Credited: 1}} + check := func(what string, groups []Group) { + t.Helper() + if len(groups) != len(want) { + t.Fatalf("%s: %d accounts, want %d: %+v", what, len(groups), len(want), groups) + } + for _, g := range groups { + w := want[g.Account] + if !near(g.Credits, w.Credits) || g.Credited != w.Credited { + t.Fatalf("%s %s: %v credits of %d calls, want %v of %d", what, g.Account, g.Credits, g.Credited, w.Credits, w.Credited) + } + } + } + check("summary", Summarize(All).Accounts) + check("requests", QueryPage(All, Filter{}, 0, 50).Accounts) +}