diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index fc4a55327..018aa631a 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -15536,7 +15536,7 @@ function renderQuotas(lazy) { const sum = keys && keysSum(subs); if (sum) { const s = el("span", "quota-sum", t("{sum} in all", { sum })); - s.title = t("The {n} keys' balances added up", { n: subs.length }); + s.title = keysSumTip(subs); head.append(s); } // many accounts (Linx on X: twenty-odd on one plugin, 顶成擎天柱): @@ -15812,6 +15812,7 @@ function byUsageOrder(list) { // balance's card id goes with it (balanceCard), for a menu bar cell // that opens it. function keyCards(list) { + list = sharedBalances(list); const plan = (q) => q.windows?.length && !q.balance && !q.error; const bal = (q) => q.balance && !q.windows?.length && !q.plan; const merged = new Map(), gone = new Set(); diff --git a/internal/gui/assets/plugins/usage/i18n.js b/internal/gui/assets/plugins/usage/i18n.js index 7087f3b0d..08cc54e40 100644 --- a/internal/gui/assets/plugins/usage/i18n.js +++ b/internal/gui/assets/plugins/usage/i18n.js @@ -2,6 +2,10 @@ // kernel adds them to i18n.js's (magpie.strings). magpie.strings({ zh: { + "+1 key": "+1 个密钥", + "+{n} keys": "+{n} 个密钥", + "One balance for the account these keys share: {keys}": "这些密钥同属一个账号,余额只显示一次:{keys}", + "The balances added up, each account's once": "余额之和,每个账号只计一次", "Deleted {date}": "{date} 已删除", "Bar chart": "柱状图", "Line chart": "折线图", @@ -205,6 +209,10 @@ magpie.strings({ "Sent upstream as {to}, as the agent spoke it": "以 {to} 协议发往上游,与 agent 所用协议相同", }, "zh-TW": { + "+1 key": "+1 個金鑰", + "+{n} keys": "+{n} 個金鑰", + "One balance for the account these keys share: {keys}": "這些金鑰同屬一個帳號,餘額只顯示一次:{keys}", + "The balances added up, each account's once": "餘額之和,每個帳號只計一次", "Deleted {date}": "{date} 已刪除", "Bar chart": "長條圖", "Line chart": "折線圖", @@ -408,6 +416,10 @@ magpie.strings({ "Sent upstream as {to}, as the agent spoke it": "以 {to} 協議發往上游,與 agent 所用協議相同", }, ja: { + "+1 key": "+1 個のキー", + "+{n} keys": "+{n} 個のキー", + "One balance for the account these keys share: {keys}": "これらのキーは同じアカウントのもので、残高は一度だけ表示されます:{keys}", + "The balances added up, each account's once": "残高の合計(各アカウントは一度だけ)", "Deleted {date}": "{date} に削除", "Bar chart": "棒グラフ", "Line chart": "折れ線グラフ", @@ -611,6 +623,10 @@ magpie.strings({ "Sent upstream as {to}, as the agent spoke it": "エージェントと同じ {to} で上流へ送信", }, de: { + "+1 key": "+1 Schlüssel", + "+{n} keys": "+{n} Schlüssel", + "One balance for the account these keys share: {keys}": "Ein Guthaben für das Konto, zu dem diese Schlüssel gehören: {keys}", + "The balances added up, each account's once": "Die Guthaben zusammengezählt, jedes Konto einmal", "Deleted {date}": "Gelöscht am {date}", "Bar chart": "Balkendiagramm", "Line chart": "Liniendiagramm", diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index d60bbaa52..39f0dac25 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -350,6 +350,35 @@ function renderCosts() { if (sessions) renderSessions(); document.dispatchEvent(new Event("magpie-costs-changed")); } +// sharedBalances (keyCards): the keys magpie found to read one account's +// balance (sharedBalance, the first one's name) as one card, the first's, +// with the keys it stands for (sharedKeys): mimi on Discord, a site's three +// keys each showing the account's $8.39 and its curve. Keys that read +// their own, or another account's, stay each its own. +function sharedBalances(list) { + if (!list.some((q) => q.sharedBalance)) return list; + const same = (a, b) => a.provider === b.provider && (a.from || "") === (b.from || "") && a.sharedBalance === b.sharedBalance; + const out = []; + for (const q of list) { + if (!q.sharedBalance) { out.push(q); continue; } + const of = list.filter((x) => x.sharedBalance && same(x, q)); + if (of[0] !== q) continue; + out.push(of.length > 1 ? { ...q, sharedKeys: of.map((x) => x.user) } : q); + } + return out; +} +// beside such a card's key, how many more keys its balance is for, and on +// hover which +function sharedKeysNote(q) { + const n = q.sharedKeys.length - 1; + const s = el("span", "quota-of quota-shared", t(n === 1 ? "+1 key" : "+{n} keys", { n })); + s.title = t("One balance for the account these keys share: {keys}", { keys: q.sharedKeys.join(", ") }); + return s; +} +// the keys' sum's tooltip: an account several keys share counted once +function keysSumTip(subs) { + return subs.some((q) => q.sharedKeys) ? t("The balances added up, each account's once") : t("The {n} keys' balances added up", { n: subs.length }); +} // quotaWho is how an account's card names it (#1515): by the name the user // gave it, the account beside it, else the account; and the key plan it // stands in for (seat) when that isn't already its name. A team's GLM @@ -375,6 +404,7 @@ function quotaWho(q) { s.title = t("The same seat as the key plan {name}, shown once, on this account's card", { name: q.seat }); out.push(s); } else if (q.seat) out[0].title += "\n" + t("The same seat as the key plan {name}, shown once, on this account's card", { name: q.seat }); + if (q.sharedKeys) out.push(sharedKeysNote(q)); if (q.user || q.alias) out.push(hideAccounts.eye(q.user || q.alias)); return out; } diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index 02a7cb5ff..00988f034 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -1117,6 +1117,14 @@ reload; DeepSeek's keys fold too, four keys aren't folded, a subscription's accounts aren't keys, an unread key leaves the sum out, and at 440px nothing is cut; in Chromium and WebKit, English and Chinese. +`usage-shared-balance.test.cjs` checks that keys found to read one account's +balance (`sharedBalance`, mimi on Discord: a site's three keys each showed +the account's $8.39 and its curve) show it once: one row with one balance +and one curve, "+2 keys" beside the key with the keys on hover, and the +head's sum counting the account once; a key with the same amount not found +to be that account's, and another provider's keys, stay their own rows, and +at 440px nothing is cut; in Chromium and WebKit, English and Chinese. + `upstream-status.test.cjs` checks the vendors' status pages on the Providers and Usage pages (#971): with Anthropic's page saying its API is down, the Anthropic provider's row and the Claude subscription's row and diff --git a/internal/gui/tests/usage-shared-balance.test.cjs b/internal/gui/tests/usage-shared-balance.test.cjs new file mode 100644 index 000000000..0fbd5aae8 --- /dev/null +++ b/internal/gui/tests/usage-shared-balance.test.cjs @@ -0,0 +1,124 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Keys of one account that read the account's balance (KeyBalances' +// sharedBalance, the first key's name) show it once on the Usage page: one +// row, its balance and its curve, with "+2 keys" beside the key's name and +// the keys on hover; the head's sum counts the account once (mimi on +// Discord: a site's keys 1-A031-Pro, 2-S009-Plus and 3-S010-Team-2 each +// showed the account's $8.39 and its own curve). A key with the same amount +// that magpie didn't find to be that account's, and another provider's keys, +// stay each its own row. At 440px nothing is cut or spills. English and +// Chinese; no backend, the API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const now = Date.now(); +const iso = (ms) => new Date(ms).toISOString(); +const trend = { points: [{ at: iso(now - 3 * 3600e3), amount: 9.2 }, { at: iso(now - 3600e3), amount: 8.8 }, { at: iso(now - 60e3), amount: 8.39 }] }; +const key = (provider, name, user, extra) => ({ provider, name, icon: "openai", user, windows: [], balance: "$8.39", readAt: iso(now), ...extra }); +const shared = { sharedBalance: "1-A031-Pro", balanceTrend: trend }; +const quotas = () => [ + key("site", "Site", "1-A031-Pro", shared), + key("site", "Site", "2-S009-Plus", shared), + key("site", "Site", "3-S010-Team-2", shared), + // the same amount, not found to be the account's: its own row + key("site", "Site", "other"), + // another provider's two keys: each its own + key("panel", "Panel", "t1"), + key("panel", "Panel", "t2"), +]; + +function serve(lang) { + const settings = { theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd" }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + 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/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/usage/quotas") return json(quotas()); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const keysOf = "1-A031-Pro, 2-S009-Plus, 3-S010-Team-2"; +const words = { + en: { more: "+2 keys", tip: "One balance for the account these keys share: " + keysOf, sum: "$16.78 in all", why: "The balances added up, each account's once", panelSum: "$16.78 in all", panelWhy: "The 2 keys' balances added up" }, + zh: { more: "+2 个密钥", tip: "这些密钥同属一个账号,余额只显示一次:" + keysOf, sum: "合计 $16.78", why: "余额之和,每个账号只计一次", panelSum: "合计 $16.78", panelWhy: "2 个密钥的余额之和" }, +}; + +const cards = (page) => page.evaluate(() => Object.fromEntries([...document.querySelectorAll("#subscriptionUsage > .subscription-card")].map((c) => [c.dataset.key, { + users: [...c.querySelectorAll(".subscription-account .user")].filter((u) => u.offsetParent).map((u) => u.title), + balances: [...c.querySelectorAll(".quota-balance b")].filter((b) => b.offsetParent).length, + curves: [...c.querySelectorAll(".balance-curve")].filter((b) => b.offsetParent).length, + shared: [...c.querySelectorAll(".quota-shared")].map((s) => [s.textContent, s.title]), + sum: c.querySelector(".quota-sum")?.textContent ?? null, + why: c.querySelector(".quota-sum")?.title ?? null, + more: c.querySelector(".quota-keys-more")?.textContent ?? null, +}]))); + +const fits = (page, key) => page.evaluate((key) => { + const c = document.querySelector(`#subscriptionUsage > [data-key=${key}]`); + const box = c.getBoundingClientRect(); + const bad = []; + if (document.documentElement.scrollWidth > innerWidth) bad.push("page scrolls sideways"); + if (c.scrollWidth > c.clientWidth) bad.push("card spills"); + for (const e of c.querySelectorAll(".subscription-head > *, .quota-balance b, .subscription-account .user, .quota-shared")) { + if (!e.offsetParent) continue; + const r = e.getBoundingClientRect(); + if (r.left < box.left - 0.5 || r.right > box.right + 0.5) bad.push(`${e.className || e.tagName} past the card`); + if (e.matches(".quota-sum, .quota-balance b, .quota-shared") && e.scrollWidth > e.clientWidth + 0.5) bad.push(`${e.className || e.tagName} cut: ${e.textContent}`); + } + return bad; +}, key); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + const w = words[lang]; + test(`${engine} ${lang}: keys of one account show its balance once`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const context = await browser.newContext({ viewport: { width: 900, height: 700 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + await page.addInitScript(() => { try { if (!sessionStorage.getItem("set")) { localStorage.clear(); localStorage.setItem("magpie.quotaRange", "2d"); sessionStorage.setItem("set", "1"); } } catch {} }); + await page.goto("http://magpie.test/?view=usage"); + await page.waitForSelector("#subscriptionUsage > [data-key=site] .subscription-account .user", { state: "attached" }); + + const got = await cards(page); + // the account's three keys: one row, one balance, one curve + assert.deepEqual(got.site.users, ["1-A031-Pro", "other"]); + assert.equal(got.site.balances, 2); + assert.equal(got.site.curves, 1); + assert.deepEqual(got.site.shared, [[w.more, w.tip]]); + // the account counted once in the sum, and the sum says so + assert.equal(got.site.sum, w.sum); + assert.equal(got.site.why, w.why); + assert.equal(got.site.more, null); + // another provider's keys with the same amount: each its own + assert.deepEqual(got.panel.users, ["t1", "t2"]); + assert.equal(got.panel.balances, 2); + assert.deepEqual(got.panel.shared, []); + assert.equal(got.panel.sum, w.panelSum); + assert.equal(got.panel.why, w.panelWhy); + + await page.setViewportSize({ width: 440, height: 700 }); + await page.waitForTimeout(300); + for (const k of ["site", "panel"]) assert.deepEqual(await fits(page, k), [], `${k} fits at 440px`); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/provider/balance.go b/internal/provider/balance.go index c3d22fb64..67002f6fc 100644 --- a/internal/provider/balance.go +++ b/internal/provider/balance.go @@ -80,12 +80,15 @@ func balanceSourceOf(p Provider) (balanceSource, bool) { if p.BalanceToken != "" { return balanceSource{"https://aihubmix.com/api/user/self", readAiHubMixAccount, p.BalanceToken, nil, nil}, true } - return balanceSource{"https://aihubmix.com/dashboard/billing/remain", readAiHubMix, "", nil, nil}, true + return balanceSource{aiHubMixKeyRemain, readAiHubMix, "", nil, nil}, true } } return balanceSource{}, false } +// aiHubMixKeyRemain is AiHubMix's query for what is left on a key +const aiHubMixKeyRemain = "https://aihubmix.com/dashboard/billing/remain" + // balancePathOf is the balance field of a provider that named its Balance // URL. func balancePathOf(p Provider) string { @@ -1191,7 +1194,7 @@ func balanceSegmentOf(raw, path string) (balanceSegment, error) { // false when there is no way to ask it. A key given limits and no quota of // its own has what its fullest window has left: what it can spend now. func Balance(ctx context.Context, p Provider) (amount string, ok bool, err error) { - amount, _, _, ws, ok, err := balanceRead(ctx, p) + amount, _, _, ws, _, ok, err := balanceRead(ctx, p) if err == nil && amount == "" && len(ws) > 0 { left := ws[0].Limit - ws[0].Amount for _, w := range ws[1:] { @@ -1206,24 +1209,25 @@ func Balance(ctx context.Context, p Provider) (amount string, ok bool, err error // the user wrote each apart (nil for a vendor magpie reads itself), what a // vendor's balance is made of when it tells that (split), and the // key's own usage windows when its reply tells them (a sub2api key's -// limits, readSub2APIKeyLimits). -func balanceRead(ctx context.Context, p Provider) (amount string, parts, split []BalancePart, ws []QuotaWindow, ok bool, err error) { +// limits, readSub2APIKeyLimits), and whether what it tells is the +// account's, the same to each of its keys (wide, balanceAccountWide). +func balanceRead(ctx context.Context, p Provider) (amount string, parts, split []BalancePart, ws []QuotaWindow, wide, ok bool, err error) { ctx = p.Via(ctx) p = keyQueryOf(p) src, ok := balanceSourceOf(p) if !ok && p.Account == nil && p.Key != "" && openCodeZen(p) { // a balance the vendor keeps from the key: said so, not left out - return "", nil, nil, nil, true, errOpenCodeNoBalance + return "", nil, nil, nil, false, true, errOpenCodeNoBalance } if !ok || p.Account != nil || p.Key == "" { - return "", nil, nil, nil, false, nil + return "", nil, nil, nil, false, false, nil } if src.token != "" && p.BalanceURL != "" { switch balanceURLPath(p.BalanceURL) { case newAPIKeyUsage: - return "", nil, nil, nil, true, errKeyUsageWithToken(p.BalanceURL) + return "", nil, nil, nil, false, true, errKeyUsageWithToken(p.BalanceURL) case sub2APIKeyUsage: - return "", nil, nil, nil, true, errSub2APIKeyUsageWithToken(p.BalanceURL) + return "", nil, nil, nil, false, true, errSub2APIKeyUsageWithToken(p.BalanceURL) } } method := http.MethodGet @@ -1231,12 +1235,12 @@ func balanceRead(ctx context.Context, p Provider) (amount string, parts, split [ // the method the user named goes with their own Balance URL only; // a vendor magpie knows is asked as it answers if method, err = balanceMethodOf(p.BalanceMethod); err != nil { - return "", nil, nil, nil, true, err + return "", nil, nil, nil, false, true, err } } req, err := http.NewRequestWithContext(ctx, method, withBalanceKey(src.url, p.Key, true), nil) if err != nil { - return "", nil, nil, nil, true, err + return "", nil, nil, nil, false, true, err } if src.token != "" { // a named endpoint still gets the provider's headers, which is @@ -1260,9 +1264,9 @@ func balanceRead(ctx context.Context, p Provider) (amount string, parts, split [ if err != nil { if k := url.QueryEscape(p.Key); k != "" && strings.Contains(err.Error(), k) { // the URL in the error has the key in it: not shown on a card - return "", nil, nil, nil, true, errors.New(strings.ReplaceAll(err.Error(), k, Mask(p.Key))) + return "", nil, nil, nil, false, true, errors.New(strings.ReplaceAll(err.Error(), k, Mask(p.Key))) } - return "", nil, nil, nil, true, err + return "", nil, nil, nil, false, true, err } defer res.Body.Close() b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) @@ -1273,23 +1277,23 @@ func balanceRead(ctx context.Context, p Provider) (amount string, parts, split [ if res.StatusCode >= 300 { msg = res.Status + ": " + msg } - return "", nil, nil, nil, true, errors.New(msg) + return "", nil, nil, nil, false, true, errors.New(msg) } if res.StatusCode >= 300 && src.failed != nil { if err := src.failed(res.StatusCode, b); err != nil { - return "", nil, nil, nil, true, err + return "", nil, nil, nil, false, true, err } } if res.StatusCode >= 300 { // what a JSON reply says, on one line; a page of HTML says nothing msg := strings.Join(strings.Fields(string(b)), " ") if !strings.HasPrefix(msg, "{") { - return "", nil, nil, nil, true, errors.New(res.Status) + return "", nil, nil, nil, false, true, errors.New(res.Status) } if r := []rune(msg); len(r) > 200 { msg = string(r[:200]) + "…" } - return "", nil, nil, nil, true, fmt.Errorf("%s: %s", res.Status, msg) + return "", nil, nil, nil, false, true, fmt.Errorf("%s: %s", res.Status, msg) } if p.BalanceURL != "" { if sub2APIKeyLimits(p) { @@ -1300,17 +1304,45 @@ func balanceRead(ctx context.Context, p Provider) (amount string, parts, split [ if len(ws) > 0 && strings.TrimSpace(p.BalancePath) == "" { // a key given limits and no quota of its own has no // "remaining": its windows are what it has left - return "", nil, nil, ws, true, nil + return "", nil, nil, ws, false, true, nil } - return "", nil, nil, nil, true, err + return "", nil, nil, nil, false, true, err } - return joinBalanceParts(parts), parts, nil, ws, true, nil + return joinBalanceParts(parts), parts, nil, ws, balanceAccountWide(p, src, b), true, nil } amount, err = src.read(b) if err == nil && src.split != nil { split = src.split(b) } - return amount, nil, split, nil, true, err + return amount, nil, split, nil, balanceAccountWide(p, src, b), true, err +} + +// balanceAccountWide says what a balance query told is the account's, +// the same whichever of the account's keys asks, rather than the key's +// own (mimi on Discord: three keys of one site each showed its $8.39). +// It goes by what was asked, never the vendor's name: an account query +// asked with its token; a vendor's own query magpie knows (DeepSeek's +// /user/balance, Moonshot's /users/me/balance, OpenRouter's /credits, +// SiliconFlow's, StepFun's, Command Code's and Ollama's), all but +// AiHubMix's /dashboard/billing/remain, which tells the key's own; and a +// sub2api key's /v1/usage when the key has no quota or limits of its own +// (mode "unrestricted"), which tells the user's wallet or the group's +// subscription. new-api's /api/usage/token and any other query the user +// named are a key's own. +func balanceAccountWide(p Provider, src balanceSource, body []byte) bool { + if src.token != "" { + return true + } + if p.BalanceURL == "" { + return src.url != aiHubMixKeyRemain + } + if !sub2APIKeyLimits(p) { + return false + } + var r struct { + Mode string `json:"mode"` + } + return json.Unmarshal(body, &r) == nil && r.Mode == "unrestricted" } // OpenCodeConsole is where OpenCode shows a workspace's credits: the @@ -1430,6 +1462,7 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { defer c.Unlock() return c.data } + kept := c.data c.Unlock() ctx, seq := quotaReading(ctx) type job struct { @@ -1481,7 +1514,9 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { jobs = append(jobs, job{q, name}) } } - jobs = slices.DeleteFunc(jobs, func(j job) bool { return !wantsCard(ctx, j.p.ID, j.user) }) + jobs = slices.DeleteFunc(jobs, func(j job) bool { + return !wantsCard(ctx, j.p.ID, j.user) && !sharesAskedCard(ctx, kept, j.p.ID, j.user) + }) out := make([]SubscriptionQuota, len(jobs)) var wg sync.WaitGroup var slots keySlots @@ -1505,7 +1540,7 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { out[i] = keepReading(ctx, q, keyTag("balance", j.p.Key)) return } - amount, parts, split, ws, _, err := balanceRead(ctx, j.p) + amount, parts, split, ws, wide, _, err := balanceRead(ctx, j.p) if errors.Is(err, errNoBalance) { return // a reply with no balance for this key: no card } @@ -1522,6 +1557,7 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { q.BalanceParts = cardParts(parts) q.BalanceSplit = split q.Windows = append(q.Windows, ws...) + q.wideBalance = wide now := time.Now() q.ReadAt = &now // what routing goes by, read just now rather than in a minute @@ -1536,10 +1572,23 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { if ctx.Err() == nil { // each balance kept, and drawn over time with its runs-out noteBalanceHistory(out, time.Now()) + // the history of the cards read now and of those kept, a partial + // read (one card's refresh) keeping the others + h := sharedBalanceHist(slices.Concat(kept, out)) c.Lock() - c.data = cacheCards(c.data, out, seq, again) + // the keys that read one account's balance, told apart afresh + // over every card (balance_shared.go) + c.data = shareBalances(cacheCards(c.data, out, seq, again), h) if !again { c.at, out = time.Now(), c.data + } else { + for i := range out { + for _, k := range c.data { + if k.Provider == out[i].Provider && strings.EqualFold(k.User, out[i].User) { + out[i].SharedBalance = k.SharedBalance + } + } + } } c.Unlock() } diff --git a/internal/provider/balance_shared.go b/internal/provider/balance_shared.go new file mode 100644 index 000000000..4183a61f3 --- /dev/null +++ b/internal/provider/balance_shared.go @@ -0,0 +1,123 @@ +package provider + +// One account's balance read through several of its keys (mimi on +// Discord: a site's three keys each showed its $8.39 and its own curve). +// A balance query that tells the account's (balanceAccountWide) answers +// every key of the account the same, so its card would be shown once a +// key. Two keys are taken for one account only when their balances moved +// together: the same amount before and after their latest change, read +// within balanceHistGap of each other. Two accounts with the same amount +// (a fresh grant each, or both at zero) stay apart until one is spent +// from, and keys whose amounts differ are never one. A key's own query +// (new-api's /api/usage/token, a quota of its own) is never shared. +// +// Each key is still read, kept and drawn over time on its own; the keys +// found to be one account are told by SharedBalance, the first one's +// name, for the Usage page to show their balance once. + +import ( + "context" + "strings" + "time" +) + +// balanceMove is a balance's latest change: from one amount to another, +// the new one first read at At. +type balanceMove struct { + from, to float64 + at time.Time +} + +// lastBalanceMove is the latest change in pts; false when it has none. +func lastBalanceMove(pts []BalancePoint) (balanceMove, bool) { + k := len(pts) + if k < 2 { + return balanceMove{}, false + } + to := pts[k-1].Amount + i := k - 1 + for i > 0 && pts[i-1].Amount == to { + i-- + } + if i == 0 { + return balanceMove{}, false + } + return balanceMove{pts[i-1].Amount, to, pts[i].At}, true +} + +// movedTogether says two balances' latest changes were the same change, +// at the same time. +func movedTogether(a, b []BalancePoint) bool { + ma, ok := lastBalanceMove(a) + mb, ok2 := lastBalanceMove(b) + if !ok || !ok2 || ma.from != mb.from || ma.to != mb.to { + return false + } + d := ma.at.Sub(mb.at) + return d <= balanceHistGap && -d <= balanceHistGap +} + +// sharesAccountBalance says q is a key's card whose balance, read just +// now, is its account's: one amount, nothing kept from before. +func sharesAccountBalance(q SubscriptionQuota) bool { + return q.wideBalance && q.User != "" && q.Balance != "" && q.Error == "" && q.AsOf == nil && + len(q.BalanceParts) == 0 && balanceCurrencies(q.Balance) == nil +} + +// sharedBalanceHist is the balances' history shareBalances goes by, read +// before the cards' lock is taken; nil when none of cards is an account's +// balance, as then none is shared. +func sharedBalanceHist(cards []SubscriptionQuota) balanceHist { + for _, q := range cards { + if sharesAccountBalance(q) { + balanceHistMu.Lock() + defer balanceHistMu.Unlock() + return readBalanceHist() + } + } + return nil +} + +// shareBalances sets SharedBalance on the keys of qs found to read one +// account's balance (see above) by their history h, afresh each time, in +// place: qs is a copy of the caller's. +func shareBalances(qs []SubscriptionQuota, h balanceHist) []SubscriptionQuota { + for i := range qs { + qs[i].SharedBalance = "" + } + if h == nil { + return qs + } + for i := range qs { + a := &qs[i] + if a.SharedBalance != "" || !sharesAccountBalance(*a) { + continue + } + for j := i + 1; j < len(qs); j++ { + b := &qs[j] + if b.SharedBalance != "" || b.Provider != a.Provider || b.From != a.From || b.Balance != a.Balance || !sharesAccountBalance(*b) { + continue + } + if movedTogether(h[quotaHistKey(a.Provider, a.User)], h[quotaHistKey(b.Provider, b.User)]) { + a.SharedBalance, b.SharedBalance = a.User, a.User + } + } + } + return qs +} + +// sharesAskedCard says the key user of provider shows its balance on the +// card a refresh asks for (another key's, SharedBalance): read again with +// it, so the card stays one. +func sharesAskedCard(ctx context.Context, kept []SubscriptionQuota, provider, user string) bool { + r, ok := refreshing(ctx) + if !ok || r.user == "" { + return false + } + for _, q := range kept { + if q.Provider == provider && strings.EqualFold(q.User, user) && q.SharedBalance != "" { + return r.wants(provider, q.SharedBalance) + } + } + return false +} diff --git a/internal/provider/balance_shared_test.go b/internal/provider/balance_shared_test.go new file mode 100644 index 000000000..8be7d481c --- /dev/null +++ b/internal/provider/balance_shared_test.go @@ -0,0 +1,183 @@ +package provider + +import ( + "context" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/agentenv" +) + +// mimi on Discord: a sub2api site's keys on the wallet each told its +// $8.39, and the Usage page showed it once a key. Keys whose balance is +// the account's, and moved with the others', are told as one account's; +// one with the same amount that didn't move with them (another account), +// a key with a quota of its own and a key's own query (new-api's +// /api/usage/token) stay each its own. +func TestKeysOfOneAccountShareItsBalance(t *testing.T) { + isolate(t) + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + t.Setenv("PATH", h) + for _, v := range agentenv.Vars { + t.Setenv(v, "") + } + keyBalanceCache.data = nil + t.Cleanup(func() { keyBalanceCache.data = nil }) + + // the replies as sub2api's /v1/usage gives them (gateway_handler.go's + // usageUnrestricted and usageQuotaLimited), and new-api's + // /api/usage/token + wallet := `{"mode":"unrestricted","isValid":true,"planName":"钱包余额","remaining":8.39,"unit":"USD","balance":8.39}` + own := `{"mode":"quota_limited","isValid":true,"status":"active","quota":{"limit":20,"used":11.61,"remaining":8.39,"unit":"USD"},"remaining":8.39,"unit":"USD"}` + token := `{"code":true,"message":"ok","data":{"object":"token_usage","total_granted":5000000,"total_used":805000,"total_available":4195000,"unlimited_quota":false}}` + var mu sync.Mutex + var asked []string + team := wallet // what the third key reads + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + mu.Lock() + asked = append(asked, key) + teamReads := team + mu.Unlock() + switch key { + case "sk-team": + w.Write([]byte(teamReads)) + case "sk-pro", "sk-plus", "sk-other": + w.Write([]byte(wallet)) + case "sk-quota": + w.Write([]byte(own)) + case "sk-t1", "sk-t2": + w.Write([]byte(token)) + default: + w.WriteHeader(http.StatusUnauthorized) + } + })) + defer srv.Close() + if err := Save(Provider{ID: "site", Name: "Site", Chat: srv.URL + "/v1", Key: "sk-pro", KeyName: "1-A031-Pro", + Keys: []KeyAccount{{Name: "2-S009-Plus", Key: "sk-plus"}, {Name: "3-S010-Team-2", Key: "sk-team"}, + {Name: "other", Key: "sk-other"}, {Name: "quota", Key: "sk-quota"}}, + BalanceURL: srv.URL + "/v1/usage"}); err != nil { + t.Fatal(err) + } + if err := Save(Provider{ID: "panel", Name: "Panel", Chat: srv.URL + "/v1", Key: "sk-t1", KeyName: "t1", + Keys: []KeyAccount{{Name: "t2", Key: "sk-t2"}}, BalanceURL: srv.URL + "/api/usage/token"}); err != nil { + t.Fatal(err) + } + shared := func() string { + var lines []string + for _, q := range KeyBalances(context.Background()) { + lines = append(lines, q.Provider+"|"+q.User+"|"+q.Balance+"|"+q.SharedBalance) + } + return strings.Join(lines, "\n") + } + + // the first reading: every one $8.39, none seen to move yet, so + // none is taken for another's account + first := "site|1-A031-Pro|$8.39|\nsite|2-S009-Plus|$8.39|\nsite|3-S010-Team-2|$8.39|\nsite|other|$8.39|\nsite|quota|$8.39|\npanel|t1|$8.39|\npanel|t2|$8.39|" + if got := shared(); got != first { + t.Fatalf("first reading:\n%s\nwant\n%s", got, first) + } + + // an hour before, the three keys of the account and the quota'd key + // and new-api's two read $8.80, the other account $8.39 already: the + // next reading has the three moved together + before := time.Now().Add(-time.Hour).UTC().Truncate(time.Second) + balanceHistMu.Lock() + bh := balanceHist{} + for _, k := range []string{"site|1-A031-Pro", "site|2-S009-Plus", "site|3-S010-Team-2", "site|quota", "panel|t1", "panel|t2"} { + p, u, _ := strings.Cut(k, "|") + bh[quotaHistKey(p, u)] = []BalancePoint{{At: before, Amount: 8.80}} + } + bh[quotaHistKey("site", "other")] = []BalancePoint{{At: before.Add(-time.Hour), Amount: 8.39}, {At: before, Amount: 8.39}} + writeBalanceHist(bh) + balanceHistMu.Unlock() + ForgetBalances() + want := "site|1-A031-Pro|$8.39|1-A031-Pro\nsite|2-S009-Plus|$8.39|1-A031-Pro\nsite|3-S010-Team-2|$8.39|1-A031-Pro\nsite|other|$8.39|\nsite|quota|$8.39|\npanel|t1|$8.39|\npanel|t2|$8.39|" + if got := shared(); got != want { + t.Fatalf("after they moved together:\n%s\nwant\n%s", got, want) + } + // as magpie quota --json and /v1/magpie/quotas tell them + for _, q := range quotaReport(nil, nil, KeyBalances(context.Background()), time.Now()) { + if q.User == "2-S009-Plus" && q.SharedBalance != "1-A031-Pro" { + t.Fatalf("the report's card: %+v", q) + } + } + + // the card's refresh reads every key it stands for, so it stays one + mu.Lock() + asked = nil + mu.Unlock() + ctx := context.WithValue(Asked(context.Background()), cardRefreshKey{}, cardRefresh{"site", "1-A031-Pro"}) + got := KeyBalances(ctx) + mu.Lock() + keys := strings.Join(asked, ",") + mu.Unlock() + for _, k := range []string{"sk-pro", "sk-plus", "sk-team"} { + if !strings.Contains(keys, k) { + t.Fatalf("the shared card's refresh asked %s, not %s", keys, k) + } + } + if strings.Contains(keys, "sk-other") || strings.Contains(keys, "sk-quota") { + t.Fatalf("the shared card's refresh asked %s", keys) + } + for _, q := range got { + if q.User == "1-A031-Pro" && q.SharedBalance != "1-A031-Pro" { + t.Fatalf("the refreshed card: %+v", q) + } + } + if got := shared(); got != want { + t.Fatalf("after the refresh:\n%s\nwant\n%s", got, want) + } + + // the keys apart again: one read another amount, so it is no longer + // the others' account + mu.Lock() + team = `{"mode":"unrestricted","isValid":true,"planName":"钱包余额","remaining":5.00,"unit":"USD","balance":5.00}` + mu.Unlock() + ForgetBalances() + apart := "site|1-A031-Pro|$8.39|1-A031-Pro\nsite|2-S009-Plus|$8.39|1-A031-Pro\nsite|3-S010-Team-2|$5.00|\nsite|other|$8.39|\nsite|quota|$8.39|\npanel|t1|$8.39|\npanel|t2|$8.39|" + if got := shared(); got != apart { + t.Fatalf("one key read another amount:\n%s\nwant\n%s", got, apart) + } +} + +// Two balances moved together when their latest change was the same, from +// and to, at the same time; not when either hasn't changed, or changed +// from another amount, or long apart. +func TestBalancesMovedTogether(t *testing.T) { + t0 := time.Date(2026, 10, 28, 8, 0, 0, 0, time.UTC) + pts := func(at time.Time, amounts ...float64) []BalancePoint { + var out []BalancePoint + for i, a := range amounts { + out = append(out, BalancePoint{At: at.Add(time.Duration(i) * time.Hour), Amount: a}) + } + return out + } + for _, c := range []struct { + name string + a, b []BalancePoint + want bool + }{ + {"the same moves", pts(t0, 9, 8.8, 8.39), pts(t0.Add(3*time.Second), 9, 8.8, 8.39), true}, + {"a run of the last amount", pts(t0, 8.8, 8.39, 8.39), pts(t0, 8.8, 8.39), true}, + {"a key added later", pts(t0, 9, 8.8, 8.39), pts(t0.Add(time.Hour), 8.8, 8.39), true}, + {"never moved", pts(t0, 8.39, 8.39), pts(t0, 8.39, 8.39), false}, + {"one never moved", pts(t0, 8.8, 8.39), pts(t0, 8.39, 8.39), false}, + {"from another amount", pts(t0, 8.8, 8.39), pts(t0, 8.5, 8.39), false}, + {"hours apart", pts(t0, 8.8, 8.39), pts(t0.Add(2*time.Hour), 8.8, 8.39), false}, + {"one point each", pts(t0, 8.39), pts(t0, 8.39), false}, + } { + if got := movedTogether(c.a, c.b); got != c.want { + t.Errorf("%s: %v, want %v", c.name, got, c.want) + } + } +} diff --git a/internal/provider/key_allowance.go b/internal/provider/key_allowance.go index 4b3a956fc..b41d6553f 100644 --- a/internal/provider/key_allowance.go +++ b/internal/provider/key_allowance.go @@ -184,7 +184,7 @@ func keyWindows(ctx context.Context, p Provider) (keyReading, error) { return r, err } var parts []BalancePart - r.balance, parts, r.split, r.ws, _, err = balanceRead(ctx, q) + r.balance, parts, r.split, r.ws, _, _, err = balanceRead(ctx, q) r.parts = cardParts(parts) return r, err } diff --git a/internal/provider/quotas.go b/internal/provider/quotas.go index 158b16d3e..3d054272f 100644 --- a/internal/provider/quotas.go +++ b/internal/provider/quotas.go @@ -87,8 +87,11 @@ type Quota struct { // BalanceSplit is what the Balance is made of, when the vendor tells // it (SubscriptionQuota's) BalanceSplit []BalancePart `json:"balanceSplit,omitempty"` - Error string `json:"error,omitempty"` - AsOf *time.Time `json:"asOf,omitempty"` // the cached reading's time, nil for a new one + // SharedBalance is the first of the keys whose Balance is this key's + // account's too (SubscriptionQuota's) + SharedBalance string `json:"sharedBalance,omitempty"` + Error string `json:"error,omitempty"` + AsOf *time.Time `json:"asOf,omitempty"` // the cached reading's time, nil for a new one // ReadDeferred says no request was made this time, rather than one failed. ReadDeferred bool `json:"readDeferred,omitempty"` // ReadAt is when the windows or balance shown were read, nil when not @@ -195,7 +198,7 @@ func quotaReport(subs, plans, balances []SubscriptionQuota, now time.Time) []Quo }{{"subscription", subs}, {"plan", plans}, {"balance", balances}} { for _, q := range g.qs { r := Quota{Provider: q.Provider, Name: q.Name, Kind: g.kind, Plan: q.Plan, User: q.User, AsOf: q.AsOf, ReadAt: q.ReadAt, ReadDeferred: q.ReadDeferred, - Windows: []QuotaSpan{}, Balance: q.Balance, BalanceSplit: q.BalanceSplit, Error: q.Error, Until: q.Until, Renew: q.Renew, Resets: q.Resets, ResetsUsed: q.ResetsUsed, From: q.From, Alias: q.Alias, Seat: q.Seat} + Windows: []QuotaSpan{}, Balance: q.Balance, BalanceSplit: q.BalanceSplit, SharedBalance: q.SharedBalance, Error: q.Error, Until: q.Until, Renew: q.Renew, Resets: q.Resets, ResetsUsed: q.ResetsUsed, From: q.From, Alias: q.Alias, Seat: q.Seat} // a pool's own windows stand in for the models' drawing on it, // as the usage page shows them for _, w := range PooledWindows(q.Windows) { diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index c093a55b2..d087253a8 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -141,6 +141,10 @@ type SubscriptionQuota struct { // BalanceTrend is the Balance over time, as magpie read it, and when // it runs out at that pace (balance_history.go) BalanceTrend *BalanceTrend `json:"balanceTrend,omitempty"` + // SharedBalance is set on each key of a provider found to read one + // account's balance with others (balance_shared.go): the name of the + // first of them, whose card shows it once for all + SharedBalance string `json:"sharedBalance,omitempty"` // Until is when the plan's paid time ends: it renews then when Renew // is "auto", is over when "off", and either when "" (the vendor // doesn't say which). @@ -220,6 +224,9 @@ type SubscriptionQuota struct { // In-process read order, separate from the vendor's ReadAt and never // persisted: restarting starts a new sequence. readSeq uint64 + // wideBalance marks a balance that is the account's, not the key's + // own (balanceAccountWide) + wideBalance bool // glmPlan marks a key's quota read from the GLM Coding Plan endpoint, // including custom providers. Only these can share ZCode's allowance. glmPlan bool