provider, netproxy, gui: allowances can be read only when asked, and a system proxy set after start is taken within seconds (#1518, RooobinYe)
The reporter starts magpie at login with the proxy on "follow system
proxy". magpie comes up before the proxy app. With no system proxy set
yet, netproxy.For gives none, so magpie's own allowance reads went out
direct, from the user's real IP. That reading was then kept for up to
15s. A system proxy that is set but not listening fails the request
("proxyconnect ... connection refused"); it never falls back to direct.
Proxy freshness:
- netproxy.System re-reads a "none" reading after 2s (noneKeep) instead
of 15s (systemKeep, unchanged for a set proxy).
- The plugin host looks again every 2s while it has no proxy
(proxyLookNone), so a host started before the proxy app takes it soon.
- Catalog sync, the update check, plugin updates and token refresh all go
through netproxy.Func / Dispatch, so they use the current proxy too.
Settings -> Allowances -> "Allowance reads": Automatic (default, as
before) or When I ask (settings.QuotaReads = "asked",
POST /api/settings/quota-reads):
- These count as asking (provider.Asked): 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.
- Every other read (quotaReading -> holdUnasked) carries netproxy.Hold.
netproxy.Func, Dispatch's choice proxies and the plugin host's calls
refuse a held request before it leaves.
- The readers return the last reading, dated (AsOf), or "not read yet".
That covers routing's Allowances / AwaitAllowance, the used-up switch,
the menu bar, alerts, Quotas/KeyBalances/PlanQuotas, Codex/Claude/
Cursor/Grok/Kiro usage and KeyAllowance.
- An account refused for its quota (StaleAllowance) or a key refused
(StaleKeyAllowance) is still read, once.
- Warm-up and check-in are unchanged.
- Strings are added in zh, zh-TW, ja and de. The docs are updated:
providers-accounts (Allowance row), provider-plugins (host proxy).
Run:
- go test -tags nogui ./... (sandbox HOME), gofmt -l, and go vet -tags
nogui on GOOS=linux/windows/darwin for ., netproxy, plugin, settings,
provider, gui and tui.
- New tests, each seen red by breaking the change by hand:
- TestSystemProxySetAfterStartIsTakenSoon and TestHeldRequestNeverLeaves
(netproxy).
- TestHostWithNoProxyLooksAgainSoon (plugin; red with 15s).
- TestAllowancesReadOnlyWhenAsked (red without the hold and without
markStaleRead), TestAllowancesReadByThemselvesByDefault and
TestKeyReadsOnlyWhenAsked (red without holdUnasked and without
unheld for a refused key).
- GUI quota-reads.test.cjs in Chromium and WebKit, at 900 and 360px, in
en/zh/zh-TW/ja/de.
- i18n-keys, gui-ja, gui-de, settings-sections, settings-groups,
currency, number-units and tray-bird.
This commit is contained in:
+2
-1
@@ -261,7 +261,8 @@ type quotaSpan = provider.QuotaSpan
|
||||
// accountRows asks each agent's accounts for their allowance at once; what
|
||||
// was asked less than a minute ago comes from magpie's cache.
|
||||
func accountRows(ls []provider.Login, now time.Time) []accountRow {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
// the user asking, read even when allowances are read only when asked
|
||||
ctx, cancel := context.WithTimeout(provider.Asked(context.Background()), 15*time.Second)
|
||||
defer cancel()
|
||||
usage := map[string]map[string]provider.SubscriptionQuota{}
|
||||
seen := map[string]bool{}
|
||||
|
||||
@@ -106,7 +106,7 @@ The host gets magpie's proxy only as `MAGPIE_*_PROXY` and applies it to each fet
|
||||
|
||||
Bun takes only http:// and https:// proxies. A SOCKS5 one, such as a Mac's system SOCKS proxy, is given to every bun magpie starts as a loopback HTTP proxy in front of it (`netproxy.Bridge`): to the host through `hostEnv`, and to `bun add`, `bun update` and `bun remove` through `bunCommand` (`netproxy.EnvForBun`). Before, an install with only a SOCKS system proxy failed as `UnsupportedProxyProtocol` (#1409). An agent CLI that bun installed is updated through the bridge too (`updateEnv` in `internal/agent/cliupdate.go`).
|
||||
|
||||
The host reads its proxy once, when it starts. When the proxy magpie would give a new host differs from the one the running host got (the system proxy set after magpie started, as at login before Clash is up, or Settings changed), the next call to the host replaces it (`proxyMoved` in [`host.go`](../../internal/plugin/host.go), looked at no more than every 15s). Before this, a host started without a proxy kept none, so the Grok plugin's `grok models` couldn't renew its token and the account read as signed out after each restart (#1363).
|
||||
The host reads its proxy once, when it starts. When the proxy magpie would give a new host differs from the one the running host got (the system proxy set after magpie started, as at login before Clash is up, or Settings changed), the next call to the host replaces it (`proxyMoved` in [`host.go`](../../internal/plugin/host.go), looked at no more than every 15s, or every 2s while the host has no proxy: `proxyLookNone`, #1518). A call made for a read nobody asked for, while allowances are read only when asked (`netproxy.Held`), never reaches the host. Before this, a host started without a proxy kept none, so the Grok plugin's `grok models` couldn't renew its token and the account read as signed out after each restart (#1363).
|
||||
|
||||
A plugin's account whose sign-in its vendor refused (`lapsed`, or an allowance read saying so) keeps Sign in again and Remove on its row, whether it is in use or the agent's own (`signedOut` in `renderAccounts`, `app.js`).
|
||||
|
||||
|
||||
@@ -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. | [`group.go`](../../internal/provider/group.go), [`grouptemplate.go`](../../internal/provider/grouptemplate.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). Cursor, Grok and a Kiro key keep the page's cards only. | [`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) |
|
||||
| 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). 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), [`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) |
|
||||
@@ -117,7 +117,7 @@ no decision model was discovered (`Test` in
|
||||
## Verification
|
||||
|
||||
```sh
|
||||
go test -tags nogui ./internal/provider -run 'TestAccount|TestImport|TestCodex|TestGroup|TestQuota|TestLogin|TestSignIn|TestSeveralKeys|TestKeyProtocol|TestSetKeyWeight|TestReadSub2APIKeyLimits|TestSub2APIKeyLimitsOnItsCard|TestKeyAllowance|TestPlanKeyAllowance|TestPayAsYouGoKeyAskedSeldom|TestClaudeAccountToldRenewed|TestPluginAccountToldRenewed'
|
||||
go test -tags nogui ./internal/provider -run 'TestAccount|TestImport|TestCodex|TestGroup|TestQuota|TestLogin|TestSignIn|TestSeveralKeys|TestKeyProtocol|TestSetKeyWeight|TestReadSub2APIKeyLimits|TestSub2APIKeyLimitsOnItsCard|TestKeyAllowance|TestPlanKeyAllowance|TestPayAsYouGoKeyAskedSeldom|TestClaudeAccountToldRenewed|TestPluginAccountToldRenewed|TestAllowancesReadOnlyWhenAsked|TestAllowancesReadByThemselvesByDefault|TestKeyReadsOnlyWhenAsked'
|
||||
go test -tags nogui ./internal/provider -run 'TestCapHeld|TestCapReached|TestWindowCapHeld|TestSetWindowCap'
|
||||
go test -tags nogui . -run TestAccountCapCmd
|
||||
node --test internal/gui/tests/account-cap.test.cjs internal/gui/tests/window-cap.test.cjs
|
||||
|
||||
@@ -1024,6 +1024,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
in.RedactRules = cur.RedactRules // the masking rules, set on their own
|
||||
// used or left is the Usage page's toggle as much as Settings', set on its own
|
||||
in.QuotaLeft = cur.QuotaLeft
|
||||
in.QuotaReads = cur.QuotaReads // set on its own (quota-reads below)
|
||||
in.UsageOrder = cur.UsageOrder // the Usage page's, dragged there
|
||||
// and what the tray panel's Allowances tab leaves out, set there
|
||||
in.PanelUsageHidden = cur.PanelUsageHidden
|
||||
@@ -1132,6 +1133,24 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
}
|
||||
writeJSON(rw, settingsState())
|
||||
})
|
||||
// when allowances are read: whenever magpie needs them, or only when
|
||||
// the user asks (#1518)
|
||||
mux.HandleFunc("POST /api/settings/quota-reads", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Reads string `json:"reads"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
s := settings.Load()
|
||||
s.QuotaReads = in.Reads
|
||||
if err := settings.Save(s); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeJSON(rw, settingsState())
|
||||
})
|
||||
// the version the header's Update pill is hidden for, until a newer one
|
||||
// is out: set from the pill, cleared ("") from Settings
|
||||
mux.HandleFunc("POST /api/settings/update-skip", func(rw http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -19650,6 +19650,11 @@ let trayUsageLoading = null;
|
||||
function renderTrayUsage(s, keep) {
|
||||
$("#quotaLeftSegs").replaceChildren(segs([[false, t("Used")], [true, t("Left")]], !!s.quotaLeft,
|
||||
(on) => { if (on !== quotaLeft) setQuotaLeft(on); }));
|
||||
// allowances read by magpie itself, or only when the user asks: at login
|
||||
// before a proxy app, a read by itself goes out direct (#1518)
|
||||
$("#quotaReadsSegs").replaceChildren(segs([["", t("Automatic")], ["asked", t("When I ask")]], s.quotaReads || "", (v) =>
|
||||
writingPrefs(api("settings/quota-reads", { reads: v })).then((ns) => { prefs = state.settings = ns; renderSettings(); })
|
||||
.catch((e) => { status(t(e.message), "err"); renderSettings(); })));
|
||||
$("#currencySegs").replaceChildren(segs(CURRENCIES.map(([id, name]) => [id, t(name)]), s.currency || "usd", (v) => savePrefs({ ...keep, currency: v })));
|
||||
// 万 and 亿 are Chinese's alone: in English a count is always K, M and B
|
||||
$("#unitsRow").hidden = locale !== "zh" && locale !== "zh-TW";
|
||||
|
||||
@@ -764,6 +764,9 @@ const I18N = {
|
||||
"magpie's icon before the allowances; off, the allowances alone, and a click on one still opens the panel": "额度前面的 magpie 图标;关闭后只显示额度,点击额度仍会打开面板",
|
||||
"Each subscription's logo before its numbers; off, the numbers alone with a thin line between subscriptions": "每个订阅的数字前显示它的图标;关闭后只显示数字,订阅之间以细线分隔",
|
||||
"Allowance display": "额度显示",
|
||||
"Allowance reads": "额度刷新",
|
||||
"When I ask": "仅手动",
|
||||
"When I ask: opening or refreshing the Usage page, a card's refresh, and magpie quota or accounts read them; routing, the menu bar and alerts go by the last reading till then. An account a vendor turns away for its quota is still read.": "仅手动:打开或刷新用量页、卡片上的刷新,以及 magpie quota 或 accounts 才会读取;在那之前,路由、菜单栏和提醒都按上次读到的额度。被厂商以额度为由拒绝的账号仍会读取。",
|
||||
"How much of each window is used, or how much is left, on the Usage page, the panel and the menu bar": "每个周期显示已用额度或剩余额度,用量页、面板和菜单栏一致",
|
||||
"Currency": "货币",
|
||||
"Number units": "数字单位",
|
||||
@@ -4853,6 +4856,9 @@ const I18N = {
|
||||
"magpie's icon before the allowances; off, the allowances alone, and a click on one still opens the panel": "額度前面的 magpie 圖示;關閉後只顯示額度,點選額度仍會打開面板",
|
||||
"Each subscription's logo before its numbers; off, the numbers alone with a thin line between subscriptions": "每個訂閱的數字前顯示它的圖示;關閉後只顯示數字,訂閱之間以細線分隔",
|
||||
"Allowance display": "額度顯示",
|
||||
"Allowance reads": "額度重新整理",
|
||||
"When I ask": "僅手動",
|
||||
"When I ask: opening or refreshing the Usage page, a card's refresh, and magpie quota or accounts read them; routing, the menu bar and alerts go by the last reading till then. An account a vendor turns away for its quota is still read.": "僅手動:開啟或重新整理用量頁、卡片上的重新整理,以及 magpie quota 或 accounts 才會讀取;在那之前,路由、選單列和提醒都依上次讀到的額度。被廠商以額度為由拒絕的帳號仍會讀取。",
|
||||
"How much of each window is used, or how much is left, on the Usage page, the panel and the menu bar": "每個週期顯示已用額度或剩餘額度,用量頁、面板和選單列一致",
|
||||
"Currency": "貨幣",
|
||||
"Number units": "數字單位",
|
||||
@@ -8911,6 +8917,9 @@ const I18N = {
|
||||
"Menu bar logos": "メニューバーのロゴ",
|
||||
"Each subscription's logo before its numbers; off, the numbers alone with a thin line between subscriptions": "各サブスクリプションの数値の前にロゴを表示します。オフにすると数値のみになり、サブスクリプションの間は細い線で区切られます",
|
||||
"Allowance display": "利用枠の表示",
|
||||
"Allowance reads": "利用枠の読み込み",
|
||||
"When I ask": "手動のみ",
|
||||
"When I ask: opening or refreshing the Usage page, a card's refresh, and magpie quota or accounts read them; routing, the menu bar and alerts go by the last reading till then. An account a vendor turns away for its quota is still read.": "手動のみ:使用状況ページを開くか更新したとき、カードの更新、magpie quota または accounts で読み込みます。それまでルーティング、メニューバー、通知は前回の値を使います。利用枠を理由にベンダーに断られたアカウントは引き続き読み込みます。",
|
||||
"How much of each window is used, or how much is left, on the Usage page, the panel and the menu bar": "使用量ページ、パネル、メニューバーで、各期間の使用済み量と残量のどちらを表示するか",
|
||||
"Currency": "通貨",
|
||||
"Number units": "数値の単位",
|
||||
@@ -12988,6 +12997,9 @@ const I18N = {
|
||||
"magpie's icon before the allowances; off, the allowances alone, and a click on one still opens the panel": "magpie-Symbol vor den Kontingenten; aus: nur die Kontingente, und ein Klick auf eines öffnet weiterhin das Panel",
|
||||
"Each subscription's logo before its numbers; off, the numbers alone with a thin line between subscriptions": "Logo jedes Abos vor seinen Zahlen; ausgeschaltet nur die Zahlen mit einer dünnen Linie zwischen den Abos",
|
||||
"Allowance display": "Kontingentanzeige",
|
||||
"Allowance reads": "Kontingente abrufen",
|
||||
"When I ask": "Nur auf Anfrage",
|
||||
"When I ask: opening or refreshing the Usage page, a card's refresh, and magpie quota or accounts read them; routing, the menu bar and alerts go by the last reading till then. An account a vendor turns away for its quota is still read.": "Nur auf Anfrage: beim Öffnen oder Aktualisieren der Nutzungsseite, beim Aktualisieren einer Karte und mit magpie quota oder accounts; bis dahin richten sich Routing, Menüleiste und Hinweise nach dem zuletzt gelesenen Stand. Ein Konto, das ein Anbieter wegen seines Kontingents abweist, wird trotzdem gelesen.",
|
||||
"How much of each window is used, or how much is left, on the Usage page, the panel and the menu bar": "Wie viel jedes Zeitfensters verbraucht oder übrig ist, auf der Seite „Nutzung“, im Panel und in der Menüleiste",
|
||||
"Currency": "Währung",
|
||||
"Number units": "Zahleneinheiten",
|
||||
|
||||
@@ -363,6 +363,10 @@
|
||||
<div class="who"><div class="name" data-t>Allowance display</div><div class="sub" data-t>How much of each window is used, or how much is left, on the Usage page, the panel and the menu bar</div></div>
|
||||
<div id="quotaLeftSegs"></div>
|
||||
</div>
|
||||
<div class="row pref" id="quotaReadsRow">
|
||||
<div class="who"><div class="name" data-t>Allowance reads</div><div class="sub" data-t>When I ask: opening or refreshing the Usage page, a card's refresh, and magpie quota or accounts read them; routing, the menu bar and alerts go by the last reading till then. An account a vendor turns away for its quota is still read.</div></div>
|
||||
<div id="quotaReadsSegs"></div>
|
||||
</div>
|
||||
<div class="row pref">
|
||||
<div class="who"><div class="name" data-t>Currency</div><div class="sub" id="currencySub"></div></div>
|
||||
<div id="currencySegs"></div>
|
||||
|
||||
@@ -158,6 +158,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
|
||||
FullContext: true,
|
||||
DesktopLongest: true,
|
||||
GatewayMode: "off",
|
||||
QuotaReads: "asked",
|
||||
}
|
||||
if err := settings.Save(was); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Settings → Allowances → Allowance reads (#1518, RooobinYe): magpie
|
||||
// started at login before the proxy app read allowances by itself, direct.
|
||||
// The row offers Automatic (the default) or When I ask; When I ask posts
|
||||
// settings/quota-reads {reads:"asked"} and is drawn chosen, Automatic takes
|
||||
// it back; the row fits a narrow window without the page scrolling
|
||||
// sideways, and no click moves the page. Every language; no backend, the
|
||||
// API is faked here.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
|
||||
function settingsPayload(over) {
|
||||
return {
|
||||
theme: "light", lang: "en", tray: "panel", quotaLeft: false, currency: "usd",
|
||||
dock: false, dockWindow: false, proxy: "", redact: false, redactPersonal: false, redactWords: [],
|
||||
codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "", workbuddyCheckin: false, noStats: false,
|
||||
trayUsage: "", trayUsages: [], trayUsageEvery: 3, vision: "", imageGen: "",
|
||||
version: "0.1.400", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425",
|
||||
proxyNow: "none", proxySource: "none", login: false,
|
||||
visionModels: [], imageGenModels: [], workbuddyCheckins: [], lanURLs: [],
|
||||
fx: { rate: 7.2, at: new Date().toISOString(), stale: false },
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
function server(lang, posts) {
|
||||
let cur = settingsPayload({ lang });
|
||||
return async (route) => {
|
||||
const req = route.request(), url = new URL(req.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:false};` });
|
||||
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" }, fx: cur.fx });
|
||||
if (url.pathname === "/api/settings/quota-reads") {
|
||||
const body = req.postDataJSON();
|
||||
posts.push(body);
|
||||
cur = { ...cur, quotaReads: body.reads || undefined };
|
||||
return json(cur);
|
||||
}
|
||||
if (url.pathname === "/api/settings") {
|
||||
// the save of every other setting leaves this one as it is (api.go)
|
||||
if (req.method() === "POST") cur = { ...cur, ...req.postDataJSON(), quotaReads: cur.quotaReads };
|
||||
return json(cur);
|
||||
}
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
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)];
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const view = (page) => page.locator("#view-settings").evaluate((v) => v.scrollTop);
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": allowances read by magpie, or only when asked", async (t) => {
|
||||
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
|
||||
for (const [lang, name, auto, asked] of [
|
||||
["en", "Allowance reads", "Automatic", "When I ask"],
|
||||
["zh", "额度刷新", "自动", "仅手动"],
|
||||
["zh-TW", "額度重新整理", "自動", "僅手動"],
|
||||
["ja", "利用枠の読み込み", "自動", "手動のみ"],
|
||||
["de", "Kontingente abrufen", "Automatisch", "Nur auf Anfrage"],
|
||||
]) {
|
||||
for (const width of [900, 360]) {
|
||||
await t.test(lang + " " + width, async () => {
|
||||
const errors = [], posts = [];
|
||||
const context = await browser.newContext({ viewport: { width, height: 420 }, reducedMotion: "reduce" });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(lang, posts));
|
||||
await page.goto("http://magpie.test/?view=usage");
|
||||
await page.locator("#prefs").click();
|
||||
await page.locator("#setTab-usage").click();
|
||||
const row = page.locator("#quotaReadsRow");
|
||||
const opts = row.locator("#quotaReadsSegs .opt");
|
||||
await opts.first().waitFor();
|
||||
assert.equal((await row.locator(".name").textContent()).trim(), name);
|
||||
const sub = (await row.locator(".sub").textContent()).trim();
|
||||
assert(sub.includes("magpie quota"), "the sub says what counts as asking: " + sub);
|
||||
if (lang !== "en") assert(!sub.startsWith("When I ask"), lang + " sub not translated");
|
||||
assert.deepEqual((await opts.allTextContents()).map((s) => s.trim()), [auto, asked]);
|
||||
assert.equal(await opts.nth(0).evaluate((b) => b.classList.contains("on")), true, "Automatic by default");
|
||||
|
||||
// in a narrow window the row fits, and the page doesn't scroll sideways
|
||||
await row.scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(300);
|
||||
const fit = await row.evaluate((r) => {
|
||||
const b = r.getBoundingClientRect(), segs = r.querySelector("#quotaReadsSegs").getBoundingClientRect();
|
||||
return { right: b.right, segsRight: segs.right, vw: document.documentElement.clientWidth,
|
||||
sideways: document.scrollingElement.scrollWidth > document.documentElement.clientWidth };
|
||||
});
|
||||
assert(fit.segsRight <= fit.vw + 0.5 && fit.right <= fit.vw + 0.5, "the row runs out of the window: " + JSON.stringify(fit));
|
||||
assert.equal(fit.sideways, false, "the page scrolls sideways");
|
||||
|
||||
const before = await view(page);
|
||||
await opts.nth(1).click();
|
||||
for (let i = 0; i < 50 && !posts.length; i++) await page.waitForTimeout(50);
|
||||
assert.deepEqual(posts.at(-1), { reads: "asked" });
|
||||
await page.waitForFunction(() => document.querySelectorAll("#quotaReadsSegs .opt")[1]?.classList.contains("on"));
|
||||
await page.waitForTimeout(200);
|
||||
assert.equal(await view(page), before, "When I ask moved the page");
|
||||
|
||||
// another setting saved keeps it
|
||||
await page.locator("#currencySegs .opt").nth(1).evaluate((b) => b.click());
|
||||
await page.waitForTimeout(300);
|
||||
assert.equal(await page.locator("#quotaReadsSegs .opt").nth(1).evaluate((b) => b.classList.contains("on")), true,
|
||||
"a save of another setting put Automatic back");
|
||||
|
||||
await page.locator("#quotaReadsSegs .opt").nth(0).click();
|
||||
for (let i = 0; i < 50 && posts.length < 2; i++) await page.waitForTimeout(50);
|
||||
assert.deepEqual(posts.at(-1), { reads: "" });
|
||||
await page.waitForFunction(() => document.querySelectorAll("#quotaReadsSegs .opt")[0]?.classList.contains("on"));
|
||||
assert.deepEqual(errors, []);
|
||||
if (process.env.ARTIFACT_DIR) {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
await row.scrollIntoViewIfNeeded();
|
||||
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-quota-reads-${lang}-${width}.png`) });
|
||||
}
|
||||
await context.close();
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -173,11 +173,15 @@ func usageRoutes(mux *http.ServeMux, w Windows) {
|
||||
// apart from the local log.
|
||||
// ?asked=1 is the user opening or refreshing the page: Claude Code's
|
||||
// own /usage is run at once (provider.AskClaudeUsage).
|
||||
// Only then are they read while the user has allowances read only
|
||||
// when asked (#1518).
|
||||
mux.HandleFunc("GET /api/usage/quotas", func(rw http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
if r.URL.Query().Get("asked") != "" {
|
||||
provider.AskClaudeUsage()
|
||||
ctx = provider.Asked(ctx)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second)
|
||||
ctx, cancel := context.WithTimeout(ctx, 12*time.Second)
|
||||
defer cancel()
|
||||
// a WorkBuddy (China) account's card says how its daily check-in
|
||||
// went (#694)
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// #1518: magpie started at login, before the proxy app. The system has no
|
||||
// proxy yet, so requests go direct; once the proxy app sets one, magpie
|
||||
// takes it within a few seconds, not the 15 a set proxy is kept for.
|
||||
func TestSystemProxySetAfterStartIsTakenSoon(t *testing.T) {
|
||||
var p atomic.Value
|
||||
p.Store(Proxy{})
|
||||
oldRead, oldNone := readSystem, noneKeep
|
||||
readSystem = func() Proxy { return p.Load().(Proxy) }
|
||||
noneKeep = 50 * time.Millisecond
|
||||
sysCache.Lock()
|
||||
sysCache.at, sysCache.p = time.Time{}, Proxy{}
|
||||
sysCache.Unlock()
|
||||
t.Cleanup(func() {
|
||||
readSystem, noneKeep = oldRead, oldNone
|
||||
sysCache.Lock()
|
||||
sysCache.at, sysCache.p = time.Time{}, Proxy{}
|
||||
sysCache.Unlock()
|
||||
})
|
||||
|
||||
if got := System(); got.URL != "" {
|
||||
t.Fatalf("no proxy yet, read %+v", got)
|
||||
}
|
||||
p.Store(Proxy{URL: "http://127.0.0.1:7890"})
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
if got := System(); got.URL != "http://127.0.0.1:7890" {
|
||||
t.Fatalf("the proxy app set the system proxy, but magpie still reads %+v", got)
|
||||
}
|
||||
// A proxy that is set is kept for its own while.
|
||||
p.Store(Proxy{})
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
if got := System(); got.URL != "http://127.0.0.1:7890" {
|
||||
t.Fatalf("a set proxy was read again within %v: %+v", systemKeep, got)
|
||||
}
|
||||
}
|
||||
|
||||
// A request made with a held context never reaches the server, whatever
|
||||
// the proxy: through http.DefaultClient (Dispatch over Func), and through
|
||||
// a provider's own proxy.
|
||||
func TestHeldRequestNeverLeaves(t *testing.T) {
|
||||
var hits atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { hits.Add(1) }))
|
||||
defer srv.Close()
|
||||
base := http.DefaultTransport.(*http.Transport).Clone()
|
||||
base.Proxy = Func
|
||||
c := &http.Client{Transport: Dispatch(base)}
|
||||
defer c.CloseIdleConnections()
|
||||
why := errors.New("not asked")
|
||||
for _, ctx := range []context.Context{
|
||||
Hold(context.Background(), why),
|
||||
With(Hold(context.Background(), why), "direct"),
|
||||
Hold(With(context.Background(), "http://127.0.0.1:9"), why),
|
||||
} {
|
||||
req, _ := http.NewRequestWithContext(ctx, "GET", srv.URL, nil)
|
||||
if resp, err := c.Do(req); err == nil {
|
||||
resp.Body.Close()
|
||||
t.Fatalf("a held request was sent")
|
||||
} else if !errors.Is(err, why) {
|
||||
t.Fatalf("held request failed with %v, not its hold", err)
|
||||
}
|
||||
}
|
||||
if hits.Load() != 0 {
|
||||
t.Fatalf("server got %d held requests", hits.Load())
|
||||
}
|
||||
req, _ := http.NewRequest("GET", srv.URL, nil)
|
||||
resp, err := c.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if hits.Load() != 1 {
|
||||
t.Fatal("a request not held didn't reach the server")
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,9 @@ func Install() {
|
||||
// context names (With), or else the global one, which a host on the
|
||||
// user's own network goes around (onLAN).
|
||||
func Func(req *http.Request) (*url.URL, error) {
|
||||
if err := Held(req.Context()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if loopback(req.URL.Hostname()) {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -52,6 +55,26 @@ func Func(req *http.Request) (*url.URL, error) {
|
||||
|
||||
type choiceKey struct{}
|
||||
|
||||
type holdKey struct{}
|
||||
|
||||
// Hold is ctx for work magpie was not asked to do and must not send: no
|
||||
// request made with it through Func, or a transport Dispatch made, leaves
|
||||
// the machine; each fails with err before it dials (#1518, allowance
|
||||
// reads while the user has them read only when asked).
|
||||
func Hold(ctx context.Context, err error) context.Context {
|
||||
return context.WithValue(ctx, holdKey{}, err)
|
||||
}
|
||||
|
||||
// Held is the error ctx holds its requests with (Hold), nil when it holds
|
||||
// none.
|
||||
func Held(ctx context.Context) error {
|
||||
if ctx == nil {
|
||||
return nil
|
||||
}
|
||||
err, _ := ctx.Value(holdKey{}).(error)
|
||||
return err
|
||||
}
|
||||
|
||||
// With is ctx for requests made on behalf of one provider, whose own proxy
|
||||
// is choice (issue #237: Codex through a proxy, a vendor at home without):
|
||||
// "" follows the global one (ctx is returned as it is), "direct" goes
|
||||
@@ -125,6 +148,9 @@ func (d *dispatch) transport(c string) *http.Transport {
|
||||
}
|
||||
t := d.base.Clone()
|
||||
t.Proxy = func(req *http.Request) (*url.URL, error) {
|
||||
if err := Held(req.Context()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if loopback(req.URL.Hostname()) {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -333,12 +359,27 @@ var sysCache struct {
|
||||
p Proxy
|
||||
}
|
||||
|
||||
// System reads the system proxy, at most every 15 seconds.
|
||||
// How long a system proxy read stands: a proxy that is set, 15 seconds;
|
||||
// none, 2. magpie started at login comes up before the proxy app does
|
||||
// (#1518), and its requests went direct for up to 15 seconds after the
|
||||
// proxy app had set the system's proxy.
|
||||
var (
|
||||
systemKeep = 15 * time.Second
|
||||
noneKeep = 2 * time.Second
|
||||
readSystem = system
|
||||
)
|
||||
|
||||
// System reads the system proxy, at most every 15 seconds while one is
|
||||
// set and every 2 while none is.
|
||||
func System() Proxy {
|
||||
sysCache.Lock()
|
||||
defer sysCache.Unlock()
|
||||
if time.Since(sysCache.at) > 15*time.Second {
|
||||
sysCache.p, sysCache.at = system(), time.Now()
|
||||
keep := systemKeep
|
||||
if sysCache.p.URL == "" {
|
||||
keep = noneKeep
|
||||
}
|
||||
if sysCache.at.IsZero() || time.Since(sysCache.at) > keep {
|
||||
sysCache.p, sysCache.at = readSystem(), time.Now()
|
||||
}
|
||||
return sysCache.p
|
||||
}
|
||||
|
||||
+31
-2
@@ -1291,6 +1291,11 @@ func Call(ctx context.Context, method string, params, out any) error {
|
||||
// Background listings allow the host its own startup budget. The optional
|
||||
// timeout begins only after initialization and bounds just the requested RPC.
|
||||
func callWithTimeout(ctx context.Context, method string, params, out any, timeout time.Duration) error {
|
||||
// a read the user didn't ask for, held back (#1518): the plugin isn't
|
||||
// asked either, nor does its host start for it
|
||||
if err := netproxy.Held(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
startup := ctx
|
||||
if timeout > 0 {
|
||||
startup = context.WithoutCancel(ctx)
|
||||
@@ -1371,7 +1376,24 @@ func hostProxy(env []string) string {
|
||||
|
||||
// proxyLookEvery is how often get asks whether the proxy moved: the
|
||||
// system's is read again at most every 15 seconds anyway (netproxy.System).
|
||||
var proxyLookEvery = 15 * time.Second
|
||||
// A host started with none asks every 2 seconds, as netproxy reads the
|
||||
// system's again then: at login the proxy app comes up after magpie
|
||||
// (#1518), and the host's requests went direct until it was asked.
|
||||
var (
|
||||
proxyLookEvery = 15 * time.Second
|
||||
proxyLookNone = 2 * time.Second
|
||||
)
|
||||
|
||||
// proxied is whether a hostProxy names a proxy at all.
|
||||
func proxied(hp string) bool {
|
||||
for _, e := range strings.Split(hp, "\x00") {
|
||||
k, v, _ := strings.Cut(e, "=")
|
||||
if v != "" && !strings.EqualFold(k, "NO_PROXY") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// proxyMoved is whether magpie's proxy is no longer the one h was started
|
||||
// with (#1363): host.js reads it once, so a host started at login before
|
||||
@@ -1382,7 +1404,11 @@ var proxyLookEvery = 15 * time.Second
|
||||
// changed in Settings never reached a running host either. Called under
|
||||
// hostMu.
|
||||
func (h *host) proxyMoved() bool {
|
||||
if h.proxyAt.IsZero() || time.Since(h.proxyAt) < proxyLookEvery {
|
||||
every := proxyLookEvery
|
||||
if !proxied(h.proxy) {
|
||||
every = min(every, proxyLookNone)
|
||||
}
|
||||
if h.proxyAt.IsZero() || time.Since(h.proxyAt) < every {
|
||||
return false
|
||||
}
|
||||
h.proxyAt = time.Now()
|
||||
@@ -1412,6 +1438,9 @@ func hostEnv(env []string) []string {
|
||||
// Fetch sends r through the provider's plugin — its loader's fetch, or
|
||||
// Bun's own when it gives none — and streams back the reply.
|
||||
func Fetch(ctx context.Context, r FetchRequest) (*http.Response, error) {
|
||||
if err := netproxy.Held(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h, err := get(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// #1518: a host started at login before the proxy app had set the
|
||||
// system's proxy asks again within seconds, not after the 15 a host with
|
||||
// a proxy waits: until then every request a plugin made went direct.
|
||||
func TestHostWithNoProxyLooksAgainSoon(t *testing.T) {
|
||||
for _, k := range []string{"HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "https_proxy", "http_proxy", "all_proxy"} {
|
||||
t.Setenv(k, "")
|
||||
}
|
||||
h := &host{proxy: hostProxy(env()), proxyAt: time.Now().Add(-3 * time.Second)}
|
||||
if proxied(h.proxy) {
|
||||
t.Skip("this machine's system proxy is set; the case needs none")
|
||||
}
|
||||
t.Setenv("HTTPS_PROXY", "http://127.0.0.1:7891")
|
||||
if !h.proxyMoved() {
|
||||
t.Fatal("the proxy was set 3s after a host with none started, and the host kept going direct")
|
||||
}
|
||||
// A host with a proxy keeps its 15 seconds.
|
||||
h = &host{proxy: hostProxy(env()), proxyAt: time.Now().Add(-3 * time.Second)}
|
||||
t.Setenv("HTTPS_PROXY", "http://127.0.0.1:7892")
|
||||
if h.proxyMoved() {
|
||||
t.Fatal("a host with a proxy looked again before its 15 seconds")
|
||||
}
|
||||
}
|
||||
@@ -863,7 +863,9 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota {
|
||||
c := &keyBalanceCache
|
||||
_, again := refreshing(ctx) // one card read again (RefreshUsage)
|
||||
c.Lock()
|
||||
if !again && c.data != nil && time.Since(c.at) < time.Minute {
|
||||
// with allowances read only when asked, the cards stand as they were
|
||||
// last read till the user asks (#1518)
|
||||
if !again && c.data != nil && (time.Since(c.at) < time.Minute || heldRead(ctx)) {
|
||||
defer c.Unlock()
|
||||
return c.data
|
||||
}
|
||||
|
||||
@@ -80,6 +80,10 @@ func cursorAuthPath() string {
|
||||
|
||||
func cursorSubscriptionUsage(ctx context.Context, plan string) SubscriptionQuota {
|
||||
q := SubscriptionQuota{Provider: "cursor", Name: "Cursor", Icon: "cursor", Plan: plan, Windows: []QuotaWindow{}}
|
||||
if holding(ctx) {
|
||||
q.Error = errNotAsked.Error()
|
||||
return q
|
||||
}
|
||||
tok, err := cursorToken()
|
||||
if err == nil {
|
||||
q.Windows, err = cursorWindows(ctx, tok)
|
||||
|
||||
@@ -139,11 +139,28 @@ func grokLoginUsage(ctx context.Context) map[string]SubscriptionQuota {
|
||||
var mu sync.Mutex
|
||||
var wg sync.WaitGroup
|
||||
u := &grokHomeUsage
|
||||
held := holding(ctx)
|
||||
for _, g := range grokLogins() {
|
||||
u.Lock()
|
||||
e, ok := u.m[g.Home]
|
||||
u.Unlock()
|
||||
if ok && time.Since(e.at) < time.Minute {
|
||||
// with allowances read only when asked, what was read last, or
|
||||
// kept on disk, unless the vendor just turned the account away
|
||||
// (StaleAllowance)
|
||||
gctx := ctx
|
||||
if held && isStaleRead("grok/"+strings.ToLower(g.User)) {
|
||||
gctx = unheld(ctx)
|
||||
} else if held {
|
||||
q := e.q
|
||||
if !ok {
|
||||
q = keepLast(SubscriptionQuota{Provider: "grok", Name: "Grok (SuperGrok)", Icon: "xai", Windows: []QuotaWindow{}, Error: errNotAsked.Error()}, g.User)
|
||||
}
|
||||
mu.Lock()
|
||||
out[g.User] = q
|
||||
mu.Unlock()
|
||||
continue
|
||||
}
|
||||
if ok && time.Since(e.at) < time.Minute && !held {
|
||||
mu.Lock()
|
||||
out[g.User] = e.q
|
||||
mu.Unlock()
|
||||
@@ -158,9 +175,10 @@ func grokLoginUsage(ctx context.Context) map[string]SubscriptionQuota {
|
||||
u.pending[g.Home] = read
|
||||
u.Unlock()
|
||||
wg.Add(1)
|
||||
takeStaleRead("grok/" + strings.ToLower(g.User))
|
||||
go func(g grokLogin) {
|
||||
defer wg.Done()
|
||||
q := keepLast(grokUsageAt(ctx, g.Home), g.User)
|
||||
q := keepLast(grokUsageAt(gctx, g.Home), g.User)
|
||||
if q.Error != "" && ok {
|
||||
q = e.q // a hiccup keeps what was known
|
||||
}
|
||||
|
||||
@@ -27,6 +27,10 @@ func grokSubscriptionUsage(ctx context.Context) SubscriptionQuota {
|
||||
if c, ok := readGrokCredential(GrokHome()); ok {
|
||||
q.User = c.Email
|
||||
}
|
||||
if holding(ctx) {
|
||||
q.Error = errNotAsked.Error()
|
||||
return q
|
||||
}
|
||||
c, err := grokAccessToken(GrokHome(), GrokExecutable(), false)
|
||||
if err == nil {
|
||||
q.Windows, err = grokWindows(ctx, c.Key)
|
||||
|
||||
@@ -34,6 +34,9 @@ type keyAllowance struct {
|
||||
// stale: made stale (StaleKeyAllowance) while a reading was out, which
|
||||
// was asked before the key said it was out and is followed by another
|
||||
stale bool
|
||||
// refused: the key said it was out (StaleKeyAllowance), so it is read
|
||||
// again even while allowances are read only when asked (#1518)
|
||||
refused bool
|
||||
// read is what routing last read of the key, for its card
|
||||
// (withKeyReadings), which only the Usage page reads
|
||||
read keyReading
|
||||
@@ -106,7 +109,9 @@ func KeyAllowance(p Provider) (Allowance, bool) {
|
||||
if len(e.a) == 0 && !e.at.IsZero() {
|
||||
age = keyNoWindowsAge
|
||||
}
|
||||
if !e.loading && time.Since(e.at) > age {
|
||||
// with allowances read only when asked, routing goes by what was read
|
||||
// last till the user asks, or the key says it is out (#1518)
|
||||
if !e.loading && time.Since(e.at) > age && (e.refused || !readsAsked()) {
|
||||
e.loading = true
|
||||
go readKeyAllowance(p, id, c.gen)
|
||||
}
|
||||
@@ -117,13 +122,19 @@ func KeyAllowance(p Provider) (Allowance, bool) {
|
||||
// fails keeps what was known, and is tried again a minute later: a failed
|
||||
// read is not known, never empty.
|
||||
func readKeyAllowance(p Provider, id string, gen int) {
|
||||
ctx, seq := quotaReading(context.Background())
|
||||
ctx := context.Background()
|
||||
c := &keyAllowances
|
||||
c.Lock()
|
||||
if e := c.m[id]; e != nil && e.refused {
|
||||
e.refused, ctx = false, unheld(ctx)
|
||||
}
|
||||
c.Unlock()
|
||||
ctx, seq := quotaReading(ctx)
|
||||
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
r, err := keyWindows(ctx, p)
|
||||
ws := r.ws
|
||||
now := time.Now()
|
||||
c := &keyAllowances
|
||||
c.Lock()
|
||||
e := c.m[id]
|
||||
if e == nil || c.gen != gen {
|
||||
@@ -236,6 +247,7 @@ func StaleKeyAllowance(p Provider) {
|
||||
c.Lock()
|
||||
if e := c.m[keyAllowanceID(p)]; e != nil {
|
||||
e.at, e.stale = time.Time{}, e.loading
|
||||
e.refused = readsAsked()
|
||||
}
|
||||
c.Unlock()
|
||||
}
|
||||
|
||||
@@ -778,6 +778,10 @@ func (l kiroLimits) windows() []QuotaWindow {
|
||||
// magpie signed in in home, or Kiro's own sign-in's.
|
||||
func kiroQuotaAt(ctx context.Context, key, home string) SubscriptionQuota {
|
||||
q := SubscriptionQuota{Provider: "kiro", Name: "Kiro", Icon: "kiro-color", Windows: []QuotaWindow{}}
|
||||
if holding(ctx) {
|
||||
q.Error = errNotAsked.Error()
|
||||
return q
|
||||
}
|
||||
a, err := KiroAuthOf(ctx, key, home, false)
|
||||
if err != nil {
|
||||
q.Error = err.Error()
|
||||
|
||||
@@ -151,10 +151,23 @@ var noteHistoryWrite = noteQuotaHistory
|
||||
func loginReading(ctx context.Context, l Login) loginUsageEntry {
|
||||
key := l.Agent + "/" + strings.ToLower(l.User)
|
||||
c := &loginUsageCache
|
||||
// with allowances read only when asked, one nobody asked for is what
|
||||
// was read last, however old, unless the vendor just turned the
|
||||
// account away for its quota (StaleAllowance), which is read (#1518)
|
||||
stale := false
|
||||
if holding(ctx) {
|
||||
if stale = isStaleRead(key); stale {
|
||||
ctx = unheld(ctx)
|
||||
}
|
||||
}
|
||||
held := holding(ctx)
|
||||
c.Lock()
|
||||
e, ok := c.m[key]
|
||||
if ok && time.Since(e.at) < time.Minute {
|
||||
if ok && (held || time.Since(e.at) < time.Minute) {
|
||||
c.Unlock()
|
||||
if held {
|
||||
e.at = time.Now() // as good as it gets until asked: Allowances keeps it its minute
|
||||
}
|
||||
return e
|
||||
}
|
||||
entry := func(read SubscriptionQuota) loginUsageEntry {
|
||||
@@ -165,7 +178,16 @@ func loginReading(ctx context.Context, l Login) loginUsageEntry {
|
||||
return loginUsageEntry{time.Now(), q, read}
|
||||
}
|
||||
r := c.pending[key]
|
||||
if r == nil && held {
|
||||
// nothing read since magpie started: the reading kept on disk,
|
||||
// as of when it was made
|
||||
c.Unlock()
|
||||
return entry(keepLast(SubscriptionQuota{Provider: loginProvider(l), Plan: l.Plan, Windows: []QuotaWindow{}, Error: errNotAsked.Error()}, l.User))
|
||||
}
|
||||
if r == nil {
|
||||
if stale {
|
||||
takeStaleRead(key)
|
||||
}
|
||||
r = &loginRead{done: make(chan struct{})}
|
||||
if c.pending == nil {
|
||||
c.pending = map[string]*loginRead{}
|
||||
|
||||
@@ -570,7 +570,9 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota {
|
||||
c := &planQuotaCache
|
||||
_, again := refreshing(ctx) // one card read again (RefreshUsage)
|
||||
c.Lock()
|
||||
if !again && c.data != nil && time.Since(c.at) < time.Minute {
|
||||
// with allowances read only when asked, the cards stand as they were
|
||||
// last read till the user asks (#1518)
|
||||
if !again && c.data != nil && (time.Since(c.at) < time.Minute || heldRead(ctx)) {
|
||||
defer c.Unlock()
|
||||
return c.data
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// Allowances read only when asked (#1518, RooobinYe): with Settings →
|
||||
// Usage → Allowance reads at "When I ask", magpie asks no vendor for an
|
||||
// account's allowance or a key's balance on its own — not for the Usage
|
||||
// page's or tray's timed refresh, the menu bar, alerts, routing, or the
|
||||
// switch to an account with room. Each shows the reading kept from the
|
||||
// last time it was read, as of then (keepLast). A read the user asked
|
||||
// for (Asked) goes out as before, and so does one of an account the
|
||||
// vendor just turned away for its quota (StaleAllowance), which routing
|
||||
// must not keep sending to.
|
||||
//
|
||||
// magpie started at login comes up before the proxy app does, and its own
|
||||
// reads went out direct from the user's real address.
|
||||
|
||||
type askedKey struct{}
|
||||
|
||||
// Asked is ctx for a read the user asked for: the Usage page opened or
|
||||
// refreshed, a card's refresh, `magpie quota`, `magpie accounts`.
|
||||
func Asked(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, askedKey{}, true)
|
||||
}
|
||||
|
||||
func wasAsked(ctx context.Context) bool {
|
||||
b, _ := ctx.Value(askedKey{}).(bool)
|
||||
return b
|
||||
}
|
||||
|
||||
// errNotAsked is what a read held back says: "not read yet", so keepLast
|
||||
// gives the reading kept from the last time instead.
|
||||
var errNotAsked = errors.New("not read yet: magpie reads allowances only when you ask (Settings → Usage)")
|
||||
|
||||
// readsAsked is whether the user has allowances read only when asked.
|
||||
func readsAsked() bool { return settings.Load().QuotaReads == "asked" }
|
||||
|
||||
// heldRead is whether a read made with ctx is held back: the user has
|
||||
// allowances read only when asked, and ctx is not one they asked for.
|
||||
func heldRead(ctx context.Context) bool { return !wasAsked(ctx) && readsAsked() }
|
||||
|
||||
// holdUnasked is ctx, its requests held (netproxy.Hold) when it is a read
|
||||
// held back: whatever a vendor's read goes through, nothing of it leaves.
|
||||
func holdUnasked(ctx context.Context) context.Context {
|
||||
if netproxy.Held(ctx) == nil && heldRead(ctx) {
|
||||
return netproxy.Hold(ctx, errNotAsked)
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
// staleReads are the accounts (agent/user) the vendor turned away for
|
||||
// their quota since they were last read (StaleAllowance): read even while
|
||||
// allowances are read only when asked.
|
||||
var staleReads struct {
|
||||
sync.Mutex
|
||||
m map[string]bool
|
||||
}
|
||||
|
||||
func markStaleRead(agent, user string) {
|
||||
staleReads.Lock()
|
||||
defer staleReads.Unlock()
|
||||
if staleReads.m == nil {
|
||||
staleReads.m = map[string]bool{}
|
||||
}
|
||||
staleReads.m[agent+"/"+strings.ToLower(user)] = true
|
||||
}
|
||||
|
||||
// takeStaleRead says whether key is to be read though not asked, and
|
||||
// forgets it: one read answers it.
|
||||
func takeStaleRead(key string) bool {
|
||||
staleReads.Lock()
|
||||
defer staleReads.Unlock()
|
||||
if staleReads.m[key] {
|
||||
delete(staleReads.m, key)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isStaleRead(key string) bool {
|
||||
staleReads.Lock()
|
||||
defer staleReads.Unlock()
|
||||
return staleReads.m[key]
|
||||
}
|
||||
|
||||
// holding is whether a read made with ctx sends nothing: held back
|
||||
// (heldRead), or made under one that was (quotaReading put the hold on).
|
||||
func holding(ctx context.Context) bool {
|
||||
return netproxy.Held(ctx) != nil || heldRead(ctx)
|
||||
}
|
||||
|
||||
// unheld is ctx for a read that goes out though not asked for: an
|
||||
// account the vendor turned away for its quota (StaleAllowance).
|
||||
func unheld(ctx context.Context) context.Context {
|
||||
return netproxy.Hold(Asked(ctx), nil)
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// dialsOut has magpie's own requests go as netproxy.Install has them, and
|
||||
// tells every host dialed that isn't this machine's, never dialing it.
|
||||
func dialsOut(t *testing.T) func() []string {
|
||||
t.Helper()
|
||||
var mu sync.Mutex
|
||||
var out []string
|
||||
base := http.DefaultTransport.(*http.Transport).Clone()
|
||||
base.Proxy = netproxy.Func
|
||||
dial := (&net.Dialer{Timeout: 5 * time.Second}).DialContext
|
||||
base.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
if host, _, _ := net.SplitHostPort(addr); host != "127.0.0.1" && host != "::1" && host != "localhost" {
|
||||
mu.Lock()
|
||||
out = append(out, addr)
|
||||
mu.Unlock()
|
||||
return nil, &net.OpError{Op: "dial", Net: network, Err: net.UnknownNetworkError("test: no network")}
|
||||
}
|
||||
return dial(ctx, network, addr)
|
||||
}
|
||||
oldT, oldC := http.DefaultTransport, http.DefaultClient.Transport
|
||||
http.DefaultTransport, http.DefaultClient.Transport = base, netproxy.Dispatch(base)
|
||||
t.Cleanup(func() {
|
||||
http.DefaultTransport, http.DefaultClient.Transport = oldT, oldC
|
||||
base.CloseIdleConnections()
|
||||
})
|
||||
return func() []string {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return append([]string(nil), out...)
|
||||
}
|
||||
}
|
||||
|
||||
func setQuotaReads(t *testing.T, v string) {
|
||||
t.Helper()
|
||||
s := settings.Load()
|
||||
s.QuotaReads = v
|
||||
if err := settings.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// #1518 (RooobinYe): with Settings → Usage → Allowance reads at "When I
|
||||
// ask", nothing magpie does by itself asks a vendor for an allowance —
|
||||
// the switch to an account with room (CodexUsedUp), routing
|
||||
// (Allowances), the Usage page's and tray's timed reads, the menu bar
|
||||
// (Quotas) — and each shows the reading kept from the last time, as of
|
||||
// then. The user asking reads, and so does an account the vendor turned
|
||||
// away for its quota (StaleAllowance).
|
||||
func TestAllowancesReadOnlyWhenAsked(t *testing.T) {
|
||||
signIn(t) // Codex on me@example.com, and a Copilot account
|
||||
rememberLogins(true)
|
||||
var asked atomic.Int32
|
||||
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/backend-api/wham/usage" {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
asked.Add(1)
|
||||
w.Write([]byte(`{"plan_type":"pro","rate_limit":{"allowed":true,"limit_reached":false,
|
||||
"primary_window":{"used_percent":37,"limit_window_seconds":18000,"reset_after_seconds":3600}}}`))
|
||||
}))
|
||||
defer fake.Close()
|
||||
old := CodexBase
|
||||
CodexBase = fake.URL + "/backend-api/codex"
|
||||
t.Cleanup(func() { CodexBase = old })
|
||||
restart := func() {
|
||||
loginUsageCache.Lock()
|
||||
loginUsageCache.m, loginUsageCache.pending = nil, nil
|
||||
loginUsageCache.Unlock()
|
||||
subscriptionUsageCache.Lock()
|
||||
subscriptionUsageCache.data, subscriptionUsageCache.at, subscriptionUsageCache.asked = nil, time.Time{}, false
|
||||
subscriptionUsageCache.Unlock()
|
||||
planQuotaCache.Lock()
|
||||
planQuotaCache.data, planQuotaCache.at = nil, time.Time{}
|
||||
planQuotaCache.Unlock()
|
||||
keyBalanceCache.Lock()
|
||||
keyBalanceCache.data, keyBalanceCache.at = nil, time.Time{}
|
||||
keyBalanceCache.Unlock()
|
||||
usedCache.Lock()
|
||||
usedCache.m, usedCache.at, usedCache.loading = map[string]map[string]Allowance{}, map[string]time.Time{}, map[string]chan struct{}{}
|
||||
usedCache.stale, usedCache.renewed, usedCache.seen = nil, nil, nil
|
||||
usedCache.Unlock()
|
||||
staleReads.Lock()
|
||||
staleReads.m = nil
|
||||
staleReads.Unlock()
|
||||
ForgetKeptCardsForTest()
|
||||
}
|
||||
restart()
|
||||
t.Cleanup(restart)
|
||||
bg := context.Background()
|
||||
|
||||
// read once, as magpie does by itself, before the setting
|
||||
if CodexUsedUp(bg) {
|
||||
t.Fatal("used up at 37%")
|
||||
}
|
||||
if n := asked.Load(); n != 1 {
|
||||
t.Fatalf("ChatGPT asked %d times, want 1", n)
|
||||
}
|
||||
|
||||
// then allowances read only when asked, and magpie started again (at
|
||||
// login, before the proxy app)
|
||||
setQuotaReads(t, "asked")
|
||||
t.Cleanup(func() { setQuotaReads(t, "") })
|
||||
restart()
|
||||
out := dialsOut(t)
|
||||
CodexUsedUp(bg)
|
||||
q := LoginUsage(bg, "codex")["me@example.com"]
|
||||
if len(q.Windows) == 0 || q.Windows[0].Used != 37 || q.AsOf == nil {
|
||||
t.Fatalf("not asked, the account shows %+v, want the kept 37%% as of then", q)
|
||||
}
|
||||
if !AwaitAllowance(bg, "codex", "me@example.com") {
|
||||
t.Fatal("routing has no allowance for the account, not even the kept one")
|
||||
}
|
||||
cards := Quotas(bg) // the Usage page's timer, the tray, the menu bar
|
||||
if c := cardOf(cards, "codex", "me@example.com"); c == nil || len(c.Windows) == 0 || c.Windows[0].Used != 37 || c.AsOf == nil {
|
||||
t.Fatalf("not asked, the card is %+v, want the kept reading as of then", c)
|
||||
}
|
||||
Quotas(bg)
|
||||
if n := asked.Load(); n != 1 {
|
||||
t.Fatalf("nobody asked, and ChatGPT was asked %d more times", n-1)
|
||||
}
|
||||
if d := out(); len(d) > 0 {
|
||||
t.Fatalf("nobody asked, and magpie dialed %v", d)
|
||||
}
|
||||
|
||||
// the vendor turns the account away for its quota: read, asked or not
|
||||
StaleAllowance("codex", "me@example.com")
|
||||
AwaitAllowance(bg, "codex", "me@example.com")
|
||||
if n := asked.Load(); n != 2 {
|
||||
t.Fatalf("an account the vendor turned away was read %d times, want once", n-1)
|
||||
}
|
||||
LoginUsage(bg, "codex")
|
||||
if n := asked.Load(); n != 2 {
|
||||
t.Fatal("read again after the one read a refusal asks for")
|
||||
}
|
||||
|
||||
// the user asks: read
|
||||
AskUsage()
|
||||
q = LoginUsage(Asked(bg), "codex")["me@example.com"]
|
||||
if n := asked.Load(); n != 3 || q.AsOf != nil {
|
||||
t.Fatalf("asked, ChatGPT was asked %d times in all (want 3), the account %+v", n, q)
|
||||
}
|
||||
}
|
||||
|
||||
// Automatic, as before: magpie reads by itself.
|
||||
func TestAllowancesReadByThemselvesByDefault(t *testing.T) {
|
||||
signIn(t)
|
||||
rememberLogins(true)
|
||||
var asked atomic.Int32
|
||||
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
asked.Add(1)
|
||||
w.Write([]byte(`{"plan_type":"pro","rate_limit":{"allowed":true,"primary_window":{"used_percent":5,"limit_window_seconds":18000,"reset_after_seconds":3600}}}`))
|
||||
}))
|
||||
defer fake.Close()
|
||||
old := CodexBase
|
||||
CodexBase = fake.URL + "/backend-api/codex"
|
||||
t.Cleanup(func() { CodexBase = old })
|
||||
forget := func() {
|
||||
loginUsageCache.Lock()
|
||||
loginUsageCache.m, loginUsageCache.pending = nil, nil
|
||||
loginUsageCache.Unlock()
|
||||
ForgetKeptCardsForTest()
|
||||
}
|
||||
forget()
|
||||
t.Cleanup(forget)
|
||||
LoginUsage(context.Background(), "codex")
|
||||
if asked.Load() != 1 {
|
||||
t.Fatal("magpie no longer reads an allowance by itself while set to")
|
||||
}
|
||||
}
|
||||
|
||||
// The same for a key's windows and balance: routing (KeyAllowance) and
|
||||
// the cards' timed reads (KeyBalances, PlanQuotas) ask nothing while
|
||||
// allowances are read only when asked; a key that said it is out
|
||||
// (StaleKeyAllowance) is read, and so is one the user asks for.
|
||||
func TestKeyReadsOnlyWhenAsked(t *testing.T) {
|
||||
keyLimitsHome(t)
|
||||
srv, asked := sub2apiServer(t, func() ([]byte, int) { return sub2apiUsage(t, true), 200 })
|
||||
p := sub2apiKey(srv)
|
||||
if err := Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
setQuotaReads(t, "asked")
|
||||
t.Cleanup(func() { setQuotaReads(t, "") })
|
||||
dialsOut(t) // magpie's own transport, which holds what nobody asked for
|
||||
bg := context.Background()
|
||||
KeyBalances(bg)
|
||||
PlanQuotas(bg)
|
||||
KeyAllowance(p)
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
if n := asked.Load(); n != 0 {
|
||||
t.Fatalf("nobody asked, and the key was read %d times", n)
|
||||
}
|
||||
StaleKeyAllowance(p)
|
||||
KeyAllowance(p)
|
||||
for i := 0; i < 100 && asked.Load() == 0; i++ {
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
if n := asked.Load(); n != 1 {
|
||||
t.Fatalf("a key that said it is out was read %d times, want once", n)
|
||||
}
|
||||
ForgetBalances()
|
||||
KeyBalances(Asked(bg))
|
||||
if n := asked.Load(); n < 2 {
|
||||
t.Fatal("the user asked, and the key's balance wasn't read")
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,10 @@ var quotaReadSequence atomic.Uint64
|
||||
|
||||
// quotaReading orders reads when they start, not when the vendor answers.
|
||||
// A card refresh shares its order across the three kinds of usage.
|
||||
// A read the user didn't ask for, while they have allowances read only
|
||||
// when asked, sends nothing (holdUnasked).
|
||||
func quotaReading(ctx context.Context) (context.Context, uint64) {
|
||||
ctx = holdUnasked(ctx)
|
||||
if seq, ok := ctx.Value(quotaReadKey{}).(uint64); ok {
|
||||
return ctx, seq
|
||||
}
|
||||
@@ -97,7 +100,7 @@ func RefreshUsage(ctx context.Context, provider, user string) {
|
||||
return
|
||||
}
|
||||
r := cardRefresh{provider, user}
|
||||
ctx = context.WithValue(ctx, cardRefreshKey{}, r)
|
||||
ctx = context.WithValue(Asked(ctx), cardRefreshKey{}, r) // a card's refresh is the user asking
|
||||
ctx, seq := quotaReading(ctx)
|
||||
if provider == "claude" {
|
||||
// Claude Code's /usage, run when the user asks (claudeWindows)
|
||||
|
||||
@@ -114,7 +114,7 @@ func ReadAllCards(ctx context.Context) {
|
||||
AskUsage()
|
||||
ForgetBalances()
|
||||
forgetPlanQuotas()
|
||||
Quotas(ctx)
|
||||
Quotas(Asked(ctx))
|
||||
}
|
||||
|
||||
var remoteCardCache struct {
|
||||
|
||||
@@ -595,6 +595,9 @@ func forgetAllowance(agent, user string) {
|
||||
// has run out.
|
||||
func StaleAllowance(agent, user string) {
|
||||
key := agent + "/" + strings.ToLower(user)
|
||||
if readsAsked() {
|
||||
markStaleRead(agent, user) // read though allowances are read only when asked (#1518)
|
||||
}
|
||||
loginUsageCache.Lock()
|
||||
delete(loginUsageCache.m, key)
|
||||
delete(loginUsageCache.pending, key) // nor a reading asked for before
|
||||
|
||||
@@ -184,13 +184,23 @@ func SubscriptionUsage(ctx context.Context) []SubscriptionQuota {
|
||||
c := &subscriptionUsageCache
|
||||
c.Lock()
|
||||
have, fresh := c.data != nil, time.Since(c.at) < time.Minute
|
||||
if c.asked {
|
||||
held := heldRead(ctx)
|
||||
if held && have {
|
||||
// allowances read only when asked (#1518): the cards stand as
|
||||
// they were last read till the user asks again
|
||||
fresh = true
|
||||
}
|
||||
if c.asked && !held {
|
||||
have, c.asked = false, false
|
||||
}
|
||||
if !fresh && c.pending == nil {
|
||||
done := make(chan struct{})
|
||||
c.pending = done
|
||||
readCtx, seq := quotaReading(context.Background())
|
||||
bg := context.Background()
|
||||
if wasAsked(ctx) {
|
||||
bg = Asked(bg)
|
||||
}
|
||||
readCtx, seq := quotaReading(bg)
|
||||
go func() {
|
||||
start := time.Now()
|
||||
out := fetchSubscriptionUsage(readCtx)
|
||||
@@ -696,7 +706,8 @@ func claudeWindows(ctx context.Context, user string, active bool) ([]QuotaWindow
|
||||
c.Unlock()
|
||||
due := e.tried.IsZero() || asked > e.tried.UnixNano() ||
|
||||
active && now.Sub(e.tried) >= e.wait && (e.heard.After(e.tried) || claudeUsedSince(e.tried))
|
||||
read := active && due && now.Sub(e.tried) >= claudeAskFloor
|
||||
// nor, with allowances read only when asked, one nobody asked for
|
||||
read := active && due && now.Sub(e.tried) >= claudeAskFloor && !holding(ctx)
|
||||
c.Lock()
|
||||
// one reading an ask or a wait, its first caller's; the others keep
|
||||
// to it
|
||||
@@ -800,6 +811,10 @@ func claudeScopeModel(name string) string {
|
||||
|
||||
func codexSubscriptionUsage(ctx context.Context, path string) SubscriptionQuota {
|
||||
q := SubscriptionQuota{Provider: "codex", Name: "Codex", Icon: "codex-color", Windows: []QuotaWindow{}}
|
||||
if holding(ctx) {
|
||||
q.Error = errNotAsked.Error()
|
||||
return q
|
||||
}
|
||||
token, accountID, err := codexToken(ctx, path)
|
||||
if err != nil {
|
||||
q.Error = err.Error()
|
||||
|
||||
@@ -275,6 +275,16 @@ type Settings struct {
|
||||
// QuotaLeft shows a subscription's windows by how much of each is left,
|
||||
// not used: the Usage page, the tray panel and the menu bar alike.
|
||||
QuotaLeft bool `json:"quotaLeft,omitempty"`
|
||||
// QuotaReads is when magpie reads subscriptions' allowances and keys'
|
||||
// balances from their vendors (#1518, RooobinYe): "" whenever it needs
|
||||
// them (the Usage page and tray, routing, alerts, the switch to an
|
||||
// account with room), "asked" only when the user asks — the Usage page
|
||||
// opened or refreshed, a card's refresh, `magpie quota`/`accounts`.
|
||||
// Otherwise the readings kept from the last time stand, marked as of
|
||||
// then; an account the vendor turned away for its quota is still read.
|
||||
// This computer's own (KeepOwn): magpie at login comes up before the
|
||||
// proxy app, and its reads went out direct.
|
||||
QuotaReads string `json:"quotaReads,omitempty"`
|
||||
// UsageAlert is how much of a subscription's or plan's window, in
|
||||
// percent, is used when magpie says so with a notification (#368):
|
||||
// once for each time the window runs, for every window routing counts
|
||||
@@ -752,7 +762,7 @@ func (s Settings) Compact() int {
|
||||
|
||||
// KeepOwn puts back cur's settings that are this computer's own, which a
|
||||
// sync or a restored backup never brings from another: the window's size
|
||||
// and whether it was maximised, the proxy, the gateway's port, the Dock, gateway mode, whether WSL is looked in, and what the menu bar or tray shows beside magpie's
|
||||
// and whether it was maximised, the proxy, the gateway's port, the Dock, gateway mode, whether WSL is looked in, when allowances are read, and what the menu bar or tray shows beside magpie's
|
||||
// icon (yoooo on Discord: usage turned off on a Mac came back from a
|
||||
// Windows box that shows it).
|
||||
func (s *Settings) KeepOwn(cur Settings) {
|
||||
@@ -763,6 +773,7 @@ func (s *Settings) KeepOwn(cur Settings) {
|
||||
s.TrayUsages, s.TrayUsage, s.TrayUsageEvery, s.TrayNoLogos, s.TrayNoBird = cur.TrayUsages, cur.TrayUsage, cur.TrayUsageEvery, cur.TrayNoLogos, cur.TrayNoBird
|
||||
s.GatewayMode = cur.GatewayMode
|
||||
s.NoWSLAgents = cur.NoWSLAgents
|
||||
s.QuotaReads = cur.QuotaReads
|
||||
}
|
||||
|
||||
// RenamePerModel moves what the user said of a provider's models to the id
|
||||
@@ -981,6 +992,9 @@ func save(s Settings, recording bool) error {
|
||||
if math.IsNaN(s.BalanceAlert) || math.IsInf(s.BalanceAlert, 0) || s.BalanceAlert < 0 {
|
||||
return fmt.Errorf("a balance alert is at an amount of 0 or more (0 for off), not %v", s.BalanceAlert)
|
||||
}
|
||||
if s.QuotaReads != "" && s.QuotaReads != "asked" {
|
||||
return fmt.Errorf(`allowances are read "" (whenever magpie needs them) or "asked" (only when asked), not %q`, s.QuotaReads)
|
||||
}
|
||||
if err := CheckPort(s.Port); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -698,7 +698,7 @@ type quotaMsg []provider.SubscriptionQuota
|
||||
|
||||
func quotasCmd() tea.Msg {
|
||||
provider.AskClaudeUsage() // the page opened, or r pressed
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
|
||||
ctx, cancel := context.WithTimeout(provider.Asked(context.Background()), 12*time.Second)
|
||||
defer cancel()
|
||||
// a WorkBuddy (China) account's line says how its daily check-in went,
|
||||
// as its card in the app does
|
||||
|
||||
+4
-2
@@ -98,7 +98,9 @@ func quotaCmd(args []string) error {
|
||||
only = append(only, strings.ToLower(a))
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
// magpie quota is the user asking: read even when allowances are read
|
||||
// only when asked (#1518)
|
||||
ctx, cancel := context.WithTimeout(provider.Asked(context.Background()), 15*time.Second)
|
||||
defer cancel()
|
||||
qs := []provider.Quota{}
|
||||
provider.AskClaudeUsage()
|
||||
@@ -191,7 +193,7 @@ func quotaResetCmd(args []string) error {
|
||||
user = a
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
ctx, cancel := context.WithTimeout(provider.Asked(context.Background()), 20*time.Second)
|
||||
defer cancel()
|
||||
// what the account holds, and whose it is when none was named
|
||||
var held *provider.SubscriptionQuota
|
||||
|
||||
+1
-1
@@ -276,7 +276,7 @@ func quotaWaitCmd(args []string) error {
|
||||
} else {
|
||||
provider.AskUsage()
|
||||
}
|
||||
rctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
rctx, cancel := context.WithTimeout(provider.Asked(ctx), 30*time.Second)
|
||||
defer cancel()
|
||||
return provider.Allotted(rctx)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user