From 6af38c0eebccc1a23a7c4e3a9fbfb36c855198f1 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 19 Nov 2026 15:35:46 +0800 Subject: [PATCH] providers: a resting key's row says what its vendor answered (@YsiCing on X) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit @YsiCing on X ("用 oai api 经常遇到额度不足情况,实际账号额度还是有很多的") showed one API key's row in the provider editor (sk-s…igYA, any protocol, all models): "暂停使用 · 400 余额不足 · 13:37 恢复 · 立即重试", posted at 13:12, so a first-rung creditRest of 30 minutes. Nothing on the row said what the vendor answered, and the screenshot names no provider, agent or error text. Cause of the missing words: 82b45888a gave every Rest the vendor's words (Rest.Error), and 63dc359fb showed them on a subscription account's row (accountRests passes Error and By), but the key rows of an API-key provider are filled in providerJSON from gateway.RestOf with Why/Status/Until/Key/Probed/Rate only, so restLineOf's .key-rest-said was never drawn for a key. A key's row now carries Error and By as an account's does. Not changed, and why: failure() reads a 400 as out of credit when its words match creditWords (balance, credit, billing, payment, 余额, 充值 …), which is right for Anthropic's 400 "credit balance is too low", DashScope's 400 Arrearage and SuperMagic's 400 积分不足 (#4095). The screenshot has no vendor words, so which 400 this relay sent, and whether creditWords read it wrongly, is unknown; changing the classifier on a guess would break those. It is not a rate limit called out of credit: a 429 shows as 429, and OpenAI's 429 rate_limit_exceeded (minuteRate) and insufficient_quota (credit) are already told apart. With the words now on the row, the reporter's next refusal says what the vendor answered. Tests: - TestKeyRestSaysVendorWords (new, internal/gui): a fake upstream answers both keys of an API-key provider 400 with an OpenAI-shaped credit error through a real gateway.New() (both keys are asked); the key it rests carries the words in /api/providers' KeyList. The last key left isn't rested on a 400 (quotaStatus is 429/402 only, ff930886a), so the test asks for at least one. Red on origin/main's providers.go (Error ""), green after. - TestKeysImportAndRest: its stubbed key rest carries Error and By, and checks they reach the row. Red on the old providers.go. - key-import.test.cjs: a new case, "a resting key says what its vendor answered", draws .key-rest-said with the words on the resting key only. A case of its own: the taller row moved "Paste several" into #6416's scroll red. Run on WSL magpie-desktop, at origin/main 7f11dfc77 plus this change and again after the rebase onto 344253c4e (vet, internal/gui ok in 83.7s, key-import the same 12/16 and 6/8) (wsl-run; mote was at load 24-31 with two full suites, and mica's disk had 157MB free, so its full run failed to build: no space left): - gofmt -l internal/gui: clean. go vet -tags nogui ./internal/gui and GOOS=windows go vet ./internal/gui: ok. - go test -tags nogui -count=1 ./internal/gui: ok (117.6s). - go test -tags nogui -count=1 ./internal/gateway ./internal/provider: ok (982s, 117s), at the same base before the test-only edits. - key-import.test.cjs, Chromium and WebKit, en and zh: 12/16 and 6/8 pass; the new case passes in all four. The reds are "Paste several takes many keys at once" in every engine and language, red the same with this commit's fixture left out. That is #6416 (now seen in WebKit and on Linux too; noted there). - Red by hand: origin/main's providers.go with these tests, TestKeyRestSaysVendorWords and TestKeysImportAndRest fail (Error "", By ""). Not run: the full go test ./... (no machine had room) and the whole GUI suite (the change is in providers.go's JSON; app.js is unchanged). Not tried with the reporter's relay, whose 400 text the screenshot doesn't show. --- internal/gui/keys_import_test.go | 68 +++++++++++++++++++++++++- internal/gui/providers.go | 7 ++- internal/gui/tests/key-import.test.cjs | 23 ++++++--- 3 files changed, 88 insertions(+), 10 deletions(-) diff --git a/internal/gui/keys_import_test.go b/internal/gui/keys_import_test.go index f04e2685c..a3c89d43b 100644 --- a/internal/gui/keys_import_test.go +++ b/internal/gui/keys_import_test.go @@ -2,6 +2,7 @@ package gui import ( "encoding/json" + "io" "net/http" "net/http/httptest" "path/filepath" @@ -26,10 +27,13 @@ func TestKeysImportAndRest(t *testing.T) { t.Fatal(err) } until := time.Now().Add(10 * time.Minute) + // the vendor's words go with the rest, for the row to show beside + // "400 · out of credit" (@YsiCing on X: the row said only that) + said := "Your credit balance is too low to access the API" was := keyRestOf keyRestOf = func(key string) (gateway.Rest, bool) { if key == p.ID+"#"+provider.KeyID("two") { - return gateway.Rest{Why: "rate", Status: 429, Until: until}, true + return gateway.Rest{Why: "credit", Status: 400, Until: until, By: "credit", Error: said}, true } return gateway.Rest{}, false } @@ -62,7 +66,7 @@ func TestKeysImportAndRest(t *testing.T) { t.Fatalf("key %d rest %+v", i, k.Rest) } } - if r := info.KeyList[1].Rest; r.Status != 429 || r.Why != "rate" || !r.Until.Equal(until) { + if r := info.KeyList[1].Rest; r.Status != 400 || r.Why != "credit" || !r.Until.Equal(until) || r.Error != said || r.By != "credit" { t.Fatalf("rest %+v", r) } for _, k := range []string{`"first"`, `"two"`, `"three"`, `"four"`} { @@ -77,3 +81,63 @@ func TestKeysImportAndRest(t *testing.T) { t.Fatalf("%d %s", w.Code, w.Body) } } + +// @YsiCing on X: a key the gateway rested showed "暂停使用 · 400 余额不足 · +// 13:37 恢复" and nothing of what its vendor answered, where an account's +// row shows it. A real refusal, from a fake upstream through the gateway, +// reaches the key's row in /api/providers with the vendor's words. +func TestKeyRestSaysVendorWords(t *testing.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")) + const said = "Your credit balance is too low to access the API. Please go to Plans & Billing to upgrade or purchase credits." + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + io.WriteString(w, `{"error":{"message":"`+said+`","type":"invalid_request_error","code":null}}`) + })) + defer up.Close() + p := provider.Provider{ID: "keyrest-words", Name: "Relay", Chat: up.URL + "/v1", Models: []string{"m1"}, Key: "k-one", Keys: []provider.KeyAccount{{Key: "k-two"}}} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + gw := gateway.New() + prev := served.Swap(gw) + t.Cleanup(func() { served.Store(prev) }) + rec := httptest.NewRecorder() + gw.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"keyrest-words/m1","messages":[{"role":"user","content":"hi"}]}`))) + if rec.Code != http.StatusBadRequest { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + mux := http.NewServeMux() + providerRoutes(mux, nil) + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/providers", nil)) + var st providersJSON + if err := json.Unmarshal(w.Body.Bytes(), &st); err != nil { + t.Fatal(err) + } + rested := 0 + for _, pj := range st.Providers { + if pj.ID != p.ID { + continue + } + for _, k := range pj.KeyList { + if k.Rest == nil { + continue + } + rested++ + if k.Rest.Status != 400 || k.Rest.Why != "credit" || !strings.Contains(k.Rest.Error, said) { + t.Fatalf("key %s rest %+v, want its vendor's words", k.Masked, k.Rest) + } + } + } + // the first key rests; the last one left is rested only on a 429 or + // 402 (quotaStatus), so a 400 leaves it be + if rested == 0 { + t.Fatalf("no key rested: %s", w.Body) + } +} diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 5bc9789b0..544fe008b 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -1085,7 +1085,10 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs if out.KeyList == nil { out.KeyList = []provider.KeyInfo{} } - // a key the gateway passes over after a failure says so on its row + // a key the gateway passes over after a failure says so on its row, + // with the vendor's words, as an account's row does (accountRests): + // without them a key's "400 · out of credit" said nothing of what its + // vendor answered (@YsiCing on X) restKey := p.RestKeys() for i, k := range out.KeyList { if !k.On { @@ -1093,7 +1096,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs } key := restKey(k) if r, ok := keyRestOf(key); ok { - out.KeyList[i].Rest = &provider.KeyRest{Why: r.Why, Status: r.Status, Until: r.Until, Key: key, Probed: r.Probed, Rate: r.Rate} + out.KeyList[i].Rest = &provider.KeyRest{Why: r.Why, Status: r.Status, Until: r.Until, Key: key, Probed: r.Probed, By: r.By, Error: r.Error, Rate: r.Rate} } } // and one with a spend cap, what it has spent of it (the gateway diff --git a/internal/gui/tests/key-import.test.cjs b/internal/gui/tests/key-import.test.cjs index ff8a1a9d8..7607e30cc 100644 --- a/internal/gui/tests/key-import.test.cjs +++ b/internal/gui/tests/key-import.test.cjs @@ -17,18 +17,18 @@ const { chromium, webkit } = require("playwright"); const assets = path.resolve(__dirname, "../assets"); const until = new Date(Date.now() + 10 * 60e3).toISOString(); -const relay = () => ({ +const relay = (said) => ({ id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "", models: [{ id: "big", name: "", on: true }], agents: [], fallback: [], headers: {}, key: { set: true, masked: "sk-…one" }, balanceToken: { takes: false, set: false }, proxy: "", keyList: [ { id: "aaaaaaaaaa", name: "", masked: "sk-…one", on: true, active: true }, - { id: "bbbbbbbbbb", name: "", masked: "sk-…two", on: true, rest: { why: "rate", status: 429, until, key: "relay#bbbbbbbbbb" } }, + { id: "bbbbbbbbbb", name: "", masked: "sk-…two", on: true, rest: { why: "rate", status: 429, until, key: "relay#bbbbbbbbbb", ...(said ? { error: said } : {}) } }, ], }); -function serve(lang, posts, adds = []) { - const p = relay(); +function serve(lang, posts, adds = [], said) { + const p = relay(said); const providers = { providers: [p], presets: [], excluded: [], gateway: { running: true, window: true } }; const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; return async (route) => { @@ -69,7 +69,7 @@ const words = { for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { for (const lang of ["en", "zh"]) { const w = words[lang]; - const open = async (t, name, adds) => { + const open = async (t, name, adds, said) => { const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); t.after(async () => { if (process.env.ARTIFACT_DIR) { @@ -85,7 +85,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); const posts = []; - await page.route("**/*", serve(lang, posts, adds)); + await page.route("**/*", serve(lang, posts, adds, said)); await page.goto("http://magpie.test/?view=providers"); await page.locator(".row.provider", { hasText: "Relay" }).first().click(); await page.locator(".editor .accts .acc.add").waitFor(); @@ -127,6 +127,17 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual(errors, []); }); + // @YsiCing on X: a key rested "400 · out of credit" said nothing of what + // its vendor answered; the row says it, as an account's does + test(`${engine} ${lang}: a resting key says what its vendor answered`, async (t) => { + const said = "Rate limit reached for gpt-x on requests per min (RPM)"; + const { page, errors } = await open(t, "said", [], said); + assert.match(await page.locator('.acc[data-account-id="bbbbbbbbbb"] .key-rest').textContent(), w.rest); + assert.equal(await page.locator('.acc[data-account-id="bbbbbbbbbb"] .key-rest-said').textContent(), said); + assert.equal(await page.locator('.acc[data-account-id="aaaaaaaaaa"] .key-rest-said').count(), 0); + assert.deepEqual(errors, []); + }); + test(`${engine} ${lang}: several keys pasted into the key field open the box with them`, async (t) => { const { page, errors } = await open(t, "paste"); await page.getByRole("button", { name: w.another }).click();