provider: a GLM key read before keeps its card when a read of it fails (larchsis on X)

larchsis (X, Windows 11): two GLM Coding Plan keys, and only one usage
card shows; after a restart both show at first, and the automatic refresh
takes the second away again, with a manual refresh not bringing it back.

Cause: a provider with several keys is never moved to the Coding Plan URL
(LearnZhipuCoding moves only a one-key provider), so its keys are read
with sure=false, where any failed read meant "no plan" and dropped the
card unless keepLast had a kept reading. keepLast keeps one only for a
passing failure, and Zhipu's /api/monitor answers its rate limits (1302
"并发数过高", 1303, ... 1399) with HTTP 200 in its envelope and Chinese
words that `passing` doesn't match. So when both keys were read at once
and one was limited, its card went until a read happened to pass.

Fix:
- readZhipuPlan says an envelope rate limit (zhipuCodeStatus 429, not
  1113 out of credit) as "429 rate limited (code): msg", so keepLast
  serves the last good reading.
- PlanQuotas' !sure branch keeps the card of a key that has a kept good
  reading (hadReading in quota_last.go), with its error when nothing can
  be served. A failed read of a key read before is unknown, not "no
  plan". A key never read that fails still has no card. This also covers
  the other sure=false sources (MiniMax, Command Code, Ollama).

Test: TestZhipuSecondKeyKeepsItsCard (two keys, first read; second key
1302 after a restart keeps its kept windows; a 500 envelope keeps the
card with its error; a never-read pay-as-you-go key gets no card).
Broken by hand on mote: without `|| known` red at line 106; without the
envelope 429 red at line 99; both restored green.

Run (mote, at c5caef7bf on 3eb5aa2ad): gofmt -l clean; go vet ./...,
GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... all ok;
go test -timeout 45m ./...: 79 packages ok, internal/gui red only in its
real-window AppKit tests killed at their deadlines (TestDockJoinLeads-
CommandTab, TestPanelCloseHidesIt, TestMainWindowCorners and 7 more),
open as #4125, #2645, #3178, #1936; nothing in internal/gui is touched.
After the rebase onto f1d5bedba: go test ./internal/provider/ on mote.

