usage: a provider's accounts together, and a routing group's (CryptoSarom on X)
CryptoSarom on X (tweet 2116797183207035245, the tray panel's Usage tab):
"能否支持合并用量和额度显示? 有时候更关心某个模型还能用多少 ... 同个供应商
同模型可以合并 ... 或者单个路由组单独显示用量和额度. 有需要关心账号限制
的时候可以进详情再去看".
What it does:
- A Usage card of several accounts has "All N accounts" under its head:
each window the accounts share, one figure and a thin bar, and how
many couldn't be read. The tray panel's group of several has the same
strip above its cards (at most 3 windows). Each account stays below it
as it was: the details are where they were.
- A routing group's row (Routing › groups) has a line for each provider
among its members: "WorkBuddy AI, 4 accounts: Credits 355 / 1,500
credits · 23.7% used · 1 couldn't be read", following Used/Left.
The design, and why:
- Only what reads alike goes together (mergeQuotas). Counted windows of
one name and unit add their amounts and limits, the share is of the
sum; wallets add balances in one unit. A window said only as a share
is the mean over accounts on one plan, whose allowances are the same
size, so the mean is the share of their allowance together; two plans
are never averaged, and a share is never added to a count. Text-only
windows are left out; unlimited only when every account read says so.
- An account whose reading failed is unknown, not 0 or 100: left out of
the figure and counted ("1 couldn't be read"). A window an earlier
reading (asOf) stands in for, past its reset, is left out the same way
and counted in its tooltip. No single reset is claimed for the whole;
the tooltip says when the first of them starts again.
- Only what two or more accounts have goes together: one account's
window is already below it.
- No switch: the strip is additive and quiet (no gradient, no coloured
stripe; the pill grey of the page, the accent bar the cards use), and
it names no account, so Hide accounts holds.
- The code is in quotaall.js, imported when a provider first has two
accounts (quotaAllJS) or a routing group's member has readings, and
each place is drawn again once it is in. app.js has the loader and the
two call sites; three comments in the quota code were cut to keep the
core inside its budget (1,533,096 of 1,533,105), no raise.
Run, at this tree (rebased on origin/main df0320156):
- mote (macOS 27), node --test: usage-merge (7/7), usage-all-accounts
(14/14: Chromium and WebKit; en, zh, zh-TW, ja, de; light and dark for
en and zh; Usage page at 440px, tray panel at 360x760, Routing), i18n-keys
(4/4), old-webkit (6/6): 31 of 31 ok.
- mote, go test -count=1 ./internal/gui: TestCoreScriptBudget ok (app.js
1,311,777, core 1,533,096); one red, TestMainWindowCorners/macOS_26_SDK,
#3949 (macOS 27, AppKit), no Go changed here.
- Screenshots of all three places in both engines, every language,
light and dark (en, zh), looked at.
- Not run: the whole GUI suite. mote had four other sessions' full GUI
suites running (1h46m+, load 57 to 240) and the WSL box three, so
per the one-suite-a-machine rule it waited and wasn't run.
Broken by hand (red, then put back):
- quotaall.js counting a failed account as read and dropping the
two-account rule: usage-merge 4 of 7 red (share vs count, failed is
unknown, plans apart, balances/unlimited). Before the move to
quotaall.js, dropping the kind from the key and the stale skip each
turned their tests red too.
- the loader not drawing again once quotaall.js is in:
usage-all-accounts 14 of 14 red (both engines, every language).
- usage-merge.test.cjs is red on the old code: quotaall.js isn't there.
Not tried: real accounts (the figures come from fixtures: WorkBuddy AI
credits, Codex Plus and Pro, Claude Max ×2, Kimi); the real tray app on
macOS, Windows or WebKitGTK; a slow first load of quotaall.js (the strip
comes in after the cards on its first draw, measured only on a local
server).
This commit is contained in:
@@ -212,6 +212,39 @@ under its id (`render`, #1835). The row itself keeps one line: the
|
||||
fullest window while idle, what it is doing while it answers. See
|
||||
`routing-seat-windows.test.cjs`.
|
||||
|
||||
### A provider's accounts together
|
||||
|
||||
A Usage card of several accounts (not a card of keys, which has its sum)
|
||||
has "All N accounts" under its head, and the tray panel's group of
|
||||
several the same strip above its cards (`quotaAll`, CryptoSarom on
|
||||
X). A routing group's row has a line for each provider among its
|
||||
members: what is left of that provider's accounts together
|
||||
(`groupQuota` in `plugins/routing/client.js`, drawn again when
|
||||
`quotas` is new). `quotaAll` and `mergeQuotas` are in `quotaall.js`, which app.js imports
|
||||
once a provider has two accounts (`quotaAllJS`) and the Routing page
|
||||
once a group's member has readings, so they weigh nothing on the core;
|
||||
each place is drawn again once it is in. All three come from
|
||||
`mergeQuotas`, which puts together only what reads alike:
|
||||
|
||||
- a counted window (`limit`) of one name and unit adds its amounts and
|
||||
limits, its share the share of the sum; a wallet (`balance`) adds its
|
||||
balances in one unit;
|
||||
- a window said only as a share is the mean of the accounts on one
|
||||
plan, the same allowance each; two plans are never averaged, and a
|
||||
window more than one plan has is named with its plan;
|
||||
- a share is never added to a count; `text` windows are left out;
|
||||
unlimited only where every account read says so;
|
||||
- an account whose reading failed is unknown, not 0, and is counted
|
||||
("1 couldn't be read"); a window an `asOf` reading stands in for,
|
||||
whose reset has passed, is left out and counted in its tooltip;
|
||||
- only what two or more accounts have goes together; family and pool
|
||||
stay, so `familyWindows` folds the result as an account's.
|
||||
|
||||
No account is named in it, and each account stays below it as it was.
|
||||
There is no switch: it is additive, and the figure follows used or left
|
||||
with the rest. See `usage-merge.test.cjs` (the merge) and
|
||||
`usage-all-accounts.test.cjs` (the three places).
|
||||
|
||||
### The Sessions page's folders
|
||||
|
||||
The Sessions page lists an agent's project folders as one list, newest
|
||||
|
||||
@@ -1005,6 +1005,20 @@ body.window .field.solo { grid-column: auto; }
|
||||
.quota-reset .quota-holds-why { flex-basis: 100%; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; opacity: .75; cursor: help; }
|
||||
.quota-track { height: 4px; border-radius: 2px; background: var(--pill); overflow: hidden; }
|
||||
.quota-track i { display: block; height: 100%; border-radius: inherit; background: var(--accent); }
|
||||
/* a provider's accounts together (CryptoSarom on X): a quiet inset under
|
||||
the card's head, each window's figure over a thin bar, side by side
|
||||
while they fit, the accounts as they were below it */
|
||||
.quota-all { display: flex; flex-wrap: wrap; gap: 6px 16px; margin: 0 0 10px; padding: 8px 10px 9px; border-radius: 8px; background: color-mix(in srgb, var(--fg) 4%, transparent); font-size: 10.5px; color: var(--muted); }
|
||||
.quota-all-head { flex-basis: 100%; color: var(--faint); font-weight: 600; cursor: help; }
|
||||
.quota-all-w { flex: 1 1 130px; display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: 2px 6px; min-width: 0; cursor: help; }
|
||||
.quota-all-name { min-width: 0; overflow-wrap: anywhere; }
|
||||
.quota-all-n { min-width: 0; color: var(--fg-2); font-weight: 600; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
|
||||
.quota-all-bar { flex-basis: 100%; height: 3px; margin-top: 2px; border-radius: 2px; background: var(--pill); overflow: hidden; }
|
||||
.quota-all-bar i { display: block; height: 100%; border-radius: inherit; background: var(--accent); }
|
||||
.quota-all-bar.full i { background: var(--amber); }
|
||||
.quota-all-unknown { flex-basis: 100%; color: var(--faint); cursor: help; }
|
||||
/* in the panel, between the vendor's head and its accounts' cards */
|
||||
.quota-all.pq-all { margin: 0; padding: 7px 12px 8px; border-radius: 10px; font-size: 11px; }
|
||||
.subscription-error { font-size: 11px; color: var(--faint); }
|
||||
/* the way to the provider's settings, on a plan card that needs its access key (#1821) */
|
||||
.subscription-error .quota-fix { font: inherit; color: var(--accent); padding: 0; background: none; border: 0; cursor: pointer; }
|
||||
|
||||
+14
-12
@@ -14279,6 +14279,11 @@ function ringName(w) {
|
||||
return w.window ? poolWord(w.pool) + " " + shortWindow(w.window) : shortWindow(w.name);
|
||||
}
|
||||
|
||||
// quotaall.js: accounts together, loaded once asked for
|
||||
function quotaAllJS() {
|
||||
return (quotaAllJS.p ||= import("./quotaall.js").then(() => renderQuotas(), () => {}));
|
||||
}
|
||||
const quotaAllOf = (...a) => window.quotaAll ? quotaAll(...a) : void quotaAllJS();
|
||||
// tiersText: a family's windows, one a line, for its tooltip.
|
||||
function tiersText(w) {
|
||||
return (w.tiers || []).map((x) => t(x.name) + " " + quotaText(x)
|
||||
@@ -15735,8 +15740,7 @@ function ownLine(sub) {
|
||||
return line;
|
||||
}
|
||||
|
||||
// lazy: drawn only if something the panel shows changed (a load's answer,
|
||||
// the window coming back), not each time it is asked (#3192)
|
||||
// lazy: drawn only if what the panel shows changed (#3192)
|
||||
function renderQuotas(lazy) {
|
||||
renderPanelQuota(lazy);
|
||||
// the tray panel never shows the Usage page: its cards and curves are
|
||||
@@ -15813,6 +15817,8 @@ function renderQuotas(lazy) {
|
||||
s.title = keysSumTip(subs);
|
||||
head.append(s);
|
||||
}
|
||||
const all = !keys && several && quotaAllOf(subs);
|
||||
if (all) card.append(all);
|
||||
// many accounts (Linx on X: twenty-odd on one plugin, 顶成擎天柱):
|
||||
// the same, each still a row of its own
|
||||
const accts = !keys && several && subs.length > ACCTS_FOLD;
|
||||
@@ -17214,16 +17220,10 @@ function renderPanelUse() {
|
||||
fit();
|
||||
}
|
||||
|
||||
// The Usage tab: accounts under their vendor, each window a ring with its
|
||||
// share in it, when the plan ends and the windows start again under the
|
||||
// account; balances as figures. All in the Usage page's order, a balance
|
||||
// where it was put there, not after the plans (#1510, JokerQyou); balances
|
||||
// side by side share one grid.
|
||||
//
|
||||
// lazy: kept as it is when nothing it draws from has changed, so the
|
||||
// window's focus and visibility coming back neither rebuild the cards nor
|
||||
// start the skeleton's shimmer again (#3192). The minute is in it, for
|
||||
// the deadlines it words by the clock.
|
||||
// The Usage tab: accounts under their vendor, a ring a window, balances as
|
||||
// figures in one grid, in the Usage page's order (#1510).
|
||||
// lazy: kept while nothing it draws from changed (#3192); the minute is in
|
||||
// it, for the deadlines it words by the clock.
|
||||
function renderPanelQuota(lazy) {
|
||||
const box = $("#panelQuota");
|
||||
if (mode !== "panel" || !box) return;
|
||||
@@ -17310,6 +17310,8 @@ function renderPanelQuota(lazy) {
|
||||
head.append(m);
|
||||
}
|
||||
g.append(head);
|
||||
const all = qs.length > 1 && quotaAllOf(qs, "pq-all", 3);
|
||||
if (all) g.append(all);
|
||||
// the accounts in full; none of them, the one in sight
|
||||
const full = qs.length > 1 ? qs.filter((q) => usageAcctOpen(q, qs)) : qs;
|
||||
for (const q of full.length ? full : [usageShown(qs)]) g.append(panelQuotaCard(q));
|
||||
|
||||
@@ -3551,6 +3551,15 @@ const I18N = {
|
||||
"Show 1 more account": "展开其余 1 个账号",
|
||||
"Show {n} more accounts": "展开其余 {n} 个账号",
|
||||
"Show fewer accounts": "收起其余账号",
|
||||
"All {n} accounts": "全部 {n} 个账号",
|
||||
"These accounts' windows together: amounts of one unit are added up; a window said only as a share is the mean of the accounts on one plan, which have the same allowance. Each account is below.": "这些账号的窗口合起来:同一单位的额度相加;只给出百分比的窗口,取同一套餐账号的平均值(它们的额度相同)。各账号在下方。",
|
||||
"The mean of {n} accounts on one plan": "同一套餐 {n} 个账号的平均值",
|
||||
"Unlimited on each of {n} accounts": "{n} 个账号都不限量",
|
||||
"Added up over {n} accounts": "{n} 个账号相加",
|
||||
"{n} more read before it started again: left out": "另有 {n} 个是重置前读到的,未计入",
|
||||
"The first of them starts again {when}": "最早的一个 {when} 重置",
|
||||
"{n} couldn't be read": "{n} 个读取失败",
|
||||
"An account whose reading failed isn't counted as empty or full: it is left out of these figures": "读取失败的账号不按用完或全满计算,而是不计入这些数字",
|
||||
"Show {n} more keys": "展开其余 {n} 个密钥",
|
||||
"Show fewer keys": "收起其余密钥",
|
||||
"{sum} in all": "合计 {sum}",
|
||||
@@ -7867,6 +7876,15 @@ const I18N = {
|
||||
"Show 1 more account": "展開其餘 1 個帳號",
|
||||
"Show {n} more accounts": "展開其餘 {n} 個帳號",
|
||||
"Show fewer accounts": "收起其餘帳號",
|
||||
"All {n} accounts": "全部 {n} 個帳號",
|
||||
"These accounts' windows together: amounts of one unit are added up; a window said only as a share is the mean of the accounts on one plan, which have the same allowance. Each account is below.": "這些帳號的視窗合起來:同一單位的額度相加;只給出百分比的視窗,取同一方案帳號的平均值(它們的額度相同)。各帳號在下方。",
|
||||
"The mean of {n} accounts on one plan": "同一方案 {n} 個帳號的平均值",
|
||||
"Unlimited on each of {n} accounts": "{n} 個帳號都不限量",
|
||||
"Added up over {n} accounts": "{n} 個帳號相加",
|
||||
"{n} more read before it started again: left out": "另有 {n} 個是重設前讀到的,未計入",
|
||||
"The first of them starts again {when}": "最早的一個 {when} 重設",
|
||||
"{n} couldn't be read": "{n} 個讀取失敗",
|
||||
"An account whose reading failed isn't counted as empty or full: it is left out of these figures": "讀取失敗的帳號不按用完或全滿計算,而是不計入這些數字",
|
||||
"Show {n} more keys": "展開其餘 {n} 個金鑰",
|
||||
"Show fewer keys": "收起其餘金鑰",
|
||||
"{sum} in all": "合計 {sum}",
|
||||
@@ -12198,6 +12216,15 @@ const I18N = {
|
||||
"Show 1 more account": "さらに 1 個のアカウントを表示",
|
||||
"Show {n} more accounts": "さらに {n} 個のアカウントを表示",
|
||||
"Show fewer accounts": "アカウントの表示を減らす",
|
||||
"All {n} accounts": "全 {n} アカウント",
|
||||
"These accounts' windows together: amounts of one unit are added up; a window said only as a share is the mean of the accounts on one plan, which have the same allowance. Each account is below.": "これらのアカウントの枠の合計:同じ単位の量は足し合わせ、割合だけの枠は同じプランのアカウント(枠の大きさが同じ)の平均です。各アカウントは下にあります。",
|
||||
"The mean of {n} accounts on one plan": "同じプランの {n} アカウントの平均",
|
||||
"Unlimited on each of {n} accounts": "{n} アカウントすべて無制限",
|
||||
"Added up over {n} accounts": "{n} アカウントの合計",
|
||||
"{n} more read before it started again: left out": "ほかに {n} 件はリセット前の読み取りのため除外",
|
||||
"The first of them starts again {when}": "最も早いものは {when} にリセット",
|
||||
"{n} couldn't be read": "{n} 件は読み取れませんでした",
|
||||
"An account whose reading failed isn't counted as empty or full: it is left out of these figures": "読み取りに失敗したアカウントは空とも満杯とも数えず、これらの数字から除外します",
|
||||
"Show {n} more keys": "さらに {n} 個のキーを表示",
|
||||
"Show fewer keys": "キーの表示を減らす",
|
||||
"{sum} in all": "合計 {sum}",
|
||||
@@ -16539,6 +16566,15 @@ const I18N = {
|
||||
"Show 1 more account": "1 weiteres Konto anzeigen",
|
||||
"Show {n} more accounts": "{n} weitere Konten anzeigen",
|
||||
"Show fewer accounts": "Weniger Konten anzeigen",
|
||||
"All {n} accounts": "Alle {n} Konten",
|
||||
"These accounts' windows together: amounts of one unit are added up; a window said only as a share is the mean of the accounts on one plan, which have the same allowance. Each account is below.": "Die Fenster dieser Konten zusammen: Mengen derselben Einheit werden addiert; ein nur als Anteil genanntes Fenster ist der Mittelwert der Konten mit demselben Tarif, die dasselbe Kontingent haben. Die einzelnen Konten stehen darunter.",
|
||||
"The mean of {n} accounts on one plan": "Mittelwert von {n} Konten mit demselben Tarif",
|
||||
"Unlimited on each of {n} accounts": "Unbegrenzt bei allen {n} Konten",
|
||||
"Added up over {n} accounts": "Summe über {n} Konten",
|
||||
"{n} more read before it started again: left out": "{n} weitere vor dem Neustart gelesen: nicht mitgezählt",
|
||||
"The first of them starts again {when}": "Das erste davon beginnt {when} neu",
|
||||
"{n} couldn't be read": "{n} nicht lesbar",
|
||||
"An account whose reading failed isn't counted as empty or full: it is left out of these figures": "Ein Konto, dessen Abfrage fehlschlug, zählt weder als leer noch als voll: Es fehlt in diesen Zahlen",
|
||||
"Show {n} more keys": "{n} weitere Schlüssel anzeigen",
|
||||
"Show fewer keys": "Weniger Schlüssel anzeigen",
|
||||
"{sum} in all": "{sum} insgesamt",
|
||||
|
||||
@@ -4866,7 +4866,7 @@ function routingPage(part) {
|
||||
let second = 0;
|
||||
function countdown() {
|
||||
if (!shown()) { clearInterval(second); second = 0; return; }
|
||||
second ||= setInterval(() => { if (!shown()) return countdown(); if (!pinned && loaded && cur) sync(); render(); renderActs(listed()); }, 1000);
|
||||
second ||= setInterval(() => { if (!shown()) return countdown(); if (!pinned && loaded && cur) sync(); render(); renderActs(listed()); groupsReadAgain(); }, 1000);
|
||||
}
|
||||
countdown();
|
||||
|
||||
@@ -5415,7 +5415,43 @@ function routingPage(part) {
|
||||
return row;
|
||||
}
|
||||
}
|
||||
// the groups' rows say what is left of their accounts (groupQuota):
|
||||
// drawn again when the Usage page's readings are new, unless a group is
|
||||
// under the reader's hands
|
||||
let groupsQuotas;
|
||||
function groupsReadAgain() {
|
||||
if (groups && typeof quotas !== "undefined" && quotas !== groupsQuotas && !gEdit && !gsec.contains(document.activeElement)) renderGroups();
|
||||
}
|
||||
// groupQuota: a line a provider of the group's members, what is left of
|
||||
// the accounts the group can send it through, together (CryptoSarom on
|
||||
// X): "WorkBuddy AI, 3 accounts: Credits 1,145 / 1,500 credits · 76%
|
||||
// left". From the Usage page's readings (mergeQuotas), nothing read
|
||||
// for it; a member that is a group, or whose provider is off, has none.
|
||||
// Each account's own is on the Usage page.
|
||||
function groupQuota(g) {
|
||||
if (!Array.isArray(quotas)) return [];
|
||||
const shown = shownMembers(g), seen = new Set(), lines = [];
|
||||
for (const i of g.memberInfo || []) {
|
||||
if (!shown.includes(i.id) || i.group || i.providerOff || !i.provider || seen.has(i.provider)) continue;
|
||||
seen.add(i.provider);
|
||||
const subs = quotas.filter((q) => !q.from && q.provider === i.provider && (q.error || q.windows?.length));
|
||||
if (!subs.length) continue;
|
||||
// mergeQuotas is quotaall.js's: once it is in, the groups are drawn again
|
||||
if (!window.mergeQuotas) { quotaAllJS().then(() => { groupsQuotas = null; }); return []; }
|
||||
const all = mergeQuotas(subs);
|
||||
const ws = (familyWindows(all.windows) || []).slice(0, 3);
|
||||
if (!ws.length) continue;
|
||||
const figs = ws.map((w) => t(w.name) + (w.plan ? " · " + w.plan : "") + " " + quotaText(w)).join(" · ");
|
||||
const text = t("{name}, {n} accounts: {windows}", { name: i.name || i.provider, n: subs.length, windows: figs });
|
||||
const line = el("div", "mem rt-gquota", all.unknown ? text + " · " + t("{n} couldn't be read", { n: all.unknown }) : text);
|
||||
line.dataset.provider = i.provider;
|
||||
line.title = t("What is left of this provider's accounts the group can use, together: amounts of one unit added up, a share the mean of the accounts on one plan. Each account is on the Usage page.");
|
||||
lines.push(line);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
function drawGroups() {
|
||||
groupsQuotas = typeof quotas === "undefined" ? undefined : quotas;
|
||||
const all = groups.groups.filter((g) => !g.hidden), hidden = groups.groups.filter((g) => g.hidden);
|
||||
const words = gQ.value.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
||||
// the group being changed stays, whatever the filter
|
||||
@@ -5907,6 +5943,7 @@ function routingPage(part) {
|
||||
const sep = g.routing === "order" ? " → " : " · ";
|
||||
const mem = manual ? pickRow(g) : el("div", "mem", shownMembers(g).map((id) => memberLabel(g, id) + (g.off?.includes(id) ? ` (${t("off")})` : "")).join(sep));
|
||||
main.append(nm, mem);
|
||||
if (!g.decides) main.append(...groupQuota(g));
|
||||
for (const p of g.patterns || []) {
|
||||
const line = el("div", "mem pat" + (p.models ? "" : " none"));
|
||||
line.append(el("code", "", p.pattern), document.createTextNode(" · " + patternWords(p.models)));
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
// kernel adds them to i18n.js's (magpie.strings).
|
||||
magpie.strings({
|
||||
zh: {
|
||||
"{name}, {n} accounts: {windows}": "{name}({n} 个账号):{windows}",
|
||||
"What is left of this provider's accounts the group can use, together: amounts of one unit added up, a share the mean of the accounts on one plan. Each account is on the Usage page.": "本组可用的这家供应商账号合起来还剩多少:同一单位的额度相加,百分比取同一套餐账号的平均值。各账号详情在用量页。",
|
||||
"Each session's context window": "各会话的上下文窗口",
|
||||
"Show this session's newest request": "显示这个会话最新的请求",
|
||||
"Its plugin sent this request itself, so magpie can't split its time": "此请求由插件自行发出,magpie 无法拆分它的耗时",
|
||||
@@ -642,6 +644,8 @@ magpie.strings({
|
||||
"Open Folder": "打开文件夹",
|
||||
},
|
||||
"zh-TW": {
|
||||
"{name}, {n} accounts: {windows}": "{name}({n} 個帳號):{windows}",
|
||||
"What is left of this provider's accounts the group can use, together: amounts of one unit added up, a share the mean of the accounts on one plan. Each account is on the Usage page.": "本組可用的這家供應商帳號合起來還剩多少:同一單位的額度相加,百分比取同一方案帳號的平均值。各帳號詳情在用量頁。",
|
||||
"Each session's context window": "各會話的上下文視窗",
|
||||
"Show this session's newest request": "顯示這個會話最新的請求",
|
||||
"Its plugin sent this request itself, so magpie can't split its time": "此請求由外掛自行發出,magpie 無法拆分它的耗時",
|
||||
@@ -1282,6 +1286,8 @@ magpie.strings({
|
||||
"Open Folder": "打開資料夾",
|
||||
},
|
||||
ja: {
|
||||
"{name}, {n} accounts: {windows}": "{name}({n} アカウント):{windows}",
|
||||
"What is left of this provider's accounts the group can use, together: amounts of one unit added up, a share the mean of the accounts on one plan. Each account is on the Usage page.": "このグループが使えるこのプロバイダーのアカウントの残りの合計:同じ単位の量は足し合わせ、割合は同じプランのアカウントの平均。各アカウントは使用量ページにあります。",
|
||||
"Each session's context window": "セッションごとのコンテキストウィンドウ",
|
||||
"Show this session's newest request": "このセッションの最新のリクエストを表示",
|
||||
"Its plugin sent this request itself, so magpie can't split its time": "このリクエストはプラグインが自ら送信したため、magpie では時間の内訳を出せません",
|
||||
@@ -1922,6 +1928,8 @@ magpie.strings({
|
||||
"Open Folder": "フォルダを開く",
|
||||
},
|
||||
de: {
|
||||
"{name}, {n} accounts: {windows}": "{name}, {n} Konten: {windows}",
|
||||
"What is left of this provider's accounts the group can use, together: amounts of one unit added up, a share the mean of the accounts on one plan. Each account is on the Usage page.": "Was von den Konten dieses Anbieters, die die Gruppe nutzen kann, zusammen übrig ist: Mengen derselben Einheit addiert, ein Anteil als Mittelwert der Konten mit demselben Tarif. Die einzelnen Konten stehen auf der Seite Nutzung.",
|
||||
"Each session's context window": "Kontextfenster jeder Sitzung",
|
||||
"Show this session's newest request": "Die neueste Anfrage dieser Sitzung zeigen",
|
||||
"Its plugin sent this request itself, so magpie can't split its time": "Diese Anfrage hat die Erweiterung selbst gesendet, daher kann magpie ihre Zeit nicht aufschlüsseln",
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
// A provider's accounts together (CryptoSarom on X: how much of a model is
|
||||
// left matters more than which account it is on). app.js imports this once
|
||||
// some provider has two accounts (quotaAllJS), and the Routing page once a
|
||||
// group's row says what its accounts have left, so it weighs nothing on
|
||||
// the core.
|
||||
//
|
||||
// mergeQuotas: one provider's accounts as one figure a window. Only what
|
||||
// reads alike is put together: a counted window (WorkBuddy's credits) adds
|
||||
// its amounts and limits, a wallet its balances, each in one unit; a window
|
||||
// said only as a share is averaged, and only over accounts on one plan,
|
||||
// whose windows are the same size, so the mean is the share of their
|
||||
// allowance together. A share is never added to a count. An account whose
|
||||
// reading failed is not 0 but unknown: it is left out and counted as that;
|
||||
// so is a window an earlier reading (asOf) stands in for whose reset has
|
||||
// passed. A window only the vendor's text says has nothing to add up and is
|
||||
// left out. Unlimited only where every account read says so, and one
|
||||
// account's window alone is that account's, already below: only what two
|
||||
// or more have goes together (a Plus and a Pro account have no 5 hours in
|
||||
// common). The windows keep their family and pool, so familyWindows folds
|
||||
// them as an account's. accounts: those with a reading; unknown: those
|
||||
// without.
|
||||
//
|
||||
// quotaAll: the strip of them under a Usage card's or the tray panel's
|
||||
// head: "All 3 accounts", each window's figure and a thin bar, and how many
|
||||
// couldn't be read. Nothing when fewer than two accounts read, or nothing
|
||||
// of theirs adds up. No account is named in it (Hide accounts).
|
||||
function mergeQuotas(subs, now = Date.now()) {
|
||||
const read = subs.filter((q) => !q.error && (q.windows?.length || q.balance));
|
||||
const unknown = subs.length - read.length;
|
||||
const plans = new Set(read.map((q) => q.plan || ""));
|
||||
const by = new Map();
|
||||
for (const q of read) {
|
||||
for (const w of q.windows || []) {
|
||||
if (w.text) continue;
|
||||
const kind = w.unlimited ? "u" : w.limit > 0 ? "c" : w.balance != null ? "b" : w.used != null ? "p:" + (q.plan || "") : "";
|
||||
if (!kind) continue;
|
||||
const k = JSON.stringify([w.name, w.family || "", w.pool || "", w.unit || "", kind]);
|
||||
let m = by.get(k);
|
||||
if (!m) by.set(k, (m = { w, kind, plan: q.plan || "", n: 0, stale: 0, amount: 0, limit: 0, balance: 0, used: 0, soon: null }));
|
||||
if (q.asOf && w.resetsAt && Date.parse(w.resetsAt) <= now) { m.stale++; continue; }
|
||||
m.n++;
|
||||
if (kind === "c") { m.amount += Math.max(0, w.amount || 0); m.limit += w.limit; }
|
||||
else if (kind === "b") m.balance += w.balance;
|
||||
else if (kind !== "u") m.used += to100(w.used);
|
||||
const at = w.resetsAt && Date.parse(w.resetsAt);
|
||||
if (at > now && (m.soon == null || at < m.soon)) m.soon = at;
|
||||
}
|
||||
}
|
||||
const windows = [];
|
||||
for (const m of by.values()) {
|
||||
if (m.n < 2) continue; // one account's is already below
|
||||
if (m.kind === "u" && m.n < read.length) continue;
|
||||
const { w } = m;
|
||||
const out = { name: w.name, family: w.family, pool: w.pool, unit: w.unit, accounts: m.n, unknown: m.stale, how: m.kind[0] };
|
||||
if (m.kind === "u") out.unlimited = true;
|
||||
else if (m.kind === "c") Object.assign(out, { amount: m.amount, limit: m.limit, used: (100 * m.amount) / m.limit });
|
||||
else if (m.kind === "b") out.balance = m.balance;
|
||||
else {
|
||||
out.used = Math.round((10 * m.used) / m.n) / 10;
|
||||
if (plans.size > 1) out.plan = m.plan;
|
||||
}
|
||||
if (m.soon) out.firstReset = new Date(m.soon).toISOString();
|
||||
windows.push(out);
|
||||
}
|
||||
return { accounts: read.length, unknown, windows };
|
||||
}
|
||||
// quotaAll: the strip (above)
|
||||
function quotaAll(subs, cls = "", max = Infinity) {
|
||||
if (subs.length < 2) return null;
|
||||
const all = mergeQuotas(subs);
|
||||
if (all.accounts < 2 || !all.windows.length) return null;
|
||||
const box = el("div", "quota-all" + (cls ? " " + cls : ""));
|
||||
const lead = el("span", "quota-all-head", t("All {n} accounts", { n: subs.length }));
|
||||
lead.title = t("These accounts' windows together: amounts of one unit are added up; a window said only as a share is the mean of the accounts on one plan, which have the same allowance. Each account is below.");
|
||||
box.append(lead);
|
||||
const ws = familyWindows(all.windows);
|
||||
for (const w of ws.slice(0, max)) {
|
||||
const item = el("span", "quota-all-w");
|
||||
const name = t(w.name) + (w.plan ? " · " + w.plan : "");
|
||||
item.append(el("span", "quota-all-name", name), el("span", "quota-all-n", quotaText(w)));
|
||||
if (!w.unlimited && !quotaNoShare(w)) {
|
||||
const bar = el("span", "quota-all-bar" + (to100(w.used) >= 90 ? " full" : ""));
|
||||
const fill = el("i");
|
||||
fill.style.width = quotaFill(w) + "%";
|
||||
bar.append(fill);
|
||||
item.append(bar);
|
||||
}
|
||||
item.title = tipLines(
|
||||
name + " · " + quotaText(w),
|
||||
t(w.how === "p" ? "The mean of {n} accounts on one plan" : w.how === "u" ? "Unlimited on each of {n} accounts" : "Added up over {n} accounts", { n: w.accounts }),
|
||||
w.unknown && t("{n} more read before it started again: left out", { n: w.unknown }),
|
||||
w.firstReset && t("The first of them starts again {when}", { when: resetClock(new Date(w.firstReset)) }),
|
||||
w.tiers && "\n" + tiersText(w));
|
||||
box.append(item);
|
||||
}
|
||||
if (all.unknown) {
|
||||
const u = el("span", "quota-all-unknown", t("{n} couldn't be read", { n: all.unknown }));
|
||||
u.title = t("An account whose reading failed isn't counted as empty or full: it is left out of these figures");
|
||||
box.append(u);
|
||||
}
|
||||
return box;
|
||||
}
|
||||
window.mergeQuotas = mergeQuotas;
|
||||
window.quotaAll = quotaAll;
|
||||
@@ -150,8 +150,9 @@ test("compat.js is the first of the page's own scripts", async () => {
|
||||
// the pointer comes over the sidebar, whatsnew.js when release notes
|
||||
// open, claudemode.js when a Claude provider's editor opens, ctxtext.js
|
||||
// when a context window part is opened, resetask.js when a Codex reset's
|
||||
// Use is pressed; the checks above still read them
|
||||
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
|
||||
// Use is pressed, quotaall.js when a provider has two accounts; the
|
||||
// checks above still read them
|
||||
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
|
||||
});
|
||||
|
||||
test("the styles hold up in Safari 15.0", async () => {
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A provider's accounts together (CryptoSarom on X: 有时候更关心某个模型还能
|
||||
// 用多少). On the Usage page a card of several accounts has "All N accounts"
|
||||
// under its head, each window's figure added up or averaged over one plan,
|
||||
// how many couldn't be read, and each account as it was below it; the tray
|
||||
// panel's group has the same strip above its accounts' cards, and a routing
|
||||
// group's row a line a provider of its members. A card whose accounts have
|
||||
// nothing in common (a Plus and a Pro Codex) and one of a single account
|
||||
// have none. Used or left turns it with the rest. No account is named in
|
||||
// it. At 440px nothing in it is cut or spills. English, Chinese (both),
|
||||
// Japanese and German, light and dark; no backend, the API is faked here.
|
||||
// SHOTS=<dir> keeps a screenshot of each place.
|
||||
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 credits = (user, amount, extra) => ({ provider: "workbuddy-ai", name: "WorkBuddy AI", kind: "subscription", icon: "generic", plan: "Pro", user, readAt: iso(now),
|
||||
windows: [{ name: "Credits", amount, limit: 500, unit: "credits", used: (100 * amount) / 500, resetsAt: iso(now + 9 * 24 * 3600e3) }], ...extra });
|
||||
const quotas = () => [
|
||||
credits("wb-1@example.com", 100),
|
||||
credits("wb-2@example.com", 250),
|
||||
credits("wb-3@example.com", 5),
|
||||
{ provider: "workbuddy-ai", name: "WorkBuddy AI", kind: "subscription", icon: "generic", user: "wb-4@example.com", error: "401 Unauthorized", windows: [] },
|
||||
{ provider: "codex", name: "Codex", kind: "subscription", icon: "openai", plan: "Plus", user: "c1@example.com", windows: [{ name: "5 hours", used: 40, resetsAt: iso(now + 2 * 3600e3) }] },
|
||||
{ provider: "codex", name: "Codex", kind: "subscription", icon: "openai", plan: "Pro", user: "c2@example.com", windows: [{ name: "5 hours", used: 10, resetsAt: iso(now + 2 * 3600e3) }] },
|
||||
// two on one plan: each window the mean of the two, side by side
|
||||
{ provider: "claude", name: "Claude", kind: "subscription", icon: "claudecode-color", plan: "Max", user: "m1@example.com", windows: [{ name: "5 hours", used: 30, resetsAt: iso(now + 3600e3) }, { name: "Weekly", used: 50, resetsAt: iso(now + 4 * 24 * 3600e3) }] },
|
||||
{ provider: "claude", name: "Claude", kind: "subscription", icon: "claudecode-color", plan: "Max", user: "m2@example.com", windows: [{ name: "5 hours", used: 70, resetsAt: iso(now + 2 * 3600e3) }, { name: "Weekly", used: 20, resetsAt: iso(now + 5 * 24 * 3600e3) }] },
|
||||
{ provider: "kimi", name: "Kimi", kind: "subscription", icon: "kimi-color", windows: [{ name: "Weekly", used: 10 }] },
|
||||
];
|
||||
const models = [{ id: "workbuddy-ai/glm-5", name: "GLM-5", providerName: "WorkBuddy AI", provider: "workbuddy-ai", icon: "generic" }];
|
||||
const groups = () => ({ models, pools: [], deciders: [], found: true, groups: [
|
||||
{ id: "glm", name: "GLM", members: ["workbuddy-ai/glm-5"], ready: true, memberInfo: [{ id: "workbuddy-ai/glm-5", ready: true, provider: "workbuddy-ai", name: "WorkBuddy AI", icon: "generic", model: "glm-5" }] },
|
||||
] });
|
||||
|
||||
function serve(lang, theme, tray) {
|
||||
const settings = { theme, lang, tray, 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:"${theme}",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, url: "http://127.0.0.1:3999" } });
|
||||
if (url.pathname === "/api/usage/quotas") return json(quotas());
|
||||
if (url.pathname === "/api/groups") return json(groups());
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/gateway/trace") {
|
||||
if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes
|
||||
return json({ mine: true, now: iso(Date.now()), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
|
||||
}
|
||||
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
|
||||
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 words = {
|
||||
en: { all: "All 4 accounts", unknown: "1 couldn't be read", used: "355 / 1,500 credits · 23.7% used", left: "1,145 / 1,500 credits · 76.3% left", line: "WorkBuddy AI, 4 accounts: Credits 355 / 1,500 credits · 23.7% used · 1 couldn't be read" },
|
||||
zh: { all: "全部 4 个账号", unknown: "1 个读取失败" },
|
||||
"zh-TW": { all: "全部 4 個帳號", unknown: "1 個讀取失敗" },
|
||||
ja: { all: "全 4 アカウント", unknown: "1 件は読み取れませんでした" },
|
||||
de: { all: "Alle 4 Konten", unknown: "1 nicht lesbar" },
|
||||
};
|
||||
|
||||
// nothing in the strip cut short or past its box, nor the page sideways
|
||||
const fits = (page, sel) => page.evaluate((sel) => {
|
||||
const bad = [];
|
||||
if (document.documentElement.scrollWidth > innerWidth) bad.push("page scrolls sideways");
|
||||
for (const box of document.querySelectorAll(sel)) {
|
||||
const b = box.getBoundingClientRect();
|
||||
if (box.scrollWidth > box.clientWidth + 0.5) bad.push("strip spills");
|
||||
for (const e of box.querySelectorAll("*")) {
|
||||
const r = e.getBoundingClientRect();
|
||||
if (!r.width) continue;
|
||||
if (r.left < b.left - 0.5 || r.right > b.right + 0.5) bad.push(`${e.className || e.tagName} past the strip`);
|
||||
}
|
||||
}
|
||||
return bad;
|
||||
}, sel);
|
||||
|
||||
const shot = async (page, name) => {
|
||||
if (!process.env.SHOTS) return;
|
||||
await fs.mkdir(process.env.SHOTS, { recursive: true });
|
||||
await page.screenshot({ path: path.join(process.env.SHOTS, name + ".png") });
|
||||
};
|
||||
|
||||
async function open(browser, lang, theme, tray, url, width = 440, height = 900) {
|
||||
const context = await browser.newContext({ viewport: { width, height }, reducedMotion: "reduce", colorScheme: theme });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(8000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, theme, tray));
|
||||
await page.addInitScript(() => { try { if (!sessionStorage.getItem("set")) { localStorage.clear(); localStorage.setItem("magpie.quotaRange", "off"); sessionStorage.setItem("set", "1"); } } catch {} });
|
||||
await page.goto(url);
|
||||
return { page, errors };
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of Object.keys(words)) {
|
||||
const w = words[lang];
|
||||
for (const theme of lang === "en" || lang === "zh" ? ["light", "dark"] : ["light"]) {
|
||||
test(`${engine} ${lang} ${theme}: a provider's accounts together on the Usage page, the panel and a routing group`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
|
||||
// the Usage page
|
||||
const { page, errors } = await open(browser, lang, theme, "window", "http://magpie.test/?view=usage");
|
||||
const card = '#subscriptionUsage > [data-key="workbuddy-ai"]';
|
||||
await page.waitForSelector(`${card} .quota-all`);
|
||||
const strip = page.locator(`${card} .quota-all`);
|
||||
assert.equal(await strip.locator(".quota-all-head").textContent(), w.all);
|
||||
assert.equal(await strip.locator(".quota-all-unknown").textContent(), w.unknown);
|
||||
assert.equal(await strip.locator(".quota-all-w").count(), 1);
|
||||
const n = await strip.locator(".quota-all-n").textContent();
|
||||
assert.ok(n.includes("355 / 1,500"), n);
|
||||
if (w.used) assert.equal(n, w.used);
|
||||
// under the head, before the accounts, each still there
|
||||
assert.ok(await page.evaluate((card) => {
|
||||
const c = document.querySelector(card), s = c.querySelector(".quota-all");
|
||||
return s.previousElementSibling.matches(".subscription-head") && c.querySelectorAll(".subscription-account").length === 4;
|
||||
}, card));
|
||||
// no account named in it
|
||||
assert.ok(!(await strip.textContent()).includes("@example.com"));
|
||||
// nothing in common, or one account: no strip
|
||||
assert.equal(await page.locator('#subscriptionUsage > [data-key="codex"] .quota-all').count(), 0);
|
||||
assert.equal(await page.locator('#subscriptionUsage > [data-key="kimi"] .quota-all').count(), 0);
|
||||
// one plan's shares: the mean, each window apart, side by side
|
||||
const max = page.locator('#subscriptionUsage > [data-key="claude"] .quota-all .quota-all-n');
|
||||
assert.equal(await max.count(), 2);
|
||||
assert.ok((await max.nth(0).textContent()).includes("50%"));
|
||||
assert.ok((await max.nth(1).textContent()).includes("35%"));
|
||||
assert.ok(await page.evaluate(() => { const [a, b] = document.querySelectorAll('#subscriptionUsage > [data-key="claude"] .quota-all-w'); return Math.abs(a.getBoundingClientRect().top - b.getBoundingClientRect().top) < 1; }), "side by side");
|
||||
assert.deepEqual(await fits(page, ".quota-all"), []);
|
||||
await shot(page, `usage-${engine}-${lang}-${theme}`);
|
||||
// used or left turns it with the rest
|
||||
await page.locator("#quotaMode .opt").nth(1).click();
|
||||
await page.waitForFunction((card) => !document.querySelector(card + " .quota-all-n").textContent.startsWith("355"), card);
|
||||
const left = await strip.locator(".quota-all-n").textContent();
|
||||
assert.ok(left.includes("1,145 / 1,500"), left);
|
||||
if (w.left) assert.equal(left, w.left);
|
||||
await page.locator("#quotaMode .opt").nth(0).click();
|
||||
|
||||
// a routing group's row
|
||||
await page.goto("http://magpie.test/?view=routing");
|
||||
const line = page.locator('.rt-groups > .rt-group[data-id="glm"] .rt-gquota');
|
||||
await line.waitFor();
|
||||
const said = await line.textContent();
|
||||
assert.ok(said.includes("WorkBuddy AI") && said.includes("355 / 1,500") && said.includes(w.unknown), said);
|
||||
if (w.line) assert.equal(said, w.line);
|
||||
assert.ok(!said.includes("@example.com"));
|
||||
if (process.env.SHOTS) { await line.evaluate((e) => e.scrollIntoView({ block: "center" })); await page.waitForTimeout(300); }
|
||||
await shot(page, `routing-${engine}-${lang}-${theme}`);
|
||||
assert.deepEqual(errors, []);
|
||||
|
||||
// the tray panel
|
||||
const panel = await open(browser, lang, theme, "panel", "http://magpie.test/?mode=panel", 360, 760);
|
||||
await panel.page.locator('#ptabs [data-ptab="usage"]').click();
|
||||
const pq = panel.page.locator("#panelQuota .pq-group .pq-all");
|
||||
await pq.first().waitFor();
|
||||
assert.equal(await pq.count(), 2, "WorkBuddy AI's and Claude's: Codex's two plans have nothing in common");
|
||||
// WorkBuddy AI's: the one with an account that couldn't be read
|
||||
const wbp = pq.filter({ has: panel.page.locator(".quota-all-unknown") });
|
||||
assert.equal(await wbp.count(), 1);
|
||||
assert.equal(await wbp.locator(".quota-all-head").textContent(), w.all);
|
||||
assert.equal(await wbp.locator(".quota-all-unknown").textContent(), w.unknown);
|
||||
assert.ok((await wbp.locator(".quota-all-n").textContent()).includes("355 / 1,500"));
|
||||
// above the accounts' cards, which are as many as before
|
||||
assert.ok(await panel.page.evaluate(() => {
|
||||
const s = document.querySelector("#panelQuota .pq-all");
|
||||
return s.previousElementSibling.matches(".pq-gh") && s.nextElementSibling.matches(".pq-card");
|
||||
}));
|
||||
assert.deepEqual(await fits(panel.page, ".pq-all"), []);
|
||||
await shot(panel.page, `panel-${engine}-${lang}-${theme}`);
|
||||
assert.deepEqual(panel.errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// A provider's accounts together (CryptoSarom on X: how much of a model is
|
||||
// left matters more than which account holds it). mergeQuotas, the shipped
|
||||
// function, puts together only what reads alike: counted windows of one
|
||||
// name and unit add their amounts and limits, wallets their balances, and a
|
||||
// window said only as a share is the mean of accounts on one plan. A share
|
||||
// is never added to a count, two units never meet, two plans' shares
|
||||
// never meet, and an account whose reading failed is unknown, not 0 or
|
||||
// 100. A window an earlier reading stands in for, past its reset, is left
|
||||
// out and counted. Needs no browser.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const vm = require("node:vm");
|
||||
const { test } = require("node:test");
|
||||
|
||||
const source = fs.readFileSync(process.env.MAGPIE_APP_JS || path.resolve(__dirname, "../assets/app.js"), "utf8").replace(/\r\n/g, "\n");
|
||||
function section(start, end) {
|
||||
const a = source.indexOf(start), b = source.indexOf(end, a);
|
||||
assert(a >= 0 && b > a, `missing ${start}`);
|
||||
return source.slice(a, b);
|
||||
}
|
||||
// quotaall.js, which app.js loads once a provider has two accounts
|
||||
const merging = fs.readFileSync(path.resolve(__dirname, "../assets/quotaall.js"), "utf8").replace(/\r\n/g, "\n");
|
||||
const ctx = vm.createContext({});
|
||||
ctx.window = ctx;
|
||||
vm.runInContext(`
|
||||
${section("function to100(", "\n")}
|
||||
${merging}
|
||||
`, ctx);
|
||||
const merge = (subs, now) => JSON.parse(JSON.stringify(ctx.mergeQuotas(JSON.parse(JSON.stringify(subs)), now)));
|
||||
const H = 3600e3, now = Date.parse("2026-11-01T12:00:00Z");
|
||||
const iso = (ms) => new Date(ms).toISOString();
|
||||
const acct = (user, windows, extra) => ({ provider: "workbuddy-ai", name: "WorkBuddy AI", user, plan: "Pro", windows, ...extra });
|
||||
const by = (r, name) => r.windows.filter((w) => w.name === name);
|
||||
|
||||
test("counted windows of one unit add up; the share is of the sum", () => {
|
||||
const r = merge([
|
||||
acct("a", [{ name: "Credits", amount: 100, limit: 500, unit: "credits", used: 20 }]),
|
||||
acct("b", [{ name: "Credits", amount: 250, limit: 500, unit: "credits", used: 50 }]),
|
||||
acct("c", [{ name: "Credits", amount: 5, limit: 500, unit: "credits", used: 1 }]),
|
||||
], now);
|
||||
assert.equal(r.accounts, 3);
|
||||
assert.equal(r.unknown, 0);
|
||||
const [w] = by(r, "Credits");
|
||||
assert.equal(w.amount, 355);
|
||||
assert.equal(w.limit, 1500);
|
||||
assert.ok(Math.abs(w.used - (100 * 355) / 1500) < 1e-9);
|
||||
assert.equal(w.accounts, 3);
|
||||
assert.equal(w.how, "c");
|
||||
});
|
||||
|
||||
test("a share is never added to a count, nor one unit to another", () => {
|
||||
const r = merge([
|
||||
acct("a", [{ name: "Monthly", amount: 100, limit: 500, unit: "credits" }, { name: "Tokens", amount: 1, limit: 10, unit: "M tokens" }]),
|
||||
acct("b", [{ name: "Monthly", used: 40 }, { name: "Tokens", amount: 3, limit: 10, unit: "requests" }]),
|
||||
], now);
|
||||
// each kind has one account only: nothing goes together
|
||||
assert.deepEqual(r.windows, []);
|
||||
});
|
||||
|
||||
test("an account whose reading failed is unknown, left out of the figure", () => {
|
||||
const r = merge([
|
||||
acct("a", [{ name: "5 hours", used: 20, resetsAt: iso(now + H) }]),
|
||||
acct("b", [{ name: "5 hours", used: 60, resetsAt: iso(now + 2 * H) }]),
|
||||
acct("c", [], { error: "401 Unauthorized" }),
|
||||
], now);
|
||||
assert.equal(r.accounts, 2);
|
||||
assert.equal(r.unknown, 1);
|
||||
const [w] = by(r, "5 hours");
|
||||
assert.equal(w.used, 40, "the mean of the two read, the failed one neither 0 nor 100");
|
||||
assert.equal(w.accounts, 2);
|
||||
assert.equal(w.firstReset, iso(now + H));
|
||||
assert.equal(w.resetsAt, undefined, "no single reset is claimed for the whole");
|
||||
});
|
||||
|
||||
test("shares are averaged within a plan only", () => {
|
||||
const r = merge([
|
||||
acct("a", [{ name: "5 hours", used: 10 }], { plan: "Plus" }),
|
||||
acct("b", [{ name: "5 hours", used: 30 }], { plan: "Plus" }),
|
||||
acct("c", [{ name: "5 hours", used: 90 }], { plan: "Pro" }),
|
||||
], now);
|
||||
const ws = by(r, "5 hours");
|
||||
assert.equal(ws.length, 1, "the Pro account alone is not merged into the Plus mean");
|
||||
assert.equal(ws[0].used, 20);
|
||||
assert.equal(ws[0].plan, "Plus", "named with its plan when the accounts have several");
|
||||
const one = merge([acct("a", [{ name: "5 hours", used: 10 }], { plan: "Plus" }), acct("b", [{ name: "5 hours", used: 30 }], { plan: "Pro" })], now);
|
||||
assert.deepEqual(one.windows, []);
|
||||
});
|
||||
|
||||
test("a stale window past its reset is left out and counted", () => {
|
||||
const r = merge([
|
||||
acct("a", [{ name: "Daily", used: 10, resetsAt: iso(now + H) }]),
|
||||
acct("b", [{ name: "Daily", used: 50, resetsAt: iso(now + H) }]),
|
||||
acct("c", [{ name: "Daily", used: 99, resetsAt: iso(now - H) }], { asOf: iso(now - 3 * H) }),
|
||||
], now);
|
||||
const [w] = by(r, "Daily");
|
||||
assert.equal(w.used, 30);
|
||||
assert.equal(w.unknown, 1);
|
||||
});
|
||||
|
||||
test("balances add up; unlimited only when every account is; text is left out", () => {
|
||||
const r = merge([
|
||||
acct("a", [{ name: "Wallet", balance: 12.5, unit: "USD" }, { name: "Chat", unlimited: true }, { name: "Overages", text: true, used: 100 }]),
|
||||
acct("b", [{ name: "Wallet", balance: 7.5, unit: "USD" }, { name: "Chat", unlimited: true }, { name: "Overages", text: true, used: 100 }]),
|
||||
acct("c", [{ name: "Wallet", balance: 1, unit: "credits" }, { name: "Chat", used: 30 }]),
|
||||
], now);
|
||||
assert.deepEqual(by(r, "Wallet").map((w) => [w.balance, w.unit]), [[20, "USD"]]);
|
||||
assert.deepEqual(by(r, "Chat").filter((w) => w.unlimited), [], "one account has a limit");
|
||||
assert.deepEqual(by(r, "Overages"), []);
|
||||
});
|
||||
|
||||
test("windows keep their family and pool, apart by them", () => {
|
||||
const r = merge([
|
||||
acct("a", [{ name: "5 hours", pool: "Gemini", used: 10 }, { name: "5 hours", pool: "Claude & GPT", used: 70 }]),
|
||||
acct("b", [{ name: "5 hours", pool: "Gemini", used: 30 }, { name: "5 hours", pool: "Claude & GPT", used: 90 }]),
|
||||
], now);
|
||||
assert.deepEqual(r.windows.map((w) => [w.pool, w.used]), [["Gemini", 20], ["Claude & GPT", 80]]);
|
||||
});
|
||||
Reference in New Issue
Block a user