providers: a key's balance picks its currency beside the field, the number kept

Changing a key's balance from $ to ¥ meant clearing the balance, switching
Settings' currency, then typing it again (a bare number kept the old
balance's currency). The balance field now has a currency button beside it
(USD/CNY, the app's menu, not a native select). It starts at the balance's
own currency, else Settings' one, which stays the default for new
balances. Picking keeps the typed number and posts nothing; Enter or
leaving the field saves, and the pill then reads ≈¥40.00 left. A typed ¥
or $ flips the button as you type. Nothing is reinterpreted: Settings'
currency still never touches a saved balance, and usage and cost displays
are unchanged. No server or API change; keybalance.js is lazy-loaded, so
app.js and the core budget are untouched.

Run (mote):
- key-own-balance.test.cjs: 20 of 20 ok (chromium + webkit, narrow width,
  every language), with new cases: $40 → CNY picked → Enter posts
  {balance:40,currency:"cny"}; ¥100 → Escape posts nothing; → USD, Tab
  away posts {balance:100}; no row runs past the window.
- Whole GUI suite (earlier run at this change): every file ok except
  i18n-keys "a plugin's words are its own", red on main already and filed
  (#5327, #5332, #5426, #5482).
- Real GUI, sandbox HOME on mote (go build -tags nogui, ports 3591/3592):
  typed 40 → ≈$40.00 left; Enter balance…, picked CNY, field kept 40,
  Enter → ≈¥40.00 left, no page errors; `magpie provider key-balance`
  read ¥40.00 typed. Screenshots taken.

Broken by hand: the old keybalance.js against the new test times out
waiting for the currency button; dropping the blur guard (saving when
focus moves to the button) makes the menu pick time out because the field
saved and redrew under it (chromium and webkit). Both red, restored.

Not run to the end: the full Go and GUI suites are queued under
suite.lock on mote behind ~20 other sessions' suites (~/runs/bc-suite);
no Go file changed. Not tried: the real desktop window, WebKitGTK on
Linux, Windows.

Reported-by: tenacious_eagle_96548
This commit is contained in:
yetone
2026-11-08 12:54:13 +08:00
parent 5849b47ca0
commit 5a27348058
4 changed files with 115 additions and 14 deletions
+1 -1
View File
@@ -361,7 +361,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
- An account's weight under `weight` routing is kept per account too (`AccountWeights`, by the account in lower case, 2–1000; one not in it weighs 1, and nothing sets one from the plan), as a key's is (`KeyAccount.Weight`), so a Max and a Pro account can share requests by how much more one allows (rubbzha on X). `SetAccountWeight` (GUI `provider/accountweight`, the chip beside each account in use in the editor while the routing is By weight; `magpie provider account-weight <id> [account [n|default]]`) sets it, `moveAccountSettings` carries it through a Copilot rename, and `withPicks` puts it on the accounts `All` gives, so the gateway's `keyWeight` reads it with no file read (`Provider.AccountWeight`).
- A usage cap is kept per account (`AccountCaps`, 1–99) and, beside it, per window (`AccountWindowCaps`, by the account and the window's `capId`, its name in lower case: `WindowCapID`). A window's own share wins over the account's; 100 is no cap on that window. `CapsOf` gives both (`WindowCaps`), `CapHeld` and `capReached` judge each window by its own, and `SetWindowCap` (GUI `provider/windowcap`, `magpie provider account-cap <id> <account> --window <name>`) sets one; `SetWindowCaps` sets several at once, as the GUI's meter for a family of models (Antigravity's Gemini 3.1 Pro, High and Low) posts its models' windows in `windows`. An Antigravity pool's own windows ("Gemini · 7 days") are set aside for routing but capped (`WithCapped`, `capId` the pool's name and its own, as `LineName`): `allowanceOf` hangs each on its members' windows (`Limit.pool`), and `CapHeld` and `NearCap` count them through `capLimits`, so a cap on one holds that pool's models only (pluviophile714 on Discord, `TestPoolWindowCapHeld`). A config without window caps reads as before. How a pool ends at its caps is kept with the provider (plugins#349): `CapStop` answers 429 rather than going on to the fallbacks once every account in use is at its cap, and `CapCareful` reads usage again near a cap and holds an account whose usage can't be told (both off by default; within 5 points of its cap an account takes one turn at a time whatever they say, [gateway routing](gateway-routing.md); `SetCapStop`, `SetCapCareful`, GUI `provider/capstop` and `provider/capcareful`, ticks under the account list once an account has a cap). `UsageRead` says when an account's usage was last read well and whether the last try failed (a failed try keeps the good reading's time), and `ReadUsageNow` reads it again. `magpie provider pool <id> [--accounts a,b,…] [--cap percent|off] [--stop on|off] [--careful on|off]` shows and sets the whole pool in one command: which accounts are on and in what order, each one's cap, and both settings, and names the accounts in use with no cap.
- A key's spend cap (`KeySpendCaps`, by the key's fingerprint, [`key_spend.go`](../../internal/provider/key_spend.go); sparkling_lemur_62868 on Discord: a team's OpenAI key whose granted credits other services spend from too) is how much magpie may spend on an API key, in USD, per calendar day or month in local time, or in all since it was set (`Since`, kept while the cap stays one in all, its amount changed or not). What counts is what the Usage page prices magpie's own calls on the key at (`usage.KeySpent`: records whose `ProviderKeyID` is the key, not turned away, not reported by an app; the log is read once and each new call added by `Append`, read again after 5 minutes), not the vendor's bill: a model with no known price counts nothing, and requests under way when it is reached still finish, so the key can go a little past it. At or past the cap the gateway passes the key over ([gateway routing](gateway-routing.md)). Only a key has one: `SetKeySpendCap` refuses a subscription, an amount not above 0 or over `MaxSpendCap` (1,000,000) and a period it doesn't know. `ReplaceKey` carries it to the new value. Set from the key's row in the editor (a pill: "$7.50 of $20.00 today", the app's menu, then the amount typed in place, drawn by `keyspend.js`, which app.js imports when it draws a key's row; GUI `provider/keyspendcap`, `key-spend-cap.test.cjs`) or `magpie provider spend-cap <id> [key [usd [day|month|total]|off]]`, which also lists each key's spend. `TestKeySpendCapSet`, `TestSpendCapWindow`, `TestParseSpendCap`, `TestKeySpentCountsTheKeysCalls`, `TestSpendCapCmd`.
- A key's balance typed by hand (`KeyOwnBalances`, by the key's fingerprint: `{usd | cny, at, refill}`, [`key_balance_own.go`](../../internal/provider/key_balance_own.go); tenacious_eagle on Discord) is for a key whose vendor tells no balance magpie can read (`TakesOwnBalance`: an API key with no balance source, not Cline's or OpenCode Zen's, not on a plan's windows). The user types what the vendor's page says is left; the key's card on the Usage page and the tray then shows it less what the Usage page prices magpie's own calls on the key at since then (`usage.KeySpent` from `at`, through the `provider.KeySpent` hook usage sets), as `≈$12.50` with `Estimate` (`set`, `at`, `spent`) and below nothing as `≈$-2.00`. Typing it again counts from then. It is an estimate, not a reading: it is kept out of the balance history (no trend or runs-out), is never shared, and routing reads nothing from it; a low-balance alert reads its number. A balance the vendor tells always wins: with a Balance URL or a source magpie knows the card is the vendor's, and a relay whose query is looked for shows the typed one only when none is found (`errNoBalance`); the typed value stays saved as the user left it. `SetKeyOwnBalance` (GUI `provider/keyownbalance`, a pill in the key's row, "≈$12.50 left" or "Set balance", drawn by `keybalance.js` while `takesOwnBalance` and no balance was found; `magpie provider key-balance <id> [key [usd|¥cny|off] [--refill …]]`) refuses a subscription, an amount outside 0 to `MaxOwnBalance` (1,000,000) in either currency, and any currency but USD and CNY; nil takes it off, `ReplaceKey` carries it to the new value, and saving the editor keeps it. It may be typed in yuan (`cny`, "¥100", or a bare number while Settings shows costs in CNY): what is spent is counted in USD and turned into yuan at `fx.Known()`, the rate `internal/fx` last fetched (cached 12h in `fxrate.json`, fetched again in the background, never on the request path); `fx.Known` never hands out `fx.Fallback`, so with no rate fetched yet and something spent the left is unknown (`left` null, the card's `Error` says why) rather than a guess. It may refill (`refill`: `{every: month, day: 1–31}`, a day past the month's end meaning its last, or `{every: week, day: 1 Monday–7 Sunday}`), at midnight in the user's local time: nothing is stored on a refill; the spend is counted from the last refill boundary after `at` (`From`), and `Next` is the next one. Typing the amount again keeps the refill. `SetKeyBalanceRefill` (GUI `provider/keybalancerefill`, the pill's menu: Refills each month…, Refills each week…, Never refills; CLI `--refill monthly[:day]|weekly[:mon…sun]|off`) refuses a key with no balance. Each key with one gets `balance` in `/api/providers`' `keyList` (`set`, `at`, `spent`, `currency`, `rate`, `left`, `from`, `refill`, `next`). `TestKnownIsNeverAGuess`, `TestTypedBalanceInYuan`, `TestTypedBalanceRefills`, `TestRefillDays`, `TestTypedBalanceCountsDown`, `TestToldBalanceWinsOverTyped`, `TestOwnBalanceParsed`, `TestKeyOwnBalanceRoutes`, `key-own-balance.test.cjs`.
- A key's balance typed by hand (`KeyOwnBalances`, by the key's fingerprint: `{usd | cny, at, refill}`, [`key_balance_own.go`](../../internal/provider/key_balance_own.go); tenacious_eagle on Discord) is for a key whose vendor tells no balance magpie can read (`TakesOwnBalance`: an API key with no balance source, not Cline's or OpenCode Zen's, not on a plan's windows). The user types what the vendor's page says is left; the key's card on the Usage page and the tray then shows it less what the Usage page prices magpie's own calls on the key at since then (`usage.KeySpent` from `at`, through the `provider.KeySpent` hook usage sets), as `≈$12.50` with `Estimate` (`set`, `at`, `spent`) and below nothing as `≈$-2.00`. Typing it again counts from then. It is an estimate, not a reading: it is kept out of the balance history (no trend or runs-out), is never shared, and routing reads nothing from it; a low-balance alert reads its number. A balance the vendor tells always wins: with a Balance URL or a source magpie knows the card is the vendor's, and a relay whose query is looked for shows the typed one only when none is found (`errNoBalance`); the typed value stays saved as the user left it. `SetKeyOwnBalance` (GUI `provider/keyownbalance`, a pill in the key's row, "≈$12.50 left" or "Set balance", drawn by `keybalance.js` while `takesOwnBalance` and no balance was found; `magpie provider key-balance <id> [key [usd|¥cny|off] [--refill …]]`) refuses a subscription, an amount outside 0 to `MaxOwnBalance` (1,000,000) in either currency, and any currency but USD and CNY; nil takes it off, `ReplaceKey` carries it to the new value, and saving the editor keeps it. It may be typed in yuan (`cny`, "¥100", or a bare number with ¥ CNY picked in the currency button beside the field, which starts at the balance's own currency, else Settings' one; picking keeps the number typed and posts nothing until the field is left or Enter is pressed, so a balance's currency changes without clearing it or going to Settings, tenacious_eagle on Discord): what is spent is counted in USD and turned into yuan at `fx.Known()`, the rate `internal/fx` last fetched (cached 12h in `fxrate.json`, fetched again in the background, never on the request path); `fx.Known` never hands out `fx.Fallback`, so with no rate fetched yet and something spent the left is unknown (`left` null, the card's `Error` says why) rather than a guess. It may refill (`refill`: `{every: month, day: 1–31}`, a day past the month's end meaning its last, or `{every: week, day: 1 Monday–7 Sunday}`), at midnight in the user's local time: nothing is stored on a refill; the spend is counted from the last refill boundary after `at` (`From`), and `Next` is the next one. Typing the amount again keeps the refill. `SetKeyBalanceRefill` (GUI `provider/keybalancerefill`, the pill's menu: Refills each month…, Refills each week…, Never refills; CLI `--refill monthly[:day]|weekly[:mon…sun]|off`) refuses a key with no balance. Each key with one gets `balance` in `/api/providers`' `keyList` (`set`, `at`, `spent`, `currency`, `rate`, `left`, `from`, `refill`, `next`). `TestKnownIsNeverAGuess`, `TestTypedBalanceInYuan`, `TestTypedBalanceRefills`, `TestRefillDays`, `TestTypedBalanceCountsDown`, `TestToldBalanceWinsOverTyped`, `TestOwnBalanceParsed`, `TestKeyOwnBalanceRoutes`, `key-own-balance.test.cjs`.
- A window whose reset time has passed has started again, whatever share it was read at (`resetPassed`). That holds for a reading kept from before (`AsOf`) and for a fresh one: Claude Code's `/usage` gives a reset to the minute and can lag it, so a run just after a reset can still say 100% with that reset. `claudeWindows` hands such a window back empty on every path, and `usedPast`, `usedUp`, `BackAt` and `capReached` leave it out when they judge an account spent, for Codex, Claude Code and `magpie quota wait` alike. A card can still show a kept reading as it was read (`reported`, for a Claude card while `/usage` is unavailable); that changes what it shows, never which account is used. A reset `/usage` gives as a time alone ("resets 3pm") can be read as its next one, a day on (`claudeResetTime`), and is then not seen as passed here.
- A restart to update can run two magpies for up to the old one's drain
([GUI shell](gui-shell.md#a-restart-to-update-hands-the-gateway-over)), each
+2
View File
@@ -2887,6 +2887,8 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.acc :is(.aspend, .abal).at-cap { color: var(--accent); background: var(--accent-soft); font-weight: 500; }
.acc :is(.aspend, .abal):hover, .acc :is(.aspend, .abal).open { color: var(--fg); background: var(--pill-hover); }
.acc :is(.aspend-in, .abal-in) { width: 72px; }
.acc .abal-cur { flex: none; display: inline-flex; align-items: center; gap: 1px; height: 24px; margin-left: -5px; padding: 0 3px 0 7px; font: inherit; font-size: 11px; color: var(--muted); border: 0; border-radius: 5px; background: none; box-shadow: inset 0 0 0 1px var(--line); cursor: default; }
.acc .abal-cur:hover, .acc .abal-cur.open { color: var(--fg); background: var(--pill-hover); }
.acc .acap-held { color: var(--fg); }
/* held for magpie's requests, not the agent signed in to it: a warning */
.acc .acap-held.acap-direct { color: var(--amber); }
+46 -7
View File
@@ -3,8 +3,8 @@
// vendor's page says is left, and magpie counts down from it by what its
// own usage prices the calls it sends on the key (provider/
// key_balance_own.go). Typing it again sets it anew. It may be typed in
// yuan ("¥100", or a bare number while Settings shows costs in CNY), and
// may refill each month or week. keyspend.js imports this when the
// yuan ("¥100", or picked beside the field, which starts at the balance's
// own currency, else Settings' one), and may refill each month or week. keyspend.js imports this when the
// provider editor draws a key's row, so it weighs nothing on the core.
const moneyText = (v, cny) => (v < 0 ? "-" : "") + (cny ? "¥" : "$") + Math.abs(v).toFixed(2);
// balanceAmount reads what was typed: an amount and whether it is in
@@ -38,11 +38,50 @@ function keyBalancePill(p, k) {
!r ? t("{who} no longer refills", { who: name })
: r.every === "week" ? t("{who} refills each {weekday}", { who: name, weekday: weekdayName(r.day) })
: t("{who} refills on day {day} of each month", { who: name, day: r.day }));
// a bare number is in the balance's own currency, else in Settings' one
const unit = b ? (cny ? "cny" : "usd") : currency === "cny" ? "cny" : "usd";
const type = () => pillNumber(pill, b ? (cny ? "¥" : "") + b.set : "", unit === "cny" ? "CNY" : "USD", "abal-in",
t(unit === "cny" ? "Balance, in CNY" : "Balance, in USD"), (s) => balanceAmount(s, unit),
t("A balance is an amount from 0 to 1,000,000, in USD or in yuan (¥)"), null, set);
// a bare number is in the currency the button beside the field shows:
// the balance's own, else Settings' one, until the user picks the other
// there (tenacious_eagle: no clearing it and going to Settings). Picking
// keeps the number typed, so 100 becomes ¥100 only by that pick.
let unit = b ? (cny ? "cny" : "usd") : currency === "cny" ? "cny" : "usd";
const type = () => {
const at = pill.parentNode;
pillNumber(pill, b ? String(b.set) : "", "", "abal-in", "", (s) => balanceAmount(s, unit),
t("A balance is an amount from 0 to 1,000,000, in USD or in yuan (¥)"), null, set);
const i = at?.querySelector(":scope > .abal-in");
if (!i) return;
const cur = el("button", "abal-cur"), save = i.onblur;
cur.type = "button";
cur.setAttribute("aria-haspopup", "menu");
cur.setAttribute("aria-expanded", "false");
let picking = false;
// a sign typed in the field says its currency, and the button follows
const now = () => (balanceAmount(i.value, unit)?.cny ?? unit === "cny") ? "cny" : "usd";
const show = () => {
const c = now();
cur.replaceChildren(c.toUpperCase(), svg(CHEV, 12, 1.6));
cur.setAttribute("aria-label", t("Currency"));
i.setAttribute("aria-label", t(c === "cny" ? "Balance, in CNY" : "Balance, in USD"));
};
i.oninput = show;
// the field saves as it is left, but not for its currency's menu
i.onblur = (e) => { if (!picking && e.relatedTarget !== cur) save(); };
cur.onblur = (e) => { if (!picking && e.relatedTarget !== i) save(); };
cur.onmousedown = (e) => e.preventDefault();
cur.onkeydown = (e) => e.stopPropagation();
cur.onclick = (e) => {
e.stopPropagation();
if (cur.classList.contains("open")) return closeProtoMenu();
picking = true;
openProtoMenu(cur, CURRENCIES.map(([v, name]) => ({ v, name, literalName: true, note: "" })), now(), (v) => {
unit = v;
i.value = i.value.trim().replace(/^(\$|¥|¥|cny|rmb|usd)\s*|\s*(元|cny|rmb|yuan|usd)$/gi, "");
show();
}, "Currency", "sess-menu");
protoMenu.done = () => { picking = false; i.focus(NO_SCROLL); };
};
show();
i.after(cur);
};
const day = (s) => { const n = Number(s.trim()); return Number.isInteger(n) && n >= 1 && n <= 31 ? n : null; };
const monthly = () => pillNumber(pill, String(b.refill?.every === "month" ? b.refill.day : 1), "1–31", "abal-in", t("Refill day of the month"), day,
t("A day of the month is a whole number from 1 to 31"), b.refill?.every === "month" ? b.refill.day : null, (d) => refill({ every: "month", day: d }));
+66 -6
View File
@@ -7,7 +7,8 @@
// menu (no native select): Enter balance…, a refill each month (a day)
// or each week (a weekday), Never refills, or No balance, posted to
// provider/keyownbalance and provider/keybalancerefill. An amount in yuan
// ("¥100") is posted as CNY and shown in yuan. An amount that isn't one is
// ("¥100", or 100 with ¥ CNY picked beside the field) is posted as CNY
// and shown in yuan; a balance's currency is picked there, the number kept. An amount that isn't one is
// refused and nothing is posted. A click moves nothing; at a phone's width the row stays
// inside the window. In every language.
const assert = require("node:assert/strict");
@@ -66,11 +67,11 @@ function serve(lang, posts) {
}
const words = {
en: { k1: "≈$12.50 left", none: "Set balance", menu: "Balance", enter: "Enter balance…", off: "No balance", k2: "≈$5.00 left", k1again: "≈$40.00 left", yuan: "≈¥100.00 left", bad: "A balance is an amount from 0 to 1,000,000, in USD or in yuan (¥)", month: "Refills each month…", week: "Refills each week…", never: "Never refills", on: "Refills on", refills: "Refills to $40.00 on" },
zh: { k1: "≈$12.50 剩余", none: "设置余额", menu: "余额", enter: "填写余额…", off: "无余额", k2: "≈$5.00 剩余", k1again: "≈$40.00 剩余", yuan: "≈¥100.00 剩余", bad: "余额是 0 到 1,000,000 之间的金额,美元或人民币(¥)", month: "每月恢复…", week: "每周恢复…", never: "不恢复", on: "恢复于", refills: "恢复为 $40.00" },
"zh-TW": { k1: "≈$12.50 剩餘", none: "設定餘額", menu: "餘額", enter: "填寫餘額…", off: "無餘額", k2: "≈$5.00 剩餘", k1again: "≈$40.00 剩餘", yuan: "≈¥100.00 剩餘", bad: "餘額是 0 到 1,000,000 之間的金額,美元或人民幣(¥)", month: "每月恢復…", week: "每週恢復…", never: "不恢復", on: "恢復於", refills: "恢復為 $40.00" },
ja: { k1: "残り ≈$12.50", none: "残高を設定", menu: "残高", enter: "残高を入力…", off: "残高なし", k2: "残り ≈$5.00", k1again: "残り ≈$40.00", yuan: "残り ≈¥100.00", bad: "残高は 0 から 1,000,000 までの金額です(USD または人民元 ¥)", month: "毎月戻す…", week: "毎週戻す…", never: "戻さない", on: "戻す曜日", refills: "$40.00 へ戻る" },
de: { k1: "≈$12.50 übrig", none: "Guthaben festlegen", menu: "Guthaben", enter: "Guthaben eingeben…", off: "Kein Guthaben", k2: "≈$5.00 übrig", k1again: "≈$40.00 übrig", yuan: "≈¥100.00 übrig", bad: "Ein Guthaben ist ein Betrag von 0 bis 1.000.000, in USD oder in Yuan (¥)", month: "Monatlich auffüllen…", week: "Wöchentlich auffüllen…", never: "Nie auffüllen", on: "Auffüllen am", refills: "wieder auf $40.00 aufgefüllt" },
en: { currency: "Currency", yuan40: "≈¥40.00 left", usd100: "≈$100.00 left", k1: "≈$12.50 left", none: "Set balance", menu: "Balance", enter: "Enter balance…", off: "No balance", k2: "≈$5.00 left", k1again: "≈$40.00 left", yuan: "≈¥100.00 left", bad: "A balance is an amount from 0 to 1,000,000, in USD or in yuan (¥)", month: "Refills each month…", week: "Refills each week…", never: "Never refills", on: "Refills on", refills: "Refills to $40.00 on" },
zh: { currency: "货币", yuan40: "≈¥40.00 剩余", usd100: "≈$100.00 剩余", k1: "≈$12.50 剩余", none: "设置余额", menu: "余额", enter: "填写余额…", off: "无余额", k2: "≈$5.00 剩余", k1again: "≈$40.00 剩余", yuan: "≈¥100.00 剩余", bad: "余额是 0 到 1,000,000 之间的金额,美元或人民币(¥)", month: "每月恢复…", week: "每周恢复…", never: "不恢复", on: "恢复于", refills: "恢复为 $40.00" },
"zh-TW": { currency: "貨幣", yuan40: "≈¥40.00 剩餘", usd100: "≈$100.00 剩餘", k1: "≈$12.50 剩餘", none: "設定餘額", menu: "餘額", enter: "填寫餘額…", off: "無餘額", k2: "≈$5.00 剩餘", k1again: "≈$40.00 剩餘", yuan: "≈¥100.00 剩餘", bad: "餘額是 0 到 1,000,000 之間的金額,美元或人民幣(¥)", month: "每月恢復…", week: "每週恢復…", never: "不恢復", on: "恢復於", refills: "恢復為 $40.00" },
ja: { currency: "通貨", yuan40: "残り ≈¥40.00", usd100: "残り ≈$100.00", k1: "残り ≈$12.50", none: "残高を設定", menu: "残高", enter: "残高を入力…", off: "残高なし", k2: "残り ≈$5.00", k1again: "残り ≈$40.00", yuan: "残り ≈¥100.00", bad: "残高は 0 から 1,000,000 までの金額です(USD または人民元 ¥)", month: "毎月戻す…", week: "毎週戻す…", never: "戻さない", on: "戻す曜日", refills: "$40.00 へ戻る" },
de: { currency: "Währung", yuan40: "≈¥40.00 übrig", usd100: "≈$100.00 übrig", k1: "≈$12.50 übrig", none: "Guthaben festlegen", menu: "Guthaben", enter: "Guthaben eingeben…", off: "Kein Guthaben", k2: "≈$5.00 übrig", k1again: "≈$40.00 übrig", yuan: "≈¥100.00 übrig", bad: "Ein Guthaben ist ein Betrag von 0 bis 1.000.000, in USD oder in Yuan (¥)", month: "Monatlich auffüllen…", week: "Wöchentlich auffüllen…", never: "Nie auffüllen", on: "Auffüllen am", refills: "wieder auf $40.00 aufgefüllt" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
@@ -101,6 +102,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const row = (id) => page.locator(`.editor .accts .acc[data-account-id="${id}"]`);
const pill = (id) => row(id).locator(".abal");
const box = (id) => row(id).locator("input.abal-in");
const cur = (id) => row(id).locator(".abal-cur");
const menu = page.locator(".proto-menu");
const item = (name) => menu.locator(".pm-item", { has: page.locator(".pm-name", { hasText: new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`) }) });
const scrolled = () => page.evaluate(() => [window.scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop > 0).map((e) => `${e.className}:${e.scrollTop}`)].join(" "));
@@ -221,12 +223,70 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await box("k2").waitFor();
n = posts.length;
await box("k2").fill("¥100");
// the sign typed says yuan, and the currency beside it follows
assert.equal((await cur("k2").textContent()).trim(), "CNY");
await box("k2").press("Enter");
p = await posted(n);
assert.deepEqual(p.body, { id: "relay", account: "k2", balance: 100, currency: "cny" });
await page.waitForTimeout(250);
assert.equal(await pill("k2").textContent(), w.yuan);
// k1's $40 was meant in yuan (tenacious_eagle): the currency is
// picked beside the field, the number kept as typed, and nothing
// is posted before Enter
await still("k1");
await menu.waitFor();
await item(w.enter).click();
await box("k1").waitFor();
assert.equal(await box("k1").inputValue(), "40");
assert.equal((await cur("k1").textContent()).trim(), "USD");
n = posts.length;
await cur("k1").click();
await menu.waitFor();
assert.equal(await menu.locator(".pm-head").textContent(), w.currency);
assert.equal(await menu.locator(".pm-item.on .pm-name").textContent(), "$ USD");
await item("¥ CNY").click();
await page.waitForTimeout(200);
assert.equal(posts.length, n, "picking the currency posted");
assert.equal(await box("k1").inputValue(), "40");
assert.equal((await cur("k1").textContent()).trim(), "CNY");
assert.equal(await box("k1").evaluate((e) => e === document.activeElement), true, "the field lost its focus");
assert.equal(await box("k1").getAttribute("aria-label"), await page.evaluate(() => t("Balance, in CNY")));
assert.equal(await page.evaluate(() => [...document.querySelectorAll(".editor .accts .acc")].filter((e) => e.getBoundingClientRect().right > innerWidth + 1).length), 0, "the field's row past the window's edge");
await box("k1").press("Enter");
p = await posted(n);
assert.deepEqual(p.body, { id: "relay", account: "k1", balance: 40, currency: "cny" });
await page.waitForTimeout(250);
assert.equal(await pill("k1").textContent(), w.yuan40);
// k2's ¥100 back to dollars by the keyboard, saved as it is left;
// Escape in the menu picks nothing and posts nothing
await still("k2");
await menu.waitFor();
await item(w.enter).click();
await box("k2").waitFor();
assert.equal(await box("k2").inputValue(), "100");
assert.equal((await cur("k2").textContent()).trim(), "CNY");
n = posts.length;
await cur("k2").click();
await menu.waitFor();
await page.keyboard.press("Escape");
await page.waitForTimeout(200);
assert.equal(await menu.count(), 0);
assert.equal(posts.length, n, "Escape in the currency's menu posted");
assert.equal((await cur("k2").textContent()).trim(), "CNY");
await cur("k2").click();
await menu.waitFor();
await item("$ USD").click();
await page.waitForTimeout(200);
assert.equal(posts.length, n, "picking the currency posted");
await page.keyboard.press("Tab");
await page.keyboard.press("Tab");
p = await posted(n);
assert.deepEqual(p.body, { id: "relay", account: "k2", balance: 100 });
await page.waitForTimeout(250);
assert.equal(await pill("k2").textContent(), w.usd100);
await still("k1");
await menu.waitFor();
n = posts.length;