From 0d0a1a567804d8f73ab7f3a004a754b2ad6ea3eb Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 11 Nov 2026 22:49:22 +0800 Subject: [PATCH] balance probe: kept across restarts, Auto-detect switch, Detect again, not-detected line in the editor (#3146, Niapyaya on X) A custom provider at a New API / Sub API / One API relay with no Balance URL has its balance query found by magpie (provider/balance_probe.go). This keeps what was found, or not found, in balance-probes.json (keyed by origins and a hash of the key, written through temp-and-rename, an unreadable file read as empty), so a restart does not probe again. The editor gets an Auto-detect switch (NoBalanceProbe), a Detect again button (ForgetBalanceProbe) and a line saying where the balance was found, or that none was, with the Balance URL field as the way out. A found balance is a balance card on the Usage page. Run at the rebased head (parent 6a3f162f0 = origin/main), on mica: - gofmt -l: clean. - go vet ./... (darwin), GOOS=linux -tags nogui, GOOS=windows: clean (at the previous base e6bf4adf1; go vet ./internal/... again at this head). - go test -count=1 internal/provider internal/gui: ok, at this head. - GUI, both engines, five languages: balance-found, gui-de/ja/zh-tw, i18n-keys, i18n-en-no-cjk, provider-billing, provider-detect*: all ok except gui-de and gui-ja "has every zh string" ({agent} twice in sessions' "isn't installed here"), which are red the same at e6bf4adf1 (filed). - At e6bf4adf1, 79 provider/gui/i18n files: 80 reds, the same 80 on the unmodified base (provider-fetch-again #5232/#5057, provider-picks-stay #4397, provider-models-rest #4396, provider-typed #4673, menu-scroll #1550, provider-max-output and provider-many-keys filed with the rest). Not tried: a real New API / Sub API relay with a real key; the full Go suite (started after the tag). --- internal/gui/assets/app.css | 1 + internal/gui/assets/app.js | 9 +- internal/gui/assets/balfound.js | 31 +++- internal/gui/assets/i18n.js | 16 ++ internal/gui/providers.go | 29 +++- internal/gui/tests/balance-found.test.cjs | 19 ++- internal/provider/balance_probe.go | 105 +++++++++++++- internal/provider/balance_probe_keep_test.go | 145 +++++++++++++++++++ internal/provider/provider.go | 3 + 9 files changed, 341 insertions(+), 17 deletions(-) create mode 100644 internal/provider/balance_probe_keep_test.go diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 3056239d6..a6e4ccb18 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -3529,6 +3529,7 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .editor .pair.bal-ask { flex-wrap: wrap; } .editor .pair.bal-ask input { flex: 1 1 160px; min-width: 0; } .editor .pair.bal-ask .segs { flex: none; align-self: center; } +.editor .pair.bal-ask > .tick { flex-basis: 100%; } .editor .bal-found { flex-basis: 100%; display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 8px; font-size: 12px; line-height: 1.45; color: var(--muted); } .editor .bal-found span { overflow-wrap: anywhere; user-select: text; -webkit-user-select: text; } .editor .side { display: flex; gap: 4px; align-items: center; flex: none; min-width: 52px; justify-content: flex-end; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 0044bf8da..433177595 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -7945,7 +7945,7 @@ function advancedSet(d, p) { !!d.proxyMode || Object.values(d.accountProxies || {}).some((x) => x?.mode) || [d.concurrency, d.maxAccounts, d.queueLimit, d.queueWait, d.maxRPM, d.priceRate, d.contexts, d.outputs, d.compacts].some((v) => String(v ?? "").trim()) || !!d.rateWindows?.length || - !!(d.searches || d.authHeader || d.passUserAgent === false || d.unredacted || d.countFree || d.billing || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff || d.http1 || d.socket || d.imageFilesOff || d.passErrors || d.clientCert || d.serverCA || d.serverPin) || + !!(d.searches || d.authHeader || d.passUserAgent === false || d.unredacted || d.countFree || d.billing || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff || d.noBalanceProbe || d.http1 || d.socket || d.imageFilesOff || d.passErrors || d.clientCert || d.serverCA || d.serverPin) || !!d.fallback?.length || !!p?.balanceToken?.set; } function priceRateError(ed) { @@ -9256,7 +9256,7 @@ function baseAPIOf(p) { // draftOf is a saved provider as its editor's form holds it. function draftOf(p) { - return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), passHeaders: (p.passHeaders || []).join(", "), icon: p.icon || "", iconFrom: p.iconFrom || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], hiddenVideomakers: [...(p.hiddenVideomakers || [])], searches: !!p.searches, unredacted: !!p.unredacted, countFree: !!p.countFree, billing: p.billing || "", insecureTLS: !!p.insecureTLS, http1: !!p.http1, clientCert: p.clientCert || "", clientKey: p.clientKey || "", serverCA: p.serverCA || "", serverPin: p.serverPin || "", socket: p.socket || "", limitRestOff: !!p.limitRestOff, upstreamProviders: !!p.upstreamProviders, passErrors: !!p.passErrors, imageFilesOff: !!p.imageFilesOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: p.passUserAgent !== false, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", listOff: !!p.listOff, contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) }; + return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), passHeaders: (p.passHeaders || []).join(", "), icon: p.icon || "", iconFrom: p.iconFrom || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], hiddenVideomakers: [...(p.hiddenVideomakers || [])], searches: !!p.searches, unredacted: !!p.unredacted, countFree: !!p.countFree, billing: p.billing || "", insecureTLS: !!p.insecureTLS, http1: !!p.http1, clientCert: p.clientCert || "", clientKey: p.clientKey || "", serverCA: p.serverCA || "", serverPin: p.serverPin || "", socket: p.socket || "", limitRestOff: !!p.limitRestOff, noBalanceProbe: !!p.noBalanceProbe, upstreamProviders: !!p.upstreamProviders, passErrors: !!p.passErrors, imageFilesOff: !!p.imageFilesOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: p.passUserAgent !== false, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", listOff: !!p.listOff, contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) }; } // duplicateProvider opens the Add form on a copy of p, its key p's unless another is pasted (#268). @@ -10187,7 +10187,7 @@ function drawEditor(p, presetID) { balPair.append(balPath); if (p) { const side = el("div", "side"); - const check = el("button", "text action", t("Check balance")); + const check = el("button", "text action bal-check", t("Check balance")); check.title = t("Ask the Balance URL now, as the form has it"); side.append(check); balPair.append(side); @@ -10195,7 +10195,7 @@ function drawEditor(p, presetID) { check.onclick = async () => { check.classList.add("busy"); res.className = "bal-res wait"; res.textContent = "…"; res.title = ""; - const body = { id: p.id, balanceURL: (draft.balanceURL || "").trim(), balancePath: (draft.balancePath || "").trim(), balanceMethod: draft.balanceMethod || "", headers: headersOf(draft.headers) }; + const body = { id: p.id, balanceURL: (draft.balanceURL || "").trim(), balancePath: (draft.balancePath || "").trim(), balanceMethod: draft.balanceMethod || "", noBalanceProbe: !!draft.noBalanceProbe, headers: headersOf(draft.headers) }; if (draft.balanceToken) body.balanceToken = draft.balanceToken; else if (draft.clearBalanceToken) body.clearBalanceToken = true; try { @@ -10282,6 +10282,7 @@ function drawEditor(p, presetID) { else pinBody(body); if (socketable()) body.socket = draft.socket || ""; if (custom) body.limitRestOff = !!draft.limitRestOff; + body.noBalanceProbe = !!draft.noBalanceProbe; if ((p?.preset || pr?.id) === "remote-magpie") body.upstreamProviders = !!draft.upstreamProviders; if (p?.takesImageFiles) body.imageFilesOff = !!draft.imageFilesOff; if (p ? p.takesPassErrors : custom) body.passErrors = !!draft.passErrors; diff --git a/internal/gui/assets/balfound.js b/internal/gui/assets/balfound.js index 5bd057427..b3e271722 100644 --- a/internal/gui/assets/balfound.js +++ b/internal/gui/assets/balfound.js @@ -7,10 +7,22 @@ let balFoundAt = null; window.balFound = function (box, p, draft, bal, pathOf) { const line = el("div", "bal-found"); line.hidden = true; - balFoundAt = { line, draft, bal, pathOf }; + balFoundAt = { line, draft, bal, pathOf, p }; box.append(line); - bal.addEventListener("input", () => { line.hidden = !line.dataset.url || !!bal.value.trim(); }); - window.balFoundShow({ found: p.balanceFound, foundField: p.balanceFoundField }); + // the look for it can be turned off, for a relay that has no balance + let row = null; + if (p.balanceProbe) { + const [rk, cb] = tick(t("Auto-detect"), !draft.noBalanceProbe); + row = rk; + cb.onchange = () => { draft.noBalanceProbe = !cb.checked; if (!cb.checked) line.hidden = true; }; + box.append(row); + } + bal.addEventListener("input", () => { + const typed = !!bal.value.trim(); + line.hidden = !line.dataset.show || typed; + if (row) row.hidden = typed; + }); + window.balFoundShow({ found: p.balanceFound, foundField: p.balanceFoundField, undetected: p.balanceUndetected }); }; // what the editor's Check balance found (app.js), drawn again window.balFoundShow = function (r) { @@ -18,8 +30,19 @@ window.balFoundShow = function (r) { if (!s || !s.line.isConnected) return; const { line, draft, bal, pathOf } = s; line.replaceChildren(); + const miss = !r.found && !!r.undetected && !draft.noBalanceProbe; line.dataset.url = r.found || ""; - line.hidden = !r.found || !!(draft.balanceURL || "").trim(); + line.dataset.show = r.found || miss ? "1" : ""; + line.hidden = !line.dataset.show || !!(draft.balanceURL || "").trim(); + if (miss) { + const none = el("span", "", t("Not detected")); + none.title = t("magpie asked this relay where relays tell a key its balance, and found none. Put in a Balance URL of your own, or detect again"); + const again = el("button", "text action", t("Detect again")); + again.type = "button"; + again.onclick = () => document.querySelector(".editor .bal-check")?.click(); + line.append(none, again); + return; + } if (!r.found) return; const txt = el("span", "", t("Found by magpie: {url}", { url: r.found + (r.foundField ? " " + r.foundField : "") })); txt.title = t("magpie asked this relay where relays tell a key its balance, and reads it here. If the amount is wrong, put in your own Balance URL and field; magpie looks again each day"); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index a3d846817..18ca8ae4d 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -73,6 +73,10 @@ const I18N = { "Collapse all": "全部收起", "Expand all": "全部展开", "Found by magpie: {url}": "magpie 自动找到:{url}", + "Auto-detect": "自动检测", + "Not detected": "未检测到", + "Detect again": "重新检测", + "magpie asked this relay where relays tell a key its balance, and found none. Put in a Balance URL of your own, or detect again": "magpie 问过这个中转站余额查询的常见地址,没有找到。请填写你自己的余额 URL,或重新检测", "magpie asked this relay where relays tell a key its balance, and reads it here. If the amount is wrong, put in your own Balance URL and field; magpie looks again each day": "magpie 在中转站常用的余额查询地址问到了这个 key 的余额,就从这里读。数额不对的话,请填上你自己的余额 URL 和字段;magpie 每天会重新找一次", "Put this query in the Balance URL and Balance field, to change it": "把这个地址填进余额 URL 和余额字段,方便修改", "No balance at /v1/usage or /api/usage/token": "在 /v1/usage 和 /api/usage/token 都没有查到余额,请填写余额 URL", @@ -5181,6 +5185,10 @@ const I18N = { "Collapse all": "全部收起", "Expand all": "全部展開", "Found by magpie: {url}": "magpie 自動找到:{url}", + "Auto-detect": "自動偵測", + "Not detected": "未偵測到", + "Detect again": "重新偵測", + "magpie asked this relay where relays tell a key its balance, and found none. Put in a Balance URL of your own, or detect again": "magpie 問過這個中轉站餘額查詢的常見位址,沒有找到。請填寫你自己的餘額 URL,或重新偵測", "magpie asked this relay where relays tell a key its balance, and reads it here. If the amount is wrong, put in your own Balance URL and field; magpie looks again each day": "magpie 在中轉站常用的餘額查詢位址問到了這個 key 的餘額,就從這裡讀。數額不對的話,請填上你自己的餘額 URL 和欄位;magpie 每天會重新找一次", "Put this query in the Balance URL and Balance field, to change it": "把這個位址填進餘額 URL 和餘額欄位,方便修改", "No balance at /v1/usage or /api/usage/token": "在 /v1/usage 和 /api/usage/token 都沒有查到餘額,請填寫餘額 URL", @@ -10274,6 +10282,10 @@ const I18N = { "Collapse all": "すべて折りたたむ", "Expand all": "すべて展開", "Found by magpie: {url}": "magpie が自動で見つけました:{url}", + "Auto-detect": "自動検出", + "Not detected": "検出なし", + "Detect again": "再検出", + "magpie asked this relay where relays tell a key its balance, and found none. Put in a Balance URL of your own, or detect again": "magpie はこの中継で残高を返す一般的なアドレスを試しましたが、見つかりませんでした。自分の残高 URL を入力するか、再検出してください", "magpie asked this relay where relays tell a key its balance, and reads it here. If the amount is wrong, put in your own Balance URL and field; magpie looks again each day": "magpie はリレーが残高を返す一般的な場所でこのキーの残高を見つけ、ここから読んでいます。金額が違う場合は、残高 URL とフィールドを自分で入力してください。magpie は毎日探し直します", "Put this query in the Balance URL and Balance field, to change it": "このクエリを残高 URL と残高フィールドに入れて、変更できるようにします", "No balance at /v1/usage or /api/usage/token": "/v1/usage と /api/usage/token のどちらにも残高がありません。残高 URL を入力してください", @@ -15369,6 +15381,10 @@ const I18N = { "Collapse all": "Alle einklappen", "Expand all": "Alle ausklappen", "Found by magpie: {url}": "Von magpie gefunden: {url}", + "Auto-detect": "Automatisch erkennen", + "Not detected": "Nicht erkannt", + "Detect again": "Erneut erkennen", + "magpie asked this relay where relays tell a key its balance, and found none. Put in a Balance URL of your own, or detect again": "magpie hat die üblichen Guthaben-Adressen dieses Relays abgefragt und nichts gefunden. Trage eine eigene Guthaben-URL ein oder erkenne erneut", "magpie asked this relay where relays tell a key its balance, and reads it here. If the amount is wrong, put in your own Balance URL and field; magpie looks again each day": "magpie hat das Guthaben dieses Schlüssels dort gefunden, wo Relays es üblicherweise angeben, und liest es hier. Stimmt der Betrag nicht, trage eigene Guthaben-URL und -Feld ein; magpie sucht jeden Tag neu", "Put this query in the Balance URL and Balance field, to change it": "Diese Abfrage in Guthaben-URL und Guthaben-Feld übernehmen, um sie zu ändern", "No balance at /v1/usage or /api/usage/token": "Kein Guthaben unter /v1/usage oder /api/usage/token; trage eine Guthaben-URL ein", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 6bcd74245..a12fcddf9 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -238,10 +238,16 @@ type providerJSON struct { BalanceURL string `json:"balanceURL,omitempty"` BalancePath string `json:"balancePath,omitempty"` BalanceMethod string `json:"balanceMethod,omitempty"` + // NoBalanceProbe: the look for a balance query is turned off + NoBalanceProbe bool `json:"noBalanceProbe,omitempty"` // the query magpie found by itself for a relay added by hand with no // Balance URL, and its field (provider.BalanceFound) BalanceFound string `json:"balanceFound,omitempty"` BalanceFoundField string `json:"balanceFoundField,omitempty"` + // whether magpie looks for a balance query for it at all (the switch + // aside), and whether it looked and found none + BalanceProbe bool `json:"balanceProbe,omitempty"` + BalanceUndetected bool `json:"balanceUndetected,omitempty"` // its keys may have a balance typed by hand, their vendor telling // none (provider.TakesOwnBalance) TakesOwnBalance bool `json:"takesOwnBalance,omitempty"` @@ -862,7 +868,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs ID: p.ID, Name: p.Name, Icon: p.Icon, IconFrom: p.IconFrom, Preset: p.Preset, Host: p.Host(), Chat: p.Chat, Responses: p.Responses, Anthropic: p.Anthropic, Gemini: p.Gemini, Decide: p.Decide, BaseAPI: p.BaseAPI, ModelTest: p.ModelTest(), TestsAs: p.TestClients(), DecideTest: p.AsksDecideModels(), MarksKinds: p.MarksKinds(), Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL, - Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountWindowAmounts: p.AccountWindowAmounts, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, Billing: p.Billing, BillingKind: p.BillingKind(), InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, ClientCert: tilde(p.ClientCert), ClientKey: tilde(p.ClientKey), ServerCA: tilde(p.ServerCA), TakesClientCert: p.TakesClientCert(), ServerPin: p.ServerPin, TakesServerPin: p.TakesServerPin(), Socket: p.Socket, TakesSocket: p.TakesSocket(), LimitRestOff: p.LimitRestOff, UpstreamProviders: p.UpstreamProviders, ImageFilesOff: p.ImageFilesOff, TakesImageFiles: p.TakesImageFiles(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: !p.MagpieUserAgent, OwnClient: p.OwnClient(), PassErrors: p.PassErrors, TakesPassErrors: p.TakesPassErrors(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, ListOff: p.ListsOff(), TakesListOff: p.Account == nil && !p.IsPlugin() && !p.DecideOnly(), TakesModelHeaders: p.Account == nil, DecideAPIKind: p.DecideAPIKind(), + Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountWindowAmounts: p.AccountWindowAmounts, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, Billing: p.Billing, BillingKind: p.BillingKind(), InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, ClientCert: tilde(p.ClientCert), ClientKey: tilde(p.ClientKey), ServerCA: tilde(p.ServerCA), TakesClientCert: p.TakesClientCert(), ServerPin: p.ServerPin, TakesServerPin: p.TakesServerPin(), Socket: p.Socket, TakesSocket: p.TakesSocket(), LimitRestOff: p.LimitRestOff, UpstreamProviders: p.UpstreamProviders, ImageFilesOff: p.ImageFilesOff, TakesImageFiles: p.TakesImageFiles(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: !p.MagpieUserAgent, OwnClient: p.OwnClient(), PassErrors: p.PassErrors, TakesPassErrors: p.TakesPassErrors(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, NoBalanceProbe: p.NoBalanceProbe, ModelsURL: p.ModelsURL, ListOff: p.ListsOff(), TakesListOff: p.Account == nil && !p.IsPlugin() && !p.DecideOnly(), TakesModelHeaders: p.Account == nil, DecideAPIKind: p.DecideAPIKind(), Ready: p.Ready(), Chosen: p.PicksOf(avail), Agents: make([]providerAgent, 0, len(agents)), Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, UseFirst: p.UseFirst, NoStandIn: p.NoStandIn, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, RestartApp: p.RestartApp, Self: p.SelfAnswered(), KeepSelf: p.KeepSelf, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts, MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate, @@ -891,6 +897,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs } if p.BalanceURL == "" { out.BalanceFound, out.BalanceFoundField, _ = provider.BalanceFound(p) + out.BalanceProbe, out.BalanceUndetected = provider.BalanceProbeState(p) } if out.Fallback == nil { out.Fallback = []string{} @@ -1696,6 +1703,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // LimitRestOff is whether a quota refusal or a 429 leaves it // asked as usual; a save that leaves it out keeps it LimitRestOff *bool `json:"limitRestOff"` + // NoBalanceProbe turns off the look for a relay's balance query; + // a save that leaves it out keeps it + NoBalanceProbe *bool `json:"noBalanceProbe"` // UpstreamProviders, on a Remote magpie, names its models by the // provider serving each there; a save that leaves it out keeps it UpstreamProviders *bool `json:"upstreamProviders"` @@ -2141,6 +2151,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) { if req.LimitRestOff != nil { in.LimitRestOff = *req.LimitRestOff } + if req.NoBalanceProbe != nil { + in.NoBalanceProbe = *req.NoBalanceProbe + } if req.UpstreamProviders != nil { in.UpstreamProviders = *req.UpstreamProviders && in.IsRemoteMagpie() } @@ -2198,6 +2211,11 @@ func providerRoutes(mux *http.ServeMux, w Windows) { } else if old != nil { in.LimitRestOff = old.LimitRestOff } + if req.NoBalanceProbe != nil { + in.NoBalanceProbe = *req.NoBalanceProbe + } else if old != nil { + in.NoBalanceProbe = old.NoBalanceProbe + } if req.UpstreamProviders != nil { in.UpstreamProviders = *req.UpstreamProviders && in.IsRemoteMagpie() } else if old != nil { @@ -2857,6 +2875,14 @@ func providerRoutes(mux *http.ServeMux, w Windows) { q := *p q.BalanceURL, q.BalancePath = strings.TrimSpace(in.BalanceURL), strings.TrimSpace(in.BalancePath) q.BalanceMethod = in.BalanceMethod + if req.NoBalanceProbe != nil { + q.NoBalanceProbe = *req.NoBalanceProbe + } + if q.BalanceURL == "" { + // no URL named: the check looks for one again, whatever was + // found before (provider.ForgetBalanceProbe) + provider.ForgetBalanceProbe(q) + } if in.Headers != nil { q.Headers = in.Headers } @@ -2876,6 +2902,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // asked where relays tell a key its balance: where, or that // neither told it out["looked"], out["found"], out["foundField"] = true, u, field + out["undetected"] = u == "" } writeJSON(rw, out) return diff --git a/internal/gui/tests/balance-found.test.cjs b/internal/gui/tests/balance-found.test.cjs index c564fc41d..2bd1d01bc 100644 --- a/internal/gui/tests/balance-found.test.cjs +++ b/internal/gui/tests/balance-found.test.cjs @@ -14,11 +14,12 @@ const relay = { id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "", models: [{ id: "model-a", name: "Model A", on: true }], agents: [], fallback: [], headers: {}, key: { set: true, masked: "sk-…one" }, keyList: [], - balanceURL: "", balancePath: "", + balanceURL: "", balancePath: "", balanceProbe: true, balanceFound: "https://relay.example.com/v1/usage", balanceFoundField: "$remaining", balanceToken: { takes: true, set: false }, }; const plain = { ...relay, id: "plain", name: "Plain", balanceFound: "", balanceFoundField: "" }; +const miss = { ...plain, id: "miss", name: "Miss", balanceUndetected: true }; const own = { ...relay, id: "own", name: "Own", balanceURL: "https://relay.example.com/mine" }; function server(lang, list, checks) { @@ -55,7 +56,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const checks = (b) => b.id === "plain" ? (b.balanceURL ? { ok: true, amount: "$1.00" } : { ok: false, amount: "", looked: true, found: "", foundField: "" }) : { ok: true, amount: "$5.00", looked: !b.balanceURL, found: b.balanceURL ? "" : "https://relay.example.com/api/usage/token", foundField: "$data.total_available / 500000" }; - await page.route("**/*", server(lang, [relay, plain, own], checks)); + await page.route("**/*", server(lang, [relay, plain, miss, own], checks)); await page.goto("http://magpie.test/?view=providers"); const tr = (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]); const open = async (name) => { @@ -98,6 +99,20 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.waitForFunction(() => document.querySelector(".editor .bal-res")?.textContent !== "…"); assert.equal(await page.locator(".editor .bal-res").textContent(), await tr("No balance at /v1/usage or /api/usage/token")); + // looked at and found nothing: said in the editor, with Detect again + await open("Miss"); + assert(await line.isVisible(), "not detected is said"); + assert.equal(await line.locator("span").textContent(), await tr("Not detected")); + if (lang !== "en") assert.notEqual(await line.locator("span").textContent(), "Not detected", "translated"); + const tickBox = page.locator(".editor .bal-ask label.tick input"); + assert(await tickBox.isChecked(), "Auto-detect is on"); + const asked = page.waitForRequest((r) => r.url().endsWith("/api/provider/balance")); + await line.getByRole("button", { name: await tr("Detect again"), exact: true }).click(); + assert.equal(JSON.parse((await asked).postData()).noBalanceProbe, false); + await tickBox.uncheck(); + assert(await line.isHidden(), "off: nothing said"); + assert.equal(await page.evaluate(() => draft.noBalanceProbe), true); + // the user's own Balance URL: nothing of magpie's await open("Own"); assert.equal(await line.count(), 0, "not drawn under a saved Balance URL"); diff --git a/internal/provider/balance_probe.go b/internal/provider/balance_probe.go index f6891e0a2..8dd73b93e 100644 --- a/internal/provider/balance_probe.go +++ b/internal/provider/balance_probe.go @@ -2,9 +2,12 @@ package provider import ( "context" + "encoding/json" "io" "net/http" "net/url" + "os" + "path/filepath" "strings" "sync" "time" @@ -44,6 +47,83 @@ var probed struct { m map[string]probeFound } +// What was found, or not found, is kept in balance-probes.json beside +// providers.json, so a restart does not ask every relay again: an entry +// holds until its time (balanceProbeHit, balanceProbeMiss), and the key +// is only a hash of the origins and the key. +type probeSaved struct { + URL string `json:"url,omitempty"` + Until time.Time `json:"until"` +} + +func probesPath() string { return filepath.Join(filepath.Dir(Path()), "balance-probes.json") } + +// probedLocked is the map, read from the file the first time. A file that +// can't be read or doesn't parse is no entries: the relays are asked again. +// The caller holds probed. +func probedLocked() map[string]probeFound { + if probed.m != nil { + return probed.m + } + probed.m = map[string]probeFound{} + var saved map[string]probeSaved + if b, err := os.ReadFile(probesPath()); err == nil && json.Unmarshal(b, &saved) == nil { + for k, v := range saved { + if v.Until.After(time.Now()) { + probed.m[k] = probeFound{v.URL, v.Until} + } + } + } + return probed.m +} + +// saveProbedLocked writes the entries still holding, for the next start. +// The caller holds probed. +func saveProbedLocked() { + saved := map[string]probeSaved{} + for k, v := range probed.m { + if v.until.After(time.Now()) { + saved[k] = probeSaved{v.url, v.until} + } + } + b, err := json.Marshal(saved) + if err != nil { + return + } + _ = os.MkdirAll(filepath.Dir(probesPath()), 0o700) + _ = writeFileAtomic(probesPath(), b) +} + +// ForgetBalanceProbe drops what was found for p, so its balance is looked +// for again at the next read (the editor's Check balance). +func ForgetBalanceProbe(p Provider) { + p = keyQueryOf(p) + if !probesBalance(p) { + return + } + probed.Lock() + delete(probedLocked(), balanceProbeKey(probeOrigins(p), p.Key)) + saveProbedLocked() + probed.Unlock() + ForgetBalances() +} + +// errBalanceUndetected is the card of a relay looked at, with neither +// query telling a balance. It is not a balance of 0, and the editor has +// the Balance URL for one of its own. +const errBalanceUndetected = "no balance query found at this address: give its Balance URL in the provider's settings" + +// balanceUndetected says p was looked at and no query told a balance. +func balanceUndetected(p Provider) bool { + if !probesBalance(p) { + return false + } + probed.Lock() + defer probed.Unlock() + f, ok := probedLocked()[balanceProbeKey(probeOrigins(p), p.Key)] + return ok && f.url == "" && time.Now().Before(f.until) +} + // balanceProbeKey is what a probe is kept by: the origins and the key // (hashed, never kept as it is). func balanceProbeKey(origins []string, key string) string { @@ -55,7 +135,7 @@ func balanceProbeKey(origins []string, key string) string { // knows the query of, and at a relay's address, never a model vendor's own // or this computer's. func probesBalance(p Provider) bool { - if p.Account != nil || p.Key == "" || strings.TrimSpace(p.BalanceURL) != "" || !relayPreset(p.Preset) { + if p.NoBalanceProbe || p.Account != nil || p.Key == "" || strings.TrimSpace(p.BalanceURL) != "" || !relayPreset(p.Preset) { return false } if _, ok := balanceSourceOf(p); ok || clineKeyCard(p) || openCodeZen(p) { @@ -186,7 +266,7 @@ func probedBalanceURL(p Provider) string { } probed.Lock() defer probed.Unlock() - return probed.m[balanceProbeKey(probeOrigins(p), p.Key)].url + return probedLocked()[balanceProbeKey(probeOrigins(p), p.Key)].url } // BalanceFound is the balance query magpie found for p by itself, with @@ -205,6 +285,19 @@ func BalanceFound(p Provider) (u, field string, looked bool) { return u, field, true } +// BalanceProbeState says whether magpie looks for p's balance query (the +// off switch aside, so the editor can offer to turn it on again), and +// whether it looked and found none. +func BalanceProbeState(p Provider) (eligible, undetected bool) { + p = keyQueryOf(p) + off := p.NoBalanceProbe + p.NoBalanceProbe = false + if !probesBalance(p) { + return false, false + } + return true, !off && balanceUndetected(p) +} + // probeBalance looks for p's balance query, asking each origin's relay // queries in turn, and is what was found (false: none told a balance). // A query that answers 200 with its field read is the one; a failure to @@ -213,7 +306,7 @@ func probeBalance(ctx context.Context, p Provider) (string, bool) { origins := probeOrigins(p) k := balanceProbeKey(origins, p.Key) probed.Lock() - f, seen := probed.m[k] + f, seen := probedLocked()[k] probed.Unlock() if seen && time.Now().Before(f.until) { return f.url, f.url != "" @@ -253,10 +346,10 @@ func probeBalance(ctx context.Context, p Provider) (string, bool) { wait = balanceProbeDown } probed.Lock() - if probed.m == nil { - probed.m = map[string]probeFound{} + probedLocked()[k] = probeFound{found, time.Now().Add(wait)} + if wait != balanceProbeDown { + saveProbedLocked() // a relay that was down is asked again at once } - probed.m[k] = probeFound{found, time.Now().Add(wait)} probed.Unlock() return found, found != "" } diff --git a/internal/provider/balance_probe_keep_test.go b/internal/provider/balance_probe_keep_test.go new file mode 100644 index 000000000..7c9ff8ef7 --- /dev/null +++ b/internal/provider/balance_probe_keep_test.go @@ -0,0 +1,145 @@ +package provider + +import ( + "context" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" +) + +// usageRelay answers /v1/usage with a balance for sk-k and counts the asks. +func usageRelay(t *testing.T, asked *atomic.Int32) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + asked.Add(1) + if r.URL.Path == "/v1/usage" && r.Header.Get("Authorization") == "Bearer sk-k" { + w.Write([]byte(`{"remaining":5,"unit":"USD"}`)) + return + } + http.NotFound(w, r) + })) + t.Cleanup(srv.Close) + return srv +} + +// restart is what a new run of magpie starts with: nothing in memory. +func restart() { + probed.Lock() + probed.m = nil + probed.Unlock() +} + +// What was found is kept on disk: after a restart the relay is not asked +// again to find it, and a miss is kept too. +func TestBalanceProbeSurvivesARestart(t *testing.T) { + probeSandbox(t) + var asked atomic.Int32 + srv := usageRelay(t, &asked) + p := Provider{ID: "keep", Name: "keep", Chat: srv.URL + "/v1", Key: "sk-k"} + if _, ok, _ := Balance(context.Background(), p); !ok { + t.Fatal("not found") + } + probes := asked.Load() + restart() + if got := probedBalanceURL(p); got != srv.URL+"/v1/usage" { + t.Fatalf("after a restart the query = %q, want it kept", got) + } + if asked.Load() != probes { + t.Errorf("the relay was asked again by reading the kept query") + } + // a miss is kept the same way + var none atomic.Int32 + dead := usageRelay(t, &none) + q := Provider{ID: "miss", Name: "miss", Chat: dead.URL + "/v1", Key: "sk-other"} + Balance(context.Background(), q) + n := none.Load() + restart() + Balance(context.Background(), q) + if none.Load() != n { + t.Errorf("a miss was asked again after a restart: %d -> %d", n, none.Load()) + } + if !balanceUndetected(q) { + t.Error("a miss kept is undetected") + } +} + +// Detect again drops what was found, so the relay is asked anew; the +// switch turns the look off, and nothing is asked. +func TestBalanceProbeDetectAgainAndSwitch(t *testing.T) { + probeSandbox(t) + var asked atomic.Int32 + srv := usageRelay(t, &asked) + p := Provider{ID: "again", Name: "again", Chat: srv.URL + "/v1", Key: "sk-k"} + Balance(context.Background(), p) + n := asked.Load() + ForgetBalanceProbe(p) + if got := probedBalanceURL(p); got != "" { + t.Fatalf("still found after forgetting: %q", got) + } + restart() // and not brought back from the file + if got := probedBalanceURL(p); got != "" { + t.Fatalf("forgotten, but the file brought it back: %q", got) + } + if _, ok, _ := Balance(context.Background(), p); !ok { + t.Fatal("not found again") + } + if asked.Load() <= n { + t.Error("detect again did not ask the relay") + } + + var off atomic.Int32 + srv2 := usageRelay(t, &off) + q := Provider{ID: "off", Name: "off", Chat: srv2.URL + "/v1", Key: "sk-k", NoBalanceProbe: true} + if amount, ok, err := Balance(context.Background(), q); ok || err != nil || amount != "" { + t.Errorf("balance with the look off = %q %v %v", amount, ok, err) + } + if off.Load() != 0 { + t.Errorf("the look is off, yet the relay was asked %d times", off.Load()) + } + if eligible, _ := BalanceProbeState(q); !eligible { + t.Error("the editor must still offer to turn it on") + } +} + +// A balance URL of the user's wins over what was found, and the key goes +// to the base URL's origin only, never where a redirect leads. +func TestBalanceProbeUserURLWinsAndKeyStaysHome(t *testing.T) { + probeSandbox(t) + var elsewhere atomic.Int32 + other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "" { + elsewhere.Add(1) + } + w.Write([]byte(`{"remaining":99}`)) + })) + defer other.Close() + home := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/mine" { + w.Write([]byte(`{"balance":7}`)) + return + } + http.Redirect(w, r, other.URL+"/v1/usage", http.StatusFound) + })) + defer home.Close() + p := Provider{ID: "home", Name: "home", Chat: home.URL + "/v1", Key: "sk-k"} + if _, ok, _ := Balance(context.Background(), p); ok { + t.Error("a redirect to another origin gave a balance") + } + if elsewhere.Load() != 0 { + t.Errorf("the key reached another origin %d times", elsewhere.Load()) + } + ForgetBalanceProbe(p) + // found at /v1/usage first, then the user names their own + var asked atomic.Int32 + srv := usageRelay(t, &asked) + q := Provider{ID: "own", Name: "own", Chat: srv.URL + "/v1", Key: "sk-k"} + Balance(context.Background(), q) + q.BalanceURL, q.BalancePath = home.URL+"/mine", "$balance" + if u, _ := BalanceQuery(q); u != home.URL+"/mine" { + t.Errorf("query = %q, want the user's", u) + } + if amount, ok, _ := Balance(context.Background(), q); !ok || amount != "$7.00" { + t.Errorf("balance = %q %v, want the user's $7.00", amount, ok) + } +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 856d9ee6d..29b53f137 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -586,6 +586,9 @@ type Provider struct { // no body, for an endpoint that answers only a POST (#2368). Any other // is refused when the balance is read (balanceMethodOf). BalanceMethod string `json:"balanceMethod,omitempty"` + // NoBalanceProbe turns off the look for a balance query on a relay + // added with no Balance URL (balance_probe.go). + NoBalanceProbe bool `json:"noBalanceProbe,omitempty"` // BalanceToken is what a vendor tells the whole account's balance to, // where a key is told only what is left on itself: AiHubMix's system // access token, or a new-api relay's for its /api/user/self named in