gui: opening the Usage page or the tray panel's Allowances reads the allowances now, once in 30s (#1588, qq666666qq)
On Windows the tray panel's Allowances tab, and the window brought back
on Usage, showed the reading magpie kept until "Read the allowances
again now" was pressed: picking the panel's tab and the panel shown
again only loaded usage/quotas without ?asked=1, which hands back the
backend's cache, and so did the window coming back to the front on
the Usage page.
Opening the allowances is now asking to see them (quotasOpened), as
Refresh now is and as #1518 counts the Usage page opened:
- the window: Usage from the nav (as before), the Overview tab picked,
and the window back to the front on the Overview;
- the tray panel: the Allowances tab picked, the panel brought up on it
(focus / visibility), and a menu bar cell clicked (panelQuotaFocus).
A panel page loaded while it is put away (hidden or without focus)
doesn't ask, so a panel prepared at login sends nothing with allowance
reads at "When I ask".
An asked read makes the backend read every account again (AskUsage
clears the caches; only Claude has its own 30s floor), so an opening
within 30s of the last asked read (QUOTAS_OPEN_GAP) sends an ordinary
read instead: switching tabs and back, focus and visibilitychange both
firing, focus-follows-mouse don't reach the vendors again. Reads stay
one at a time: an opening during an ordinary read goes after it
(loadQuotas, unchanged). Refresh now still asks every time; the timed
refresh is unchanged and never asks.
Written against main from qq666666qq's fork patch
(qq666666qq/magpie#1), which asked on every tab click and every return
without a gap; this keeps their entries and adds the gap, the Overview
tab, and the hidden-panel guard.
Run: new allowance-open-read.test.cjs (Chromium and WebKit, en and zh,
panel at 360px): passes; red on the old app.js (the panel's Allowances
never asks; the window re-asks on every nav click), red with
QUOTAS_OPEN_GAP = 0, and red with the window-return line removed. The
GUI tests touching the allowances (every test naming usage/quotas, the
Usage view or the panel's Allowances tab) in both engines, and
go test -tags nogui ./internal/gui. No Go changes. Not tried in the
native Windows tray.
Of the GUI run (3164 tests, load ~120-230), the 8 failures passed when
their files were run again, except library-mcp-tool-switch in WebKit,
which fails the same with main's app.js (76db4c6c2): filed as #1609.
Rebased onto f6e1e98ee; the new test, claude-usage-asked, panel-usage,
panel-arrange, click-scroll and ./internal/gui run again after it.
This commit is contained in:
@@ -153,6 +153,7 @@ retry after a failed read. See `TestRecentCallBodiesOnDemand` and
|
||||
- A click never moves the page. Code scrolls a view only with the reader's event in hand (`scrollOnPurpose`); `click-scroll.test.cjs` guards this. A click is taken where the reader left the view: a scroll not theirs made just before it, whose scroll event the browser sends only at the next frame, after the click, is put back first (`backToReader` in the click guard, #1554).
|
||||
- There are no native `<select>` elements and no colored left-border stripes. State is shown with a dot or a swatch.
|
||||
- The Usage page's cards and the tray panel's Allowances tab share one order, `settings.UsageOrder` (`byUsageOrder`). In the panel a balance-only card stands where that order puts it, and balances next to each other share one *Balances* grid (`panelBalances`, #1510); none is gathered after the plans. The panel's *Arrange* (`panelArrange`) moves rows in it and hides subscriptions from that tab alone (`settings.PanelUsageHidden`); both save through `POST /api/usage/arrange`, which changes only the field it is sent, and the Settings save keeps both. Hiding is display only: a menu bar cell's card shows though hidden (`panelPeek`). See `TestUsageArrangePanelHidden`, `panel-arrange.test.cjs` and `panel-balance-order.test.cjs`.
|
||||
- Opening the allowances is asking to see them (#1588, `quotasOpened` in `app.js`): the Usage page from the nav or its Overview tab picked, the window brought back to the front on the Overview, the tray panel's Allowances tab picked or the panel brought up on it, and a menu bar cell clicked each load `usage/quotas?asked=1`, as Refresh now does. An asked read makes the backend read every account again (`AskClaudeUsage`), so an opening within 30s (`QUOTAS_OPEN_GAP`) of the last asked read sends an ordinary read instead, which joins one on its way; Refresh now always asks. A panel page loaded while it is put away (hidden, or without focus) doesn't ask. The timed refresh is unchanged and never asks. See `allowance-open-read.test.cjs`.
|
||||
- The Usage page's cards are packed into columns, never stretched to a row's height (`packUsage`, #860): each card in that order goes to the leftmost column that ends highest, on 1px grid rows, so short cards stack beside a tall one. The page's order (DOM, dragging, Alt+arrows) stays `UsageOrder`. The column count is the most 260px columns that fit, or one fewer when that leaves much less empty room; it is chosen again only when the cards change or the width fits another number of columns, so a card opened or folded stays where it is, even as the scrollbar comes in. See `usage-pack.test.cjs`.
|
||||
- The page must work in Chromium (Windows' WebView2) and WebKit (macOS, and WebKitGTK on Linux). GUI tests run in both engines.
|
||||
- On Linux the panel is frameless and the main window has a hidden title bar (`plainTitlebar`). GTK 3 asks KDE's Wayland session (KWin's decoration protocol) for a frame drawn by KWin on any window without client-side decorations, an undecorated one too, so `ownFrame` tells KWin the panel draws its own on each realize (#1283). GTK 4 builds ask for none themselves. With no KWin title bar, and with a Wayland window placed by the compositor rather than by the icon, the panel's header is its drag handle on Linux, as the window's is (`--wails-draggable` in `app.js`; `panel-drag-linux.test.cjs`); on the Mac and Windows the panel isn't dragged (#1430).
|
||||
|
||||
@@ -31,7 +31,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| Import from files | `ImportLogins` (ChatGPT, Claude), `ImportGoogleAccounts` (Antigravity) and `ImportFactoryKeys` take other tools' files, from the window (`signin/import`) or `magpie accounts import` (#1453). ChatGPT reads Codex's `auth.json`, CLIProxyAPI's and Cockpit Tools' files, Sub2API's export (`sub2apiEntry`) and codexbar's `~/.codexbar/config.json` (`codexbarEntries`: the `openai_oauth` provider's accounts and `openAI.remoteConnectionAccounts`, the workspace from `openAIAccountId`). Each ChatGPT and Google sign-in is refreshed before it is added, so the tool the file came from is signed out of it; both surfaces say so first, and the command imports nothing without `--yes` or a yes. Claude's are kept as the file has them. A refresh token magpie holds already is `exists`, never refreshed; accounts are matched by email and workspace (`sameLogin`). An entry with an access token and no refresh token is refused (`accessOnly`). One file of several that holds no account is a failed row with its place (`ImportedAccount.File`), never skipped. The files are only read. | [`login_import.go`](../../internal/provider/login_import.go), [`google_import.go`](../../internal/provider/google_import.go), [`factory_key.go`](../../internal/provider/factory_key.go), [`accounts_cli.go`](../../accounts_cli.go) |
|
||||
| Used-up switch | When the account Codex or Claude Code is signed in to has used its allowance, the agent is signed in to the next account that is on and has room (#208). | [`codex_switch.go`](../../internal/provider/codex_switch.go) |
|
||||
| Routing groups | User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). Members are `provider/model[:effort]`. A group can nest another (`group/<id>`); `SaveGroup` refuses loops. `Match` takes a glob or `re:` pattern (#766). A found group follows its providers: one switched off or removed leaves it, and one on again is back. A found group the user changed (an `auto-…` id stored) is read without the members of providers magpie no longer has (`withoutRemoved`, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing page says them as switched off (`memberJSON.providerOff`). The user's own groups keep their members. Three templates make a group in one click from the models the user has (`provider.Templates`, `AddTemplate`; the Routing page's cards before a first group and its Templates menu after, `magpie group template [kind] [name]`): `smart` sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); `thrifty` starts on two cheap models of different providers and sends high reasoning to the strongest; `steady` fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (`sizeOf`); one over `tooDear` (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (`Need`). It is saved under a name and id no group has (`freeGroupName`, shared with `CopyGroup`), never over one. A group is shared as text (`ShareGroup`, a group row's Copy to share): JSON marked `"magpie": "routing-group"` with a format `version` (`ShareVersion`), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only `provider/model` ids, never a key, account or address, and the derived matches, found/hidden/off flags and the rules that hold by a folder (a path on the sharer's machine, `Rule.Folders`) stay behind; a pasted one is left out too. `ImportGroup` (the Routing page's Import, `POST /api/groups/import`) reads it with words or a code fence around it, refuses another text, a newer format or none (`ShareError`, said in the reader's language). A member whose provider the importer has is kept; else the same model (`AutoGroupOf`) under the first provider of theirs that serves it (`Instead`); else it is left out and named (`Missing`), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. A group of patterns only that match nothing now (a plugin's models not listed) has no members: `/api/groups` says them, and an unmakeable template's, as `[]`, never `null`; the Routing page reads the response through `groupsFrom` and draws a group it still can't draw as one row saying so, so one bad group never hides the rest (#1585). | [`group.go`](../../internal/provider/group.go), [`grouptemplate.go`](../../internal/provider/grouptemplate.go), [`group_share.go`](../../internal/provider/group_share.go) |
|
||||
| Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it. A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). Each key of a remote-magpie provider also gets a card of its own, under `<remote>/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=<remote>/~keys&user=<key name>`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page opened or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) |
|
||||
| Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it. A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). Each key of a remote-magpie provider also gets a card of its own, under `<remote>/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=<remote>/~keys&user=<key name>`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) |
|
||||
| A remote magpie's prices | A local magpie asks a remote magpie's `/v1/models` with `X-Magpie-Prices` (`PricesHeader`, sent by `listHeaders`). The remote answers each model's `magpie_price`: what its own Usage page counts the model at (`EntryPriceIn`: the price its user set, else its provider's list price at its price rate; a routing group only when every member costs the same). It tells it only to a request from its own computer or one let in with a gateway key (`local` or `sharedWith`); a list that didn't ask gets no prices (a remote request without a valid key never reaches the list: `lanGuard` refuses it). The local keeps the price with the fetched list (`catalog.Model.Price`; a value that isn't a price, or has a negative part, is dropped, the model kept) and uses it as that provider's list price (`ListPrice` → `remotePrice`). A price the local user set (`provider/model`, `provider/*`, `*/model`) still comes first, and the local provider's own price rate still applies on top. A remote from before this sends no field and the models stay priced as before; an older local sends no header and is sent nothing new. The model editor says the greyed price is the other magpie's (`remoteList`). | [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`models.go`](../../internal/provider/models.go), [`gateway.go`](../../internal/gateway/gateway.go) (`models`), [`live.go`](../../internal/catalog/live.go) |
|
||||
| A remote magpie's service tiers | A remote magpie's `/v1/models`, asked with `X-Magpie-Drawers` (`DrawersHeader`), gives each model the `service_tiers` its own Codex is offered on it (`codexTiers` → `codexcat.ServiceTiers`, from the same `CodexCatalog` and `codexcat.Entries` as its `/v1/codex/models`: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). The local keeps the ids (`catalog.Model.Tiers` → `Entry.Tiers`), `codexListed` hands them on for the remote's models, and `codexcat.Entries` offers them to the local Codex with Codex's own names (`namedTiers`). The gateway sends the tier Codex asks for to a remote magpie as it was asked (`Request.OwnTier`, as for a provider added by its address; dropped and not sent again if refused), and the remote serves it as its own Codex's turn (#1234). A remote from before this sends no tiers, and its models are offered none, as before. | [`codexcat.go`](../../internal/codexcat/codexcat.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`gateway.go`](../../internal/gateway/gateway.go), [`live.go`](../../internal/catalog/live.go) |
|
||||
| A membership's $0 catalog | models.dev lists every model of Kimi Code's plans (`kimi-code-plan-global`, `kimi-code-plan-cn`) at $0: what the membership charges per token, not what the model costs. `membershipCatalogs` are never read for a price (`priceCatalogs`, `makerPriceCatalogs`), so a Kimi Code provider's model is priced at the Kimi API model it is (`kimiCodeAPI`, from Kimi Code's docs: k3 and k3-256k are kimi-k3, kimi-for-coding-highspeed is kimi-k2.7-code-highspeed), and kimi-for-coding (K2.8 Preview, not on the API) is unpriced rather than free (#1370). The alias is Kimi Code's alone: a relay's own `k3` keeps its own price. The Requests list names the API model it was priced as (`PricedNameFor`). | [`models.go`](../../internal/provider/models.go) |
|
||||
|
||||
@@ -3298,12 +3298,16 @@ async function load(again) {
|
||||
paintUpdateAll(true);
|
||||
loadCLIs(); // after the rows, never holding them up
|
||||
loadInstalls();
|
||||
if (mode === "panel") { renderPanelQuota(); loadQuotas(); }
|
||||
// the panel brought up on its Allowances tab is the reader opening
|
||||
// them (#1588); the page loaded while the panel is still put away is not
|
||||
if (mode === "panel") { renderPanelQuota(); panelTab === "usage" && !document.hidden && (again || document.hasFocus()) ? quotasOpened() : loadQuotas(); }
|
||||
// an open provider editor is someone typing: coming back to the window
|
||||
// must not rebuild it under them
|
||||
if ((view === "providers" || view === "gateway") && !(editing || adding)) await loadProviders();
|
||||
// the window back on the Usage page reads the tab shown as its own timer
|
||||
// does: drawn again only on a change, with no skeleton between
|
||||
// does: drawn again only on a change, with no skeleton between; on the
|
||||
// Overview, where the allowances are, that is opening them (#1588)
|
||||
if (view === "usage" && again && usageTab === "usage") quotasOpened();
|
||||
if (view === "usage") await (again && usageDrawn() ? refreshUsage() : loadUsage());
|
||||
// so is an open sync form (WebDAV, export, import): its passwords are
|
||||
// never sent back, so a rebuild would empty it
|
||||
@@ -13479,7 +13483,7 @@ let usageRead = 0;
|
||||
async function loadUsage(asked) {
|
||||
renderUsageTab();
|
||||
renderUsageEvery(); // the refresh's tooltip says what it reads on this tab
|
||||
if (asked) loadQuotas(true);
|
||||
if (asked) quotasOpened();
|
||||
if (usageTab === "sessions") return loadSessions();
|
||||
if (usageTab === "requests") return loadLedger();
|
||||
if (usageTab === "context") return window.loadContext?.();
|
||||
@@ -13492,6 +13496,21 @@ async function loadUsage(asked) {
|
||||
renderUsage();
|
||||
}
|
||||
|
||||
// quotasOpened: the reader opened what shows the allowances (the Usage
|
||||
// page's Overview, the tray panel's Allowances tab, a menu bar cell, either
|
||||
// brought back to the front), which is asking to see them now (#1588,
|
||||
// qq666666qq), as Refresh now is: an asked read, the one that goes out
|
||||
// with allowances read only when asked (#1518). Each one asked makes the
|
||||
// backend read every account again, so opening within QUOTAS_OPEN_GAP of
|
||||
// the last asked read (switching tabs and back, the window's focus and
|
||||
// visibility both firing, focus-follows-mouse) asks nothing: it takes what
|
||||
// is kept, or the read on its way. Refresh now asks every time.
|
||||
const QUOTAS_OPEN_GAP = 30e3;
|
||||
let quotasAskedAt = -Infinity;
|
||||
function quotasOpened() {
|
||||
return loadQuotas(performance.now() - quotasAskedAt >= QUOTAS_OPEN_GAP);
|
||||
}
|
||||
|
||||
// An asked load is never swallowed by one already on its way that wasn't:
|
||||
// it goes after it.
|
||||
// An answer said to be read while the accounts' usage is being read again
|
||||
@@ -13502,6 +13521,7 @@ async function loadUsage(asked) {
|
||||
let quotasLoading = null, quotasLater = 0, quotasTries = 0;
|
||||
function loadQuotas(asked, again) {
|
||||
if (quotasLoading && (!asked || quotasLoading.asked)) return quotasLoading;
|
||||
if (asked) quotasAskedAt = performance.now();
|
||||
if (!again) quotasTries = 0;
|
||||
let reading = false, same = false;
|
||||
const p = Promise.resolve(quotasLoading).catch(() => {})
|
||||
@@ -14728,6 +14748,7 @@ function panelQuotaFocus(id) {
|
||||
panelPeek = id;
|
||||
panelArranging = false;
|
||||
setPanelTab("usage");
|
||||
quotasOpened(); // the cell clicked opens them (#1588)
|
||||
renderPanelQuota();
|
||||
requestAnimationFrame(focusQuotaCard);
|
||||
}
|
||||
@@ -14738,7 +14759,8 @@ if (mode === "panel") {
|
||||
tabs.setAttribute("role", "tablist");
|
||||
for (const b of tabs.querySelectorAll("button")) {
|
||||
b.setAttribute("role", "tab");
|
||||
b.onclick = () => setPanelTab(b.dataset.ptab);
|
||||
// Allowances picked is the reader opening them (#1588)
|
||||
b.onclick = () => { setPanelTab(b.dataset.ptab); if (panelTab === "usage") quotasOpened(); };
|
||||
}
|
||||
setPanelTab(panelTab);
|
||||
// the bar drawn before the panel has its width puts the card again, still;
|
||||
@@ -17624,7 +17646,8 @@ function renderUsageTab() {
|
||||
usageTab = id;
|
||||
try { localStorage.setItem("magpie.usageTab", id); } catch {}
|
||||
$("#usageCost").replaceChildren();
|
||||
loadUsage().catch((e) => status(e.message, "err"));
|
||||
// to the Overview is to the allowances (#1588)
|
||||
loadUsage(id === "usage").catch((e) => status(e.message, "err"));
|
||||
};
|
||||
seg.append(b);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Opening the allowances reads them now (#1588, qq666666qq): the Usage page
|
||||
// from the nav, the window brought back on it, the tray panel's Allowances
|
||||
// tab picked or the panel brought back on it, and a menu bar cell each load
|
||||
// usage/quotas?asked=1, as Refresh now does. The vendors aren't asked again
|
||||
// for an opening within 30s of the last asked read (switching tabs and
|
||||
// back, focus and visibility both firing); Refresh now always asks, and the
|
||||
// timed refresh never does. The fake backend answers an unasked read with
|
||||
// the reading it kept, an asked one with the new reading, as AskUsage has
|
||||
// the backend do. Chromium and WebKit, English and Chinese, the panel at
|
||||
// its narrow width.
|
||||
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(process.env.MAGPIE_ASSETS || path.join(__dirname, "../assets"));
|
||||
|
||||
function serve(lang, acct) {
|
||||
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: { lang, theme: "light", quotaReads: "asked" } });
|
||||
if (url.pathname === "/api/usage/quotas") {
|
||||
const asked = url.searchParams.get("asked") === "1";
|
||||
acct.reads.push(asked ? "asked" : "kept");
|
||||
if (acct.hold) await acct.hold;
|
||||
if (asked) acct.kept = acct.vendor;
|
||||
return json([{ provider: "codex", name: "Codex", user: "a@example.com", plan: "plus",
|
||||
windows: [{ name: "5 hours", used: acct.kept, resetsAt: "2030-01-01T00:00:00Z" }] }]);
|
||||
}
|
||||
if (url.pathname === "/api/usage/quotas/history") return json([]);
|
||||
if (url.pathname === "/api/usage") return json({ calls: 1, input: 100, output: 10, cost: 0.01, series: [], agents: [], models: [] });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true } });
|
||||
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: "" }); }
|
||||
};
|
||||
}
|
||||
|
||||
async function open(browser, t, surface, lang) {
|
||||
const acct = { reads: [], kept: 10, vendor: 40, hold: null };
|
||||
const errors = [];
|
||||
const context = await browser.newContext({ viewport: surface === "panel" ? { width: 360, height: 640 } : { width: 1000, height: 760 }, reducedMotion: "reduce" });
|
||||
t.after(() => context.close());
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.clock.install();
|
||||
await page.route("**/*", serve(lang, acct));
|
||||
await page.goto(surface === "panel" ? "http://magpie.test/?mode=panel" : "http://magpie.test/");
|
||||
const card = surface === "panel" ? ".pq-card" : ".subscription-card";
|
||||
// what the page shows once the reads on their way are in
|
||||
const shows = (n) => page.waitForFunction(([s, n]) => !quotasLoading && document.querySelector(s)?.textContent.includes(n + "%"), [card, n]);
|
||||
const settle = () => page.waitForFunction(() => !quotasLoading);
|
||||
const asked = () => acct.reads.filter((r) => r === "asked").length;
|
||||
return { page, acct, errors, shows, settle, asked };
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh"]) {
|
||||
test(`${engine} ${lang}: opening the Usage page reads the allowances, once in 30s`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const { page, acct, errors, shows, settle, asked } = await open(browser, t, "window", lang);
|
||||
const nav = (v) => page.locator(`#nav [data-view="${v}"]`).click();
|
||||
await page.locator('#nav [data-view="usage"]').waitFor();
|
||||
await settle();
|
||||
assert.equal(asked(), 0, "the Agents page asks nothing");
|
||||
|
||||
await nav("usage");
|
||||
await shows(40);
|
||||
assert.equal(asked(), 1, `opening Usage asks: ${acct.reads}`);
|
||||
|
||||
// back and forth, and the window's focus and visibility both firing,
|
||||
// within the gap: the vendors aren't asked again
|
||||
acct.vendor = 55;
|
||||
await nav("agents");
|
||||
await nav("usage");
|
||||
await page.evaluate(() => { window.dispatchEvent(new Event("focus")); document.dispatchEvent(new Event("visibilitychange")); });
|
||||
await settle();
|
||||
assert.equal(asked(), 1, `reopened within 30s, nothing asked: ${acct.reads}`);
|
||||
await shows(40);
|
||||
|
||||
// the window brought back to the front on Usage later asks, once,
|
||||
// though focus and visibility both fire
|
||||
await page.clock.fastForward(31e3);
|
||||
await settle();
|
||||
const n = asked();
|
||||
await page.evaluate(() => { window.dispatchEvent(new Event("focus")); document.dispatchEvent(new Event("visibilitychange")); });
|
||||
await shows(55);
|
||||
assert.equal(asked(), n + 1, `the window back on Usage asks once: ${acct.reads}`);
|
||||
|
||||
// Refresh now asks whatever the gap
|
||||
acct.vendor = 70;
|
||||
await page.locator("#usageReload").click();
|
||||
await shows(70);
|
||||
assert.equal(asked(), n + 2, `Refresh now asks: ${acct.reads}`);
|
||||
|
||||
// the Requests tab doesn't show allowances, the Overview picked again does
|
||||
await page.clock.fastForward(31e3);
|
||||
await settle();
|
||||
const m = asked();
|
||||
await page.locator("#usageTab .opt").nth(1).click();
|
||||
await page.evaluate(() => window.dispatchEvent(new Event("focus")));
|
||||
await settle();
|
||||
assert.equal(asked(), m, `the Requests tab brought back asks nothing: ${acct.reads}`);
|
||||
acct.vendor = 80;
|
||||
await page.locator("#usageTab .opt").first().click();
|
||||
await shows(80);
|
||||
assert.equal(asked(), m + 1, `the Overview picked asks: ${acct.reads}`);
|
||||
|
||||
// the timed refresh, left alone for minutes, never asks
|
||||
const k = asked();
|
||||
for (let i = 0; i < 4; i++) { await page.clock.fastForward(61e3); await settle(); }
|
||||
assert(acct.reads.length > 0);
|
||||
assert.equal(asked(), k, `the timer asks nothing: ${acct.reads}`);
|
||||
assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), "the page fits");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang}: opening the tray panel's Allowances reads them, once in 30s`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const { page, acct, errors, shows, settle, asked } = await open(browser, t, "panel", lang);
|
||||
const tab = (v) => page.locator(`#ptabs [data-ptab="${v}"]`).click();
|
||||
await shows(10);
|
||||
assert.equal(asked(), 0, "the panel on Agents asks nothing");
|
||||
// on Agents, the panel brought back asks nothing either
|
||||
await page.evaluate(() => window.dispatchEvent(new Event("focus")));
|
||||
await settle();
|
||||
assert.equal(asked(), 0, "the panel back on Agents asks nothing");
|
||||
|
||||
await tab("usage");
|
||||
await shows(40);
|
||||
assert.equal(asked(), 1, `Allowances picked asks: ${acct.reads}`);
|
||||
|
||||
acct.vendor = 55;
|
||||
await tab("agents");
|
||||
await tab("usage");
|
||||
await tab("usage");
|
||||
await page.evaluate(() => { window.dispatchEvent(new Event("focus")); document.dispatchEvent(new Event("visibilitychange")); panelQuotaFocus("codex|a@example.com"); });
|
||||
await settle();
|
||||
assert.equal(asked(), 1, `reopened within 30s, nothing asked: ${acct.reads}`);
|
||||
|
||||
// the panel brought back up on Allowances later asks, once
|
||||
await page.clock.fastForward(31e3);
|
||||
await settle();
|
||||
let n = asked();
|
||||
await page.evaluate(() => { window.dispatchEvent(new Event("focus")); document.dispatchEvent(new Event("visibilitychange")); });
|
||||
await shows(55);
|
||||
assert.equal(asked(), n + 1, `the panel back on Allowances asks once: ${acct.reads}`);
|
||||
|
||||
// a menu bar cell clicked later asks too
|
||||
await page.clock.fastForward(31e3);
|
||||
await settle();
|
||||
n = asked();
|
||||
acct.vendor = 60;
|
||||
await page.evaluate(() => panelQuotaFocus("codex|a@example.com"));
|
||||
await shows(60);
|
||||
assert.equal(asked(), n + 1, `a menu bar cell asks: ${acct.reads}`);
|
||||
|
||||
// an ordinary read on its way doesn't swallow the opening: the asked
|
||||
// one goes after it, one at a time
|
||||
await page.clock.fastForward(31e3);
|
||||
await settle();
|
||||
await tab("agents");
|
||||
let release;
|
||||
acct.hold = new Promise((r) => (release = r));
|
||||
const before = acct.reads.length;
|
||||
await page.evaluate(() => { loadQuotas(); });
|
||||
await page.waitForFunction(() => !!quotasLoading);
|
||||
acct.vendor = 65;
|
||||
await tab("usage");
|
||||
acct.hold = null;
|
||||
release();
|
||||
await shows(65);
|
||||
assert.deepEqual(acct.reads.slice(before), ["kept", "asked"], "the asked read went after the one on its way");
|
||||
|
||||
// the card fits the narrow panel
|
||||
assert(await page.locator(".pq-card").first().evaluate((e) => e.scrollWidth <= e.clientWidth + 1), "the card fits");
|
||||
assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), "the panel fits");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,8 @@
|
||||
// Code's own /usage, and only when the Usage page is opened or Refresh is
|
||||
// pressed. Opening the page and Refresh (the header's, which on the Overview
|
||||
// is the allowances' too, #486) load usage/quotas?asked=1; the
|
||||
// window coming back to the front and the timed reload load it without; an
|
||||
// window coming back to the front within 30s of that (#1588,
|
||||
// allowance-open-read.test.cjs) and the timed reload load it without; an
|
||||
// asked load isn't swallowed by an unasked one already on its way, it goes
|
||||
// after it. Chromium and WebKit; no backend, the API is faked here.
|
||||
const assert = require("node:assert/strict");
|
||||
@@ -156,7 +157,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await settle(1);
|
||||
assert.equal(asked(), 1, `opening Usage asks once: ${JSON.stringify(asks)}`);
|
||||
|
||||
// the window coming back to the front reads what is kept, asking nothing
|
||||
// the window coming back to the front at once reads what is kept, asking nothing
|
||||
let n = asks.length;
|
||||
await page.evaluate(() => window.dispatchEvent(new Event("focus")));
|
||||
await settle(n + 1);
|
||||
|
||||
Reference in New Issue
Block a user