From c9e47f043ed04a7f3379909455140c78fd78fbc1 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 29 Sep 2026 17:42:30 +0800 Subject: [PATCH] =?UTF-8?q?balance:=20a=20custom=20provider's=20balance=20?= =?UTF-8?q?token=20can't=20be=20left=20where=20it=20is=20never=20asked,=20?= =?UTF-8?q?and=20new-api's=20refusals=20say=20what=20to=20do=20(TJHHHH:=20?= =?UTF-8?q?OK=E4=BA=86=EF=BC=8C=E5=B8=8C=E6=9C=9B=E6=9C=89=E9=98=B2?= =?UTF-8?q?=E5=91=86=E6=9C=BA=E5=88=B6=20=E2=80=94=20a=20new-api=20relay's?= =?UTF-8?q?=20System=20Access=20Token=20pasted=20beside=20a=20Balance=20UR?= =?UTF-8?q?L=20of=20/api/usage/token,=20no=20New-Api-User=20header,=20and?= =?UTF-8?q?=20the=20Usage=20page=20never=20showed=20a=20balance)=20?= =?UTF-8?q?=E2=80=94=20new-api=20has=20two=20balance=20queries:=20/api/usa?= =?UTF-8?q?ge/token=20tells=20a=20key=20what=20is=20left=20on=20it=20and?= =?UTF-8?q?=20takes=20the=20key=20alone,=20and=20/api/user/self=20tells=20?= =?UTF-8?q?the=20account's=20quota=20to=20the=20access=20token=20with=20th?= =?UTF-8?q?e=20user's=20id=20in=20New-Api-User.=20A=20token=20beside=20the?= =?UTF-8?q?=20first=20could=20only=20ever=20be=20turned=20down,=20and=20th?= =?UTF-8?q?e=20second=20without=20the=20header=20answered=20{"success":fal?= =?UTF-8?q?se,"message":"=E6=97=A0=E6=9D=83=E8=BF=9B=E8=A1=8C=E6=AD=A4?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=EF=BC=8C=E6=9C=AA=E6=8F=90=E4=BE=9B=20New-Ap?= =?UTF-8?q?i-User"},=20which=20a=20401=20showed=20as=20JSON=20and=20a=2020?= =?UTF-8?q?0=20read=20as=20a=20field=20missing.=20The=20editor=20now=20say?= =?UTF-8?q?s=20so=20under=20the=20token=20as=20soon=20as=20it=20is=20there?= =?UTF-8?q?:=20beside=20=E2=80=A6/api/usage/token,=20or=20with=20no=20Bala?= =?UTF-8?q?nce=20URL=20at=20all=20(the=20token=20field=20is=20now=20offere?= =?UTF-8?q?d=20on=20every=20custom=20provider,=20not=20only=20one=20with?= =?UTF-8?q?=20a=20URL=20saved),=20a=20warning=20with=20one=20button,=20Use?= =?UTF-8?q?=20https:///api/user/self,=20which=20sets=20the=20URL,=20?= =?UTF-8?q?sets=20the=20Balance=20field=20to=20$data.quota=20/=20500000=20?= =?UTF-8?q?when=20it=20was=20empty=20or=20named=20/api/usage/token's=20fie?= =?UTF-8?q?lds,=20and=20opens=20More=20endpoints=20to=20show=20it;=20once?= =?UTF-8?q?=20the=20URL=20is=20/api/user/self=20and=20no=20New-Api-User=20?= =?UTF-8?q?header=20has=20a=20value,=20it=20asks=20for=20New-Api-User=20?= =?UTF-8?q?=3D=20your=20user=20ID=20(shown=20in=20the=20site's=20personal?= =?UTF-8?q?=20settings)=20until=20one=20is=20typed.=20The=20URL=20is=20not?= =?UTF-8?q?=20switched=20behind=20the=20user's=20back:=20what=20the=20edit?= =?UTF-8?q?or=20shows=20is=20what=20is=20asked,=20and=20the=20field=20type?= =?UTF-8?q?d=20for=20/api/usage/token's=20reply=20wouldn't=20read=20/api/u?= =?UTF-8?q?ser/self's=20anyway.=20Behind=20it,=20Balance=20never=20sends?= =?UTF-8?q?=20a=20token=20to=20/api/usage/token=20and=20says=20what=20to?= =?UTF-8?q?=20set=20instead;=20a=20reply=20of=20success:false=20with=20a?= =?UTF-8?q?=20message,=20at=20a=20401=20or=20a=20200,=20is=20that=20messag?= =?UTF-8?q?e=20as=20the=20error,=20with=20the=20header=20to=20add=20put=20?= =?UTF-8?q?in=20front=20when=20it=20is=20about=20New-Api-User=20(not=20pro?= =?UTF-8?q?vided,=20format=20error=20or=20mismatch,=20in=20new-api's=20Chi?= =?UTF-8?q?nese=20or=20English);=20and=20/api/user/self=20with=20an=20empt?= =?UTF-8?q?y=20field=20reads=20the=20quota,=20$1=20to=20500000.=20The=20Ba?= =?UTF-8?q?lance=20field=20has=20a=20Check=20balance=20button=20(POST=20/a?= =?UTF-8?q?pi/provider/balance)=20that=20asks=20as=20the=20form=20has=20it?= =?UTF-8?q?,=20before=20a=20Save,=20the=20saved=20provider=20with=20the=20?= =?UTF-8?q?form's=20URL,=20field,=20headers=20and=20token;=20it=20and=20th?= =?UTF-8?q?e=20Usage=20page's=20card=20say=20either=20fix=20plainly,=20the?= =?UTF-8?q?=20relay's=20own=20words=20on=20hover.=20A=20JWT=20beside=20new?= =?UTF-8?q?-api's=20URL=20is=20not=20warned=20about:=20new-api's=20own=20d?= =?UTF-8?q?ashboard=20sign-ins=20are=20JWTs=20now,=20so=20a=20token's=20sh?= =?UTF-8?q?ape=20can't=20tell=20new-api=20from=20a=20sub2api=20panel.=20Te?= =?UTF-8?q?sted=20with=20new=20TestKeyUsageWithAccessToken=20(never=20aske?= =?UTF-8?q?d,=20the=20fix=20said,=20the=20key=20alone=20still=20asks),=20T?= =?UTF-8?q?estUserSelfDefaultField=20and=20TestNewAPIUserRefusal=20(401=20?= =?UTF-8?q?and=20200,=20Chinese=20and=20English,=20the=20mismatch,=20and?= =?UTF-8?q?=20an=20unrelated=20refusal=20left=20as=20it=20came),=20which?= =?UTF-8?q?=20all=20fail=20on=20main;=20and=20a=20new=20internal/gui/tests?= =?UTF-8?q?/balance-fix.test.cjs=20in=20Chromium=20and=20WebKit=20(the=20w?= =?UTF-8?q?arning=20on=20the=20saved=20setup,=20the=20click,=20the=20heade?= =?UTF-8?q?r=20hint=20going=20once=20typed,=20Check=20balance=20with=20and?= =?UTF-8?q?=20without=20the=20header=20and=20what=20it=20posted,=20Save,?= =?UTF-8?q?=20the=20Usage=20card's=20words,=20every=20new=20string=20in=20?= =?UTF-8?q?Chinese,=20and=20a=20new=20provider=20with=20a=20token=20and=20?= =?UTF-8?q?no=20URL).=20go=20build=20(and=20GOOS=3Dlinux,=20GOOS=3Dwindows?= =?UTF-8?q?),=20go=20test=20-tags=20nogui=20./...=20and=20the=20other=20GU?= =?UTF-8?q?I=20tests=20pass?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gui/assets/app.css | 11 ++ internal/gui/assets/app.js | 119 ++++++++++++++++-- internal/gui/assets/i18n.js | 9 ++ internal/gui/providers.go | 28 +++++ internal/gui/tests/README.md | 9 +- internal/gui/tests/balance-fix.test.cjs | 161 ++++++++++++++++++++++++ internal/provider/balance.go | 74 +++++++++++ internal/provider/balance_test.go | 82 ++++++++++++ 8 files changed, 484 insertions(+), 9 deletions(-) create mode 100644 internal/gui/tests/balance-fix.test.cjs diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index dddaac31d..8b12935f3 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -1167,6 +1167,17 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .editor .ehead .note { font-size: 12px; color: var(--muted); } .editor label { font-size: 12px; color: var(--muted); text-align: right; padding-top: 5px; } .editor .hint { font-size: 11px; color: var(--faint); margin-top: 4px; } +/* what a balance token's URL wants instead, and a balance checked in the form */ +.editor .bal-fix { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; margin-top: 6px; font-size: 12px; line-height: 1.45; color: var(--muted); } +.editor .bal-fix:empty { display: none; } +.editor .bal-fix.warn { color: var(--amber); } +.editor .bal-fix .text.action { height: 24px; font-size: 11.5px; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.editor .pair.wrap { flex-wrap: wrap; } +.editor .bal-res { flex-basis: 100%; font-size: 12px; line-height: 1.45; color: var(--muted); overflow-wrap: anywhere; user-select: text; -webkit-user-select: text; } +.editor .bal-res:empty { display: none; } +.editor .bal-res.ok { color: var(--green); } +.editor .bal-res.bad { color: var(--red); } +.editor .bal-res.wait { color: var(--faint); } .stepplan .state { flex: 1; min-width: 0; font-size: 12px; color: var(--muted); line-height: 1.4; } .stepplan .steps { margin: 0; padding-left: 18px; display: flex; flex-direction: column; gap: 8px; font-size: 12px; color: var(--muted); line-height: 1.5; } .stepplan .steps .pair { margin-top: 2px; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 5dba2022c..28dbe3fbb 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -2808,23 +2808,35 @@ function renderEditor(p, presetID) { // a vendor that tells the whole account's balance only to a token of its // own (AiHubMix's system access token), where a key knows just its own - if (p?.balanceToken?.takes) { - const tok = input(draft.balanceToken || "", p.balanceToken.set && !draft.clearBalanceToken ? t("saved · paste a new one to replace it") : t("optional · the account's system access token"), "password"); + // — or a custom provider's, whose Balance URL may not be named yet: a + // token pasted there says at once which URL it wants (balanceFix) + let balFix = null; + if (p?.balanceToken?.takes || custom) { + const saved = !!p?.balanceToken?.set; + const tok = input(draft.balanceToken || "", saved && !draft.clearBalanceToken ? t("saved · paste a new one to replace it") : t("optional · the account's system access token"), "password"); tok.oninput = () => { draft.balanceToken = tok.value.trim(); }; tok.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Escape") cancelEdit(); }; const pair = el("div", "pair"); pair.append(tok); - if (p.balanceToken.set && !draft.clearBalanceToken) { + if (saved && !draft.clearBalanceToken) { const side = el("div", "side"); const drop = el("button", "text", t("Remove")); - drop.onclick = () => { draft.clearBalanceToken = true; draft.balanceToken = ""; tok.value = ""; tok.placeholder = t("optional · the account's system access token"); drop.remove(); }; + drop.onclick = () => { draft.clearBalanceToken = true; draft.balanceToken = ""; tok.value = ""; tok.placeholder = t("optional · the account's system access token"); drop.remove(); balFix?.refresh(); }; side.append(drop); pair.append(side); } - const tokHelp = p.balanceURL + const tokHelp = custom || p.balanceURL ? t("What the Balance URL is asked with in place of the key, when it wants the account's own token: a new-api relay's System Access Token, or a sub2api panel's login token (a JWT, sent as a Bearer); it is used for nothing else.") : t("A key tells only what is left on itself. For the whole account's balance on the Usage page, generate a System Access Token in {p}'s settings and paste it here; it is used for nothing else.", { p: pr?.name || p.name }); - ed.append(...field(t("Account balance"), pair, tokHelp)); + const [label, wrap] = field(t("Account balance"), pair, tokHelp); + if (custom) { + balFix = balanceFix(p); + wrap.append(balFix); + // whatever is typed — the token, the Balance URL, a header — may + // make it or unmake it + ed.addEventListener("input", () => balFix.refresh()); + } + ed.append(label, wrap); } // StepFun tells a Step Plan's 5-hour, weekly and credit windows only to @@ -2921,11 +2933,40 @@ function renderEditor(p, presetID) { cat.oninput = () => { draft.catalog = cat.value; }; inner.append(...field(t("Catalog"), cat, t("Display names and reasoning levels for the models; for a gateway that serves several vendors, list them all, first match wins"))); const bal = input(draft.balanceURL, "https://…/api/usage/token", "url"); + bal.classList.add("bal-url"); bal.oninput = () => { draft.balanceURL = bal.value; }; inner.append(...field(t("Balance URL"), bal, t("Where the vendor tells what is left on the key, asked with it like a chat request; shown on the Usage page"))); const balPath = input(draft.balancePath, "data.balance"); + balPath.classList.add("bal-path"); balPath.oninput = () => { draft.balancePath = balPath.value; }; - inner.append(...field(t("Balance field"), balPath, t("Where the amount is in the reply, e.g. data.balance; it can be a sum with + - * / and brackets, e.g. data.total / 500000 or (1 - credits.used / 70) %; \"$\" in front adds the sign, \"%\" after it shows a percent; several, each with a label, go apart by \";\", e.g. 5h: a.used / a.cap %; $credits.left"))); + // asked as the form has it, before a Save: what the Usage page would show + const balPair = el("div", "pair"); + balPair.append(balPath); + if (p) { + const side = el("div", "side"); + const check = el("button", "text action", t("Check balance")); + check.title = t("Ask the Balance URL now, as the form has it"); + side.append(check); + balPair.append(side); + const res = el("div", "bal-res"); + 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(), headers: headersOf(draft.headers) }; + if (draft.balanceToken) body.balanceToken = draft.balanceToken; + else if (draft.clearBalanceToken) body.clearBalanceToken = true; + try { + const r = await api("provider/balance", body); + res.className = "bal-res " + (r.error ? "bad" : r.ok ? "ok" : ""); + res.textContent = r.error ? balanceError(r.error) || r.error : r.ok ? t("Balance") + " " + r.amount : t("No Balance URL to ask"); + res.title = r.error || ""; + } catch (e) { res.className = "bal-res bad"; res.textContent = e.message; } + check.classList.remove("busy"); + }; + balPair.append(res); + balPair.classList.add("wrap"); + } + inner.append(...field(t("Balance field"), balPair, t("Where the amount is in the reply, e.g. data.balance; it can be a sum with + - * / and brackets, e.g. data.total / 500000 or (1 - credits.used / 70) %; \"$\" in front adds the sign, \"%\" after it shows a percent; several, each with a label, go apart by \";\", e.g. 5h: a.used / a.cap %; $credits.left"))); more.append(inner); ed.append(more); } @@ -4122,7 +4163,69 @@ function quotaError(err) { if (/violation of Terms of Service/i.test(err)) return t("Google has suspended this account — hover for details"); if (/access token is invalid or expired|didn't take the access token/.test(err)) return t("AiHubMix didn't take the access token — paste a new one in the provider's settings"); if (/this key has no limit/.test(err)) return t("This key has no limit — add the account's access token in the provider's settings to see its balance"); - return t("Usage unavailable"); + return balanceError(err) || t("Usage unavailable"); +} + +// balanceError: a balance that couldn't be read, said plainly where magpie +// knows the fix (see balance.go); "" for any other. +function balanceError(err) { + if (/takes the API key, not the access token/.test(err)) return t("The Balance URL …/api/usage/token takes the API key, not the access token — set it to …/api/user/self in the provider's settings"); + if (/New-Api-User/i.test(err)) return t("Add the header New-Api-User = your user ID (shown in the site's personal settings) to the provider's Headers"); + return ""; +} + +// balanceFix: under a custom provider's balance token, what its Balance URL +// wants in place of what is there, with the one click that sets it: +// new-api's /api/usage/token is asked with the key alone and never with the +// token (balance.go doesn't send it there), and a token without a URL is +// asked nowhere; new-api's /api/user/self takes the token, with the user's +// id in New-Api-User, which is said too while no such header is set. A URL +// of any other kind (a sub2api panel's) is left alone: a token's shape +// can't tell the two apart, new-api's own sign-ins being JWTs too. +function balanceFix(p) { + const box = el("div", "bal-fix"); + const origin = (u) => { try { const x = new URL(u); return /^https?:$/.test(x.protocol) ? x.origin : ""; } catch { return ""; } }; + box.refresh = () => { + box.replaceChildren(); + box.className = "bal-fix"; + const tok = !!draft.balanceToken || (!!p?.balanceToken?.set && !draft.clearBalanceToken); + if (!tok) return; + const u = (draft.balanceURL || "").trim(); + let path = ""; + try { path = new URL(u).pathname.replace(/\/+$/, ""); } catch {} + let why = ""; + if (path === "/api/usage/token") why = t("…/api/usage/token takes the API key, not this token: a new-api relay tells the account's balance to the token at /api/user/self."); + else if (!u) why = t("The token needs a Balance URL: a new-api relay tells the account's balance to it at /api/user/self."); + if (why) { + box.classList.add("warn"); + box.append(el("span", "", why)); + const site = origin(u) || origin(draft.chat || draft.anthropic || draft.responses || ""); + if (!site) return; + const to = site + "/api/user/self"; + const use = el("button", "text action", t("Use {url}", { url: to })); + use.onclick = () => { + draft.balanceURL = to; + // /api/usage/token's fields aren't in /api/user/self's reply; the + // account's quota is, $1 to 500000 of it + if (!(draft.balancePath || "").trim() || /total_(available|granted|used)|unlimited_quota/.test(draft.balancePath)) draft.balancePath = "$data.quota / 500000"; + const ed = box.closest(".editor"); + const set = (sel, v) => { const i = ed?.querySelector(sel); if (i) i.value = v; }; + set(".bal-url", draft.balanceURL); + set(".bal-path", draft.balancePath); + // what changed, in view below + const more = ed?.querySelector("details.more"); + if (more) more.open = true; + box.refresh(); + }; + box.append(use); + return; + } + if (path === "/api/user/self" && !(draft.headers || []).some((h) => (h[0] || "").trim().toLowerCase() === "new-api-user" && (h[1] || "").trim())) { + box.append(el("span", "", t("A new-api relay also wants the header New-Api-User = your user ID (shown in the site's personal settings): add it under Headers."))); + } + }; + box.refresh(); + return box; } // accountQuota: an account's allowance as a line of small meters under its diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 1b8549bae..b8eb679dc 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -746,6 +746,15 @@ const I18N = { "saved · paste a new one to replace it": "已保存 · 粘贴新的即可替换", "optional · the account's system access token": "可选 · 账户的系统访问令牌", "What the Balance URL is asked with in place of the key, when it wants the account's own token: a new-api relay's System Access Token, or a sub2api panel's login token (a JWT, sent as a Bearer); it is used for nothing else.": "余额接口需要账户自己的令牌时,用它代替 Key 去请求:new-api 中转站填「系统访问令牌」,sub2api 面板填登录令牌(JWT,会以 Bearer 发送);不作他用。", + "…/api/usage/token takes the API key, not this token: a new-api relay tells the account's balance to the token at /api/user/self.": "…/api/usage/token 只认 API Key,不认这个令牌:new-api 中转站用 /api/user/self 凭令牌查账户余额。", + "The token needs a Balance URL: a new-api relay tells the account's balance to it at /api/user/self.": "令牌还需要一个余额查询地址:new-api 中转站用 /api/user/self 凭令牌查账户余额。", + "Use {url}": "改用 {url}", + "A new-api relay also wants the header New-Api-User = your user ID (shown in the site's personal settings): add it under Headers.": "new-api 中转站还需要请求头 New-Api-User = 你的用户 ID(在站点的个人设置里可以看到),请在「请求头」里添加。", + "The Balance URL …/api/usage/token takes the API key, not the access token — set it to …/api/user/self in the provider's settings": "余额查询地址 …/api/usage/token 只认 API Key,不认访问令牌,请在供应商设置里改为 …/api/user/self", + "Add the header New-Api-User = your user ID (shown in the site's personal settings) to the provider's Headers": "请在供应商的「请求头」里添加 New-Api-User = 你的用户 ID(在站点的个人设置里可以看到)", + "Check balance": "查询余额", + "Ask the Balance URL now, as the form has it": "按表单当前的填写立即查询一次余额", + "No Balance URL to ask": "没有可查询的余额地址", "A key tells only what is left on itself. For the whole account's balance on the Usage page, generate a System Access Token in {p}'s settings and paste it here; it is used for nothing else.": "API key 只能查到它自己的剩余额度。要在用量页显示整个账户的余额,请在 {p} 的设置中生成系统访问令牌并粘贴到这里;它不作他用。", "Antigravity hasn't set this account up — hover for why": "Antigravity 还没为这个账号开通,悬停查看原因", "Resets {when}": "重置于 {when}", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index a11a2378f..85b9f2b56 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -621,6 +621,34 @@ func providerRoutes(mux *http.ServeMux, w Windows) { Provider providerJSON `json:"provider"` }{p.Test(ctx), providerInfo(*p, agentUses(agent.Detected(), provider.GroupFinder()))}) return + case "balance": + // the editor's check of a balance as it stands in the form, + // before a Save: the saved provider with the form's URL, field, + // headers and token (a blank one keeping the saved) + p, err := provider.Find(in.ID) + if err != nil { + fail(rw, err) + return + } + q := *p + q.BalanceURL, q.BalancePath = strings.TrimSpace(in.BalanceURL), strings.TrimSpace(in.BalancePath) + if in.Headers != nil { + q.Headers = in.Headers + } + if in.BalanceToken != "" { + q.BalanceToken = in.BalanceToken + } else if req.ClearBalanceToken { + q.BalanceToken = "" + } + ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) + defer cancel() + amount, ok, err := provider.Balance(ctx, q) + out := map[string]any{"ok": ok, "amount": amount} + if err != nil { + out["error"] = err.Error() + } + writeJSON(rw, out) + return case "unfetch": // the vendor's list, forgotten until the next Refresh if err := catalog.SaveLive(in.ID, "", nil); err != nil { diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index a72eaad3f..beb1a4f9f 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -28,10 +28,17 @@ a title, memories, a turn on Luna Reserve, a kind it does not know yet): each has a grey tag by its model in the Requests list, in English and Chinese, the model keeping its room first, and the request's story says what it was. +`balance-fix.test.cjs` opens a custom provider whose balance token sits +beside new-api's `/api/usage/token` (and a new one with a token and no +Balance URL): the editor says so, one click moves it to `/api/user/self` +with the quota as its field, the New-Api-User header is asked for until it +is typed, Check balance asks as the form has it and says the fix plainly, +and the Usage page's card does too. + With Node.js and Playwright available: ```sh -node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs +node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs ``` If Playwright is installed outside the repository, set `NODE_PATH` to the diff --git a/internal/gui/tests/balance-fix.test.cjs b/internal/gui/tests/balance-fix.test.cjs new file mode 100644 index 000000000..f487bf6b8 --- /dev/null +++ b/internal/gui/tests/balance-fix.test.cjs @@ -0,0 +1,161 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A custom provider's balance token beside new-api's /api/usage/token, which +// takes only the key, is said in the editor with the one click that moves it +// to /api/user/self (and its field to the quota); the New-Api-User header +// that wants is asked for until it is set, Check balance asks as the form +// has it, and the Usage page says the fix for either refusal plainly. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const 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: "https://relay.example.com/api/usage/token", balancePath: "$data.total_available / 500000", + balanceToken: { takes: true, set: true }, +}; +const providers = { providers: [relay], presets: [], excluded: [], gateway: { running: true, window: true } }; +const state = { agents: [], profiles: [], settings: { lang: "en", theme: "light" } }; + +function server(posted) { + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: 'window.bootPrefs = {lang:"en",theme:"light",web:true};' }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname.startsWith("/api/provider/")) { + const body = route.request().postDataJSON(); + posted.push({ action: url.pathname.slice("/api/provider/".length), body }); + if (url.pathname === "/api/provider/balance") { + // new-api's /api/user/self: the quota once New-Api-User is there + if (body.headers?.["New-Api-User"]) return json({ ok: true, amount: "$3.00" }); + return json({ ok: true, amount: "", error: "401 Unauthorized: add the header New-Api-User = your user ID (shown in the site's personal settings) to this provider's Headers; the relay said: 无权进行此操作,未提供 New-Api-User" }); + } + return json(providers); + } + 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 }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a balance token on /api/usage/token is moved to /api/user/self", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const context = await browser.newContext({ viewport: { width: 900, height: 760 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const posted = []; + await page.route("**/*", server(posted)); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, engine + "-balance-fix.png") }); + } + await browser.close(); + }); + + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: "Relay" }).click(); + const fix = page.locator(".editor .bal-fix"); + await fix.waitFor(); + assert(await fix.evaluate((e) => e.classList.contains("warn")), "the saved token beside /api/usage/token is a warning"); + assert.match(await fix.textContent(), /\/api\/usage\/token takes the API key, not this token/); + const use = fix.getByRole("button", { name: "Use https://relay.example.com/api/user/self" }); + await use.click(); + + assert.equal(await page.locator(".editor .bal-url").inputValue(), "https://relay.example.com/api/user/self"); + assert.equal(await page.locator(".editor .bal-path").inputValue(), "$data.quota / 500000", "usage/token's field gives way to the quota"); + assert(await page.locator(".editor details.more").evaluate((d) => d.open), "what changed is in view"); + assert(!(await fix.evaluate((e) => e.classList.contains("warn")))); + assert.match(await fix.textContent(), /New-Api-User = your user ID/, "the header /api/user/self wants is asked for"); + + // asked as the form has it, without the header: the fix said plainly + const check = page.getByRole("button", { name: "Check balance" }); + const res = page.locator(".editor .bal-res"); + await check.click(); + await page.locator(".editor .bal-res.bad").waitFor(); + assert.equal(await res.textContent(), "Add the header New-Api-User = your user ID (shown in the site's personal settings) to the provider's Headers"); + assert.match(await res.getAttribute("title"), /未提供 New-Api-User/, "the relay's own words on hover"); + let asked = posted.filter((p) => p.action === "balance").at(-1).body; + assert.equal(asked.id, "relay"); + assert.equal(asked.balanceURL, "https://relay.example.com/api/user/self"); + assert.equal(asked.balancePath, "$data.quota / 500000"); + + // the header typed in, the hint goes and the balance reads + const row = page.locator(".editor .headers .pair").first(); + await row.locator("input").nth(0).fill("New-Api-User"); + await row.locator("input").nth(1).fill("42"); + assert.equal(await fix.textContent(), "", "no hint once New-Api-User is set"); + await check.click(); + await page.locator(".editor .bal-res.ok").waitFor(); + assert.equal(await res.textContent(), "Balance $3.00"); + asked = posted.filter((p) => p.action === "balance").at(-1).body; + assert.deepEqual(asked.headers, { "New-Api-User": "42" }); + + // Save keeps what the click set + await page.locator(".editor .bar").getByRole("button", { name: "Save" }).click(); + await page.waitForTimeout(300); + const saved = posted.filter((p) => p.action === "save").at(-1).body; + assert.equal(saved.balanceURL, "https://relay.example.com/api/user/self"); + assert.equal(saved.balancePath, "$data.quota / 500000"); + assert.deepEqual(saved.headers, { "New-Api-User": "42" }); + + // the Usage page's card says either fix plainly, in English and Chinese + const said = await page.evaluate(() => [ + quotaError("the Balance URL https://relay.example.com/api/usage/token takes the API key, not the access token: set it to https://relay.example.com/api/user/self (Balance field $data.quota / 500000) for the account's balance, or remove the token for the key's own"), + quotaError("401 Unauthorized: add the header New-Api-User = your user ID (shown in the site's personal settings) to this provider's Headers; the relay said: 无权进行此操作,未提供 New-Api-User"), + quotaError("401 Unauthorized: something else"), + ]); + assert.match(said[0], /set it to …\/api\/user\/self/); + assert.match(said[1], /^Add the header New-Api-User = your user ID/); + assert.equal(said[2], "Usage unavailable"); + const missing = await page.evaluate(() => [ + "…/api/usage/token takes the API key, not this token: a new-api relay tells the account's balance to the token at /api/user/self.", + "The token needs a Balance URL: a new-api relay tells the account's balance to it at /api/user/self.", + "Use {url}", "Check balance", "Ask the Balance URL now, as the form has it", "No Balance URL to ask", + "A new-api relay also wants the header New-Api-User = your user ID (shown in the site's personal settings): add it under Headers.", + "The Balance URL …/api/usage/token takes the API key, not the access token — set it to …/api/user/self in the provider's settings", + "Add the header New-Api-User = your user ID (shown in the site's personal settings) to the provider's Headers", + ].filter((k) => !I18N.zh[k])); + assert.deepEqual(missing, [], "every new string has its Chinese"); + assert.deepEqual(errors, []); + }); + + test(engine + ": a token on a new custom provider with no Balance URL is pointed at /api/user/self", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const context = await browser.newContext({ viewport: { width: 900, height: 760 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server([])); + t.after(() => browser.close()); + + await page.goto("http://magpie.test/?view=providers"); + await page.locator("#providers .row.provider").first().waitFor(); + await page.evaluate(() => { adding = true; editing = { custom: true }; draft = null; renderProviders(); }); + const tok = page.locator(".editor input[type=password]").nth(1); + await page.locator(".editor input[type=url]").first().fill("https://relay.example.com/v1"); + const fix = page.locator(".editor .bal-fix"); + assert.equal(await fix.textContent(), "", "no token, no hint"); + await tok.fill("access-token"); + assert.match(await fix.textContent(), /The token needs a Balance URL/); + await fix.getByRole("button", { name: "Use https://relay.example.com/api/user/self" }).click(); + assert.equal(await page.locator(".editor .bal-url").inputValue(), "https://relay.example.com/api/user/self"); + assert.equal(await page.locator(".editor .bal-path").inputValue(), "$data.quota / 500000"); + assert.equal(await page.locator(".editor .bal-res").count(), 0, "a provider not yet added has nothing to check with"); + assert.deepEqual(errors, []); + }); +} diff --git a/internal/provider/balance.go b/internal/provider/balance.go index 64889604e..f78f784ab 100644 --- a/internal/provider/balance.go +++ b/internal/provider/balance.go @@ -14,6 +14,7 @@ import ( "io" "math" "net/http" + "net/url" "strconv" "strings" "sync" @@ -35,6 +36,11 @@ type balanceSource struct { func balanceSourceOf(p Provider) (balanceSource, bool) { if p.BalanceURL != "" { path := p.BalancePath + if strings.TrimSpace(path) == "" && balanceURLPath(p.BalanceURL) == newAPIUserSelf { + // new-api's account query with its field left out: the quota, + // in new-api's units, as it reports it + path = newAPIQuotaPath + } // a token saved beside it (a new-api relay's access token, its // /api/user/self telling the account's quota) is asked with // instead of the key @@ -71,6 +77,62 @@ func balanceSourceOf(p Provider) (balanceSource, bool) { return balanceSource{}, false } +// new-api's two balance queries: /api/usage/token tells a key what is left +// on it and is asked with the key alone (its token check takes no access +// token), /api/user/self tells the account's quota, $1 to 500000 of it, to +// the account's access token with the user's id in New-Api-User. +const ( + newAPIKeyUsage = "/api/usage/token" + newAPIUserSelf = "/api/user/self" + newAPIQuotaPath = "$data.quota / 500000" +) + +// balanceURLPath is a balance URL's path, without a slash at its end. +func balanceURLPath(raw string) string { + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil { + return "" + } + return strings.TrimRight(u.Path, "/") +} + +// errKeyUsageWithToken is a balance token beside new-api's query for a key, +// which never takes it: asked, it could only be refused, so what to name in +// its place is said instead. +func errKeyUsageWithToken(raw string) error { + self := newAPIUserSelf + if u, err := url.Parse(strings.TrimSpace(raw)); err == nil && u.Host != "" { + self = u.Scheme + "://" + u.Host + newAPIUserSelf + } + return fmt.Errorf("the Balance URL %s takes the API key, not the access token: set it to %s (Balance field %s) for the account's balance, or remove the token for the key's own", raw, self, newAPIQuotaPath) +} + +// balanceRefusal is what a reply of {"success":false,"message":…} says, a +// new-api relay's way of turning a request down, with a 401 and a 200 +// alike; a reply without the two is not one. +func balanceRefusal(b []byte) (string, bool) { + var r struct { + Success *bool `json:"success"` + Message string `json:"message"` + } + if json.Unmarshal(b, &r) != nil || r.Success == nil || *r.Success || strings.TrimSpace(r.Message) == "" { + return "", false + } + return strings.TrimSpace(r.Message), true +} + +// newAPIUserHint puts what to do before a new-api refusal about the +// New-Api-User header, which its /api/user/self wants beside the access +// token ("无权进行此操作,未提供 New-Api-User", "Unauthorized, New-Api-User +// header not provided", or its format error or mismatch); any other +// message is left as it came. +func newAPIUserHint(msg string) string { + if !strings.Contains(strings.ToLower(msg), "new-api-user") { + return msg + } + return "add the header New-Api-User = your user ID (shown in the site's personal settings) to this provider's Headers; the relay said: " + msg +} + // TakesBalanceToken says the provider's vendor tells the account's balance // to a token of its own (BalanceToken), which the editor then asks for. func TakesBalanceToken(p Provider) bool { @@ -527,6 +589,9 @@ func Balance(ctx context.Context, p Provider) (amount string, ok bool, err error if !ok || p.Account != nil || p.Key == "" { return "", false, nil } + if src.token != "" && p.BalanceURL != "" && balanceURLPath(p.BalanceURL) == newAPIKeyUsage { + return "", true, errKeyUsageWithToken(p.BalanceURL) + } req, err := http.NewRequestWithContext(ctx, http.MethodGet, src.url, nil) if err != nil { return "", true, err @@ -555,6 +620,15 @@ func Balance(ctx context.Context, p Provider) (amount string, ok bool, err error } defer res.Body.Close() b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + if msg, refused := balanceRefusal(b); refused { + // said as the relay says it, whatever the status: not a field + // missing from a reply that was never the balance + msg = newAPIUserHint(msg) + if res.StatusCode >= 300 { + msg = res.Status + ": " + msg + } + return "", true, errors.New(msg) + } if res.StatusCode >= 300 { // what a JSON reply says, on one line; a page of HTML says nothing msg := strings.Join(strings.Fields(string(b)), " ") diff --git a/internal/provider/balance_test.go b/internal/provider/balance_test.go index b39932f90..25b4d8682 100644 --- a/internal/provider/balance_test.go +++ b/internal/provider/balance_test.go @@ -230,3 +230,85 @@ func TestNamedBalanceWithSub2APIJWT(t *testing.T) { t.Fatal("a new-api access token goes as it is") } } + +// An access token beside new-api's /api/usage/token, which takes only the +// key, is never sent there: what to name in its place is said instead. +func TestKeyUsageWithAccessToken(t *testing.T) { + asked := false + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + asked = true + w.WriteHeader(http.StatusUnauthorized) + w.Write([]byte(`{"success":false,"message":"无效的令牌"}`)) + })) + defer srv.Close() + p := Provider{ID: "relay", Chat: srv.URL + "/v1", Key: "sk-one", BalanceToken: "tok", + BalanceURL: srv.URL + "/api/usage/token/", BalancePath: "$data.total_available / 500000"} + _, ok, err := Balance(context.Background(), p) + if !ok || err == nil || asked { + t.Fatalf("ok %v, err %v, asked %v", ok, err, asked) + } + if want := srv.URL + "/api/user/self (Balance field $data.quota / 500000)"; !strings.Contains(err.Error(), want) || !strings.Contains(err.Error(), "takes the API key, not the access token") { + t.Fatalf("err = %v", err) + } + // the key alone still asks it + p.BalanceToken = "" + if _, _, err := Balance(context.Background(), p); !asked || err == nil { + t.Fatalf("without the token: asked %v, err %v", asked, err) + } +} + +// new-api's /api/user/self with its field left out reads the quota as +// new-api counts it, $1 to 500000. +func TestUserSelfDefaultField(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte(`{"success":true,"data":{"quota":1000000}}`)) + })) + defer srv.Close() + p := Provider{ID: "relay", Chat: srv.URL + "/v1", Key: "sk-one", BalanceToken: "tok", BalanceURL: srv.URL + "/api/user/self"} + if got, _, err := Balance(context.Background(), p); err != nil || got != "$2.00" { + t.Fatalf("balance = %q %v", got, err) + } + p.BalancePath = "data.quota" + if got, _, err := Balance(context.Background(), p); err != nil || got != "1000000.00" { + t.Fatalf("a field given is kept: %q %v", got, err) + } +} + +// new-api turns an access token without New-Api-User down with a 401 (and +// some builds, or a bad token, with a 200) of {"success":false,…}: the +// message is the error, with what to add, not a field missing. +func TestNewAPIUserRefusal(t *testing.T) { + for _, c := range []struct { + status int + body string + want []string + }{ + {401, `{"success":false,"message":"无权进行此操作,未提供 New-Api-User"}`, []string{"401 Unauthorized: ", "add the header New-Api-User = your user ID", "未提供 New-Api-User"}}, + {200, `{"success":false,"message":"Unauthorized, New-Api-User header not provided"}`, []string{"add the header New-Api-User = your user ID", "header not provided"}}, + {401, `{"success":false,"message":"无权进行此操作,New-Api-User 与登录用户不匹配"}`, []string{"add the header New-Api-User", "不匹配"}}, + {200, `{"success":false,"message":"无权进行此操作,access token 无效"}`, []string{"access token 无效"}}, + } { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(c.status) + w.Write([]byte(c.body)) + })) + p := Provider{ID: "relay", Chat: srv.URL + "/v1", Key: "sk-one", BalanceToken: "tok", + BalanceURL: srv.URL + "/api/user/self", BalancePath: "$data.quota / 500000"} + _, ok, err := Balance(context.Background(), p) + srv.Close() + if !ok || err == nil { + t.Fatalf("%s: ok %v, err %v", c.body, ok, err) + } + for _, w := range c.want { + if !strings.Contains(err.Error(), w) { + t.Errorf("%s: %q lacks %q", c.body, err, w) + } + } + if strings.Contains(err.Error(), "nothing at") { + t.Errorf("%s: read as a missing field: %v", c.body, err) + } + if !strings.Contains(c.body, "New-Api-User") && strings.Contains(err.Error(), "add the header") { + t.Errorf("%s: told to add the header: %v", c.body, err) + } + } +}