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();