providers: a subscription account's rest, or its model's, shows on its row (maxleebeta)

maxleebeta on Discord (#feedback): WorkBuddy answered 429
{"type":"rate_limit_error","message":"WorkBuddy: 您的使用量已超出频率限制,将在
2026-11-03 23:57:19 UTC+8 重置,您也可以切换其他模型继续使用。"} while the
provider's card said 1,934/2,350 credits left (82%), and nothing on the
Providers page said the account was held back.

Routing already handled the refusal: resetsWhen reads the time (UTC+8, the
space before 重置 included), failure() gives failQuota, and since it says
切换其他模型 the rest is that model's alone (restID), by "resets", till
15:57:19 UTC; the account's other models are still asked (#1669). What
was missing was the page: a key's rest showed on its row, an account's
never did.

- gateway.RestsUnder(prefix) lists the rests in force under a key prefix
  (provider@ for a subscription's accounts, provider@user/model for a
  model's), with Key and the rest's note (Model, By, Error).
- providerJSON.accountRests gives them by user in lower case, the model
  filled in from the key when the note has none; provider.KeyRest gains
  By, Model and Error.
- app.js: the account row in the provider editor gets a line per rest
  (accountRestLines): "<model> resting · 429 quota used up · back at
  <time>" or "Resting · …" for the whole account, the vendor's words
  beside it (shown whole when it names a time magpie couldn't read, so
  an unknown format still says why), and Try now (gateway/unrest by the
  rest's key). The key row's rest line is now the same helper
  (restLineOf), so app.js grows ~800 bytes, under the core budget.
- New strings in zh, zh-TW, ja and de. docs/subsystems/gateway-routing.md
  says where the Providers page reads them.

Not changed: the "-sg" maxleebeta saw in pi is WorkBuddy AI's own model
id (deepseek-v4.1-flash-sg, the paid Singapore id beside the free
deepseek-v4.1-flash); pi's footer and model picker show ids by design,
and the name magpie writes for it is the vendor's ("Deepseek-V4.1-Flash",
"(SG)" added by the plugin only where two ids share a name). Neither
magpie nor the plugin appends "-sg"; the CN build has no -sg ids.

Run (mote, through mote-run):
- go test ./internal/gateway ./internal/gui ./internal/provider at f0df4bb2b
  (base 06944e065): gateway ok (737s), provider ok, gui ok except
  TestMainWindowCorners/macOS_26_SDK, red on macOS 27 as on main (#3949).
- Rebased on 889767b7b: TestCoreScriptBudget, TestI18n*,
  TestAccountRestsInProviderState and the written-reset tests ok;
  gofmt -l clean. GOOS=linux and GOOS=windows go vet -tags nogui ok at
  f0df4bb2b, before the rebase. Then rebased once more onto 8ee172ca0,
  which changes only gateway search files; not re-run there.
- internal/gui/tests/account-rest.test.cjs: chromium and webkit, en, zh,
  zh-TW, ja, de, at 900 and 360px, ok. rest-try-now.test.cjs's 15 webkit
  reds fail the same on origin/main 06944e065 (#2564, #4127).
- Broken by hand: TestRateLimitedModelListedUnderAccount red with
  RestsUnder returning nothing, TestAccountRestsInProviderState red
  without accountRests, account-rest.test.cjs red without
  accountRestLines.

Not tried: a real WorkBuddy account hitting this 429, so the line has
not been seen on a live gateway; the whole GUI suite (mote under another
session's suite). The line shows in the provider editor's account rows,
not on the collapsed provider row.
This commit is contained in:
yetone
2026-11-03 14:09:42 +08:00
parent 8ee172ca03
commit 63dc359fb4
10 changed files with 362 additions and 18 deletions
+1
View File
@@ -238,6 +238,7 @@ recorded as a prediction failure (`noPrediction`).
- An account resting out of its window (a Claude account by the time Claude Code's refusal named, `resets`, or any by `window`) is back once magpie's reading of its windows (`provider.Allowances`) finds it full till sooner: the window used below `SpentShareOf`, or its reset passed, with no other window over the same models still full. The reading tells `provider.OnRenewed` as the account's `UsageAgent` and user, and `renewed` lifts that account's rests out of quota or by `window`; its rests for a rate limit, its credit, a verification or a failure stay, as a key's do, and so does every rest of other accounts still out of their windows. Planning reads every account candidate's allowance, ordered groups included, so this needs no step of its own in `restingOf`.
- Only an account is held at a usage cap (`capHeld`) or rested out of one model's pool (`pooled`); a key's windows order it and rest it, nothing more.
- A rest of one model alone (keyed by `restID`: a pool, a model not served, a paid model beside free ones) names that model in the trace (`Rest.Model`). The Routing page shows it on that model's rows only: the account's other models' rows on the stage, and the account's row under Accounts and keys, don't read as resting. The account's row names the models resting on a line of their own under what it has left, and its Try now lifts their rests. A kept request from before `Rest.Model` has the model on the end of `Rest.Key`, which the page reads the same (`restModel` in `plugins/routing/client.js`, #1960, `routing-model-rest.test.cjs`).
- The Providers page shows a subscription account's rests in force on its row there too: `RestsUnder("<provider>@")` lists them, `providerJSON.accountRests` gives them by user in lower case (the account's own, and each model's, with `Rest.Model`, `Until`, `By` and the vendor's words, `Rest.Error`), and the row's line says which model, why and when it is back, the vendor's words beside it, with Try now lifting it by its key (`accountRestLines` in app.js). Before, only a key's rest showed there, and a WorkBuddy AI account whose model rested on a 429 "将在 … 重置" read as fine, its credits 82% left (maxleebeta on Discord; `TestRateLimitedModelListedUnderAccount`, `TestAccountRestsInProviderState`, `account-rest.test.cjs`).
- A group member let go for no first content within the group's `FirstToken` (`hw.slow` in [`gateway.go`](../../internal/gateway/gateway.go), 504 "no first token in Ns", `failSlow`) doesn't rest the first time: a long prompt is slow to start anywhere. Slow again on the same account's model with no answer from it in between, and within `slowForget` (30 minutes) of its last slow start, that model rests on that account (`restSlow` in [`routing.go`](../../internal/gateway/routing.go), keyed by `restID`, `Rest.Model` set): a minute from the second time (`slowRests`), doubling each time after, up to the provider's rest cap (`RestCapOr(longestRetry)`), and never for a provider whose cap is off. Its answer clears the count (`servedCandidate`). A request its client cancelled counts nothing, as the cancel is read before `hw.slow`. Before it, each new request asked the stalled member first again and waited out the whole `FirstToken` (小八 on Discord: a WorkBuddy account's kimi-k3-1 and glm-5.3 stalled 58 times on the vendor's per-model token limit, 15 times in 17 minutes in one session). The same model on another account and another model on the same account are asked as before (`TestSlowStartsRestTheModelOnItsAccount`, `TestCanceledSlowStartRestsNothing`; the Routing page's story, `routing-went-on.test.cjs`).
- A plugin's try that isn't the last candidate is sent with `x-magpie-fallback: 1` (`provider.FallbackHeader`, `withFallback`), so a plugin whose vendor queues the request (Qoder's 10605, CodeArts' `queue-status: queued`) answers a `busy` 503 with Retry-After and the queue's reason at once instead of waiting minutes in the queue, and the next is asked; the last candidate isn't told and waits as the vendor's client does ([provider-plugins](provider-plugins.md#whether-another-candidate-follows), `TestPluginToldAnotherFollows`).
- A 402 is out of credit, unless it speaks of a usage limit (`usedUpWords`) and nothing of money (`creditWords`, `insufficient_quota`): then it is out of quota, and rests only the model when the account's windows say its pool is the one used up (`pooled`). Factory answers Standard's pool used up with 402 "You've reached your weekly standard usage limit (resets in …). Switch to Droid Core …"; read as credit, it rested the account 30 minutes and its Droid Core models with it (#1979). Both the built-in's windows and the plugin's (Standard's `notModels`, Core's `models`) are held to it. As a quota rest it lasts until the time the refusal names (`resetsAfter`: "resets in 0h 19min", "resets in 2d 3h", held to `longestWritten`), else the window's end, else `quotaRest` or the provider's own `quota-rest`, and is lifted once a reading finds the window renewed (`renewed`), which a credit rest never was (`TestFactoryStandardOutLeavesCore`, `TestPaymentRequiredReadByItsWords`, `TestResetsInWords`). An account whose windows weren't read yet (a start, or a reading that failed) can't tell the model's pool from the account's, so it rests whole, and `narrowWhenRead` waits off the request for a reading (`AwaitAllowance`, up to `allowanceWait`) and moves the rest to the model alone (`restID`, the same end) when the reading says its pool is the one used up; no reading in time, or one that says the whole account, leaves the account's rest, as does a rest lifted or made again meanwhile (#2036; `TestFactoryStandardOutLeavesCore`'s unread case, `TestResetsInWords`). The request itself isn't held for the reading: it has failed over already, and the rest's scope only matters to later requests.
+28
View File
@@ -13,12 +13,14 @@ package gateway
import (
"bytes"
"cmp"
"context"
"encoding/json"
"fmt"
"math"
"net/http"
"regexp"
"slices"
"sort"
"strconv"
"strings"
@@ -833,6 +835,32 @@ var (
// passed over now, while it is.
func RestOf(key string) (Rest, bool) { return restOf(key) }
// RestsUnder are the rests in force now of what rests by a key starting
// with prefix — a subscription's accounts by "<provider>@", each its own
// (provider@user) and each of its models' (provider@user/model) — with
// Key, and Model for a model's, filled in, soonest back first. The
// Providers page shows them on the account's row (maxleebeta on Discord:
// WorkBuddy's 429 "将在 … 重置" rested a model with credits left, and
// nothing there said so).
func RestsUnder(prefix string) []Rest {
restingUntil.Lock()
defer restingUntil.Unlock()
now := time.Now()
var out []Rest
for k, until := range restingUntil.m {
if !strings.HasPrefix(k, prefix) || !now.Before(until) {
continue
}
r := restingUntil.note[k]
r.Key, r.Until = k, until
out = append(out, r)
}
slices.SortFunc(out, func(a, b Rest) int {
return cmp.Or(a.Until.Compare(b.Until), strings.Compare(a.Key, b.Key))
})
return out
}
// Unrest lifts the rest of what rests by key — an account just verified
// with its vendor, say — so the next request asks it again: rate limited
// with Sink on, it is no longer sent to the back of the order either.
+78
View File
@@ -375,3 +375,81 @@ func TestFailureReadsEscapedWords(t *testing.T) {
}
}
}
// maxleebeta's 429 from WorkBuddy AI (Discord, 11-03), byte for byte: its
// "WorkBuddy: " in ASCII and a space before 重置, with 82% of the
// account's credits left. It is read as resetting at 15:57:19 UTC, rests
// that model alone till then, and RestsUnder lists that rest under the
// account for the Providers page, with the model and the vendor's words;
// a rest gone by, another account's and another provider's are not
// listed.
func TestRateLimitedModelListedUnderAccount(t *testing.T) {
const said = `{"type":"rate_limit_error","message":"WorkBuddy: 您的使用量已超出频率限制,将在 2026-11-03 23:57:19 UTC+8 重置,您也可以切换其他模型继续使用。"}`
cst := time.FixedZone("", 8*3600)
now := time.Date(2026, 11, 3, 21, 0, 0, 0, cst)
if got, want := resetsAt([]byte(said), now), 2*time.Hour+57*time.Minute+19*time.Second; got != want {
t.Fatalf("resets in %v, want %v", got, want)
}
if got := now.Add(resetsAt([]byte(said), now)).UTC(); !got.Equal(time.Date(2026, 11, 3, 15, 57, 19, 0, time.UTC)) {
t.Fatalf("resets at %v", got)
}
if f := failure(429, []byte(said)); f != failQuota {
t.Fatalf("failure %s", f)
}
old := allowances
defer func() { allowances = old }()
allowances = func(string) map[string]provider.Allowance { return nil }
s := &Server{}
acct := func(id, user, model string) candidate {
return candidate{p: provider.Provider{ID: id, Account: &provider.Account{Agent: id, User: user}}, model: model, rest: id + "#" + user}
}
// the same words, the time moved to 3 hours from now
back := 3 * time.Hour
body := []byte(strings.Replace(said, "2026-11-03 23:57:19", time.Now().Add(back).In(cst).Format("2006-01-02 15:04:05"), 1))
c := acct("workbuddy-ai", "Max.Lee@Example.com", "gpt-6-astra")
r := s.restAfter(c, 429, http.Header{}, body)
if r.Why != failQuota || r.By != "resets" || r.Key != c.restID() {
t.Fatalf("rests %+v", r)
}
if !resting(c) || resting(acct("workbuddy-ai", "Max.Lee@Example.com", "deepseek-v4.1-flash-sg")) {
t.Fatal("not the model alone")
}
// beside it: a rest gone by, another account's, another provider's
restingUntil.Lock()
restingUntil.m["workbuddy-ai@max.lee@example.com/glm-5.3-flash"] = time.Now().Add(-time.Minute)
restingUntil.m["workbuddy-ai@other@example.com"] = time.Now().Add(time.Hour)
restingUntil.m["workbuddy@max.lee@example.com/gpt-6-astra"] = time.Now().Add(time.Hour)
restingUntil.Unlock()
defer func() {
restingUntil.Lock()
for _, k := range []string{c.restID(), "workbuddy-ai@max.lee@example.com/glm-5.3-flash", "workbuddy-ai@other@example.com", "workbuddy@max.lee@example.com/gpt-6-astra"} {
delete(restingUntil.m, k)
delete(restingUntil.note, k)
}
restingUntil.Unlock()
}()
got := RestsUnder("workbuddy-ai@max.lee@example.com")
if len(got) != 1 {
t.Fatalf("listed %+v", got)
}
g := got[0]
if g.Key != "workbuddy-ai@max.lee@example.com/gpt-6-astra" || g.Model != "gpt-6-astra" || g.Why != failQuota || g.Status != 429 || g.By != "resets" {
t.Fatalf("listed %+v", g)
}
if d := time.Until(g.Until); d > back || d < back-time.Minute {
t.Fatalf("until in %v, want %v", d, back)
}
if !strings.Contains(g.Error, "将在") || !strings.Contains(g.Error, "重置") {
t.Fatalf("the vendor's words: %q", g.Error)
}
// the provider's: each account's, never another provider's
seen := map[string]bool{}
for _, r := range RestsUnder("workbuddy-ai@") {
seen[r.Key] = true
}
if !seen[c.restID()] || !seen["workbuddy-ai@other@example.com"] || seen["workbuddy@max.lee@example.com/gpt-6-astra"] || seen["workbuddy-ai@max.lee@example.com/glm-5.3-flash"] {
t.Fatalf("the provider's accounts: %v", seen)
}
}
+68
View File
@@ -0,0 +1,68 @@
package gui
import (
"encoding/json"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
)
// A subscription account the gateway rests, or one of its models, is in
// the Providers page's state by the account's user in lower case, with
// the model, until when and the vendor's words, and the key Try now lifts
// it by (maxleebeta on Discord: WorkBuddy AI's 429 "将在 … 重置" rested a
// model with 82% of the credits left, and the page said nothing). Another
// provider's rests, and a provider with no rest, add nothing.
func TestAccountRestsInProviderState(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"))
until := time.Now().Add(3 * time.Hour).Truncate(time.Second)
said := "WorkBuddy: 您的使用量已超出频率限制,将在 2026-11-03 23:57:19 UTC+8 重置,您也可以切换其他模型继续使用。"
was := restsUnder
asked := []string{}
restsUnder = func(prefix string) []gateway.Rest {
asked = append(asked, prefix)
if prefix != "workbuddy-ai@" {
return nil
}
return []gateway.Rest{
{Why: "quota", Status: 429, Until: until, By: "resets", Key: "workbuddy-ai@max.lee@example.com/gpt-6-astra", Model: "gpt-6-astra", Error: said},
{Why: "rate", Status: 429, Until: until, By: "cooldown", Key: "workbuddy-ai@other@example.com"},
}
}
defer func() { restsUnder = was }()
p := provider.Provider{ID: "workbuddy-ai", Name: "WorkBuddy AI", Account: &provider.Account{Agent: "workbuddy-ai", User: "Max.Lee@Example.com"}}
out := providerInfo(p, nil)
b, err := json.Marshal(out)
if err != nil {
t.Fatal(err)
}
var got struct {
AccountRests map[string][]provider.KeyRest `json:"accountRests"`
}
if err := json.Unmarshal(b, &got); err != nil {
t.Fatal(err)
}
m := got.AccountRests["max.lee@example.com"]
if len(m) != 1 || m[0].Model != "gpt-6-astra" || m[0].Key != "workbuddy-ai@max.lee@example.com/gpt-6-astra" || !m[0].Until.Equal(until) || m[0].Status != 429 || m[0].By != "resets" || m[0].Error != said {
t.Fatalf("max: %+v (%s)", m, b)
}
if o := got.AccountRests["other@example.com"]; len(o) != 1 || o[0].Model != "" || o[0].Key != "workbuddy-ai@other@example.com" || o[0].Why != "rate" {
t.Fatalf("other: %+v", o)
}
// a provider with keys, none resting: nothing, and not asked by "@"
asked = asked[:0]
k := providerInfo(provider.Provider{ID: "relay", Name: "Relay", Chat: "https://example.invalid/v1", Key: "k"}, nil)
if k.AccountRests != nil || strings.Contains(strings.Join(asked, ","), "relay@") {
t.Fatalf("a key provider: %+v, asked %v", k.AccountRests, asked)
}
}
+1
View File
@@ -2816,6 +2816,7 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.acc .key-rest-line { flex: 1 0 100%; display: flex; align-items: center; gap: 8px; min-width: 0; padding-left: 25px; }
.acc .key-rest-line .key-rest { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
.acc .key-rest-line .key-unrest { flex: none; white-space: nowrap; }
.acc .key-rest-line .key-rest-said { flex: 1 1 0; min-width: 0; font-size: 11px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.acc .proto { flex: none; display: inline-flex; align-items: center; gap: 3px; height: 20px; padding: 0 5px 0 7px; font: inherit; font-size: 11px; color: var(--muted); border: 0; border-radius: 5px; background: var(--pill); white-space: nowrap; cursor: default; transition: opacity .15s, background .12s, color .12s; }
.acc .proto svg { opacity: .7; transition: transform .15s var(--ease); }
.acc .proto.open svg { transform: rotate(180deg); }
+31 -18
View File
@@ -13231,6 +13231,7 @@ function renderAccounts(a, p) {
if (l.until) aq.append(Object.assign(planSpan({ until: l.until }), { className: "aq-until" }));
row.append(aq);
row.classList.add("with-aq"); // not :has(.aq), which Safari 15.0 lacks (#220)
if (p) row.append(...accountRestLines(p, l.user)); // maxleebeta on Discord
// Remove goes under ⋯ too, but beside Sign in again while signed out
if (!row.classList.contains("signed-out")) tools.append(...line.querySelectorAll(":scope > .text.quiet"));
if (tools.childElementCount) {
@@ -14532,24 +14533,7 @@ function renderKeyAccounts(p) {
// a line of its own under the key's, so the row's controls stay in reach
let restLine = null;
if (k.rest && new Date(k.rest.until) > Date.now()) {
const r = el("span", "key-rest", t("Resting · {why} · back at {time}", { why: (k.rest.status ? k.rest.status + " " : "") + t(KEY_FAIL[k.rest.why] || "failed"), time: restBack(k.rest.until) }) + (k.rest.probed ? " · " + t("checked in the background, back as soon as it answers") : ""));
r.title = t("The gateway passes this key over until then, and tries the next one");
// lifted by hand (#1869): the next request asks it again, and a
// refusal then rests it again as before
const go = el("button", "text key-unrest", t("Try now"));
go.title = t("Ends the rest: the next request asks it again. Refused again, it rests again.");
go.onclick = async (e) => {
e.stopPropagation();
go.classList.add("busy");
try {
await api("gateway/unrest", { key: k.rest.key });
k.rest = null;
renderProviders();
status(t("{key} is asked again from the next request", { key: k.name || k.masked }), "ok");
} catch (err) { go.classList.remove("busy"); statusErr(err); }
};
restLine = el("div", "key-rest-line");
restLine.append(r, go);
restLine = restLineOf(k.rest, "", t("The gateway passes this key over until then, and tries the next one"), k.name || k.masked, () => { k.rest = null; });
row.classList.add("resting");
}
if (k.on && several) row.append(keyWeight(p, k, weightOf(k), weights));
@@ -14812,6 +14796,35 @@ function splitKeys(text) {
}
return out;
}
// 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 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"));
go.title = t("Ends the rest: the next request asks it again. Refused again, it rests again.");
go.onclick = async (e) => {
e.stopPropagation();
go.classList.add("busy");
try {
await api("gateway/unrest", { key: r.key });
lifted();
renderProviders();
status(t("{key} is asked again from the next request", { key: name }), "ok");
} catch (err) { go.classList.remove("busy"); statusErr(err); }
};
const line = el("div", "key-rest-line");
line.append(s);
if (r.error) line.append(Object.assign(el("span", "key-rest-said", r.error), { title: r.error }));
line.append(go);
return line;
}
const accountRestLines = (p, user) => {
const u = String(user).toLowerCase(), rs = p.accountRests?.[u] || [];
return rs.filter((r) => new Date(r.until) > Date.now()).map((r) => restLineOf(r, r.model, r.model ? t("Until then {model} goes to another account; its other models are used as before", { model: r.model }) : t("The gateway passes this account over until then, and tries the next one"), r.model ? r.model + " · " + user : user, () => p.accountRests[u] = rs.filter((x) => x !== r)));
};
// 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" };
+12
View File
@@ -1891,6 +1891,9 @@ const I18N = {
"checked in the background, back as soon as it answers": "后台自动检测,恢复即用",
"Resting · {why} · back at {time}": "暂停使用 · {why} · {time} 恢复",
"The gateway passes this key over until then, and tries the next one": "在此之前网关会跳过这个密钥,改用下一个",
"{model} resting · {why} · back at {time}": "{model} 暂停使用 · {why} · {time} 恢复",
"Until then {model} goes to another account; its other models are used as before": "在此之前网关会把 {model} 的请求交给其他账号,这个账号的其他模型照常使用",
"The gateway passes this account over until then, and tries the next one": "在此之前网关会跳过这个账号,改用下一个",
"Paste the keys, one a line or separated by commas": "粘贴密钥,每行一个,或用逗号分隔",
"1 key": "1 个密钥",
"{n} keys added, {m} already there": "已添加 {n} 个密钥,{m} 个已存在",
@@ -6369,6 +6372,9 @@ const I18N = {
"checked in the background, back as soon as it answers": "背景自動偵測,恢復即用",
"Resting · {why} · back at {time}": "暫停使用 · {why} · {time} 恢復",
"The gateway passes this key over until then, and tries the next one": "在此之前閘道會跳過這個金鑰,改用下一個",
"{model} resting · {why} · back at {time}": "{model} 暫停使用 · {why} · {time} 恢復",
"Until then {model} goes to another account; its other models are used as before": "在此之前閘道會把 {model} 的請求交給其他帳號,這個帳號的其他模型照常使用",
"The gateway passes this account over until then, and tries the next one": "在此之前閘道會跳過這個帳號,改用下一個",
"Paste the keys, one a line or separated by commas": "貼上金鑰,每行一個,或用逗號分隔",
"1 key": "1 個金鑰",
"{n} keys added, {m} already there": "已新增 {n} 個金鑰,{m} 個已存在",
@@ -10823,6 +10829,9 @@ const I18N = {
"checked in the background, back as soon as it answers": "バックグラウンドで自動確認し、応答すれば復帰",
"Resting · {why} · back at {time}": "休止中 · {why} · {time} に復帰",
"The gateway passes this key over until then, and tries the next one": "それまでゲートウェイはこのキーを飛ばし、次のキーを使います",
"{model} resting · {why} · back at {time}": "{model} 休止中 · {why} · {time} に復帰",
"Until then {model} goes to another account; its other models are used as before": "それまでゲートウェイは {model} を別のアカウントに送り、このアカウントの他のモデルはそのまま使います",
"The gateway passes this account over until then, and tries the next one": "それまでゲートウェイはこのアカウントを飛ばし、次のアカウントを使います",
"Paste the keys, one a line or separated by commas": "キーを貼り付け(1 行に 1 つ、またはカンマ区切り)",
"1 key": "1 個のキー",
"{n} keys added, {m} already there": "{n} 個のキーを追加しました({m} 個は登録済み)",
@@ -15308,6 +15317,9 @@ const I18N = {
"checked in the background, back as soon as it answers": "wird im Hintergrund geprüft, zurück sobald erreichbar",
"Resting · {why} · back at {time}": "Pausiert · {why} · zurück um {time}",
"The gateway passes this key over until then, and tries the next one": "Bis dahin überspringt das Gateway diesen Schlüssel und nimmt den nächsten",
"{model} resting · {why} · back at {time}": "{model} pausiert · {why} · zurück um {time}",
"Until then {model} goes to another account; its other models are used as before": "Bis dahin schickt das Gateway {model} an ein anderes Konto; die übrigen Modelle dieses Kontos werden wie gewohnt genutzt",
"The gateway passes this account over until then, and tries the next one": "Bis dahin überspringt das Gateway dieses Konto und nimmt das nächste",
"Paste the keys, one a line or separated by commas": "Schlüssel einfügen, einer pro Zeile oder durch Kommas getrennt",
"1 key": "1 Schlüssel",
"{n} keys added, {m} already there": "{n} Schlüssel hinzugefügt, {m} waren schon da",
+29
View File
@@ -315,6 +315,10 @@ type providerJSON struct {
// Move is where a built-in subscription stands with the community
// plugin that can run it (provider.Move): set for those that have one
Move *moveJSON `json:"move,omitempty"`
// a subscription account's rests in force, by its user in lower case:
// its own and each of its models' (maxleebeta on Discord: WorkBuddy's
// 429 "将在 … 重置" rested a model, credits left, and nothing here said so)
AccountRests map[string][]provider.KeyRest `json:"accountRests,omitempty"`
}
type moveJSON struct {
@@ -807,6 +811,9 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs
}
}
}
if p.Account != nil {
out.AccountRests = accountRests(p.ID)
}
exposed := map[string]bool{}
exposedList := ls.Exposed
for _, m := range exposedList {
@@ -1002,6 +1009,28 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs
// keyRestOf is gateway.RestOf, swapped in tests.
var keyRestOf = gateway.RestOf
// restsUnder is gateway.RestsUnder, swapped in tests.
var restsUnder = gateway.RestsUnder
// accountRests are the rests in force of a subscription's accounts, by
// user in lower case: an account's own (provider@user) and each of its
// models' (provider@user/model), as the gateway keys them (restKey,
// restID); nil when none rests.
func accountRests(id string) map[string][]provider.KeyRest {
var out map[string][]provider.KeyRest
for _, r := range restsUnder(id + "@") {
user, model, _ := strings.Cut(strings.TrimPrefix(r.Key, id+"@"), "/")
if user == "" {
continue
}
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})
}
return out
}
func providersState() providersJSON {
// an account signed in since start-up is listed with its vendor's
// models, not magpie's own list of them (#204): asked behind the page,
+106
View File
@@ -0,0 +1,106 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A subscription account the gateway rests says so on its row on the
// Providers page, as a key does (maxleebeta on Discord: WorkBuddy AI
// answered 429 "您的使用量已超出频率限制,将在 2026-11-03 23:57:19 UTC+8
// 重置,您也可以切换其他模型继续使用。" with 82% of its credits left, and
// the page said nothing). A rest of one model names the model and when it
// is back; the vendor's words show beside it, so a refusal whose time magpie
// couldn't read is still explained; Try now lifts it by the gateway's key.
// A rest gone by, and an account not resting, show nothing. It fits at
// 360px. In every language.
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-03 23:57:19 UTC+8 重置,您也可以切换其他模型继续使用。";
const USER = "Max@Example.com", OTHER = "two@example.com", THIRD = "three@example.com";
const fresh = (until) => ({
id: "workbuddy-ai", name: "WorkBuddy AI", icon: "", chat: "", responses: "", anthropic: "", catalog: "",
models: [{ id: "gpt-6-astra", name: "GPT-6-Astra", on: true }, { id: "deepseek-v4.1-flash-sg", name: "Deepseek-V4.1-Flash", on: true }],
agents: [], fallback: [], headers: {}, keyList: [], proxy: "",
account: {
agent: "workbuddy-ai", agentName: "WorkBuddy AI", user: USER, plan: "",
logins: [{ user: USER, active: true, on: true }, { user: OTHER, on: true }, { user: THIRD, on: true }],
},
accountRests: {
"max@example.com": [{ why: "quota", status: 429, until, key: "workbuddy-ai@max@example.com/gpt-6-astra", by: "resets", model: "gpt-6-astra", error: SAID }],
// the whole account, gone by: nothing
"three@example.com": [{ why: "rate", status: 429, until: new Date(Date.now() - 60000).toISOString(), key: "workbuddy-ai@three@example.com", by: "cooldown" }],
},
});
function serve(lang, until, lifted) {
const settings = { theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd" };
const providers = { providers: [fresh(until)], presets: [], excluded: [], gateway: { running: true, window: true },
plugins: [{ id: "workbuddy-ai", pid: "workbuddy", name: "WorkBuddy AI", icon: "", spec: "@magpie-community/opencode-workbuddy-auth" }] };
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: [], profiles: [], settings });
if (url.pathname === "/api/settings") return json(settings);
if (url.pathname === "/api/providers") return json(providers);
if (url.pathname === "/api/gateway/unrest") { lifted.push(JSON.parse(route.request().postData() || "{}")); return json({}); }
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 === "/api/login/usage") return json({});
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 LANGS = ["en", "zh", "zh-TW", "ja", "de"];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of LANGS) {
test(`${engine} ${lang}: an account's model the gateway rests says so on its row, with the vendor's words and Try now`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const width of [900, 360]) {
const until = new Date(Date.now() + 3 * 3600e3).toISOString(), lifted = [];
const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, until, lifted));
await page.goto("http://magpie.test/?view=providers");
await page.locator(".row.provider", { hasText: "WorkBuddy AI" }).first().click();
const row = (id) => page.locator(`.editor .accts .acc[data-account-id="${id}"]`);
await row(USER).waitFor();
const tr = (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]);
const back = await page.evaluate((u) => restBack(u), until);
const why = "429 " + (await tr("quota used up"));
const line = row(USER).locator(".key-rest-line");
assert.equal(await line.count(), 1);
assert.equal(await line.locator(".key-rest").textContent(), await tr("{model} resting · {why} · back at {time}", { model: "gpt-6-astra", why, time: back }));
assert.equal(await line.locator(".key-rest").getAttribute("title"), await tr("Until then {model} goes to another account; its other models are used as before", { model: "gpt-6-astra" }));
assert.equal(await line.locator(".key-rest-said").textContent(), SAID);
assert.ok(await line.locator(".key-rest").isVisible());
assert.ok(await line.locator(".key-unrest").isVisible());
// an account not resting, and a rest gone by: nothing
assert.equal(await row(OTHER).locator(".key-rest-line").count(), 0);
assert.equal(await row(THIRD).locator(".key-rest-line").count(), 0);
// the row's own line is untouched, and nothing scrolls sideways
const box = await row(USER).boundingBox(), lb = await line.boundingBox();
assert.ok(lb.x >= box.x && lb.x + lb.width <= box.x + box.width + 1, `the rest line fits its row at ${width}px`);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth), 0, `no sideways scroll at ${width}px`);
// Try now lifts it by the gateway's key
await line.locator(".key-unrest").click();
await page.waitForFunction(() => !document.querySelector(".editor .key-rest-line"));
assert.deepEqual(lifted, [{ key: "workbuddy-ai@max@example.com/gpt-6-astra" }]);
assert.deepEqual(errors, []);
await page.context().close();
}
});
}
}
+8
View File
@@ -66,6 +66,14 @@ type KeyRest struct {
// Probed: the gateway asks it again in the background, and lifts the
// rest as soon as it answers (gateway/rest_probe.go)
Probed bool `json:"probed,omitempty"`
// By: what set how long (gateway.Rest.By): "resets" or "retry-after"
// when the vendor named the time
By string `json:"by,omitempty"`
// Model: the one model resting, the account still answering its
// others; "" for the whole account or key
Model string `json:"model,omitempty"`
// Error: what the vendor said
Error string `json:"error,omitempty"`
}
// RestKey is what the gateway rests the key k of a provider by: the