Not tried: a real Zhipu account with two keys (none here); Zhipu's real
rate-limit reply on /api/monitor is inferred from its 13xx codes, not
seen; no run on the Windows box (no OS-specific code); no GUI run
(app.js unchanged).
This commit is contained in:
yetone
2026-10-31 07:26:46 +08:00
parent f1d5bedba6
commit a6951cc63a
3 changed files with 150 additions and 2 deletions
+15 -2
View File
@@ -104,6 +104,13 @@ func readZhipuPlan(b []byte) (string, []QuotaWindow, error) {
if code, msg, ok := zhipuEnvelope(b); ok && ZhipuKeyRefused(code) {
// the key itself refused, which no plan can be read past
return "", nil, zhipuKeyRefusal{msg}
} else if ok && code != 1113 && zhipuCodeStatus(code) == http.StatusTooManyRequests {
// /api/monitor answers its rate limits 200 in the envelope too
// (1302 "并发数过高", 1303 "频率过高", …), in Chinese words a
// passing failure isn't recognised by: said as the 429 it is, so
// the card keeps what was last read (keepLast) instead of losing
// it to a read that told nothing about the plan
return "", nil, fmt.Errorf("429 rate limited (%d): %s", code, msg)
}
if r.Success != nil && !*r.Success || r.Data == nil {
if r.Msg != "" {
@@ -782,9 +789,15 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota {
case err == nil && len(ws) == 0:
return // a key with no plan
case err != nil && !j.src.sure:
// no plan, unless one was read before
// no plan, unless one was read before: a key whose windows
// were read is a plan's, and a read of it that fails is
// unknown, not "no plan" — its card stays, with what was
// last read when the failure passes, else with why
// (larchsis on X: the second of two GLM Coding Plan keys
// lost its card on each refresh)
q.Error = err.Error()
if q = keepReading(ctx, q, tag); q.AsOf != nil {
known := hadReading(q.Provider, tag)
if q = keepReading(ctx, q, tag); q.AsOf != nil || known {
got[i] = &q
}
return
+15
View File
@@ -120,6 +120,21 @@ func keepLast(q SubscriptionQuota, user string) SubscriptionQuota {
return out
}
// hadReading is whether a good reading of provider's account (or key
// tag) user is kept: the account or key was read with windows or a
// balance before.
func hadReading(provider, user string) bool {
if provider == "" || user == "" {
return false
}
c := &lastQuotas
c.Lock()
defer c.Unlock()
c.load()
_, ok := c.m[provider+"/"+strings.ToLower(user)]
return ok
}
// readDeferred is whether err says no read was made this time (allowances
// read only when asked, a Claude account's /usage not run) rather than a
// read that failed. A read held back by holdUnasked fails inside the
+120
View File
@@ -0,0 +1,120 @@
package provider
import (
"context"
"net/http"
"net/http/httptest"
"path/filepath"
"sync/atomic"
"testing"
"github.com/yetone/magpie/internal/agentenv"
)
// larchsis on X: two GLM Coding Plan keys in one provider, and only one
// card on the Usage page; after a restart both showed at first, and the
// automatic refresh took the second away again. Zhipu's /api/monitor
// answers a rate limit 200 in the platform's envelope, in Chinese
// ("并发数过高"), which wasn't taken for a passing failure, and a key on a
// provider whose OpenAI URL is still pay as you go (one with several keys
// is never moved to the plan's, LearnZhipuCoding) lost its card to any
// failed read. A key read before is a plan's: a read that fails keeps its
// card, as last read when the failure passes, else with why.
func TestZhipuSecondKeyKeepsItsCard(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, "")
}
restart := func() {
lastQuotas.Lock()
lastQuotas.m, lastQuotas.loaded = nil, false
lastQuotas.Unlock()
forgetPlanQuotas()
}
restart()
t.Cleanup(restart)
// what the second key's quota read answers: "" its plan
var second atomic.Value
second.Store("")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.Header.Get("X-Host")+r.URL.Path != "open.bigmodel.cn/api/monitor/usage/quota/limit" {
w.WriteHeader(http.StatusNotFound) // the term and resets: not known
return
}
if r.URL.RawQuery != "" { // a team's: none
w.Write([]byte(`{"code":500,"msg":"no team","success":false}`))
return
}
if said := second.Load().(string); said != "" && r.Header.Get("Authorization") == "glm-b.secondkey" {
w.Write([]byte(said))
return
}
w.Write([]byte(`{"code":200,"msg":"操作成功","success":true,"data":{"level":"pro","limits":[
{"type":"TOKENS_LIMIT","unit":3,"number":5,"percentage":12,"nextResetTime":4102444800000},
{"type":"TOKENS_LIMIT","unit":6,"number":1,"percentage":40,"nextResetTime":4102444800000}]}}`))
}))
defer srv.Close()
old := http.DefaultClient.Transport
http.DefaultClient.Transport = rewrite{srv}
t.Cleanup(func() { http.DefaultClient.Transport = old })
if err := Save(Provider{ID: "zhipu", Name: "Zhipu GLM", Preset: "zhipu", Key: "glm-a.firstkey", KeyName: "one",
Keys: []KeyAccount{{Name: "two", Key: "glm-b.secondkey"}},
Chat: "https://open.bigmodel.cn/api/paas/v4", Anthropic: "https://open.bigmodel.cn/api/anthropic"}); err != nil {
t.Fatal(err)
}
read := func() map[string]SubscriptionQuota {
forgetPlanQuotas()
out := map[string]SubscriptionQuota{}
for _, q := range PlanQuotas(context.Background()) {
out[q.User] = q
}
return out
}
cards := read()
for _, u := range []string{"one", "two"} {
if q := cards[u]; len(q.Windows) != 2 || q.Error != "" || q.AsOf != nil {
t.Fatalf("first read, key %s: %+v", u, q)
}
}
// rate limited, as the envelope says it
second.Store(`{"code":1302,"msg":"您当前使用该API的并发数过高,请降低并发,或联系客服增加限额。","success":false}`)
lastQuotas.Lock()
lastQuotas.m, lastQuotas.loaded = nil, false // from disk, as after a restart
lastQuotas.Unlock()
cards = read()
if q := cards["one"]; len(q.Windows) != 2 || q.AsOf != nil {
t.Fatalf("first key while the second is limited: %+v", q)
}
if q, ok := cards["two"]; !ok || len(q.Windows) != 2 || q.Error != "" || q.AsOf == nil || q.Windows[1].Used != 40 {
t.Fatalf("second key rate limited: kept card wanted, got %v %+v", ok, q)
}
// a failure that says nothing known: the card stays, saying why
second.Store(`{"code":500,"msg":"系统繁忙","success":false}`)
cards = read()
if q, ok := cards["two"]; !ok || q.Error == "" {
t.Fatalf("second key failing: a card with its error wanted, got %v %+v", ok, q)
}
// a key never read that fails still has no card: nothing says it's a plan's
if err := Save(Provider{ID: "zhipu-payg", Name: "Pay as you go", Preset: "zhipu", Key: "glm-b.secondkey",
Chat: "https://open.bigmodel.cn/api/paas/v4"}); err != nil {
t.Fatal(err)
}
forgetPlanQuotas()
for _, q := range PlanQuotas(context.Background()) {
if q.Provider == "zhipu-payg" {
t.Fatalf("a key never read has a card: %+v", q)
}
}
}