usage: a Zhipu pay-as-you-go key's balance card; SiliconFlow's says its query is gone

nam.haid on Discord: the Usage page showed no balance for a Zhipu key,
and SiliconFlow's card always said only "暂时无法获取额度".

Zhipu / Z.ai: nothing read a pay-as-you-go key's balance. BigModel has no
documented balance API; its console asks
/api/biz/account/query-customer-account-report with the key as a Bearer,
and it answered a real key (the owner's, 2026-11-03) the same at
open.bigmodel.cn, www.bigmodel.cn and api.z.ai:
{"code":200,...,"data":{"balance":0E-9,...,"availableBalance":0E-9,
"frozenBalance":0E-9,...},"success":true}; a bad key gets code 1000 at
HTTP 200. zhipuBalanceSource reads availableBalance at the key's own host
(¥ on bigmodel.cn, $ on api.z.ai). A refused key says so in the words the
Coding Plan card already uses (zhipuRefused), another code says its code
and msg, a reply without availableBalance is an error, never a balance. A
GLM Coding Plan key (a base under /api/coding/, or a key on the "coding"
plan) isn't asked: its plan windows are its card. A key seen only at the
shared /api/anthropic endpoint gets a card only once the account was ever
paid in. KeyBalances now skips a key whose own plan has no balance
source, so a mixed provider's Coding Plan key gets no stray card.

SiliconFlow: /v1/user/info answers 410 (code 20092) since 2026-08-14 and
its release notes list no replacement through 2026-10-21. The reason was
already read but shown as the generic line, with the last balance kept.
It is now a typed error (siliconFlowRetired): no kept balance, the card
says the API is gone in the user's language (en, zh, zh-TW, ja, de) and
its "Open the console" button opens cloud.siliconflow.cn (or .com).

Run at this head, rebased on origin/main bc10a6198: on mote, go test
./internal/provider (ok, full package), ./internal/tui (ok), the
budget tests in ./internal/gui (ok); ./internal/gui and ./internal/cli
are red only in TestMainWindowCorners (#3949) and
TestEveryRouteHasACommandOrIsNamed (#5026), the same on main. go vet:
GOOS=windows provider and gui, GOOS=linux provider (ok); gui for linux
needs cgo, not run. gofmt -l clean. GUI on mote at 9335e23d3: the 126
files matching balance|quota|usage|i18n|glm, 1819 of 1856; the reds are
the Usage page's (usage-agents-hide #3414, usage-fold #3415,
usage-ledger #5048), and in WSL the six of them plus
siliconflow-balance and i18n-keys, chromium and webkit, give 32 red at
this head and 35 at bc10a6198 itself, the same tests. siliconflow-balance
20 of 20 (en, zh, zh-TW, ja, de; 900 and 420 wide).

Broken by hand, each red then green: no Zhipu source (TestZhipuBalance,
TestZhipuAndSiliconFlowBalanceCards), no SiliconFlow SeeAt (the cards
test), no per-key plan check (the cards test), the never-paid-in rule
("anthropic, never paid in: <nil>"), the GUI mapping
(siliconflow-balance.test.cjs 0 of 20).

Not tried: a funded Zhipu account (only a never-paid-in one answered, so
the funded fixture is that reply with amounts filled in); a real
SiliconFlow key (the 410 shape is the one TestSiliconFlowRetiredBalanceQuery already held); the credit
line (creditBalance) isn't read; a provider whose own plan is the Coding
Plan with a pay-as-you-go key beside it still gets no balance for that
key. The account report is undocumented and may change.
This commit is contained in:
yetone
2026-11-03 16:26:17 +08:00
parent 694f4a6d65
commit b967b16208
6 changed files with 470 additions and 12 deletions
+1 -1
View File
@@ -38,7 +38,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| Accounts at once | `MaxAccounts *int` is the user's own count of keys or accounts taking requests at the same time: nil takes the plugin's (`PluginAtOnce`: `maxAccounts` on the plugin's auth hook or package.json `magpie`, host.js `atOnceOf`), 0 is no limit, saved clamped to 0..`MaxLimit`; a subscription's is kept with its picks (`withPicks`). `AtOnce()` answers the one in force, `SetAtOnce` sets it (`magpie provider at-once`, the editor's Accounts at once; GUI save leaves it as it was when the body has none). The gateway's use is in [gateway routing](gateway-routing.md) (`TestAtOnce`, `TestAtOnceSave`, `TestAtOnceCmd`). | [`concurrency.go`](../../internal/provider/concurrency.go) |
| A provider with no key | A provider of the user's own saves, imports and is `Ready` with no key when it is a preset with `NoKey` or its host is on this computer or the user's own network (`keyOptional`, `ownNetwork`): localhost, a loopback, private, link-local or carrier-grade NAT (Tailscale's 100.64/10) address, or a `.local` name, read from the URL alone with no lookup. A company's keyless relay at a LAN address is taken as a local server is (iSnow_999 on X: a Codex relay at http://<LAN IP>:8080 was left out of a CC Switch import as "it has no API key"); a keyless address on the internet still needs its key. With no key it is asked as one on 127.0.0.1 is: a Responses request carries no `Authorization`. | [`provider.go`](../../internal/provider/provider.go), [`importapps.go`](../../internal/provider/importapps.go), [`import_lan_test.go`](../../internal/provider/import_lan_test.go) |
| A key a provider | One vendor's keys saved a provider each — an app that keeps an entry a key, as CC Switch does, imported (yuluo_yx on X: "NVIDIA #001" to "#600" at one address, "Mistral #0001"…) — are folded into one provider with those keys (`FoldCopies` at start-up, `foldAdded` after `ImportFromApps`): hundreds of copies listed every model hundreds of times in every agent's picker and found group, and 3,000 made `/api/state` 86 MB. At start-up only copies by name are folded: a base name and that name with a number after it (`copyBase`: " #12", or `freeName`'s " 2"), one at least numbered; an import folds what it added whatever their names. Either way they must be alike in all but their key (`foldShape`: the provider with its id, name, keys and on/off left out), what the settings say of their models (`modelPrefs`) and where they are named (`foldRefs`: Visible, the agents' picked, hidden and ordered models, the groups, the providers falling back to them), so one key shown to one agent and another to another stays apart. Not folded: a subscription's, a hidden one, one without a key, Vertex, one with a StepFun sign-in of its own. The first on, in the providers' order, takes the rest in; its name becomes the base and its key is named its old name. Each other is a key in order, named its name, off if it was off (all off: the provider is off, its keys on); its id goes in `Was`, so its calls count with the provider by their key (`ProviderKeyID` is the key's fingerprint, unchanged) and a model picked by the old id still reaches it. Group members, rules, weights and fallbacks naming them name the provider once; their per-model settings and fetched lists go; balance and window history kept by their id moves to their key's name (`foldHistories`). A providers.json that doesn't parse is left alone. It runs at every start and writes nothing when there is nothing to fold. `TestFoldCopies`, `TestFoldCopiesIntoOneOn`, `TestFoldCopiesUnreadable`, `TestImportFoldsAKeyAnEntry`. | [`fold.go`](../../internal/provider/fold.go), [`importapps.go`](../../internal/provider/importapps.go), [`main.go`](../../internal/cli/main.go) |
| A key's plan | A vendor whose plans take keys of their own (`PresetDef.KeyPlans`: zhipu, zai, stepfun, stepfun-cn, xiaomi, baidu-qianfan, tencent-cloud, huaweicloud, volcengine, siliconflow) lets each key say which of the preset's Regions it is for (`KeyAccount.Plan`, `Provider.KeyPlan` for the first; yckonnnn on X: a Volcengine pay-as-you-go key and an Agent Plan key in one provider). No plan, or the provider's own, is the provider's plan, as every key was before, and is stored as none (`SetKeyPlan`, the GUI's `keys/plan`). `WithKey` moves a key's copy to its plan's endpoints (`atKeyPlan`: chat, Responses, Anthropic, decide, key page, docs and catalog; a provider at a host of its own, a mirror or a test's fake vendor, keeps that host) and marks it a key's view (`keyView`), so nothing judges plans on it again. Only when the keys in use are on more than one plan (`PlansMixed`) does anything differ: the model list is each key's plan's (`fetch` goes to `fetchPerKey`; a plan with no list of its own, `planOnly`, is its preset list without a request, so Ark's Coding and Agent Plans ask nothing while pay as you go asks `/api/v3/models` with its own key); plan media (`planMedia`) are every plan's; each key serves its plan's models alone (`PlanServing`, read by the gateway's `perKeyBarred`; a model set for the key in `AccountModels` it serves); plan windows (`PlanQuotas`), Volcengine's and Tencent Cloud's access-key windows (`planViews`) and balances (`balance.go`) are read at each key's plan. Volcengine's keys carry nothing that says their plan, so none is guessed; Xiaomi's `tp-`, Tencent's `sk-tp-`, MiniMax's `sk-cp-` and Bailian's `sk-sp-` prefixes are documented in code but not used to set a plan. The editor's key row has a plan chip (`planPicker`, the app's own menu) while the provider has several keys or the key has a plan. Not done: a gateway key held to some keys of a mixed provider's video (`videoAsker`) may pick another key's plan; a mixed provider whose own plan has no balance source while a key's plan has is not read; StepFun's plan windows are a sign-in per site, unchanged. `TestKeyPlanEndpoints`, `TestKeyPlanServing`, `TestKeyPlanOldConfigsUnchanged`, `TestSetKeyPlan`, `TestKeyPlanModelList`, `TestKeyPlanViews`, `key-plan.test.cjs`. | [`key_plans.go`](../../internal/provider/key_plans.go), [`keys.go`](../../internal/provider/keys.go), [`models.go`](../../internal/provider/models.go) |
| A key's plan | A vendor whose plans take keys of their own (`PresetDef.KeyPlans`: zhipu, zai, stepfun, stepfun-cn, xiaomi, baidu-qianfan, tencent-cloud, huaweicloud, volcengine, siliconflow) lets each key say which of the preset's Regions it is for (`KeyAccount.Plan`, `Provider.KeyPlan` for the first; yckonnnn on X: a Volcengine pay-as-you-go key and an Agent Plan key in one provider). No plan, or the provider's own, is the provider's plan, as every key was before, and is stored as none (`SetKeyPlan`, the GUI's `keys/plan`). `WithKey` moves a key's copy to its plan's endpoints (`atKeyPlan`: chat, Responses, Anthropic, decide, key page, docs and catalog; a provider at a host of its own, a mirror or a test's fake vendor, keeps that host) and marks it a key's view (`keyView`), so nothing judges plans on it again. Only when the keys in use are on more than one plan (`PlansMixed`) does anything differ: the model list is each key's plan's (`fetch` goes to `fetchPerKey`; a plan with no list of its own, `planOnly`, is its preset list without a request, so Ark's Coding and Agent Plans ask nothing while pay as you go asks `/api/v3/models` with its own key); plan media (`planMedia`) are every plan's; each key serves its plan's models alone (`PlanServing`, read by the gateway's `perKeyBarred`; a model set for the key in `AccountModels` it serves); plan windows (`PlanQuotas`), Volcengine's and Tencent Cloud's access-key windows (`planViews`) and balances (`balance.go`) are read at each key's plan. Volcengine's keys carry nothing that says their plan, so none is guessed; Xiaomi's `tp-`, Tencent's `sk-tp-`, MiniMax's `sk-cp-` and Bailian's `sk-sp-` prefixes are documented in code but not used to set a plan. The editor's key row has a plan chip (`planPicker`, the app's own menu) while the provider has several keys or the key has a plan. Not done: a gateway key held to some keys of a mixed provider's video (`videoAsker`) may pick another key's plan; a mixed provider whose own plan has no balance source while a key's plan has is not read (`KeyBalances` reads each key at its own plan, and a key whose plan has none, a GLM Coding Plan's, gets no balance card beside its plan windows; Zhipu/Z.ai pay-as-you-go keys read `/api/biz/account/query-customer-account-report`, undocumented, at their own host, and SiliconFlow's card says its query is gone with the console to open, `siliconFlowRetired`, nam.haid on Discord); StepFun's plan windows are a sign-in per site, unchanged. `TestKeyPlanEndpoints`, `TestKeyPlanServing`, `TestKeyPlanOldConfigsUnchanged`, `TestSetKeyPlan`, `TestKeyPlanModelList`, `TestKeyPlanViews`, `key-plan.test.cjs`. | [`key_plans.go`](../../internal/provider/key_plans.go), [`keys.go`](../../internal/provider/keys.go), [`models.go`](../../internal/provider/models.go) |
| Google Vertex AI | `google-vertex` (`VertexPreset`, `IsVertex`) is a provider of the user's own with no key. `Provider.Vertex` holds `project`, `location` (`global`, `us`, `eu` or a region; `global` when empty), `credentials` (a file; empty for Application Default Credentials) and `impersonate` (a service account's email). Save refuses a key given it, then normalizes them (`Normal`) and checks each (`check`); `normalize` clears the four URLs and any key put in `providers.json` by hand, which stands in for neither a token nor a project and leaves the provider as found savable, so the provider's one address is `vertexBase`, `https://<host>/v1/projects/<project>/locations/<location>`, its host following the location (`vertexHost`). It speaks chat completions, Anthropic's Messages API and Gemini (`Speaks`, `Base`), each model one of them (`ListedAPIs`, which `ModelAPI` can't change for it): a Gemini model on generateContent at that address, a partner model (`VertexPartner`: a `publisher/model` id, as every one models.dev lists for `google-vertex` has, such as `deepseek-ai/deepseek-v4.1-flash-maas`) on Google's OpenAI-compatible chat completions at `<address>/endpoints/openapi`, and Claude (`VertexClaude`: an id starting `claude-` with no publisher, `claude-opus-5-5` or Vertex's dated `claude-sonnet-4-5@20250929`) on the Messages API at that address, each request at its model's own path (`VertexClaudeRequest`: `/publishers/anthropic/models/<model>:streamRawPredict` or `:rawPredict`, `count-tokens:rawPredict` for a count, `anthropic_version` `vertex-2023-10-16` in the body), as Anthropic's Vertex SDK in Claude Code asks it. The preset lists the current Claude models at `global` under the ids Claude Code gives them for Vertex. The provider's test asks Gemini alone, since a partner model or Claude answers only after the project turns it on in Model Garden. Each such model has its own test (`TestModel`, `TestVertexPartnerModels`, `TestVertexClaudeModels`), and a test as Codex is refused as it is for Claude Code. It is `Ready` once that address can be made, never from a key or an account; until then the app, `magpie providers` and the TUI say it needs a project, and `magpie provider <id>` says how to give it one. `hasEndpoint` counts it as a provider of the user's own, not a subscription's picks. An import link naming it is refused (`ParseImport`): its project and credentials are the user's own, which no link hands over. `Sign` refuses any other address and sets the bearer token before the user's `Headers`; `AuthHeaders` gives it no key header. Its models are its location's (`vertexModels`, in `planModels`): the preset has `NoList`, because Vertex AI has no list that says what a location serves. The lists are in the [reference](../reference.md#google-vertex-ai). | [`vertex.go`](../../internal/provider/vertex.go), [`provider.go`](../../internal/provider/provider.go), [`account.go`](../../internal/provider/account.go), [`rename.go`](../../internal/provider/rename.go), [`models.go`](../../internal/provider/models.go), [`importurl.go`](../../internal/provider/importurl.go) |
| Vertex AI tokens | `vertexCredentialsFile` finds the credentials as Google's libraries find Application Default Credentials: the provider's `credentials`, else the file `GOOGLE_APPLICATION_CREDENTIALS` names, else `application_default_credentials.json` in gcloud's folder (`CLOUDSDK_CONFIG`, else `~/.config/gcloud`, `%APPDATA%\gcloud` on Windows); a `~/` that starts any of them is the home. `mint` reads three kinds: `authorized_user` (a refresh-token grant), `service_account` (an RS256 JWT, RFC 7523: `signed`) and gcloud's `impersonated_service_account`, whose `source_credentials` are minted and traded at IAM Credentials, along its `delegates`, for the account its `service_account_impersonation_url` names (`impersonationURL`: the token never goes to that URL's host). With `impersonate` set, the token those give is traded at IAM Credentials' `generateAccessToken` for a `cloud-platform` token of that account's, as gcloud's `--impersonate-service-account` does (`impersonateFor`); the credentials' account needs `roles/iam.serviceAccountTokenCreator` on it, which the 403 names. `vertexTokens` keeps one token per file and impersonated account, in memory only; requests made together mint it once, and those that waited through a mint that failed are given its error rather than each minting in turn (`mints`, `failed`). A mint cut short because its own request was given up on fails none of them: the next one mints. It is minted again within `vertexRefreshLead` (5 minutes) of expiry, or when the file's size or modification time has changed (gcloud signed in again). One mint, every exchange included, gets `vertexMintWait` (30 seconds). The file is only read. | [`vertex.go`](../../internal/provider/vertex.go), [`signin.go`](../../internal/provider/signin.go) |
| Amazon Bedrock Mantle | `bedrock-mantle` ("Amazon Bedrock (Mantle)", @marktoown on X) is a vendor preset beside the runtime's `bedrock`, with the same Bedrock API key and seventeen regions of its own (`mantleRegions`: the `bedrock-mantle.{region}.api.aws` hosts that answered on 2026-10-16). Chat completions and Responses are at `/v1`, Messages at `/anthropic`; unlike the runtime it lists its models (`GET /v1/models`; `NoList` stays the runtime's alone). Its OpenAI APIs serve each model under one of two prefixes: OpenAI's closed GPTs and xAI's Grok under `/openai/v1`, the rest under `/v1` (`MantleBase`, used by the gateway and the provider test's `tinyBody`). `IsBedrockMantle` is the preset or a provider added at a Mantle host (`mantleHost`), and `IsBedrock` includes it, so every Bedrock rule holds there too: Claude on Messages alone, the key as `x-api-key` alone, `max_completion_tokens`, no metadata, no Priority. A provider added at a Mantle address is given the APIs it wasn't (`mantleEndpoints`, in `normalize`), and a chat or Responses URL given at `/openai/v1` is moved to `/v1`, where the list is. | [`presets.go`](../../internal/provider/presets.go), [`provider.go`](../../internal/provider/provider.go), [`test.go`](../../internal/provider/test.go) |
+1
View File
@@ -13605,6 +13605,7 @@ function balanceError(err) {
if (/New-Api-User/i.test(err)) return t("Fill in your user ID (shown in the site's personal settings) under the provider's Account balance");
// errOpenCodeNoBalance: not a reading that failed
if (/^OpenCode tells no API key its balance/.test(err)) return t("OpenCode doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits");
if (/^SiliconFlow retired its balance query/.test(err)) return t("SiliconFlow no longer has a balance API — see the balance and vouchers on its console");
return "";
}
+4
View File
@@ -3233,6 +3233,7 @@ const I18N = {
"No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace": "这个 Key 没有 OpenCode Go — 请用订阅者本人在该工作区创建的 Key",
"OpenCode didn't take this key — paste a current one in the provider's settings": "OpenCode 不认这个 Key — 请在提供商设置里换一个有效的 Key",
"OpenCode doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits": "OpenCode 不会把余额告诉 API Key — 请在 OpenCode 控制台的 Overview → Credits 查看 Zen 的余额",
"SiliconFlow no longer has a balance API — see the balance and vouchers on its console": "硅基流动已停用余额查询 API — 请在其控制台查看余额和代金券",
"Open the console ↗": "打开控制台 ↗",
"{vendor} didn't take this key — it expired, was deleted or is mistyped; paste a current one in the provider's settings": "{vendor} 不认这个 Key — 它已过期、被删除或填错了;请在提供商设置里换一个有效的 Key",
"OpenCode Go answered in a form magpie doesn't read — hover for what it sent": "OpenCode Go 返回的格式 magpie 读不懂 — 悬停查看它返回了什么",
@@ -7740,6 +7741,7 @@ const I18N = {
"No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace": "這個 Key 沒有 OpenCode Go — 請用訂閱者本人在該工作區建立的 Key",
"OpenCode didn't take this key — paste a current one in the provider's settings": "OpenCode 不認這個 Key — 請在供應商設定裡換一個有效的 Key",
"OpenCode doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits": "OpenCode 不會把餘額告訴 API Key — 請在 OpenCode 主控台的 Overview → Credits 查看 Zen 的餘額",
"SiliconFlow no longer has a balance API — see the balance and vouchers on its console": "矽基流動已停用餘額查詢 API — 請在其主控台查看餘額和代金券",
"Open the console ↗": "開啟主控台 ↗",
"{vendor} didn't take this key — it expired, was deleted or is mistyped; paste a current one in the provider's settings": "{vendor} 不認這個 Key — 它已過期、被刪除或填錯了;請在供應商設定裡換一個有效的 Key",
"OpenCode Go answered in a form magpie doesn't read — hover for what it sent": "OpenCode Go 回傳的格式 magpie 讀不懂 — 懸停查看它回傳了什麼",
@@ -12251,6 +12253,7 @@ const I18N = {
"No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace": "このキーには OpenCode Go がありません — 契約したメンバー本人がそのワークスペースで作ったキーを使ってください",
"OpenCode didn't take this key — paste a current one in the provider's settings": "OpenCode がこのキーを受け付けませんでした — プロバイダ設定で有効なキーを貼り付けてください",
"OpenCode doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits": "OpenCode は API キーに残高を教えません — Zen のクレジットは OpenCode コンソールの Overview → Credits で確認してください",
"SiliconFlow no longer has a balance API — see the balance and vouchers on its console": "SiliconFlow は残高照会 API を廃止しました — 残高とクーポンはコンソールで確認してください",
"Open the console ↗": "コンソールを開く ↗",
"{vendor} didn't take this key — it expired, was deleted or is mistyped; paste a current one in the provider's settings": "{vendor} がこのキーを受け付けませんでした — 期限切れ、削除済み、または入力ミスです。プロバイダ設定で有効なキーを貼り付けてください",
"OpenCode Go answered in a form magpie doesn't read — hover for what it sent": "OpenCode Go の応答は magpie が読めない形式です — ホバーで内容を表示",
@@ -16773,6 +16776,7 @@ const I18N = {
"No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace": "Kein OpenCode Go auf diesem Schlüssel — nimm einen Schlüssel, den das abonnierende Mitglied in diesem Workspace erstellt hat",
"OpenCode didn't take this key — paste a current one in the provider's settings": "OpenCode hat diesen Schlüssel nicht angenommen — füge in den Anbieter-Einstellungen einen gültigen ein",
"OpenCode doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits": "OpenCode nennt einem API-Schlüssel sein Guthaben nicht — sieh Zens Guthaben in der OpenCode-Konsole unter Overview → Credits",
"SiliconFlow no longer has a balance API — see the balance and vouchers on its console": "SiliconFlow hat seine Guthaben-API eingestellt — Guthaben und Gutscheine stehen in seiner Konsole",
"Open the console ↗": "Konsole öffnen ↗",
"{vendor} didn't take this key — it expired, was deleted or is mistyped; paste a current one in the provider's settings": "{vendor} hat diesen Schlüssel nicht angenommen — er ist abgelaufen, gelöscht oder vertippt; füge in den Anbieter-Einstellungen einen gültigen ein",
"OpenCode Go answered in a form magpie doesn't read — hover for what it sent": "OpenCode Go hat in einer Form geantwortet, die magpie nicht liest — für den Inhalt darüberfahren",
@@ -0,0 +1,107 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// nam.haid on Discord: every SiliconFlow card said only "Allowance
// unavailable — hover for why". SiliconFlow retired its balance query on
// 2026-08-14 with nothing in its place, so the card says that, in the
// user's language, with the reason in its tooltip and a button that opens
// its console (seeAt). The editor's "Check balance" says the same
// (balanceError). A Zhipu key's balance card, read now, shows its amount.
// No backend, the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
// siliconFlowRetired's words (internal/provider/balance.go)
const GONE = "SiliconFlow retired its balance query (/v1/user/info) and has no API for it in its place yet; the balance and vouchers are on https://cloud.siliconflow.cn (余额充值 → 代金券)";
const CONSOLE = "https://cloud.siliconflow.cn";
const quotas = [
{ provider: "siliconflow", name: "SiliconFlow", icon: "siliconcloud-color", error: GONE, seeAt: CONSOLE, windows: [] },
{ provider: "zhipu", name: "Zhipu GLM", icon: "zhipu-color", balance: "¥12.50", windows: [] },
{ provider: "kimi", name: "Kimi", icon: "kimi-color", error: "HTTP 503", windows: [] },
];
function serve(lang, opened) {
const settings = { theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd" };
return async (route) => {
const req = route.request();
const url = new URL(req.url());
const json = (body) => route.fulfill({ json: body });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings });
if (url.pathname === "/api/settings") return json(settings);
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/usage/quotas") return json(quotas);
if (url.pathname === "/api/usage/quotas/history") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/open") {
opened.push(JSON.parse(req.postData() || "{}").url);
return route.fulfill({ status: 204, body: "" });
}
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const said = "SiliconFlow no longer has a balance API — see the balance and vouchers on its console";
const button = "Open the console ↗";
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const width of [900, 420]) {
test(`${engine} ${lang} ${width}px: a SiliconFlow key's card says its balance API is gone and opens the console; a Zhipu key shows its balance`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const errors = [];
const opened = [];
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
page.on("pageerror", (e) => errors.push(e.message));
await page.addInitScript(() => {
window.__opened = [];
window.open = (url) => { window.__opened.push(url); return null; };
});
await page.route("**/*", serve(lang, opened));
// app.js is large: its first load on a busy machine takes more than 5s
await page.goto("http://magpie.test/?view=usage", { timeout: 30000 });
const err = page.locator(".subscription-card", { hasText: "SiliconFlow" }).locator(".subscription-error");
await err.waitFor();
assert.equal(await err.getAttribute("title"), GONE, "the reason in the tooltip");
const [words, open, generic] = await page.evaluate(([a, b]) => [t(a), t(b), t("Allowance unavailable — hover for why")], [said, button]);
if (lang !== "en") {
assert.notEqual(words, said, `${lang} has its own words for the card`);
assert.notEqual(open, button, `${lang} has its own words for the button`);
}
assert.ok((await err.textContent()).includes(words), await err.textContent());
assert.ok(!(await err.textContent()).includes(generic));
const go = err.locator(".quota-fix");
assert.equal((await go.textContent()).trim(), open);
// a card that failed for another reason has no such button
assert.equal(await page.locator(".subscription-card", { hasText: "Kimi" }).locator(".quota-fix").count(), 0);
const glm = page.locator(".subscription-card", { hasText: "Zhipu GLM" });
assert.ok((await glm.textContent()).includes("12.50"), await glm.textContent());
assert.equal(await glm.locator(".subscription-error").count(), 0);
const [e, b] = [await err.boundingBox(), await go.boundingBox()];
assert.ok(e.x + e.width <= width && b.x + b.width <= width, "the error and its button fit the page");
await go.click();
// in a browser api("open") is window.open (the app posts /api/open)
await page.waitForFunction(() => window.__opened.length > 0);
assert.deepEqual(await page.evaluate(() => window.__opened), [CONSOLE]);
assert.deepEqual(opened, []);
assert.equal(new URL(page.url()).searchParams.get("view"), "usage", "the page stays where it was");
// the editor's Check balance says the same
assert.equal(await page.evaluate((z) => balanceError(z), GONE), words);
assert.deepEqual(errors, []);
});
}
}
}
+156 -11
View File
@@ -1,13 +1,16 @@
package provider
// What is left on an API key, as the vendor's own balance endpoint tells
// it: DeepSeek, Kimi, OpenRouter, SiliconFlow, StepFun, Command Code, Ollama Cloud and AiHubMix are known by their hosts
// (AiHubMix tells the whole account's to its access token, BalanceToken);
// it: DeepSeek, Kimi, OpenRouter, StepFun, Command Code, Ollama Cloud,
// AiHubMix and Zhipu/Z.ai pay-as-you-go keys are known by their hosts
// (AiHubMix tells the whole account's to its access token, BalanceToken;
// SiliconFlow's query is gone, siliconFlowRetired);
// any other provider can name an endpoint and where the amount sits in its
// reply (BalanceURL, BalancePath), the way a relay's own usage query does,
// with {key} where it wants the key in the URL (withBalanceKey).
import (
"bytes"
"context"
"encoding/json"
"errors"
@@ -52,6 +55,9 @@ func balanceSourceOf(p Provider) (balanceSource, bool) {
// instead of the key
return balanceSource{p.BalanceURL, func(b []byte) (string, error) { return readBalancePath(b, path) }, p.BalanceToken, nil, nil}, true
}
if src, ok := zhipuBalanceSource(p); ok {
return src, true
}
hosts := []string{hostOf(p.Chat), hostOf(p.Responses), hostOf(p.Anthropic)}
for _, h := range hosts {
switch h {
@@ -64,9 +70,9 @@ func balanceSourceOf(p Provider) (balanceSource, bool) {
case "openrouter.ai":
return balanceSource{"https://openrouter.ai/api/v1/credits", readOpenRouter, "", nil, nil}, true
case "api.siliconflow.cn":
return balanceSource{"https://api.siliconflow.cn/v1/user/info", readSiliconFlow("¥"), "", siliconFlowGone("https://cloud.siliconflow.cn (余额充值 → 代金券)"), nil}, true
return balanceSource{"https://api.siliconflow.cn/v1/user/info", readSiliconFlow("¥"), "", siliconFlowGone("https://cloud.siliconflow.cn", " (余额充值 → 代金券)"), nil}, true
case "api.siliconflow.com":
return balanceSource{"https://api.siliconflow.com/v1/user/info", readSiliconFlow("$"), "", siliconFlowGone("https://cloud.siliconflow.com"), nil}, true
return balanceSource{"https://api.siliconflow.com/v1/user/info", readSiliconFlow("$"), "", siliconFlowGone("https://cloud.siliconflow.com", ""), nil}, true
case "api.stepfun.com":
return balanceSource{"https://api.stepfun.com/v1/accounts", readStepFun("¥"), "", nil, nil}, true
case "api.stepfun.ai":
@@ -471,10 +477,13 @@ func readSiliconFlow(sign string) func([]byte) (string, error) {
// siliconFlowGone words SiliconFlow's answer to /v1/user/info since it
// retired the query on 2026-08-14 (410, {"code":20092,"message":"This
// endpoint is deprecated and is no longer available.","data":null}, #1094):
// it has no API for the balance in its place yet, and the balance given
// before 2025-12 is a voucher now, so both are read on the console. A key
// refused for itself (401 30014) is still said as it came.
func siliconFlowGone(console string) func(int, []byte) error {
// it has no API for the balance in its place yet (its release notes of
// 2026-08-11 promise an account-level one "in due course", and none is
// listed up to 2026-11), and the balance given before 2025-12 is a voucher
// now, so both are read on the console, where the card's button opens
// (siliconFlowRetired). A key refused for itself (401 30014) is still
// said as it came.
func siliconFlowGone(console, where string) func(int, []byte) error {
return func(status int, b []byte) error {
var r struct {
Code int `json:"code"`
@@ -483,10 +492,122 @@ func siliconFlowGone(console string) func(int, []byte) error {
if status != http.StatusGone && r.Code != 20092 {
return nil
}
return fmt.Errorf("SiliconFlow retired its balance query (/v1/user/info) and has no API for it in its place yet; the balance and vouchers are on %s", console)
return siliconFlowRetired{console, where}
}
}
// siliconFlowRetired is SiliconFlow's retired balance query: not a read
// that failed for now, so its card says where the balance is shown and
// opens that console (SeeAt), and keeps no balance read before the query
// went (nam.haid on Discord: every SiliconFlow card said only
// "Allowance unavailable").
type siliconFlowRetired struct{ console, where string }
func (e siliconFlowRetired) Error() string {
return "SiliconFlow retired its balance query (/v1/user/info) and has no API for it in its place yet; the balance and vouchers are on " + e.console + e.where
}
// zhipuBalanceSource is Zhipu's (BigModel's) and Z.ai's account report,
// /api/biz/account/query-customer-account-report on the API's own host,
// which their consoles read and which takes the API key as a Bearer: it
// is not in docs.bigmodel.cn, so a reply in another shape is said as
// unread, never as a balance. Asked with a GLM Coding Plan's endpoints it
// isn't: the plan's windows are that key's card (planQuotaSourceOf), and
// its cash balance, ¥0 for most, would be noise beside them. nam.haid on
// Discord: a Zhipu key had no card at all.
func zhipuBalanceSource(p Provider) (balanceSource, bool) {
host, payg := "", false
for _, base := range []string{p.Chat, p.Responses, p.Anthropic} {
h := hostOf(base)
if !zhipuHost(h) {
continue
}
if strings.Contains(base, "/api/coding/") {
return balanceSource{}, false
}
host = strings.ToLower(h)
payg = payg || basePath(strings.TrimRight(strings.TrimSpace(base), "/")) == zhipuPaygPath
}
if host == "" {
return balanceSource{}, false
}
sign := "¥"
if host == "api.z.ai" {
sign = "$"
}
u := "https://" + host + zhipuAccountReport
return balanceSource{u, readZhipuBalance(u, sign, payg), "", nil, nil}, true
}
// zhipuAccountReport is the account report's path on both hosts.
const zhipuAccountReport = "/api/biz/account/query-customer-account-report"
// readZhipuBalance reads the account report, as BigModel and Z.ai answer
// it to a key (asked 2026-11-03):
//
// {"code":200,"msg":"操作成功","data":{"balance":0E-9,"rechargeAmount":0.000000,
// "giveAmount":0.000000,"totalSpendAmount":0E-9,"todaySpendAmount":null,
// "availableBalance":0E-9,"frozenBalance":0E-9,"creditBalance":null,
// "availableCreditBalance":null,"creditStatus":"NOT_OPEN",…},"success":true}
//
// availableBalance being what is left to spend, the frozen part taken
// out. A refusal comes 200 too, in the platform's envelope ({"code":1000,
// "msg":"身份验证失败。","success":false}): a refused key is said as one
// (zhipuRefused), any other code with its words. Asked at only the
// Anthropic endpoint, which a Coding Plan's key shares, an account that
// was never paid or given anything has no card (errNoBalance); at the
// pay-as-you-go endpoint its ¥0.00 is the balance it has.
func readZhipuBalance(u, sign string, payg bool) func([]byte) (string, error) {
return func(b []byte) (string, error) {
if code, msg, ok := zhipuEnvelope(b); ok {
if ZhipuKeyRefused(code) {
return "", zhipuRefused(u, zhipuKeyRefusal{msg})
}
if msg == "" {
msg = "refused"
}
return "", fmt.Errorf("%s answered the balance read with code %d: %s", zhipuVendor(u), code, msg)
}
var r struct {
Data *struct {
Available any `json:"availableBalance"`
Balance any `json:"balance"`
Recharged any `json:"rechargeAmount"`
Given any `json:"giveAmount"`
} `json:"data"`
}
d := json.NewDecoder(bytes.NewReader(b))
d.UseNumber()
if err := d.Decode(&r); err != nil {
return "", err
}
if r.Data == nil {
return "", fmt.Errorf("%s's account report has no data in it", zhipuVendor(u))
}
v, ok := number(r.Data.Available)
if !ok {
return "", fmt.Errorf("%s's account report has no availableBalance in it", zhipuVendor(u))
}
if !payg {
bal, _ := number(r.Data.Balance)
paid, _ := number(r.Data.Recharged)
given, _ := number(r.Data.Given)
if v == 0 && bal == 0 && paid == 0 && given == 0 {
return "", errNoBalance
}
}
return money(sign, v), nil
}
}
// zhipuVendor names the vendor of a Zhipu or Z.ai URL.
func zhipuVendor(u string) string {
if hostOf(u) == "api.z.ai" {
return "Z.ai"
}
return "Zhipu"
}
// readStepFun: {"object":"account","type":"prepaid","balance":26.00,
// "total_cash_balance":0.00,"total_voucher_balance":26.00}, balance being
// what is left to spend, vouchers included, and the totals what was ever
@@ -1493,8 +1614,14 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota {
others++
}
}
// a key on a plan with no balance query of its own (a GLM Coding
// Plan's, whose windows are its card) has no balance card; a
// provider read some other way (ClinePass) keeps its card
keyCard := func(q Provider) bool { return !ok || hasBalanceSource(q) }
if others == 0 {
jobs = append(jobs, job{p, ""})
if keyCard(p.atKeyPlan(p.KeyPlan)) {
jobs = append(jobs, job{p, ""})
}
continue
}
first := p.KeyName
@@ -1503,13 +1630,18 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota {
}
// each key asked at its own plan's host (KeyAccount.Plan):
// SiliconFlow's China key and its international one
jobs = append(jobs, job{p.atKeyPlan(p.KeyPlan), first})
if q := p.atKeyPlan(p.KeyPlan); keyCard(q) {
jobs = append(jobs, job{q, first})
}
for _, k := range p.Keys {
if k.Off || k.Key == "" || k.Key == p.Key {
continue
}
q := p.atKeyPlan(k.Plan)
q.Key = k.Key
if !keyCard(q) {
continue
}
name := k.Name
if name == "" {
name = Mask(k.Key)
@@ -1553,6 +1685,13 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota {
out[i] = q
return
}
var gone siliconFlowRetired
if errors.As(err, &gone) {
// the same: a balance read before the query went is stale
q.Error, q.SeeAt = err.Error(), gone.console
out[i] = q
return
}
if err != nil {
q.Error = err.Error()
} else {
@@ -1598,6 +1737,12 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota {
return out
}
// hasBalanceSource says magpie knows where p's balance is asked.
func hasBalanceSource(p Provider) bool {
_, ok := balanceSourceOf(p)
return ok
}
// cardParts are the amounts a balance's card shows each apart, the
// percent a meter: several, or one asked as a percent; nil for one amount
// alone, the figure as it always was.
+201
View File
@@ -0,0 +1,201 @@
package provider
import (
"context"
"crypto/tls"
"errors"
"net"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/agentenv"
)
// zhipuReport is BigModel's account report as it answered a real key on
// 2026-11-03 (open.bigmodel.cn, www.bigmodel.cn and api.z.ai alike), the
// account never paid in.
const zhipuReport = `{"code":200,"msg":"操作成功","data":{"balance":0E-9,"rechargeAmount":0.000000,"giveAmount":0.000000,"totalSpendAmount":0E-9,"todaySpendAmount":null,"availableBalance":0E-9,"frozenBalance":0E-9,"creditBalance":null,"availableCreditBalance":null,"creditStatus":"NOT_OPEN","modelSpendAmountList":null,"isKA":false},"success":true}`
// zhipuReportFunded is the same reply of an account with money on it,
// some of it frozen.
const zhipuReportFunded = `{"code":200,"msg":"操作成功","data":{"balance":15.500000000,"rechargeAmount":20.000000,"giveAmount":0.000000,"totalSpendAmount":4.500000000,"todaySpendAmount":0.120000,"availableBalance":12.500000000,"frozenBalance":3.000000000,"creditBalance":null,"availableCreditBalance":null,"creditStatus":"NOT_OPEN","modelSpendAmountList":null,"isKA":false},"success":true}`
// zhipuReportRefused is its answer to a key it doesn't take, 200 too.
const zhipuReportRefused = `{"code":1000,"msg":"身份验证失败。","success":false}`
// fakeVendors sends every TLS request to srv, whatever host it names.
func fakeVendors(t *testing.T, srv *httptest.Server) {
t.Helper()
addr := srv.Listener.Addr().String()
old := http.DefaultClient.Transport
http.DefaultClient.Transport = &http.Transport{
DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
return (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, network, addr)
},
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
t.Cleanup(func() { http.DefaultClient.Transport = old })
}
// nam.haid on Discord: a Zhipu key had no balance card at all. A
// pay-as-you-go key's card reads the account report at its own host, in
// that host's currency, with the key as a Bearer; a refused key says so
// in the words the plan's card uses; a GLM Coding Plan's key isn't asked,
// and one asked at only the Anthropic endpoint that was never paid in has
// no card.
func TestZhipuBalance(t *testing.T) {
var mu sync.Mutex
body := zhipuReport
var asked []string
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
asked = append(asked, r.Host+r.URL.Path+" "+r.Header.Get("Authorization"))
b := body
mu.Unlock()
if r.URL.Path != zhipuAccountReport {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json;charset=UTF-8")
w.Write([]byte(b))
}))
t.Cleanup(srv.Close)
fakeVendors(t, srv)
set := func(b string) {
mu.Lock()
body, asked = b, nil
mu.Unlock()
}
zhipu := Provider{ID: "zhipu", Preset: "zhipu", Chat: "https://open.bigmodel.cn/api/paas/v4", Anthropic: "https://open.bigmodel.cn/api/anthropic", Key: "abc.def"}
zai := Provider{ID: "zai", Preset: "zai", Chat: "https://api.z.ai/api/paas/v4", Anthropic: "https://api.z.ai/api/anthropic", Key: "abc.def"}
for _, c := range []struct {
p Provider
body string
want string
}{
{zhipu, zhipuReport, "¥0.00"},
{zhipu, zhipuReportFunded, "¥12.50"},
{zai, zhipuReportFunded, "$12.50"},
} {
set(c.body)
got, ok, err := Balance(context.Background(), c.p)
if !ok || err != nil || got != c.want {
t.Errorf("%s: %q %v %v, want %q", c.p.ID, got, ok, err, c.want)
}
host := hostOf(c.p.Chat)
if want := host + zhipuAccountReport + " Bearer abc.def"; len(asked) != 1 || asked[0] != want {
t.Errorf("%s asked %q, want %q", c.p.ID, asked, want)
}
}
set(zhipuReportRefused)
for _, c := range []struct {
p Provider
vendor string
}{{zhipu, "Zhipu"}, {zai, "Z.ai"}} {
_, ok, err := Balance(context.Background(), c.p)
if !ok || err == nil || !strings.HasPrefix(err.Error(), c.vendor+" didn't take this key (身份验证失败。)") {
t.Errorf("%s refused: %v %v", c.p.ID, ok, err)
}
}
set(`{"code":500,"msg":"系统繁忙","success":false}`)
if _, _, err := Balance(context.Background(), zhipu); err == nil || !strings.Contains(err.Error(), "code 500: 系统繁忙") {
t.Errorf("other code: %v", err)
}
// a reply in another shape is unread, never a balance
set(`{"code":200,"msg":"操作成功","data":{"cash":1},"success":true}`)
if got, _, err := Balance(context.Background(), zhipu); err == nil || got != "" {
t.Errorf("no availableBalance: %q %v", got, err)
}
// a GLM Coding Plan's key: its windows are its card, nothing asked
set(zhipuReportFunded)
for _, coding := range []Provider{
{ID: "glm", Chat: "https://open.bigmodel.cn/api/coding/paas/v4", Anthropic: "https://open.bigmodel.cn/api/anthropic", Key: "k"},
{ID: "glm", Anthropic: "https://api.z.ai/api/coding/paas/v4", Key: "k"},
zhipu.atKeyPlan("coding"),
} {
if _, ok, err := Balance(context.Background(), coding); ok || err != nil {
t.Errorf("coding %s: %v %v", coding.Chat+coding.Anthropic, ok, err)
}
}
if len(asked) != 0 {
t.Errorf("coding plan asked %q", asked)
}
// at only the Anthropic endpoint, which a plan's key shares: an
// account never paid in has no card, one with money its balance
anth := Provider{ID: "glm", Anthropic: "https://open.bigmodel.cn/api/anthropic", Key: "k"}
set(zhipuReport)
if _, _, err := Balance(context.Background(), anth); !errors.Is(err, errNoBalance) {
t.Errorf("anthropic, never paid in: %v", err)
}
set(zhipuReportFunded)
if got, _, err := Balance(context.Background(), anth); err != nil || got != "¥12.50" {
t.Errorf("anthropic, funded: %q %v", got, err)
}
}
// The Usage page's cards: a Zhipu provider's pay-as-you-go key has its
// balance card and its Coding Plan key none; a SiliconFlow key, whose
// vendor retired its balance query, says so with its console to open
// (SeeAt) instead of a read that failed for now (nam.haid on Discord).
func TestZhipuAndSiliconFlowBalanceCards(t *testing.T) {
isolate(t)
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
t.Setenv("PATH", h)
for _, v := range agentenv.Vars {
t.Setenv(v, "")
}
keyBalanceCache.data = nil
t.Cleanup(func() { keyBalanceCache.data = nil })
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case r.URL.Path == zhipuAccountReport && r.Header.Get("Authorization") == "Bearer payg.key":
w.Write([]byte(zhipuReportFunded))
case r.URL.Path == zhipuAccountReport:
w.Write([]byte(zhipuReportRefused))
case r.URL.Path == "/v1/user/info":
w.WriteHeader(http.StatusGone)
w.Write([]byte(`{"code":20092,"message":"This endpoint is deprecated and is no longer available.","data":null}`))
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
fakeVendors(t, srv)
if err := Save(Provider{ID: "zhipu", Name: "Zhipu GLM", Preset: "zhipu", Chat: "https://open.bigmodel.cn/api/paas/v4", Anthropic: "https://open.bigmodel.cn/api/anthropic",
Key: "payg.key", KeyName: "payg", Keys: []KeyAccount{{Name: "plan", Key: "plan.key", Plan: "coding"}}}); err != nil {
t.Fatal(err)
}
if err := Save(Provider{ID: "siliconflow", Name: "SiliconFlow", Preset: "siliconflow", Chat: "https://api.siliconflow.cn/v1", Key: "sk-sf"}); err != nil {
t.Fatal(err)
}
var lines []string
var sf *SubscriptionQuota
for _, q := range KeyBalances(context.Background()) {
lines = append(lines, q.Provider+"|"+q.User+"|"+q.Balance)
if q.Provider == "siliconflow" {
sf = &q
}
}
if got, want := strings.Join(lines, ","), "zhipu|payg|¥12.50,siliconflow||"; got != want {
t.Errorf("cards:\n%s\nwant\n%s", got, want)
}
if sf == nil || sf.SeeAt != "https://cloud.siliconflow.cn" || !strings.HasPrefix(sf.Error, "SiliconFlow retired its balance query") {
t.Errorf("SiliconFlow's card: %+v", sf)
}
}