From 74d1cda421a2bda7f78a0887be288f142c0447fc Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 6 Nov 2026 04:09:30 +0800 Subject: [PATCH] gateway: a rate limit with a bracketed reset time rests the model until then, and says rate limited MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit taoxiaoxin on Discord (v0.1.2992, WorkBuddy China, plugin 0.2.24): deepseek-v4.1-flash got 429 {"error":{"code":null,"message":"WorkBuddy: 您的使用量已超出频率限制,将在 2026-11-06 17:13:04 (UTC+8) 重置,您也可以切换其他模型继续使用。", "param":null,"type":"rate_limit_error"}} with credits left, and Routing showed the account as 额度用尽. Cause: WorkBuddy now writes the offset in brackets, "(UTC+8)". resetsWhen read "UTC+8" only bare, so the reset time went unread, the refusal fell to plannedWords (用量) as failQuota with no time, and the whole account rested a quarter of an hour as quota used up. With the time read, the existing path (resetsWhen + otherModels) rests only that model on that account until 17:13. - resetsWhen takes an optional ASCII or fullwidth bracket round the offset (zh and en forms); a body cut inside or after the bracket, before 重置, still reads no time. - Rest.Rate (and provider.KeyRest.Rate): a refusal read as out of quota until a named time whose words say rate/frequency limit. Routing is unchanged (it rests as the quota it is until then); the Providers row, Routing's stage row, its Accounts line and the account tallies (live and the day's, history.go) say "rate limited" (限流, 限流, レート制限, Rate-Limit; strings already translated) with "back at {time}". - workbuddy-ai gets the same: one path, tested for both ids. The plugin (opencode-workbuddy-auth) already reads the bracketed time; no plugin version or mover min. Run (mote, at this tree): - go test ./internal/gateway -run 'TestDayTallies|TestResetsWritten| TestWrittenReset|TestBracketedReset|TestMonthlyWritten| TestRateLimitBelieves': ok - go test ./internal/gui ./internal/provider: provider ok; gui red only in TestMainWindowCorners/macOS_26_SDK, #3949 (macOS 27, untouched) - go vet (darwin) gateway, gui, provider; GOOS=linux and GOOS=windows go vet gateway, provider: ok; gofmt -l clean - node --test account-rate-rest (new; chromium + webkit, en zh zh-TW ja de, 1100 and 420px): 10/10 - GUI routing-*, account-*, i18n*, key-rest*, rate-limited-* (194 files, 3127 tests): 3086 pass, 41 red. Rerun at concurrency 2 here and at origin/main 8fbf8e0af: the same 9 files red on both, each filed: i18n-keys (#5332), routing-intent-entry (#5392), routing-rule-drag (#3789), routing-rule-remove (#3096, #4585), routing-row-swap (#3799), routing-steady (#3412, #1804), routing-steps-cap (#4628), routing-story-shrinks (#3954), routing-order-unknown (#4627). account-weight, routing-levels, rule-models, rules-line passed on the rerun. - TestCoreScriptBudget: app.js under 1,533,802 without a raise Broken by hand: - old resetsWhen: TestResetsWritten's bracket cases and TestBracketedResetRestsTheModelRateLimited red ("rests 14m59.99s by quota (quota), want 5h13m0s by resets": the whole account, 15 min) - Rate forced false: "a frequency limit not marked a rate limit" - history.go's count off: TestDayTalliesCountARateLimitAsOne red ("tallied map[quota:3]") - app.js and routing client.js at HEAD: account-rate-rest 10/10 red Not tried: a real WorkBuddy account answering this 429 (the body is the reporter's literal one); the live app. --- internal/gateway/history.go | 3 + internal/gateway/history_tallies_test.go | 21 ++++ internal/gateway/routing.go | 22 +++- internal/gateway/written_reset_test.go | 72 +++++++++++ internal/gui/assets/app.js | 6 +- internal/gui/assets/plugins/routing/client.js | 34 ++--- internal/gui/providers.go | 4 +- internal/gui/tests/account-rate-rest.test.cjs | 118 ++++++++++++++++++ internal/provider/keys.go | 3 + 9 files changed, 262 insertions(+), 21 deletions(-) create mode 100644 internal/gui/tests/account-rate-rest.test.cjs diff --git a/internal/gateway/history.go b/internal/gateway/history.go index b5f71c479..aa53bbdf1 100644 --- a/internal/gateway/history.go +++ b/internal/gateway/history.go @@ -678,6 +678,9 @@ func foldTally(tallies map[string]*Tally, line []byte) { if f == "" { f = "other" } + if f == failQuota && tr.Rest != nil && tr.Rest.Rate { + f = failRate // counted as the vendor called it + } if a.Fails == nil { a.Fails = map[string]int{} } diff --git a/internal/gateway/history_tallies_test.go b/internal/gateway/history_tallies_test.go index fafa1d13d..0c07bafa9 100644 --- a/internal/gateway/history_tallies_test.go +++ b/internal/gateway/history_tallies_test.go @@ -123,3 +123,24 @@ func TestDayTalliesSayWhenSignInWasRefused(t *testing.T) { t.Errorf("after an answer: refused at %d, answered at %d", a.AuthAt, a.Last) } } + +// A refusal the vendor called a rate limit until a time it named is +// counted as one in the day's tally (taoxiaoxin on Discord: WorkBuddy's +// "您的使用量已超出频率限制,将在 … (UTC+8) 重置" was tallied "额度用尽"); a +// quota used up stays one. +func TestDayTalliesCountARateLimitAsOne(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + now := historyNoon(t) + route := func(i int, rest *Rest) Route { + w := Weighed{ID: "workbuddy@b", Provider: "workbuddy", Name: "WorkBuddy", Kind: "account", Who: "b@example.com", Model: "deepseek-v4.1-flash"} + tr := Try{ID: w.ID, Start: now.Add(time.Duration(i) * time.Minute), Done: true, Millis: 100, Status: 429, Fail: failQuota, Rest: rest} + return Route{ID: int64(i + 1), Time: tr.Start, Done: true, Model: w.Model, Provider: "workbuddy", Order: []Weighed{w}, Tries: []Try{tr}} + } + saveRoute(route(0, &Rest{Why: failQuota, By: "resets", Rate: true, Model: "deepseek-v4.1-flash"})) + saveRoute(route(1, &Rest{Why: failQuota, By: "resets", Model: "deepseek-v4.1-flash"})) + saveRoute(route(2, nil)) + a := DayTallies()[`["workbuddy","b@example.com"]`] + if a.Fails[failRate] != 1 || a.Fails[failQuota] != 2 { + t.Errorf("tallied %v, want 1 rate and 2 quota", a.Fails) + } +} diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index fea72b715..73fb59550 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -388,8 +388,11 @@ var ( // there (重置, or a comma or full stop), so a refusal cut short after // "UTC", "UTC+" or Ark's "+0800" isn't read as UTC: another vendor's // date in passing ("deprecated on …"), or one with no offset, is not a - // reset time. - resetsWhen = regexp.MustCompile(`(?i)(?:\bresets? at|将在|将于)\s*(\d{4})-(\d{1,2})-(\d{1,2})[ T](\d{1,2}):(\d{2}):(\d{2})\s*(?:(?:UTC|GMT)([+-])(\d{1,2})(?::?(\d{2}))?|([+-])(\d{2})(\d{2}) (?-i:[A-Z]{2,5}))(?:\s*(?:重置|[,.;,。;]))`) + // reset time. The offset may sit in brackets, as WorkBuddy's China + // build writes it since November (taoxiaoxin on Discord: "将在 + // 2026-11-06 17:13:04 (UTC+8) 重置"): unread, the refusal rested the + // whole account a quarter of an hour as out of quota. + resetsWhen = regexp.MustCompile(`(?i)(?:\bresets? at|将在|将于)\s*(\d{4})-(\d{1,2})-(\d{1,2})[ T](\d{1,2}):(\d{2}):(\d{2})\s*[((]?\s*(?:(?:UTC|GMT)([+-])(\d{1,2})(?::?(\d{2}))?|([+-])(\d{2})(\d{2}) (?-i:[A-Z]{2,5}))\s*[))]?(?:\s*(?:重置|[,.;,。;]))`) // monthlyWords: a refusal that says the allowance it used up is a // month's, as Ark's does ("You have exceeded the monthly usage quota") // and Zhipu's 1310 ("Weekly/Monthly Limit Exhausted"): the reset time @@ -759,6 +762,12 @@ type Rest struct { // (GanHei37443 on X: three WorkBuddy accounts each "failed · back in // 16s", and nothing on the row said why) Error string `json:"error,omitempty"` + // Rate: the vendor called it a rate (frequency) limit and named when + // it lifts (rateUntilSaid). It rests as out of quota until then, and + // the app says rate limited, not quota used up: WorkBuddy's "您的使用 + // 量已超出频率限制,将在 … 重置,您也可以切换其他模型继续使用" rests + // one model of an account with credits left (taoxiaoxin on Discord) + Rate bool `json:"rate,omitempty"` // the subscription account resting, when it is one; agent "" and its // provider.KeyAllowanceID for a key out of its own windows @@ -1650,6 +1659,7 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo if id == c.restID() { r.Model = c.model } + r.Rate = rateUntilSaid(why, r.By, body) r.Probed = probeable(c, r, header, now) && !probeMissed(id, now) restingUntil.Lock() if why == failQuota || why == failCredit { @@ -1700,6 +1710,14 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo return r } +// rateUntilSaid says a refusal read as out of quota until the time it +// names (by "resets") calls itself a rate or frequency limit (rateWords, +// words in a link apart): the app words its rest as rate limited, with +// that time. How long it rests, and what it rests, are a quota's. +func rateUntilSaid(why, by string, body []byte) bool { + return why == failQuota && by == "resets" && rateWords.Match(urlWords.ReplaceAll(wordsOf(body), nil)) +} + // vendorOverloaded says a failure is the vendor's servers too busy for // the request — a 529 (Anthropic's overloaded_error, the ChatGPT backend's // server_is_overloaded), or a 5xx whose words say overloaded (Gemini's diff --git a/internal/gateway/written_reset_test.go b/internal/gateway/written_reset_test.go index 6a1aa77af..d044c15b5 100644 --- a/internal/gateway/written_reset_test.go +++ b/internal/gateway/written_reset_test.go @@ -33,6 +33,15 @@ const ( }` ) +// wbTao is WorkBuddy's China build's refusal of deepseek-v4.1-flash as +// taoxiaoxin's agent got it (magpie v0.1.2992, plugin 0.2.24, Discord +// 11-06), its offset in brackets: the account had credits left, and the +// Routing page read it as quota used up. +const ( + wbTaoSaid = "WorkBuddy: 您的使用量已超出频率限制,将在 2026-11-06 17:13:04 (UTC+8) 重置,您也可以切换其他模型继续使用。" + wbTao = `{"error":{"code":null,"message":"` + wbTaoSaid + `","param":null,"type":"rate_limit_error"}}` +) + // arkAt is Ark's monthly refusal (arkCNife), saying it resets at t. func arkAt(t time.Time) string { return strings.Replace(arkCNife, "2026-10-25 23:59:59", t.In(time.FixedZone("", 8*3600)).Format("2006-01-02 15:04:05"), 1) @@ -120,6 +129,14 @@ func TestResetsWritten(t *testing.T) { {"ark's form, not monthly, 9 days off", strings.Replace(arkWyx, "monthly ", "", 1), at("2026-10-22 12:00:00"), 0}, {"en 9 days off", wbEn, at("2026-10-02 12:00:00"), 0}, {"retry after, Ark's form", "Too many requests, retry after 2026-10-11 12:37:53 +0800 CST.", at("2026-10-11 10:00:00"), 0}, + // WorkBuddy's China build since November, its offset in brackets, + // as taoxiaoxin's agent was given it on Discord + {"zh (UTC+8)", wbTao, at("2026-11-06 12:00:00"), 5*time.Hour + 13*time.Minute + 4*time.Second}, + {"zh (UTC+8) escaped", escaped(wbTaoSaid, "null"), at("2026-11-06 12:00:00"), 5*time.Hour + 13*time.Minute + 4*time.Second}, + {"zh (UTC+8)", strings.Replace(wbTao, "(UTC+8)", "(UTC+8)", 1), at("2026-11-06 12:00:00"), 5*time.Hour + 13*time.Minute + 4*time.Second}, + {"zh (UTC+8) cut in the brackets", wbTao[:strings.Index(wbTao, "+8)")], at("2026-11-06 12:00:00"), 0}, + {"zh (UTC+8) cut after them", wbTao[:strings.Index(wbTao, " 重置")], at("2026-11-06 12:00:00"), 0}, + {"en (UTC+8)", strings.Replace(wbEn, "UTC+8,", "(UTC+8),", 1), at("2026-10-11 10:00:00"), 2*time.Hour + 37*time.Minute + 53*time.Second}, } { if got := resetsWritten([]byte(c.body), c.now); got != c.want { t.Errorf("%s: %v, want %v (%q)", c.name, got, c.want, c.body) @@ -453,3 +470,58 @@ func TestRateLimitedModelListedUnderAccount(t *testing.T) { t.Fatalf("the provider's accounts: %v", seen) } } + +// WorkBuddy's refusal with its offset in brackets (taoxiaoxin on Discord: +// "将在 2026-11-06 17:13:04 (UTC+8) 重置") rests the model it refused on +// that account alone until the time it names, as the bare offset's did, +// and says it is a rate limit, so the page doesn't read the account's +// credits as gone. Unread, it rested the whole account a quarter of an +// hour as quota used up. A quota's refusal that names its reset (Ark's +// month) still reads as a quota. +func TestBracketedResetRestsTheModelRateLimited(t *testing.T) { + old := allowances + defer func() { allowances = old }() + allowances = func(string) map[string]provider.Allowance { return nil } + s := &Server{} + near := func(d, want time.Duration) bool { return d > want-time.Minute && d <= want } + back := 5*time.Hour + 13*time.Minute + until := time.Now().Add(back).In(time.FixedZone("", 8*3600)).Format("2006-01-02 15:04:05") + for _, site := range []string{"workbuddy", "workbuddy-ai"} { + for name, body := range map[string]string{ + "as said": strings.Replace(wbTao, "2026-11-06 17:13:04", until, 1), + "escaped": escaped(strings.Replace(wbTaoSaid, "2026-11-06 17:13:04", until, 1), "null"), + "en": strings.Replace(wbAt("en", time.Now().Add(back)), "UTC+8,", "(UTC+8),", 1), + } { + user := site + "-" + strings.ReplaceAll(name, " ", "-") + "@x.com" + c := candidate{p: provider.Provider{ID: site, Account: &provider.Account{Agent: site, User: user}}, model: "deepseek-v4.1-flash", rest: site + "#" + user} + other := c + other.model = "glm-5.1" + clearRest(c.restKey()) + clearRest(c.restID()) + if f := failure(429, []byte(body)); f != failQuota { + t.Fatalf("%s %s: read as %s", site, name, f) + } + r := s.restAfter(c, 429, http.Header{}, []byte(body)) + if r.By != "resets" || !near(time.Until(r.Until), back) { + t.Fatalf("%s %s: rests %v by %s (%s), want %v by resets", site, name, time.Until(r.Until), r.By, r.Why, back) + } + if r.Key != c.restID() || r.Model != c.model { + t.Fatalf("%s %s: rests %s (model %q), not the model alone", site, name, r.Key, r.Model) + } + if !resting(c) || resting(other) { + t.Fatalf("%s %s: the model rests %v, another of the account %v", site, name, resting(c), resting(other)) + } + if !r.Rate { + t.Fatalf("%s %s: a frequency limit not marked a rate limit", site, name) + } + clearRest(c.restID()) + } + } + // a month's quota names its reset too, and stays a quota + k := candidate{p: provider.Provider{ID: "ark-plan"}, model: "m", rest: "ark-plan#k"} + clearRest(k.restKey()) + if r := s.restAfter(k, 429, http.Header{}, []byte(arkAt(time.Now().Add(3*24*time.Hour)))); r.By != "resets" || r.Rate { + t.Fatalf("Ark's month: by %s, rate %v", r.By, r.Rate) + } + clearRest(k.restKey()) +} diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 41ca338e4..26a182d6b 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -14862,7 +14862,7 @@ function keyMatches(k, q) { if (!words.length) return true; const resting = k.rest && new Date(k.rest.until) > Date.now(); const text = [k.name, k.masked, k.on ? "" : "off " + t("turned off"), - resting ? "resting " + t("resting") + " " + (KEY_FAIL[k.rest.why] || "failed") + " " + t(KEY_FAIL[k.rest.why] || "failed") + " " + (k.rest.status || "") : ""].join(" ").toLowerCase(); + resting ? "resting " + t("resting") + " " + keyFail(k.rest) + " " + t(keyFail(k.rest)) + " " + (k.rest.status || "") : ""].join(" ").toLowerCase(); return words.every((w) => text.includes(w)); } // keyDead: a key the gateway is passing over for good reason, not a rate @@ -14950,7 +14950,7 @@ function splitKeys(text) { } // a rest's line: why, till when, the vendor's words, Try now (#1869) function restLineOf(r, model, title, name, lifted) { - const why = (r.status ? r.status + " " : "") + t(KEY_FAIL[r.why] || "failed"), time = restBack(r.until); + const why = (r.status ? r.status + " " : "") + t(keyFail(r)), time = restBack(r.until); const s = el("span", "key-rest", (model ? t("{model} resting · {why} · back at {time}", { model, why, time }) : t("Resting · {why} · back at {time}", { why, time })) + (r.probed ? " · " + t("checked in the background, back as soon as it answers") : "")); s.title = title; const go = el("button", "text key-unrest", t("Try now")); @@ -14979,6 +14979,8 @@ const accountRestLines = (p, user) => { // a key's rest, worded as the Routing page words a failure const KEY_FAIL = { rate: "rate limited", credit: "out of credit", quota: "quota used up", other: "failed", auth: "sign-in required", verify: "needs verification", refused: "refused (safety filter)", proxy: "proxy not reachable", slow: "slow to start" }; +// Rest.Rate: the vendor called it a rate limit +const keyFail = (r) => r.why === "quota" && r.rate ? KEY_FAIL.rate : KEY_FAIL[r.why] || "failed"; // protoPicker: which protocol a key works with. Some relays hand out one // key for Anthropic and another for OpenAI; a key set to one is used on diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index a0d7e6198..1baa6378a 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -566,11 +566,15 @@ function routingPage(part) { : (w.limit > 0 ? quotaCount(w) + " · " : "") + t(quotaLeft ? left : used, { n: pct(share(w)), ...vars }); const fill = (w) => Math.max(0, Math.min(100, share(w))) + "%"; const FAIL = { rate: "rate limited", credit: "out of credit", quota: "quota used up", other: "failed", auth: "sign-in required", canceled: "canceled", foreign: "another account's reasoning", floor: "reply too short", verify: "needs verification", refused: "refused (safety filter)", shape: "request not understood", sight: "images not taken", proxy: "proxy not reachable", offline: "network down", overloaded: "servers overloaded", effort: "reasoning effort not in its plan", overflow: "too long for its model", room: "reply asked past the window left", slow: "slow to start", prompt: "agent's prompt turned away", restricted: "account restricted by the vendor" }; - const failWord = (why) => t(FAIL[why] || "failed"); + // a refusal the vendor called a rate limit, resting as out of quota + // until the time it named (Rest.Rate), says rate limited: WorkBuddy's + // per-model "频率限制" read as the account's quota used up, its credits + // left (taoxiaoxin on Discord) + const failWord = (why, rest) => t(why === "quota" && rest?.rate ? FAIL.rate : FAIL[why] || "failed"); // a resting row: a failure that names no kind says the status it // answered, and the vendor's own words are over it (restTip), as // "failed · back in 16s" alone said nothing of why (GanHei37443 on X) - const restSay = (rest) => `${!FAIL[rest.why] || rest.why === "other" ? (rest.status ? rest.status + " · " : "") : ""}${failWord(rest.why)} · ${restWhen(rest)}`; + const restSay = (rest) => `${!FAIL[rest.why] || rest.why === "other" ? (rest.status ? rest.status + " · " : "") : ""}${failWord(rest.why, rest)} · ${restWhen(rest)}`; const restTip = (rest) => (typeof rest.error === "string" && rest.error) || ""; // a try that answered: one whose reply broke off after it began (its 200 // sent, then the vendor's error, #733) didn't, and has a fail @@ -999,7 +1003,7 @@ function routingPage(part) { continue; } if (x.sunk && !x.rest) out.push(t("{who} was rate limited at {time} while it had quota left, so it went to the back: it comes round again once those ahead of it are rate limited in turn.", { who: who(x), time: clock(x.sunk) })); - else if (x.rest) out.push(t("{who} is resting — {why}, {when} — so it waits at the back.", { who: who(x), why: `${x.rest.status} · ${failWord(x.rest.why)}`, when: restWhen(x.rest, at(r.time)) })); + else if (x.rest) out.push(t("{who} is resting — {why}, {when} — so it waits at the back.", { who: who(x), why: `${x.rest.status} · ${failWord(x.rest.why, x.rest)}`, when: restWhen(x.rest, at(r.time)) })); else if (smart(x) && x.known && group(x) === "spent" && x.credits) out.push(t("{who} is at {n} of its allowance but goes on on its credits — ahead of those used up with nothing to go on with, after those with allowance left.", { who: who(x), n: pct(x.used) })); else if (smart(x) && x.known && group(x) === "spent" && weighedWith(r, x).length > 1) out.push(t("{who} is at {n} — all but used up, it answers only when nothing else can.", { who: who(x), n: pct(x.used) })); else if (smart(x) && x.known && group(x) === "low" && weighedWith(r, x).length > 1) out.push(t("{who} is at {n} — kept for when the others can't.", { who: who(x), n: pct(x.used) })); @@ -1412,7 +1416,7 @@ function routingPage(part) { if (tr.status < 400 && tr.fail) return tr.rest ? t("{who} began answering, then broke off · {fail}. {agent} got what was said before the error; {how}, so {agent}'s next request goes to another first.", - { who: name, fail: failWord(tr.fail), how: restHow(tr.rest, at(tr.start) + (tr.ms || 0)), agent }) + { who: name, fail: failWord(tr.fail, tr.rest), how: restHow(tr.rest, at(tr.start) + (tr.ms || 0)), agent }) : t("{who} began answering, then broke off. {agent} got what was said before the error; the conversation isn't kept on {who} for its next request.", { who: name, agent }); if (tr.status < 400) { const tk = (r.tokens ? " · " + t("{n} tokens", { n: tokens(r.tokens) }) : "") + firstNote(r, tr); @@ -1479,17 +1483,17 @@ function routingPage(part) { // story ends there, not on a retry that never came if (tr.gone) return t("{who} answered {status} · {fail}, and was to be asked again in {d}, but {agent} canceled the request before then, so nobody is asked again.", - { who: name, status: tr.status, fail: failWord(tr.fail), d: took(tr.again), agent }); + { who: name, status: tr.status, fail: failWord(tr.fail, tr.rest), d: took(tr.again), agent }); if (tr.replan) return t("{who} answered {status} · {fail}, and every member had failed with an error that may pass, so after {d} the {n} of them are asked again, in turn, before any of the reply reaches {agent}. The group waits up to {p} for one to answer.", - { who: name, status: tr.status, fail: failWord(tr.fail), d: took(tr.again), n: tr.replan, p: took((tr.patience || 0) * 1000), agent }); + { who: name, status: tr.status, fail: failWord(tr.fail, tr.rest), d: took(tr.again), n: tr.replan, p: took((tr.patience || 0) * 1000), agent }); // kept on it for its cache, so asked once more before it moves (jiabubu) if (tr.again && tr.kept) return t("{who} answered {status} · {fail}, a failure that may pass. The conversation is kept on {who} for what its vendor cached of it, so it is asked once more in {d} before the request moves to another.", - { who: name, status: tr.status, fail: failWord(tr.fail), d: took(tr.again) }); + { who: name, status: tr.status, fail: failWord(tr.fail, tr.rest), d: took(tr.again) }); if (tr.again) return t("{who} answered {status} · {fail}, and nobody else is left to ask — a failure that may pass, so it is tried again in {d}, before any of the reply reaches {agent}.", - { who: name, status: tr.status, fail: failWord(tr.fail), d: took(tr.again), agent }); + { who: name, status: tr.status, fail: failWord(tr.fail, tr.rest), d: took(tr.again), agent }); // the last one left out of its allowance, after another failed // otherwise: the agent was told that one's error (Try.Earlier) if (tr.earlier && !next) @@ -1500,12 +1504,12 @@ function routingPage(part) { if (next) return tr.rest ? t("{who} answered {status} · {fail}. {how}; the request goes on to {next} before any of the reply reaches {agent}.", - { who: name, status: tr.status, fail: failWord(tr.fail), how, next: nw ? who(nw) : t("the next"), agent }) + { who: name, status: tr.status, fail: failWord(tr.fail, tr.rest), how, next: nw ? who(nw) : t("the next"), agent }) : t("{who} answered {status}, and the request goes on to {next} before any of the reply reaches {agent}. {who} doesn't rest for it.", { who: name, status: tr.status, next: nw ? who(nw) : t("the next"), agent }); if (tr.rest) return t("{who} answered {status} · {fail}. {how}; nobody is left to try, so {agent} gets the error.", - { who: name, status: tr.status, fail: failWord(tr.fail), how, agent }); + { who: name, status: tr.status, fail: failWord(tr.fail, tr.rest), how, agent }); // the gateway stopped here with accounts left in the order: one it // would not go on from (the same history refused on every account of // a vendor, with no other vendor left) @@ -2759,8 +2763,8 @@ function routingPage(part) { named = titleOf(trying.get(id)); } else if (answered.has(id)) { s = (agents.size > 1 ? t("answered {agent}", { agent: agentName(r.agent) }) : t("answered this request")) + (said && " · " + said); named = titleOf(r); } - else if (gave.has(id)) s = t("{status} · {fail} · passed to {agent}", { status: gave.get(id).status, fail: failWord(gave.get(id).fail), agent: agentName(r.agent) }); - else if (went.has(id)) s = t("{status} · {fail} · went on to the next", { status: went.get(id).status, fail: failWord(went.get(id).fail) }); + else if (gave.has(id)) s = t("{status} · {fail} · passed to {agent}", { status: gave.get(id).status, fail: failWord(gave.get(id).fail, gave.get(id).rest), agent: agentName(r.agent) }); + else if (went.has(id)) s = t("{status} · {fail} · went on to the next", { status: went.get(id).status, fail: failWord(went.get(id).fail, went.get(id).rest) }); else if (w.noURL) s = noURLWord(w); else if (w.reserve) s = t("in reserve · {n} at once", { n: w.reserve }); else if (w.sunk && !lifted(sunkKey(w), at(w.sunk))) s = t("rate limited at {time} · at the back", { time: clock(w.sunk) }); @@ -3527,7 +3531,7 @@ function routingPage(part) { // last one's place, the route says that one's kind (fail): an // earlier 529 overload read "529 · quota used up" beside the last // account's usage limit (danzi002 on Discord) - const endWord = (r, last) => `${r.status} · ${failWord(last.gone ? "canceled" : r.fail || last.fail)}`; + const endWord = (r, last) => `${r.status} · ${failWord(last.gone ? "canceled" : r.fail || last.fail, (!r.fail || r.fail === last.fail) && last.rest)}`; // what a request not yet out at a vendor is doing: being masked // (Settings → Privacy, the gateway's "redact" phase), or being routed @@ -4442,7 +4446,7 @@ function routingPage(part) { } else { a.tried++; if (tryOk(tr)) { a.ok++; a.last = Math.max(a.last, end); const m = tr.model || r.order.find((x) => x.id === tr.id)?.model; if (m) a.models.add(m); } - else a.fails[tr.fail || "other"] = (a.fails[tr.fail || "other"] || 0) + 1; + else { const k = tr.fail === "quota" && tr.rest?.rate ? "rate" : tr.fail || "other"; a.fails[k] = (a.fails[k] || 0) + 1; } } const rm = tr.rest ? restModel(tr.rest, tr.model || r.order.find((x) => x.id === tr.id)?.model) : ""; if (rm) modelRest(a, rm, tr.rest, end); @@ -4908,7 +4912,7 @@ function routingPage(part) { // of its 1.8s (yuancjun on Discord). A failure again on the row // starts the 1.8s over rerun(row.li, "hit", "rthit"); row.li.classList.add("tagged", "lift"); - row.tg.textContent = `${tr.status} · ${failWord(tr.fail)}`; + row.tg.textContent = `${tr.status} · ${failWord(tr.fail, tr.rest)}`; clearTimeout(tagFor.get(row.li)); tagFor.set(row.li, setTimeout(() => { row.li.classList.remove("tagged"); diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 2a0419234..4d5068eef 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -812,7 +812,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} + out.KeyList[i].Rest = &provider.KeyRest{Why: r.Why, Status: r.Status, Until: r.Until, Key: key, Probed: r.Probed, Rate: r.Rate} } } // and one with a spend cap, what it has spent of it (the gateway @@ -1096,7 +1096,7 @@ func accountRests(id string) map[string][]provider.KeyRest { if out == nil { out = map[string][]provider.KeyRest{} } - out[user] = append(out[user], provider.KeyRest{Why: r.Why, Status: r.Status, Until: r.Until, Key: r.Key, Probed: r.Probed, By: r.By, Model: cmp.Or(r.Model, model), Error: r.Error}) + out[user] = append(out[user], provider.KeyRest{Why: r.Why, Status: r.Status, Until: r.Until, Key: r.Key, Probed: r.Probed, By: r.By, Model: cmp.Or(r.Model, model), Error: r.Error, Rate: r.Rate}) } return out } diff --git a/internal/gui/tests/account-rate-rest.test.cjs b/internal/gui/tests/account-rate-rest.test.cjs new file mode 100644 index 000000000..81dc57e2b --- /dev/null +++ b/internal/gui/tests/account-rate-rest.test.cjs @@ -0,0 +1,118 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A model the vendor rate-limits until a time it names says "rate limited", +// not "quota used up" (taoxiaoxin on Discord: WorkBuddy answered +// deepseek-v4.1-flash 429 "您的使用量已超出频率限制,将在 2026-11-06 17:13:04 +// (UTC+8) 重置,您也可以切换其他模型继续使用。" with credits left, and +// Routing called the account's quota used up). The gateway marks such a rest +// Rate; the Providers row, Routing's stage row and its Accounts line all say +// rate limited, with the time it is back. In every language, at a wide and a +// narrow window, in Chromium and WebKit. +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 SAID = "WorkBuddy: 您的使用量已超出频率限制,将在 2026-11-06 17:13:04 (UTC+8) 重置,您也可以切换其他模型继续使用。"; +const USER = "me@x.test", MODEL = "deepseek-v4.1-flash"; +const now = new Date(); +const until = new Date(now.getTime() + 5 * 3600e3).toISOString(); +const rest = { why: "quota", status: 429, rate: true, until, by: "resets", key: `workbuddy@${USER}/${MODEL}`, model: MODEL, error: SAID }; + +const provider = { + id: "workbuddy", name: "WorkBuddy", icon: "", chat: "", responses: "", anthropic: "", catalog: "", + models: [{ id: MODEL, name: "DeepSeek-V4.1-Flash", on: true }, { id: "glm-5.1", name: "GLM-5.1", on: true }], + agents: [], fallback: [], headers: {}, keyList: [], proxy: "", + account: { agent: "workbuddy", agentName: "WorkBuddy", user: USER, plan: "", logins: [{ user: USER, active: true, on: true }] }, + accountRests: { [USER]: [rest] }, +}; + +function routes() { + const seat = (model, extra = {}) => ({ id: "workbuddy@" + USER, provider: "workbuddy", name: "WorkBuddy", kind: "account", icon: "", who: USER, model, known: true, ...extra }); + const order = [seat(MODEL, { rest }), seat("glm-5.1")]; + const time = new Date(now.getTime() - 60e3).toISOString(); + const tries = [ + { id: order[0].id, model: MODEL, start: time, done: true, status: 429, ms: 300, fail: "quota", rest, error: SAID }, + { id: order[1].id, model: "glm-5.1", start: time, done: true, status: 200, ms: 900 }, + ]; + return [{ id: 1, seq: 1, time, agent: "codex", model: "group/g", provider: "workbuddy", order, tries, done: true, status: 200, ms: 2000 }]; +} + +function serve(lang) { + const settings = { theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd" }; + 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:"${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: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings }); + if (url.pathname === "/api/settings") return json(settings); + if (url.pathname === "/api/providers") return json({ providers: [provider], presets: [], excluded: [], gateway: { running: true, window: true }, + plugins: [{ id: "workbuddy", pid: "workbuddy", name: "WorkBuddy", icon: "", spec: "@magpie-community/opencode-workbuddy-auth" }] }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.has("wait")) return; + return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 1, rerouted: 1, errors: 0 }, routes: routes() }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + 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).catch(() => ""), contentType }); + }; +} + +const sideways = (page) => page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth + 1); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + test(`${engine} ${lang}: a model rate-limited until a named time says rate limited, not quota used up`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const width of [1100, 420]) { + const page = await (await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + + // Providers: the account's row + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: "WorkBuddy" }).first().click(); + const acc = page.locator(`.editor .accts .acc[data-account-id="${USER}"]`); + await acc.waitFor(); + const tr = (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]); + const rate = await tr("rate limited"), quota = await tr("quota used up"); + assert.notEqual(rate, quota); + const back = await page.evaluate((u) => restBack(u), until); + const line = acc.locator(".key-rest-line .key-rest"); + assert.equal(await line.textContent(), await tr("{model} resting · {why} · back at {time}", { model: MODEL, why: "429 " + rate, time: back }), `${width}px providers`); + assert(!(await acc.textContent()).includes(quota), `${width}px: the account's row says ${quota}`); + assert(!(await sideways(page)), `${width}px: Providers scrolls sideways`); + + // Routing: the stage row and the Accounts line + await page.goto("http://magpie.test/?view=routing"); + await page.locator(".rt-act").first().waitFor(); + const row = page.locator("li", { has: page.locator("code.mdl", { hasText: new RegExp(`^${MODEL.replace(/\./g, "\\.")}$`) }) }).filter({ has: page.locator(".who", { hasText: USER }) }); + await row.first().evaluate((e) => new Promise((done) => { const ok = () => e.classList.contains("rest") ? done() : requestAnimationFrame(ok); setTimeout(done, 5000); ok(); })); + assert(await row.first().evaluate((e) => e.classList.contains("rest")), `${width}px: the stage row doesn't rest`); + const said = (await row.first().locator("em").textContent()).trim(); + assert(said.includes(rate), `${width}px: the stage row says ${said}`); + const part = page.locator(".rt-act", { hasText: USER }).locator(".st.rest.part"); + assert.equal(await part.count(), 1); + const text = await part.textContent(); + assert(text.startsWith(MODEL + " · ") && text.includes(rate), `${width}px: the Accounts line says ${text}`); + // the account's tally counts the refusal as the vendor called it + assert((await page.locator(".rt-act", { hasText: USER }).locator(".tally .bad").textContent()).includes("1 " + rate), `${width}px: the tally doesn't count it as ${rate}`); + assert(!(await page.locator("body").textContent()).includes(quota), `${width}px: Routing says ${quota} `); + assert(!(await sideways(page)), `${width}px: Routing scrolls sideways`); + assert.deepEqual(errors, []); + await page.context().close(); + } + }); + } +} diff --git a/internal/provider/keys.go b/internal/provider/keys.go index 2e8dcfbdd..58825c92e 100644 --- a/internal/provider/keys.go +++ b/internal/provider/keys.go @@ -87,6 +87,9 @@ type KeyRest struct { Model string `json:"model,omitempty"` // Error: what the vendor said Error string `json:"error,omitempty"` + // Rate: the vendor called it a rate limit and named when it lifts + // (gateway.Rest.Rate): the page says rate limited, not quota used up + Rate bool `json:"rate,omitempty"` } // RestKey is what the gateway rests the key k of a provider by: the