balance: a custom provider's balance token can't be left where it is never asked, and new-api's refusals say what to do (TJHHHH: OK了,希望有防呆机制 — a new-api relay's System Access Token pasted beside a Balance URL of /api/usage/token, no New-Api-User header, and the Usage page never showed a balance) — new-api has two balance queries: /api/usage/token tells a key what is left on it and takes the key alone, and /api/user/self tells the account's quota to the access token with the user's id in New-Api-User. A token beside the first could only ever be turned down, and the second without the header answered {"success":false,"message":"无权进行此操作,未提供 New-Api-User"}, which a 401 showed as JSON and a 200 read as a field missing. The editor now says so under the token as soon as it is there: beside …/api/usage/token, or with no Balance URL at all (the token field is now offered on every custom provider, not only one with a URL saved), a warning with one button, Use https://<site>/api/user/self, which sets the URL, sets the Balance field to $data.quota / 500000 when it was empty or named /api/usage/token's fields, and opens More endpoints to show it; once the URL is /api/user/self and no New-Api-User header has a value, it asks for New-Api-User = your user ID (shown in the site's personal settings) until one is typed. The URL is not switched behind the user's back: what the editor shows is what is asked, and the field typed for /api/usage/token's reply wouldn't read /api/user/self's anyway. Behind it, Balance never sends a token to /api/usage/token and says what to set instead; a reply of success:false with a message, at a 401 or a 200, is that message as the error, with the header to add put in front when it is about New-Api-User (not provided, format error or mismatch, in new-api's Chinese or English); and /api/user/self with an empty field reads the quota, $1 to 500000. The Balance field has a Check balance button (POST /api/provider/balance) that asks as the form has it, before a Save, the saved provider with the form's URL, field, headers and token; it and the Usage page's card say either fix plainly, the relay's own words on hover. A JWT beside new-api's URL is not warned about: new-api's own dashboard sign-ins are JWTs now, so a token's shape can't tell new-api from a sub2api panel. Tested with new TestKeyUsageWithAccessToken (never asked, the fix said, the key alone still asks), TestUserSelfDefaultField and TestNewAPIUserRefusal (401 and 200, Chinese and English, the mismatch, and an unrelated refusal left as it came), which all fail on main; and a new internal/gui/tests/balance-fix.test.cjs in Chromium and WebKit (the warning on the saved setup, the click, the header hint going once typed, Check balance with and without the header and what it posted, Save, the Usage card's words, every new string in Chinese, and a new provider with a token and no URL). go build (and GOOS=linux, GOOS=windows), go test -tags nogui ./... and the other GUI tests pass
This commit is contained in:
@@ -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; }
|
||||
|
||||
+111
-8
@@ -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
|
||||
|
||||
@@ -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}",
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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, []);
|
||||
});
|
||||
}
|
||||
@@ -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)), " ")
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user