Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
gateway: a key resting after an outage is asked again in the background
yetone0daf36332598
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex 6c54040df..4fb1063b4 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -196,6 +196,7 @@ recorded as a prediction failure (`noPrediction`).- The order of the steps a request's accounts go through, how much the accounts' own order (*Make first*) counts under each routing, and how often an allowance is read are described for users in [How magpie picks an account](../reference.md#how-magpie-picks-an-account). Smart compares renewals window by window, biggest first, each truncated to the hour (`weighRouted`), so the order decides only when every window falls in the same hour. A window's renewal is its reset, or, when what it has left runs out sooner or it has no reset, that moment (`Limit.RunsOut`, from `QuotaWindow.RunsOutAt`; `Allowance.Renewal`): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). When the renewals tie to the hour, Smart goes by that moment once more (`Allowance.Lapse`, `Seat.Lapse`), so of accounts renewing together (WorkBuddy's free accounts all reset at the month's end, plugin 0.1.35) the one whose credits left lapse first, after that end, goes first, and one telling none goes after (zhaocai_83020 on Discord). Only Smart reads it; Weekly pace, the 90%/98% tiers and rests go by the window's share and reset as before. A row on the Routing page says the share used (the fullest window's, `Allowance.For`) with when that same window renews (`Allowance.Fullest`, the trace's `usedRenews`), not the biggest window's: a Factory account 32% into its week and 16% into its month reads "32% used · renews in 3 days" while Smart still ranks it by its month (#1778). A route from before `usedRenews` says when only for an account of one window. Affinity keeps a conversation on an account at 90–97%: only `SpentShareOf` (98%, 100% In order) stops it (`affine`), while the 90% tier (`lowShare`) orders only conversations nobody has answered.- A turn's end is told to the app for the "Task done alert" notification (itieniu on X, `turndone.go`). The trace follows each agent session's turn (`turns`, keyed by agent and session): a request is of the turn unless it has a `Kind` or is a Claude Code subagent's (`agentTurnOf`), and its reply is scanned on the way to the agent for a tool call in any wire format (`toolScan`, a JSON value such as `"type":"tool_use"` or `"finish_reason":"tool_calls"`, never a key or text). The turn is done when no request of it is going, the last reply was whole, under 400 and called no tool, and nothing more came for `turnQuiet` (4s); a session idle past `turnStale` (30m) starts over. Only a turn that ran at least `settings.TurnDoneAlert` seconds is told (`TurnDone`, set by the GUI; nil under `magpie serve`, so nothing is followed). The ChatGPT backend path (`codexBackend`) is followed the same way. `TestTurnDoneSaidAtTheTurnsEnd`, `TestTurnDoneCodexBackend`, `TestToolScan`, `turn-done.test.cjs`.- A resting candidate is tried last (`restLast`). Of the resting candidates, a request asks only the one whose rest ends soonest, the first in order on a tie (`probeOne`, #1799). The others aren't asked by that request, so a member that is down isn't asked by every request its rest was meant to spare it from, and a group that is down whole takes one upstream request per request, not one per member. Every ready candidate is still asked in its order. A lone candidate is tried even while it rests, because there is no other. The trace still lists every member, the resting ones with their rest. Only rests are read, and a failure about the request's content or its model rests no member (a model refusal rests only `restID`), so neither leaves a member out. The same applies in `count_tokens`, embeddings and rerank, image accounts and a group's System One decision models. A Codex reset (`autoReset`) still looks over every candidate. This is like AxonHub's error-aware load balancing: the rest and its backoff are the penalty that decays, and the member back soonest is the one asked to show it is back. Keys out of their allowance aren't asked even so, not even the one back soonest or a lone one (#1772: four Ollama Cloud keys out for the week, each asked again and refused on every request). The refusal given again says when they are asked again on this magpie's clock with its offset (`heldClock`: "20:12 UTC+8", "Oct 16 09:00 UTC+8"), as do the gateway's other held errors (a capped window, a spent searcher or describer): its reader may be a Remote magpie's user on another clock. When every candidate left is a key (not a subscription account, whose resets `autoReset` may spend) resting out of quota or credit after a 429 or 402, none is asked. The first one's refusal is given again (`quotaHeld`, its words kept in the rest's `said`), saying when it is asked again. A key whose rest magpie guessed the length of, the vendor and the user naming no time (`creditRest`, or `quotaRest` with no `Provider.OwnQuotaRest`), is held so only once it was refused so twice in a row (`Rest.first`): a single refusal may be a moment's, and the next request, the agent's retry first, asks it again (zoecats on Discord: a local aggregator said 429 `insufficient_quota` "quota exhausted" for the moment it switched upstreams, and every request was answered from its rest of 15 or 30 minutes, which only the provider's "Rests" switch, `LimitRestOff`, let through before). Held, it is asked again a minute on (`Rest.askAt`, `fallbackCooldown`), once, and held again if refused (`Rest.asksAt`); a time the vendor named, or the user set, holds it from the first refusal to then. The rest itself stays as long as before, so the order still passes it over for a candidate that is ready. The last key left rests too when it is refused so, as the keys before it do. Any 429 that reaches the agent without a vendor `Retry-After`, while every candidate tried is resting, carries one: the seconds until the first of them is asked again (`soonestBack`, by `asksAt`), none after a key's first refusal. `TestRetryAfterALimitIsAsked`, `TestHeldLimitAskedAgainInAMinute`. A quota refusal with no word of when it is back rests `quotaRest` (15 minutes), or the provider's own `quotaRest` in minutes (`Provider.QuotaRestFor`, at most `MaxQuotaRest`, 8 days; `magpie provider quota-rest <id> 7d`), or until the time of day the user said its allowance comes back (`QuotaResetAt`, `Provider.OwnQuotaRest`; `magpie provider quota-rest <id> until 08:00`, or `until 00:00+08:00` on the vendor's clock; #2008, a free tier's "today's free-model token quota"). Whichever of the two was set last counts. A time the vendor names stands over it, and so does its `Retry-After`, unless that was more than `longestWait` (an hour) and so cut to it while the user's own rest is longer: then the user's stands (`TestQuotaRestsUntilTheTimeOfDaySet`). A key listed in `keys` as well as in `key` is one candidate (`KeysOn`), not asked twice. `TestAllRestingAnswersFromRest`, `TestOwnQuotaRest`, `TestQuotaHeldOnlyForKeysOutOfAllowance`, `TestFirstKeyListedTwiceAskedOnce`.+- A key resting after an outage that names no time is asked again in the background (`rest_probe.go`, heatonz on Discord). Behind ready keys, `probeOne` never asks it before its rest ends, though its vendor may be back in a minute. `restAfterMarked` marks the rest `Probed` when it is a key's own (not an account's or a plugin's, not one model's `restID`), `failOther` by `backoff` after a 5xx, a 408 or no connection, with no Retry-After or reset header, at a provider whose `List` asks over the network (`Provider.ListAsks`), and long enough for a first ask. `keepProbingRests`, started in `ListenAndServe`, then asks the vendor's model list with that key through its proxy (`Provider.List`, which saves nothing) 1, 2, 5 and then every 10 minutes into the rest, while it is the same rest. When the list answers, the rest is lifted as Try now lifts it (`liftedLocked`, `unsink`, the trace's lift). Not asked: rate limits (a list answers while the chat endpoint still refuses, and lifting one early would undo Sink), quota, credit, a Retry-After or reset, a refused key (401, 403, 400), restrictions and verification, each of which ends on its own time or the vendor's. A key a probe lifted that fails again within 30 minutes isn't asked again until it answers a request (`probeMissed`, `probeAnswered` in `served`): the list answered for the vendor, not for its chat. Only the loop's own `Server` asks (`restProbes.asking`), so a test's `Server` never reaches the network. The cost is one list per resting key per step, never one per request. The key list (`KeyRest.Probed`) and Routing's words for the try (`restHow`) add "checked in the background, back as soon as it answers". `TestRestProbeLiftsAKeyBackUp`, `TestRestProbeLeavesOtherRests`, `TestRestProbeOnlyByARunningLoop`, `rest-probed.test.cjs`.- A provider whose keys are on different plans (`KeyAccount.Plan`, `PlansMixed`; yckonnnn on X) sends each key to its plan's endpoints: every key path takes its copy through `WithKey`, which moves it there (`atKeyPlan`), on the first try and on a failover alike. `perKeyBarred` leaves out a key whose plan's list lacks the model (`PlanServing`: a pay-as-you-go model id at the Agent Plan's endpoint only answers 404), not shown in the trace; only when no key's plan has it are those keys asked. Embeddings and drawing go through the same `perKeyBarred` and `WithKey`; a video started on a mixed provider names its key in the task id (`videoStart.onKey`, `keyMark`) so its poll goes to that key's plan. `TestKeyPlansEachToItsOwnEndpoint`.- A subscription's account whose own model list lacks the model (`Account.Lists`: an Antigravity account's `fetchAvailableModels`, a plugin account's `models`) isn't planned while another of its accounts lists it (`perKeyBarred`'s `left`, `planned.unlisted`, the Routing page's "unlisted, skipped"). It is the next asked when every account of the subscription that lists the model has been asked and one refused it as a model it doesn't serve (`unservedTry`: `modelRefused`, or Code Assist's 404 NOT_FOUND, `codeAssistModelMissing`), before any later member or fallback (`unlistedNext`, `askUnlisted` moves its row from the route's left to its order after the one that refused). A list is fetched once and can be stale: 01huadalang's Gemini 4 was served by one Antigravity account of several, and the one whose list named it refused it with a 404 the agent got while the other could answer. The one that refused rests for that model alone. Not for another refusal (a 403, a quota), a request pinned to an account, a native compaction sealed to one, or a conversation kept strictly on one; a gateway key held to some accounts narrows the unlisted ones too (`allowedCandidates`). `TestUnlistedAccountAskedAfterModelRefused`, `TestUnlistedAccountNotAskedForOtherRefusals`.- A member whose model is known to take less than the request isn't asked it (`roomy` in [`fallback.go`](../../internal/gateway/fallback.go), in `serve` after the rules, affinity, the image filter and `pinTo`, before `probeOne`; dgqyushen on Discord: OpenCode Zen's free DeepSeek V4.1 Flash, 200K, first in a group and a 1M subscription of it second). It is a check before sending, not a retry: the request's tokens are estimated as the overflow fall-over does (`estimate`, bytes/4 over text, tool arguments and schemas), and a candidate whose window (`windowOf`: the provider's `Contexts`, the catalog, `ContextOf`) is known and no larger is left out of the candidates and of the trace's order, and listed in the trace's `left` with `window` set to that window. Asked, such a member only refuses, and a refusal that doesn't say why, for a request short of `tooLongUnsaid`'s 1.2 margin, reached the agent as the vendor's error while the next member had room; it also spent a request against the member's limits. A conversation kept on a member by affinity moves once it outgrows it. Nothing is left out when its window isn't known, when the body doesn't parse, when only one model is among the candidates, or when no candidate holds the request: then the first is asked, and its overflow reaches the agent as one, to compact (`withRoom`, `failOverflow` and `tooLongUnsaid` stay for the window the estimate misses, which counts low on code and high on CJK text). A body shorter than four bytes per token of the least window isn't parsed. `count_tokens` (a count on the group's first member, not a send) and System One's decision models (short decision text) don't go through it. Those left out are the last resort: when the last candidate with room fails out of its allowance or credit (`failQuota`/`failCredit`), nothing before it having failed otherwise (`other`), and no account is pinned, the ones left out that aren't resting are asked after all, their rows moved from the trace's `left` to its order, and the one that failed rests as one before the last does. Its overflow tells the agent to compact, where the 429 only told it to wait for an allowance hours away (Kai on Discord: both Claude accounts spent until the next day, the Claude provider's Fallback a Codex model of 272K under a longer conversation, never asked). Another failure (a busy vendor, a bad key) still reaches the agent as it was, the small one not asked. The Routing page keeps a row for a member left out and not asked, saying the request is longer than its window and that it was passed over, and its why list says so (#3749; it used to show it only by its absence from the order). `TestMemberTooSmallIsNotAsked`, `TestMemberTooSmallIsTheLastResort`, `TestClaudeAccountsSpentFallBackToCodex`, `TestConversationOutgrowingItsMemberMoves`, `TestRoomyLeavesWhatItCantJudge`.diff --git a/internal/gateway/rest_probe.go b/internal/gateway/rest_probe.gonew file mode 100644index 000000000..4de1b7fa9--- /dev/null+++ b/internal/gateway/rest_probe.go@@ -0,0 +1,259 @@+package gateway++// A key resting after an outage that names no time — a 5xx, its vendor+// unreachable — rests a minute, longer each time it fails again, while+// the keys ready beside it take the requests, so nothing asks it whether+// it is back before its rest ends (heatonz on Discord: a key back up+// waited out its rest, or a click on Try now). The gateway asks it in the+// background instead: its vendor's model list, with the key and the proxy+// it goes through, a minute into its rest, then two minutes on, then+// five, then every ten, and lifts the rest as soon as the list answers.+// A list costs no allowance, and none is asked of a subscription's+// account, a plugin's, or a rest whose end the vendor or the user named+// (out of quota or credit, a Retry-After, a window full), which ends on+// time; nor of a rate limit, which a list answers while the chat endpoint+// still refuses, or of one model alone. A list answers for the vendor,+// not for every model behind it, so a rest the list lifted that fails+// again is not asked again until the key answers a request.++import (+ "context"+ "log"+ "net/http"+ "sync"+ "time"++ "github.com/yetone/magpie/internal/provider"+)++// restProbeSteps is how long after a rest begins its key is first asked+// again, and how long after each list that failed the next is asked; the+// last is kept from then on.+var restProbeSteps = []time.Duration{time.Minute, 2 * time.Minute, 5 * time.Minute, 10 * time.Minute}++// restProbeWait is how long one list is waited for.+var restProbeWait = 20 * time.Second++// restProbeMiss is how soon after a probe lifted a key's rest a failure+// counts against the probe: the list answered, the requests didn't.+const restProbeMiss = 30 * time.Minute++// listForProbe asks p's vendor its model list; swapped in tests.+var listForProbe = func(ctx context.Context, p provider.Provider) error {+ _, err := p.List(ctx)+ return err+}++type restProbe struct {+ by *Server // the gateway whose loop asks it+ p provider.Provider // the key, as the request had it+ until time.Time // the rest it is for: another since ends it+ next time.Time // when it is asked next+ step int // which of restProbeSteps comes next+ busy bool // being asked now+}++var restProbes = struct {+ sync.Mutex+ m map[string]restProbe // rest key → its probe+ lifted map[string]time.Time // rest key → when a probe lifted its rest+ missed map[string]bool // rest key → failed again after a probe lifted it+ // asking: the gateways whose loop runs; another's rests (a test's+ // Server) are not asked+ asking map[*Server]bool+ wake chan struct{}+}{m: map[string]restProbe{}, lifted: map[string]time.Time{}, missed: map[string]bool{}, asking: map[*Server]bool{}, wake: make(chan struct{}, 1)}++// probeable says r, the rest c just took, is one asked again in the+// background: a key's own (not one model's), after a failure that says+// nothing of when it is back and isn't about the key itself — a server+// error, a timeout or no connection — at a vendor whose list is asked over+// the network, and long enough for the first ask to come before it ends.+// A Retry-After the vendor sent with it is its word on when to ask again,+// which a list asked sooner would go around.+func probeable(c candidate, r Rest, header http.Header, now time.Time) bool {+ if retryAfter(header, now) > 0 || c.p.Account != nil || r.Model != "" || r.Key != c.restKey() || r.Why != failOther || !c.p.ListAsks() {+ return false+ }+ if r.By != "backoff" {+ return false+ }+ if r.Status < 500 && r.Status != http.StatusRequestTimeout && r.Status != 0 {+ return false+ }+ return probeBefore(now.Add(restProbeSteps[0]), r.Until)+}++// probeBefore says an ask at is worth making before a rest ending at+// until: half the first step at least before it ends on its own.+func probeBefore(at, until time.Time) bool {+ return at.Before(until.Add(-restProbeSteps[0] / 2))+}++// probeMissed says key isn't to be asked again in the background: a probe+// lifted its rest a moment ago and it failed again all the same, or did+// so before and hasn't answered a request since.+func probeMissed(key string, now time.Time) bool {+ restProbes.Lock()+ defer restProbes.Unlock()+ if at, ok := restProbes.lifted[key]; ok {+ delete(restProbes.lifted, key)+ if now.Sub(at) < restProbeMiss {+ restProbes.missed[key] = true+ }+ }+ return restProbes.missed[key]+}++// probeAnswered forgets what the probes knew of key once it answers a+// request: a later outage is asked again.+func probeAnswered(key string) {+ restProbes.Lock()+ delete(restProbes.lifted, key)+ delete(restProbes.missed, key)+ restProbes.Unlock()+}++// probeLater has s's loop (keepProbingRests) ask p again during r.+func (s *Server) probeLater(p provider.Provider, r Rest, now time.Time) {+ restProbes.Lock()+ if !restProbes.asking[s] {+ restProbes.Unlock()+ return+ }+ restProbes.m[r.Key] = restProbe{by: s, p: p, until: r.Until, next: now.Add(restProbeSteps[0])}+ restProbes.Unlock()+ select {+ case restProbes.wake <- struct{}{}:+ default:+ }+}++// keepProbingRests asks the keys resting after an outage again as their+// turns come (probeLater), until ctx ends, and returns once the asks under+// way have.+func (s *Server) keepProbingRests(ctx context.Context) {+ restProbes.Lock()+ restProbes.asking[s] = true+ restProbes.Unlock()+ var asks sync.WaitGroup+ defer func() {+ asks.Wait()+ restProbes.Lock()+ delete(restProbes.asking, s)+ for key, pr := range restProbes.m {+ if pr.by == s {+ delete(restProbes.m, key)+ }+ }+ restProbes.Unlock()+ }()+ t := time.NewTimer(time.Hour)+ defer t.Stop()+ for {+ next := s.probeDue(ctx, &asks, time.Now())+ wait := time.Hour+ if !next.IsZero() {+ wait = max(time.Until(next), 0)+ }+ t.Reset(wait)+ select {+ case <-ctx.Done():+ return+ case <-restProbes.wake:+ case <-t.C:+ }+ }+}++// probeDue starts asking each of s's keys whose turn has come, lets go of+// those whose rest ended or changed, and says when the next turn is.+func (s *Server) probeDue(ctx context.Context, asks *sync.WaitGroup, now time.Time) time.Time {+ var next time.Time+ restProbes.Lock()+ defer restProbes.Unlock()+ for key, pr := range restProbes.m {+ if pr.by != s {+ continue+ }+ if !restingAt(key, pr.until) {+ delete(restProbes.m, key)+ continue+ }+ if pr.busy {+ continue+ }+ if now.Before(pr.next) {+ if next.IsZero() || pr.next.Before(next) {+ next = pr.next+ }+ continue+ }+ pr.busy = true+ restProbes.m[key] = pr+ asks.Add(1)+ go func() {+ defer asks.Done()+ c, done := context.WithTimeout(ctx, restProbeWait)+ err := listForProbe(c, pr.p)+ done()+ if ctx.Err() != nil {+ return+ }+ s.probed(key, pr.until, err, time.Now())+ }()+ }+ return next+}++// restingAt says key still rests the rest that ends at until.+func restingAt(key string, until time.Time) bool {+ restingUntil.Lock()+ defer restingUntil.Unlock()+ u, ok := restingUntil.m[key]+ return ok && u.Equal(until) && time.Now().Before(u)+}++// probed takes in what asking key's vendor came back with: answered, its+// rest is lifted, as Try now would; else it is asked again at the next+// step, unless its rest ends first.+func (s *Server) probed(key string, until time.Time, err error, now time.Time) {+ restProbes.Lock()+ pr, ok := restProbes.m[key]+ if !ok || !pr.until.Equal(until) {+ restProbes.Unlock()+ return // another rest, or none, since it was asked+ }+ if err != nil {+ pr.busy = false+ pr.next = now.Add(restProbeSteps[min(pr.step+1, len(restProbeSteps)-1)])+ pr.step+++ if probeBefore(pr.next, until) {+ restProbes.m[key] = pr+ } else {+ delete(restProbes.m, key) // its rest ends before then+ }+ restProbes.Unlock()+ select {+ case restProbes.wake <- struct{}{}:+ default:+ }+ return+ }+ delete(restProbes.m, key)+ restingUntil.Lock()+ lifted := restingUntil.m[key].Equal(until)+ if lifted {+ delete(restingUntil.m, key)+ delete(restingUntil.note, key)+ liftedLocked(key, now)+ restProbes.lifted[key] = now+ }+ restingUntil.Unlock()+ restProbes.Unlock()+ if lifted {+ log.Printf("gateway: %s answered again; its rest is lifted", key)+ unsink(key)+ s.trace.lifted()+ }+}diff --git a/internal/gateway/rest_probe_test.go b/internal/gateway/rest_probe_test.gonew file mode 100644index 000000000..9a3f0b391--- /dev/null+++ b/internal/gateway/rest_probe_test.go@@ -0,0 +1,238 @@+package gateway++import (+ "context"+ "errors"+ "net/http"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/provider"+)++// probing starts s's probe loop with short steps and a stand-in for the+// vendor's list, and ends both with the test.+func probing(t *testing.T, list func(context.Context, provider.Provider) error) *Server {+ t.Helper()+ steps, was := restProbeSteps, listForProbe+ restProbeSteps = []time.Duration{20 * time.Millisecond, 40 * time.Millisecond}+ listForProbe = list+ s := &Server{}+ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan struct{})+ go func() { s.keepProbingRests(ctx); close(done) }()+ t.Cleanup(func() {+ cancel()+ <-done+ restProbeSteps, listForProbe = steps, was+ })+ untilState(t, "the loop to start", func() bool {+ restProbes.Lock()+ defer restProbes.Unlock()+ return restProbes.asking[s]+ })+ return s+}++// untilState waits for ok to hold, as long as a loaded machine may need.+func untilState(t *testing.T, what string, ok func() bool) {+ t.Helper()+ deadline := time.Now().Add(30 * time.Second)+ for !ok() {+ if time.Now().After(deadline) {+ t.Fatalf("waited 30s for %s", what)+ }+ time.Sleep(5 * time.Millisecond)+ }+}++func probeKey(t *testing.T, id string) candidate {+ t.Helper()+ c := candidate{p: provider.Provider{ID: id, Key: "sk-" + id}, model: "m", rest: id}+ forget := func() {+ routed.Lock()+ delete(routed.failures, c.restKey())+ delete(routed.failures, c.restID())+ routed.Unlock()+ clearRest(c.restKey())+ clearRest(c.restID())+ probeAnswered(c.restKey())+ restProbes.Lock()+ delete(restProbes.m, c.restKey())+ restProbes.Unlock()+ }+ forget()+ t.Cleanup(forget)+ return c+}++func probeQueued(key string) bool {+ restProbes.Lock()+ defer restProbes.Unlock()+ _, ok := restProbes.m[key]+ return ok+}++const outage = `{"error":{"message":"upstream unavailable","type":"api_error"}}`++// heatonz on Discord: a key resting after a 5xx stayed out for its whole+// rest though its vendor was back. It is asked again in the background+// with its own key, and back as soon as it answers.+func TestRestProbeLiftsAKeyBackUp(t *testing.T) {+ var asked atomic.Int32+ var mu sync.Mutex+ var keys []string+ s := probing(t, func(_ context.Context, p provider.Provider) error {+ mu.Lock()+ keys = append(keys, p.Key)+ mu.Unlock()+ if asked.Add(1) == 1 {+ return errors.New("still down")+ }+ return nil+ })+ c := probeKey(t, "probe-up")+ r := s.restAfter(c, http.StatusServiceUnavailable, http.Header{}, []byte(outage))+ if !r.Probed || r.By != "backoff" || r.Key != c.restKey() {+ t.Fatalf("a 503 rests %+v, not asked again", r)+ }+ if _, ok := restOf(c.restKey()); !ok {+ t.Fatal("not resting")+ }+ untilState(t, "the rest to be lifted", func() bool { _, ok := restOf(c.restKey()); return !ok })+ if n := asked.Load(); n != 2 {+ t.Fatalf("asked %d times, want a failed ask and an answered one", n)+ }+ mu.Lock()+ defer mu.Unlock()+ if keys[0] != "sk-probe-up" || keys[1] != "sk-probe-up" {+ t.Fatalf("asked with %v, not the resting key", keys)+ }+ if probeQueued(c.restKey()) {+ t.Fatal("still queued after it answered")+ }++ // the list answered and the requests still don't: no ask again until+ // a request is answered+ r = s.restAfter(c, http.StatusBadGateway, http.Header{}, []byte(outage))+ if r.Probed || probeQueued(c.restKey()) {+ t.Fatalf("failed again right after a probe lifted it, and asked again: %+v", r)+ }+ clearRest(c.restKey())+ served(c.restKey(), c.restKey(), 1)+ routed.Lock()+ delete(routed.failures, c.restID())+ routed.Unlock()+ if r = s.restAfter(c, http.StatusBadGateway, http.Header{}, []byte(outage)); !r.Probed {+ t.Fatalf("a later outage, after it answered, isn't asked again: %+v", r)+ }+}++// A rest whose end the vendor named, or that is about the key or the+// request, or one model, or a subscription's account, ends on time: none+// is asked again in the background.+func TestRestProbeLeavesOtherRests(t *testing.T) {+ var asked atomic.Int32+ s := probing(t, func(context.Context, provider.Provider) error { asked.Add(1); return nil })+ retryAfter := http.Header{}+ retryAfter.Set("Retry-After", "300")+ for _, tc := range []struct {+ name string+ status int+ header http.Header+ body string+ acct bool+ }{+ {"retry-after", http.StatusServiceUnavailable, retryAfter, outage, false},+ {"rate limit", http.StatusTooManyRequests, http.Header{}, `{"error":{"message":"rate limit exceeded"}}`, false},+ {"quota", http.StatusTooManyRequests, http.Header{}, `{"error":{"message":"You exceeded your current quota","type":"insufficient_quota"}}`, false},+ {"refused key", http.StatusUnauthorized, http.Header{}, `{"error":{"message":"invalid api key"}}`, false},+ {"bad request", http.StatusBadRequest, http.Header{}, `{"error":{"message":"bad things"}}`, false},+ {"account", http.StatusServiceUnavailable, http.Header{}, outage, true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ c := probeKey(t, "probe-"+tc.name)+ if tc.acct {+ c.p.Account = &provider.Account{Agent: "codex", User: "[email protected]"}+ t.Cleanup(func() {+ routed.Lock()+ delete(routed.failures, c.restKey())+ delete(routed.failures, c.restID())+ routed.Unlock()+ clearRest(c.restKey())+ clearRest(c.restID())+ })+ }+ r := s.restAfter(c, tc.status, tc.header, []byte(tc.body))+ if r.Probed || probeQueued(r.Key) {+ t.Fatalf("%s (rests by %s, %s) asked again in the background", tc.name, r.By, r.Why)+ }+ })+ }+ if n := asked.Load(); n != 0 {+ t.Fatalf("asked %d times", n)+ }+}++// A gateway whose loop isn't running (a test's) asks nothing, and a loop+// that ends lets go of its keys once the asks under way have ended.+func TestRestProbeOnlyByARunningLoop(t *testing.T) {+ c := probeKey(t, "probe-idle")+ if r := (&Server{}).restAfter(c, http.StatusServiceUnavailable, http.Header{}, []byte(outage)); probeQueued(c.restKey()) {+ t.Fatalf("queued with no loop: %+v", r)+ }+ clearRest(c.restKey())++ steps, was := restProbeSteps, listForProbe+ t.Cleanup(func() { restProbeSteps, listForProbe = steps, was })+ restProbeSteps = []time.Duration{20 * time.Millisecond}+ started, release, ended := make(chan struct{}), make(chan struct{}), make(chan struct{})+ listForProbe = func(ctx context.Context, _ provider.Provider) error {+ close(started)+ <-ctx.Done()+ <-release // an ask slow to see it was cut short+ close(ended)+ return ctx.Err()+ }+ s := &Server{}+ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan struct{})+ go func() { s.keepProbingRests(ctx); close(done) }()+ untilState(t, "the loop to start", func() bool {+ restProbes.Lock()+ defer restProbes.Unlock()+ return restProbes.asking[s]+ })+ routed.Lock()+ delete(routed.failures, c.restKey())+ delete(routed.failures, c.restID())+ routed.Unlock()+ if r := s.restAfter(c, http.StatusServiceUnavailable, http.Header{}, []byte(outage)); !r.Probed {+ t.Fatalf("not asked again: %+v", r)+ }+ <-started+ cancel()+ // the loop waits for its ask: ended while it is held, it left it+ // behind. Only a loop that ends early can fail here, however slow the+ // machine; one ending early on a very slow one may pass unseen+ select {+ case <-done:+ t.Fatal("the loop ended before its ask did")+ case <-time.After(100 * time.Millisecond):+ }+ close(release)+ <-done+ select {+ case <-ended:+ default:+ t.Fatal("the loop ended before its ask did")+ }+ if probeQueued(c.restKey()) {+ t.Fatal("an ended loop's key is still queued")+ }+ if _, ok := restOf(c.restKey()); !ok {+ t.Fatal("an ask cut short lifted the rest")+ }+}diff --git a/internal/gateway/routing.go b/internal/gateway/routing.goindex 57c95d456..388292657 100644--- a/internal/gateway/routing.go+++ b/internal/gateway/routing.go@@ -72,6 +72,7 @@ func served(rest, key string, tokens int) {delete(routed.failures, rest)routed.Unlock()clearRest(key)+ probeAnswered(key)}// servedCandidate records an answer and ends both the provider's rest and,@@ -567,6 +568,10 @@ type Rest struct {Model string `json:"model,omitempty"`// Link: where the vendor said to verify the account, for failVerifyLink string `json:"link,omitempty"`+ // Probed: a key resting after an outage that names no time (a 5xx, its+ // vendor unreachable) is asked again in the background, and its rest+ // lifted as soon as it answers (rest_probe.go)+ Probed bool `json:"probed,omitempty"`// the subscription account resting, when it is one; agent "" and its// provider.KeyAllowanceID for a key out of its own windows@@ -1267,6 +1272,7 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, boif id == c.restID() {r.Model = c.model}+ r.Probed = probeable(c, r, header, now) && !probeMissed(id, now)restingUntil.Lock()if why == failQuota || why == failCredit {// out for as long as magpie guessed: refused so the time before@@ -1282,6 +1288,9 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, borestingUntil.m[id] = r.UntilrestingUntil.note[id] = rrestingUntil.Unlock()+ if r.Probed {+ s.probeLater(c.p, r, now)+ }if unread && id == c.restKey() && id != c.restID() {narrowing.Add(1)go narrowWhenRead(c, r)diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.jsindex d6464874c..61aa9158e 100644--- a/internal/gui/assets/app.js+++ b/internal/gui/assets/app.js@@ -14320,7 +14320,7 @@ function renderKeyAccounts(p) {// a line of its own under the key's, so the row's controls stay in reachlet 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: new Date(k.rest.until).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit" }) }));+ 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: hhmm(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@@ -17523,13 +17523,10 @@ function resetsUsedLine(q) {if (!used.length) return null;const line = el("span", "ar-used");const last = used[0];- line.textContent = t("Last reset used: {when} · {why}", { when: resetUsedWhen(last.at), why: resetUsedWhy(last.why) });- line.title = used.map((u) => resetUsedWhen(u.at) + " · " + resetUsedWhy(u.why)).join("\n");+ line.textContent = t("Last reset used: {when} · {why}", { when: stamp(last.at), why: resetUsedWhy(last.why) });+ line.title = used.map((u) => stamp(u.at) + " · " + resetUsedWhy(u.why)).join("\n");return line;}-function resetUsedWhen(at) {- return new Date(at).toLocaleString(intlLang(), { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });-}function resetUsedWhy(why) {if (why === "week") return t("by itself, its week used up");if (why === "expiring") return t("by itself, before it expired");@@ -19979,9 +19976,12 @@ function refreshAfterSync() {api("state").then((s) => { state = s; renderAgents(); }).catch(() => {});}+// hhmm: a time's hours and minutes, in the user's language+const hhmm = (d) => new Date(d).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit" });+function syncWhen(iso) {const d = new Date(iso);- const time = d.toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit" });+ const time = hhmm(d);return new Date().toDateString() === d.toDateString() ? t("at {time}", { time }) : d.toLocaleDateString(intlLang()) + " " + time;}@@ -21553,7 +21553,7 @@ function searchKeysRow(s, a, row, set) {const notes = [];if (q.known && q.of === "plan") notes.push(q.plan ? t("{plan} plan, shared by its account's keys", { plan: q.plan }) : t("the plan's, shared by its account's keys"));if (q.paygoLeft > 0) notes.push(t("{n} pay-as-you-go left", { n: num(q.paygoLeft) }));- if (q.resting) notes.push(t("asked last until {time}: {why}", { time: new Date(q.restUntil).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit" }),+ if (q.resting) notes.push(t("asked last until {time}: {why}", { time: hhmm(q.restUntil),why: { "turned away": t("turned away"), "out of credit": t("out of credit"), "rate limited": t("rate limited"), "used up": t("used up") }[q.resting] || q.resting }));const used = el("span", q.known ? (q.usedUp ? "used warn" : "used") : "used err", said);line.append(el("code", "", q.key), used);diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.jsindex 0309482c7..cb0b00b6a 100644--- a/internal/gui/assets/i18n.js+++ b/internal/gui/assets/i18n.js@@ -1698,6 +1698,7 @@ const I18N = {"Its key, {key}, only stands for one: paste your own API key.": "其中的密钥 {key} 只是占位符:请粘贴你自己的 API 密钥。","Make first": "设为首选","{name} tries {key} first": "{name} 会先用 {key}",+ "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": "在此之前网关会跳过这个密钥,改用下一个","Paste the keys, one a line or separated by commas": "粘贴密钥,每行一个,或用逗号分隔",@@ -5747,6 +5748,7 @@ const I18N = {"Its key, {key}, only stands for one: paste your own API key.": "其中的金鑰 {key} 只是預留位置:請貼上你自己的 API 金鑰。","Make first": "設為首選","{name} tries {key} first": "{name} 會先用 {key}",+ "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": "在此之前閘道會跳過這個金鑰,改用下一個","Paste the keys, one a line or separated by commas": "貼上金鑰,每行一個,或用逗號分隔",@@ -9773,6 +9775,7 @@ const I18N = {"Its key, {key}, only stands for one: paste your own API key.": "キー {key} はプレースホルダーです。ご自身の APIキーを貼り付けてください。","Make first": "最初にする","{name} tries {key} first": "{name} は最初に {key} を試します",+ "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": "それまでゲートウェイはこのキーを飛ばし、次のキーを使います","Paste the keys, one a line or separated by commas": "キーを貼り付け(1 行に 1 つ、またはカンマ区切り)",@@ -13829,6 +13832,7 @@ const I18N = {"Its key, {key}, only stands for one: paste your own API key.": "Sein Schlüssel {key} ist nur ein Platzhalter: Füge deinen eigenen API-Schlüssel ein.","Make first": "An erste Stelle setzen","{name} tries {key} first": "{name} versucht zuerst {key}",+ "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","Paste the keys, one a line or separated by commas": "Schlüssel einfügen, einer pro Zeile oder durch Kommas getrennt",diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.jsindex 0aa482e8d..cb99a9c0f 100644--- a/internal/gui/assets/plugins/routing/client.js+++ b/internal/gui/assets/plugins/routing/client.js@@ -635,9 +635,11 @@ function routingPage(part) {case "restricted": return t("The vendor restricted the account: it rests {d}, as only the vendor lifting the restriction brings it back. Appeal with the vendor; once it's lifted, try it again here", { d });case "backoff": return rest.why === "rate"? t("It was rate limited again as soon as it was back ({n} times in a row): it rests {d}, longer each time until it answers", { n: rest.failures, d })- : rest.failures > 1- ? t("It has failed {n} times in a row: it rests {d}, longer each time", { n: rest.failures, d })- : t("It rests {d}, longer if it fails again", { d });+ : (rest.failures > 1+ ? t("It has failed {n} times in a row: it rests {d}, longer each time", { n: rest.failures, d })+ : t("It rests {d}, longer if it fails again", { d }))+ // asked in the background meanwhile, and back once it answers+ + (rest.probed ? " · " + t("checked in the background, back as soon as it answers") : "");case "cooldown": return rest.why === "rate"? t("It cools down {d}: the vendor didn't say for how long", { d }): t("It rests {d}", { d });diff --git a/internal/gui/providers.go b/internal/gui/providers.goindex 4d912e055..c717ed414 100644--- a/internal/gui/providers.go+++ b/internal/gui/providers.go@@ -688,7 +688,7 @@ func providerInfoWith(p provider.Provider, agents []agentUse, desktop map[string}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}+ out.KeyList[i].Rest = &provider.KeyRest{Why: r.Why, Status: r.Status, Until: r.Until, Key: key, Probed: r.Probed}}}if !out.Key.Set && p.Ready() {diff --git a/internal/gui/tests/rest-probed.test.cjs b/internal/gui/tests/rest-probed.test.cjsnew file mode 100644index 000000000..12e37da96--- /dev/null+++ b/internal/gui/tests/rest-probed.test.cjs@@ -0,0 +1,127 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// A key resting after an outage that names no time (a 5xx, its vendor+// unreachable) is asked again in the background and back as soon as it+// answers (heatonz on Discord; gateway/rest_probe.go). Its rest says so:+// beside "Resting · … back at" in the provider's key list, and in the+// Routing page's words for the try that rested it. A rest the gateway+// doesn't ask again (a rate limit here) says nothing of it. In every+// language, at a wide and a narrow window, in both engines.+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(process.env.MAGPIE_REST_PROBED_ASSETS || path.join(__dirname, "../assets"));+const now = new Date();+const day = [now.getFullYear(), now.getMonth() + 1, now.getDate()].map((n) => String(n).padStart(2, "0")).join("-");+const start = new Date(now.getTime() - 60e3).toISOString();+const until = new Date(now.getTime() + 4 * 60e3).toISOString();+const a = { id: "relay#bbbbbbbbbb", provider: "relay", name: "Relay", kind: "key", who: "Team", model: "big" };+const b = { id: "ww2", provider: "ww2", name: "WW2", kind: "provider", model: "big" };+const rest = { why: "other", status: 503, until, by: "backoff", failures: 2, key: "relay#bbbbbbbbbb", probed: true };+const routes = [{+ id: 100, seq: 100, time: start, agent: "codex", model: "group/g", provider: "relay",+ order: [a, b],+ tries: [+ { id: a.id, model: a.model, start, done: true, status: 503, ms: 300, fail: "other", rest, error: "Relay: upstream unavailable" },+ { id: b.id, model: b.model, start, done: true, status: 200, ms: 900 },+ ],+ done: true, status: 200, ms: 1300,+}];+const relay = () => ({+ 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: "Solo", masked: "sk-…one", on: true, active: true, rest: { why: "rate", status: 429, until, key: "relay#aaaaaaaaaa" } },+ { id: "bbbbbbbbbb", name: "Team", masked: "sk-…two", on: true, rest: { why: "other", status: 503, until, key: "relay#bbbbbbbbbb", probed: true } },+ ],+});++function serve(lang) {+ const state = { agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } };+ const providers = { providers: [relay()], presets: [], excluded: [], gateway: { running: true, window: true } };+ 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(state);+ if (url.pathname === "/api/plugins") return json({ plugins: [] });+ if (url.pathname === "/api/gateway/trace") {+ if (url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3));+ return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });+ }+ if (url.pathname === "/api/gateway/history") {+ const d = url.searchParams.get("day");+ return json({ cut: false, days: [{ day, requests: routes.length }], routes: d ? routes : [] });+ }+ if (url.pathname === "/api/groups") return json({ groups: [] });+ if (url.pathname === "/api/providers") return json(providers);+ 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), contentType });+ };+}++const probed = {+ en: "checked in the background, back as soon as it answers",+ zh: "后台自动检测,恢复即用",+ "zh-TW": "背景自動偵測,恢復即用",+ ja: "バックグラウンドで自動確認し、応答すれば復帰",+ de: "wird im Hintergrund geprüft, zurück sobald erreichbar",+};++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 Object.keys(probed)) {+ for (const width of [1100, 420]) {+ const open = async (t, name, view) => {+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));+ const context = await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" });+ const page = await context.newPage();+ page.setDefaultTimeout(5000);+ const errors = [];+ page.on("pageerror", (e) => errors.push(e.message));+ await page.route("**/*", serve(lang));+ t.after(async () => {+ if (process.env.ARTIFACT_DIR) {+ await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });+ await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-${name}.png`), fullPage: true });+ }+ await browser.close();+ });+ await page.goto("http://magpie.test/?view=" + view);+ return { page, errors };+ };++ test(`${engine} ${lang} ${width}px: a key asked again in the background says so in the provider's list`, async (t) => {+ const { page, errors } = await open(t, "keys-probed", "providers");+ await page.locator(".row.provider", { hasText: "Relay" }).first().click();+ const team = page.locator('.acc[data-account-id="bbbbbbbbbb"] .key-rest');+ const solo = page.locator('.acc[data-account-id="aaaaaaaaaa"] .key-rest');+ await team.waitFor();+ await solo.waitFor();+ assert((await team.textContent()).endsWith(" · " + probed[lang]), `the probed key says: ${await team.textContent()}`);+ assert(!(await solo.textContent()).includes(probed[lang]), "a rate limit's rest says it is asked again");+ assert(!(await sideways(page)), "the page scrolls sideways");+ assert.deepEqual(errors, []);+ });++ test(`${engine} ${lang} ${width}px: Routing's words for the try say it is asked again in the background`, async (t) => {+ const { page, errors } = await open(t, "routing-probed", "routing");+ await page.locator(".rt-days .rt-day").nth(1).click();+ await page.locator(".rt-req").first().waitFor();+ await page.locator(".rt-req").first().click();+ await page.locator(".rt-steps li").first().waitFor();+ const steps = (await page.locator(".rt-steps li").evaluateAll((ls) => ls.map((l) => l.textContent.replace(/\s+/g, " ")))).join("\n");+ assert(steps.includes(probed[lang]), `the steps say:\n${steps}`);+ assert(!(await sideways(page)), "the page scrolls sideways");+ assert.deepEqual(errors, []);+ });+ }+ }+}diff --git a/internal/provider/keys.go b/internal/provider/keys.goindex 97cb515bd..daf27b4aa 100644--- a/internal/provider/keys.go+++ b/internal/provider/keys.go@@ -63,6 +63,9 @@ type KeyRest struct {Status int `json:"status"`Until time.Time `json:"until"`Key string `json:"key"`+ // 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"`}// RestKey is what the gateway rests the key k of a provider by: thediff --git a/internal/provider/models.go b/internal/provider/models.goindex fae543be4..c85c53174 100644--- a/internal/provider/models.go+++ b/internal/provider/models.go@@ -441,6 +441,20 @@ func (p Provider) List(ctx context.Context) ([]catalog.Model, error) {return catalog.Chat(l.models), nil}+// ListAsks says List asks a vendor over the network, with p's own key,+// what p serves: a key's provider, not a subscription's account, a+// plugin's or a decision API, nor a preset with no list to ask, whose List+// answers the preset's models without asking anyone. The gateway asks it+// of a key resting after an outage, to tell whether it is back+// (gateway/rest_probe.go).+func (p Provider) ListAsks() bool {+ if p.Account != nil || p.DecideOnly() {+ return false+ }+ pr := Preset(p.Preset)+ return pr == nil || !pr.NoList || strings.TrimSpace(p.ModelsURL) != "" || p.listRegion(pr)+}+// newFetches is when each account with no list from its vendor yet was// last asked for one by FetchNew.var newFetches = struct {