Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
codex: a reset set to go when the week runs out is spent before the credits
yetone0e2739743b1f
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex 1371fa3ed..1c29183fd 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -169,7 +169,7 @@ recorded as a prediction failure (`noPrediction`).- A rule by agent (`Rule.Agents`, `agents=codex,sillytavern`) matches the agent the gateway names the request's (`agentOf` in [`gateway.go`](../../internal/gateway/gateway.go): its `magpie-<name>` key, else its User-Agent), in lower case (`cleanRules`, `MatchesBesidesIntent`, `Pauses`). A client magpie doesn't know is named by its User-Agent's product name, before the first `/` or space (`usage.AgentOf`), so a rule can hold SillyTavern or one's own app (raikyou on Discord). The editor's agent picker lists the agents magpie knows, then those `/api/usage?period=30d` heard from that it doesn't (not `other`, nor `magpie`), and takes a name typed in its filter as the gateway reads a User-Agent (`uaName` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js), through the picker's `field.typed`): "MyApp/2.0 (Linux)" is `myapp`. `routing-rule-agent-typed.test.cjs`.- A pause rule (`Rule.Pause`, `pause=<model>`; John on Discord: a model of the group paused in its vendor's peak hours) leaves the model it names out of the group while it holds (`provider.PausedOut`, on `ruleClock`): the group's own rules and each nested group's on the way down to a member, a group named taking all its models, and a model named taking it wherever a group in the group has it (#625). It runs before planning, on every request rather than once a turn, so the model is not first, not a failover, and not kept by affinity, and comes back as soon as the hours end. It holds by hours, days, agents and folders only (`cleanRules` refuses another condition), and is not a send-to rule: `Matches`, `MatchRule`, `ThenUses`, `Ruled` and the compaction rules leave it out. A send-to rule naming a paused model finds it unready and the group routes as without it. The trace keeps what was paused (`GroupRef.Paused`), and the Routing page says so. Every model paused answers 503 (`pausedError`) naming each rule. Embeddings go by the same pauses; manual groups have no rules (`Live`), so none pause there. A pause by folder (#1606, Ti800: a subscription's quota kept for the long task in one folder, `pause=<model> except-folders=~/big-task`) reads the folder only when such a pause is on the way (`provider.PausesByFolder`, then `workDir`): outside its except-folders, which includes a request that says no folder (a subagent's or a small model's that doesn't), the model is left out; with `folders=`, only requests known to be in them. Embeddings and System One's decision calls have no folder. `Paused.Folder`/`ByFolder` carry what was read, and the Routing page says the folder or that none was said. `rules_pause_test.go`, `TestPauseByFolder`, `TestPauseByFolderRule`, `TestParsePauseByFolder`, `routing-pause-folder.test.cjs`.- A rule's hours and days (`Rule.Time`, `provider.TimeWindow`) are read on `ruleClock` in the zone they were set in (`TimeWindow.Zone`, an IANA name; gaubeebangeel on X: magpie on a cloud server in UTC, its user in Beijing, the hours 8 off). The GUI saves the browser's zone when the hours or days are changed in the editor and leaves a rule's zone alone otherwise; the CLI (`magpie group rule add … time=09:00-18:00@Asia/Shanghai` or `tz=`) and the TUI save the one typed, or this computer's (`provider.LocalZone`: `$TZ`, `time.Local`, the `/etc/localtime` link) when it has an IANA name. A window with no zone, every one saved before zones were kept, stays on magpie's own clock. A zone magpie doesn't know is refused on save (`TimeWindow.clean`), and one in a file edited by hand makes the window never hold (`zoneOf`): the rule is as if absent, never always on and never hours off. Zones come from Go's embedded tzdata, so Windows knows them too. `/api/groups` gives magpie's clock (`clock`: its zone and offset in seconds), and when it differs from the hours' zone the Routing page tells the zone beside them, on the group's rules and in the editor (`zoneNote` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js)): the zone's name, or the server's offset for hours with none. `TestRuleTimeWindowInItsZone`, `TestRuleTimeWindowInItsZoneAtTurnStart`, `TestRuleTimeWindowUnknownZone`, `TestParseRuleTimeZone`, `TestGroupRuleTimeZoneCmd`, `routing-time-zone.test.cjs`.-3. Candidates come from `planGroup` for a group or `plan` for a provider. They are filtered by `sealedReaders` and `allowedCandidates`. An account past its share is held out of the candidates (`capHeld`): a usage cap's share, each window at its own where the account gives it one (`AccountWindowCaps`, willz on Discord: 50% of the five hours, 40% of the week) and at the account's cap otherwise, or 100% of a window for a Codex account set not to spend its credits (`provider.HoldCaps`, `WindowCaps.Of`, `CodexNoCredits`). A ChatGPT account's call on `codex-auto-review`, which OpenAI counts in no window, is held by no usage cap, only by credits it may not spend (`freeOnChatGPT`, #1593, `TestAccountCapLetsAutoReviewThrough`); a Free plan's call is capped as any other (`TestAccountCapHoldsAutoReviewOnAFreePlan`). The account is held while any window is past its own share, and `cappedError` and the trace name the fullest such window's share and cap. When every candidate is held and one held for its credits spends its resets by itself, `autoReset` spends a reset on it and it is tried (`planned.held`); otherwise a capped or barred set returns `cappedError` or `barredError`. A provider with Stop at the caps on (`CapStop`, plugins#349) answers that 429 instead of going on to its fallbacks when every primary account is held (`plan`, `TestCapStopSkipsTheFallbacks`); off, the default, the fallbacks take it as before. A careful provider (`CapCareful`, plugins#349, off by default, `cap_careful.go`) has `readCareful` read a capped account's usage again before planning when its reading is over 15s old within 5 points of a cap, or over 5m old at all, waiting at most 10s and asking a failed account again at most every 15s; `capHold` then holds an account whose usage was never read, whose last read failed or whose reading is still that old (`carefulDoubt`, `Weighed.Unread` in the trace), as one at its cap is: unknown is not spent (`TestCarefulHoldsWhatItCantTell`, `TestCarefulReadsAgainNearTheCap`, `TestCarefulEveryAccountUnread`, `TestCarefulOffByDefault`). Then `affine` moves the conversation's last answerer first, unless it is resting or nearly used up. An `X-Magpie-Account` header (`AccountHeader`) pins the request to one account: only that account is tried, and when it can't answer the caller is told why.+3. Candidates come from `planGroup` for a group or `plan` for a provider. They are filtered by `sealedReaders` and `allowedCandidates`. An account past its share is held out of the candidates (`capHeld`): a usage cap's share, each window at its own where the account gives it one (`AccountWindowCaps`, willz on Discord: 50% of the five hours, 40% of the week) and at the account's cap otherwise, or 100% of a window for a Codex account set not to spend its credits (`provider.HoldCaps`, `WindowCaps.Of`, `CodexNoCredits`). A ChatGPT account's call on `codex-auto-review`, which OpenAI counts in no window, is held by no usage cap, only by credits it may not spend (`freeOnChatGPT`, #1593, `TestAccountCapLetsAutoReviewThrough`); a Free plan's call is capped as any other (`TestAccountCapHoldsAutoReviewOnAFreePlan`). The account is held while any window is past its own share, and `cappedError` and the trace name the fullest such window's share and cap. When every candidate is held and one held for its credits spends its resets by itself, `autoReset` spends a reset on it and it is tried (`planned.held`). A Codex account let spend its credits is never held or refused for its week, so before a try goes to one whose week its last reading says is used up and that spends a reset when its week runs out, `resetBeforeCredits` spends one first, one a week at most, in routing and in the relay (`resetBeforeCreditsOn`); a reset is free and credits cost money (tongzhenbao on X, `TestCodexResetBeforeCredits`). Otherwise a capped or barred set returns `cappedError` or `barredError`. A provider with Stop at the caps on (`CapStop`, plugins#349) answers that 429 instead of going on to its fallbacks when every primary account is held (`plan`, `TestCapStopSkipsTheFallbacks`); off, the default, the fallbacks take it as before. A careful provider (`CapCareful`, plugins#349, off by default, `cap_careful.go`) has `readCareful` read a capped account's usage again before planning when its reading is over 15s old within 5 points of a cap, or over 5m old at all, waiting at most 10s and asking a failed account again at most every 15s; `capHold` then holds an account whose usage was never read, whose last read failed or whose reading is still that old (`carefulDoubt`, `Weighed.Unread` in the trace), as one at its cap is: unknown is not spent (`TestCarefulHoldsWhatItCantTell`, `TestCarefulReadsAgainNearTheCap`, `TestCarefulEveryAccountUnread`, `TestCarefulOffByDefault`). Then `affine` moves the conversation's last answerer first, unless it is resting or nearly used up. An `X-Magpie-Account` header (`AccountHeader`) pins the request to one account: only that account is tried, and when it can't answer the caller is told why.4. The candidate loop calls `attempt` on each candidate in turn, through a `holdWriter`. The writer holds the reply until it is clearly passing. A candidate that fails before anything is sent rests (`failure`): out of credit for 30 minutes, out of quota until reset, rate limited until retry-after, otherwise a minute and longer on repeats: doubled each time, up to `longestRetry` (10 minutes) for a failure and `longestRateRest` (30 minutes) for a rate limit back as soon as its rest is over, or up to the provider's own `restCap` in minutes (`Provider.RestCapOr`, at most `MaxQuotaRest`; `magpie provider rest-cap <id> 4h`, #2008: a free key down for hours was asked every 10 minutes). A time the vendor names stands over it as before (`TestOwnRestCap`). An error `failure` reads as out of credit is `retryable` at any 4xx, so the next account or member is asked and this one rests as credit; before, a 400 or 422 counted only by `quotaWords`, and SuperMagic's 400 「您的可用积分已不足…通过「充值」通道补充积分」 went to the agent with another account of 6,467 points unasked, the empty one never rested (#4095, mycf_711; `TestCredit400MovesToTheNextAccount`). A shape refusal that also says so (`creditWords` in `shapeRefused`) is the credit it says. The failure count is kept per key or account (`restKey`), and any of its models' answers clears it (`served`). Each model's own count (`restID`) is kept beside it and cleared only by that model's answer (`servedCandidate`): once it is past the account's, a sibling model answered since it last did, so the failure is the model's and it climbs its own ladder and rests alone, its siblings still served (#2241, weizsw: an Antigravity seat's gemini-3.5-flash-lite rested a minute 41 times of 43 while gemini-3.8-flash kept answering; `TestModelLadderClimbsPastSiblingAnswers`). Every model failing with no answer between still climbs the account's ladder and rests the account, and a candidate naming no model has the account's count alone. `rest-cap <id> off` (`provider.RestCapOff`, `restCap: -1`) is for a relay or account pool whose unknown errors come now and then and pass by the next request (Kismet Alan on Discord): a failure that says nothing of why (`failOther`: a 5xx, a dropped connection) then rests nobody and isn't counted, its trace rest `by: "off"` with no time left. A 401 or 403, a model not served, an account's window full, a rate limit (magpie's own 30-minute cap), quota, credit and a restriction still rest it as before (`TestRestCapOff`). A provider the user added can be set never to rest for a limit instead (`provider.LimitRestOff`, `limitRestOff` in providers.json; the editor's Advanced fold, "Set it aside when out of quota or rate limited", ticked by default): a refusal `restAfterMarked` reads as out of quota, out of credit or rate limited, and any 429, then rests nothing, isn't counted or sunk, and is `by: "off"`; `restDrawer` rests no image model of it. The next request is sent to it as usual. It is for a relay whose limits pass in a moment (zoecats on Discord: a local aggregator said "quota exhausted" while it switched upstreams, and magpie answered itself for 30 minutes; `TestLimitRestOffKeepsAsking`, `TestLimitRestOffRestsNothingForALimit`). A 401, a model not served and a plain failure still rest it. The shortest cap otherwise is a minute, the first rest; `rest-cap <id> 30s` is turned away and names `off`. A 400, 403, 404 or 422 that says the model isn't served (`unservedWords`) and says nothing of quota, credit or a rate limit rests only that key's or account's model (`modelRefused`, keyed by `restID`, its backoff counted apart): its other models are still served first in order (#1235, SenseNova's 403 "model is not available in the current token plan"). A Google account's Code Assist (the Antigravity and Gemini CLI built-ins) answering 404 `NOT_FOUND` ("Requested entity was not found.") rests its model the same way, as its endpoint is the same for every model (`codeAssistModelMissing`; Packing1 on Discord: Argon, listed for a Google AI Pro account, answered 404 and rested the whole account; `TestCodeAssistMissingModelRestsTheModel`). A refusal for want of quota, credit or rate, for an account its vendor restricted, or for a verify it asks of its account there, from another computer's magpie (a Remote magpie provider, LAN share) rests only the model it was about (`remoteModelRest`, keyed by `restID`, in `restAfterMarked` and `rateRest`): that magpie serves each of its models from its own providers and rests them itself, so one out of quota there says nothing of the others (bigsteven on Discord: a 429 for one model rested every model on the remote for the 3 hours it named, so a group never moved on to the remote's other models; `TestRemoteMagpieQuotaRestsTheModel`, `TestRemoteMagpieRestrictedRestsTheModel`). Another magpie added by hand, as an OpenAI-compatible provider of the user's own name rather than the preset, is read as one by its reply: a magpie names the provider that answered or held it (`X-Magpie-Provider`, `providerHeader`; `noteMember`, also on a `quotaHeld` or `verifyHeld` answer), as no vendor does, and `keepRetry` notes it as `answeredThereHeader`, since this magpie writes its own provider into the same header of its reply and the note is kept from the client (lagrangepoint1813 on Discord: "Remote Magpie: Claude Code: You've hit your session limit" answered every model of it, from `quotaHeld`, for the five hours it named; `TestAnotherMagpieAddedByHandRestsTheModel`, asked there and held there). Its key refused, the computer unreachable, or the key's own limit there (`keyLimited`'s 429, which carries `X-Magpie-Limit-Reset`, `remoteKeyLimitHeader`), still rests it whole: #2077's reporter had a Claude Code session limit on the other magpie refuse its Qoder models here (`TestRemoteMagpieRestsTheModel`, two gateways over HTTP; `TestRemoteMagpieKeyLimitRestsTheKey`). The held try keeps that marker only as a note of magpie's own (`keepRetry` sets `keyLimitThereHeader`, which `holdWriter` never passes on), so the rest is whole however the 429 came, and the marker never reaches the agent or a magpie this one answers, which would read it as this magpie's own key limit (#2791, ggbdpq; `TestRemoteMagpieKeyLimitRestsTheRemote`, `TestRemoteMagpieKeyLimitMarkerStaysHere`). A 400, 404, 410 or 422 that says the model is retired (`retiredWords`: OpenCode Zen's 410 `ModelDeprecated` "Model exo-free has been deprecated.", whose own model list still names it; MOMO on Discord) rests only that model the same way, is retryable so a group's next member or another provider of it is asked, and is remembered (`provider.Retire`, `retired.json` beside `providers.json`): the model leaves that provider's entries in the catalog (`buildEntries`), so /v1/models, every agent's model list and the found groups go without it, until a request on it is answered again (`Unretire` in `servedCandidate`) or a week has passed. A refresh of the vendor's list doesn't bring it back early, since that list is where it still is. A `provider/model` request for it is still sent. A 400 or 422 that says this upstream's API can't take the request's shape (`shapeWords`: xAI's 422 "unknown item type" (#350), OpenAI's "Unknown parameter", and a limit of a model's own on tool schemas, OpenCode Go's 400 "JSON schema exceeds the maximum nesting depth of 10 levels" on muse-spark-1.3-contributor, #1870), or that it is served on another API than the one asked (`wrongEndpoint`, once the member has tried every API it has a URL for: #2670, a relay with a Chat URL alone refusing tools with reasoning and `none` too), rests nobody: the next candidate is asked once (`shapeRefused`, `failShape`), and the last one's error reaches the agent. A request missing what every API requires ("field required") isn't one, nor is a 200 that mentions it. Command Code's Provider API turning a request away with nothing but a trace id (`unsaidWords`: `{"message":"invalid request error trace_id: <hex>","type":"invalid_request_error"}`, a 400, or a 422 before) is handled the same way: it turns away a request whose history and asked-for output together are over a limit below the model's listed context (the reporter's A/B: one ~748K-token agent conversation answered 200 with `max_completion_tokens` 64000 and this 400 with 384000, the model's listed max output), which another member's model may take, and the key is fine (#2313, `TestGroupFailsOverCommandCodesBare400`). Its overflow, which names the model's context length before the trace id, and an error that names a `param`, aren't one. A relay's own cap on one request's input that says so (`tooLongRe`: B.ai's 400 "Input token exceed the limit", on a 380K request under the model's 1M window; #2445, worksyang) is taken as an overflow (`overflowed`), which no word list of `retryable` matched: a group's next member that may hold the request is asked (`withRoom`, `failOverflow`), nobody rests, another account of the same model isn't asked, and with no member left the agent is told the conversation is too long, so it compacts. A rate limit worded with input tokens (`paceWords`) isn't one, and a plain bad request is still asked of nobody else (`TestRelayInputCapGoesToTheNextMember`). A subscription account that fails any other way with a window full, by magpie's latest reading of its windows, rests until that window renews. A 401 or 403 is the exception: one that names a quota is out of quota already (`usedUpWords`), and one that doesn't is about the key or the request, so it rests on the backoff ladder whatever the reading says (plugins#243, zygs1083-dotcom: a Factory account read at 98% sat out its week over one plain 403; `TestPlain403DoesNotRestUntilTheWindow`). A plain 403 (`plainForbidden`: no quota, credit, rate, verification, restriction or model not served) from a second key or account of the same provider, model and reasoning in one request is the request refused, not each account: neither rests, the first one's rest and counted failure are taken back (`forbiddenAlike`, `unforbid`), and the provider's other mates are asked last (`matesLast`). Before, that one request walked every account of the provider into backoff (`TestPlain403OnTwoMatesRestsNeither`). One account's plain 403 alone still rests it. Both quota rests and window rests are held to `longestQuota` (8 days), so a reset time read wrong (a year off) doesn't bench the account for that long. The next candidate is then tried. A failed provider waits `fallbackCooldown` (1 minute) at the back. A WorkBuddy account the vendor restricted (#1849: 403 `{"code":11140,"msg":"request illegal","displayMsg":{"en":"Your account has been restricted due to unusual activity",…}}`) rests `restrictedRest` (2 hours) as `restricted` (`failRestricted`), not the minutes of an unknown failure: only WorkBuddy lifting the restriction, after the user's appeal, brings it back. Both shapes are known: the built-in's `wbExplain` and the plugin's `explained()` (0.1.17, the mover's `min`) end the error with `provider.WBRestrictedHint` (`restrictedSaid`), and the vendor's own body, its code 11140 or its words (`provider.WBRestricted`), counts only from a WorkBuddy candidate (`restrictedRefused`, `isWorkBuddy`), as another vendor's 11140 is its own. Bare "request illegal" isn't matched. WorkBuddy's 11128 channel refusal stays `promptRefused` and rests nobody. The Routing page names it "account restricted by the vendor", says the appeal is the way back, and gives the account's row a button that lifts the rest (`/api/gateway/unrest`) once the vendor has. Every other rest a key or account takes (quota, rate limit, retry-after, a failure's backoff) can be lifted by hand the same way (#1869): "Try now" on its row on the Routing page and beside its rest note in the provider's key list. It ends the rest, and with Sink on puts the key back from the back of the order; the backoff count stays, and a refusal after it rests the key again the usual way. Every lift before its time (Try now, `UnrestAll` for a replaced key, `renewed` for windows that renewed) is noted by its rest key (`restingUntil.lifted`) and handed to the Routing page in the trace (`TraceState.Lifted`, `lifted` in `/api/gateway/trace`), and a lift wakes a page waiting on the trace though no route changed (`trace.lifted`). The page stops showing a rest or a sink found before its lift, wherever the lift was asked for (zoecats on Discord: Try now in the provider's editor left Routing at 429 until a restart; `TestTryNowToldToTheRoutingPage`, `routing-lifted-elsewhere.test.cjs`). With another magpie serving the gateway, Try now lifts nothing (#3555). The vendor's safety filter refusing a reply rests nobody, whether it refuses the turn before any of the reply is said or once some of it has been said (`refused`, `refusedAfter`). So does one said in a stream a client is answered whole from (a Codex account is streamed upstream for a `stream:false` Responses, Chat or Messages request): each decoder gives the refusal's error event status 400 and its code (`filterRefused`), a whole reply it cut is answered the refusal rather than its words so far, and Anthropic's error shape, which has no code, carries it in `refusedHeader`; before, it was answered 502 `api_error`, asked again, and each account rested (#3274). `restAfterMarked` itself rests nobody, and counts no failure, for a 400 whose error object `policyRefusal` reads as a refusal, by its code, never by words a body may echo of the request. Its note on the try (and in the error the agent gets when nobody is left) is the vendor's reason, with Anthropic's `stop_details` category and explanation when it gave them (`refusedDetail`, #1768: "safety filter: refusal (category cyber)"); none is made up when it gave none. `stop_details` is carried through the IR (`Event.StopDetails`), so a Claude subscription run through the claude CLI and a translated Anthropic route keep it for an Anthropic client too. How many more candidates a refusal before any of the reply is asked of is Settings' `RefusalRetries` (`refusalAsksAgain`, counted per request in the candidate loop; a group's other members count too): unset, every one left (#248); 0, none (#1925, DD on Discord). When nobody is left, an agent on Anthropic's Messages API gets the held refusal itself, the vendor's 200 with `stop_reason` `refusal` and its `stop_details`, streamed or whole (`holdWriter.handBack`), since that is what Claude Code switches to its fallback model on; a 400 is only an API error to it. Codex and Chat clients still get `failTo`'s 400 (`refusedStatus`), which they don't ask again for. `TestRefusalRetries*` in [`refusal_retries_test.go`](../../internal/gateway/refusal_retries_test.go) cover keys, a group and the Claude subscription. The ChatGPT backend's 502 "response protection is unavailable" is about the request's content, not the account: the same history fails the same on each of its accounts and models. It rests nobody, isn't tried again after a moment, and isn't asked of the provider's other accounts or models; another provider left in a group is asked once (`protectionRefused`, `elsewhere`). One cause is known (#1270): a history that replays the backend's own `web_search_call` in a request that doesn't declare the `web_search` tool is refused so, whatever the account, model or turn (a plain turn, a thread's description, a compaction, Codex's own text compaction for a custom provider with `tools: []`). Every request to the ChatGPT backend with such a history therefore declares cached-only search (`{"type":"web_search","external_web_access":false}`, `provider.DeclareSearch`): an account's in `codexBody`, Codex's own sign-in relayed in `codexUpstreamOn`. It goes in the tools, or for Responses Lite (its header, `reasoning.context` `all_turns`, or an `additional_tools` item already there), which refuses a top-level `web_search`, in the `additional_tools` item. A request that offered no tools gets `tool_choice` `none` so the model can't search; one with a forced choice keeps it. A history without a search, or a request that declares search already, is relayed unchanged; Codex's own `web.run` (a function in the `web` namespace, which Codex offers in place of the hosted tool on a Responses Lite model or with its standalone web search on, and runs through `/alpha/search`) counts as declaring it, since the backend refuses a request carrying both `web.run` and the hosted `web_search` (Savin on Discord, Codex 0.163.0-alpha; `TestSearchedConversationUnderWebRun`). siwc, API-key requests to openai.com and the legacy `/responses/compact` are left as they were. Command Code turning a model away for its Zero Data Retention setting (its plugin's switch, 0.1.14, which sends `x-cmd-zdr: 1`; magpie-community/plugins#246) is a refusal of that request's setting, not of the model or the account: the Provider API's 422 with `"code":"cmd_zdr_no_providers"` and the 400 the plugin makes of Go's error line with `"type":"cmd_zdr_no_providers"` (`zdrCoded`, matched as the error's code or type, never by its words, whose "…a different model.","type":"invalid_request_error" read as a model unserved and rested the model on the account). `keepRetry` notes it beside the error (`zdrHeader`), since the error the agent gets may keep no code (Anthropic's shape, or the 400's numeric code). It rests nobody, anywhere (`restAfterMarked` returns `by: "off"`), so the model answers as soon as the switch is off; it isn't asked of the provider's other accounts at that model, which carry the same header (`notMates`), nor again after a moment; another member, the provider's other models among them, is asked once, and with none left the agent gets Command Code's words (`TestCommandCodeZDRRefusalRestsNothing`, `TestZDRRefusalNeverRests`). Another vendor's refusal in the same words, without the code, still rests the model (`TestZDRRefusalIsCommandCodesCodeOnly`).5. The last candidate's error reaches the agent, with one exception for a group (#1418, `patience.go`), which a plain provider shares once its same-one retries are spent (below). When every member has failed in a way that passes (`busy`: 408, 500, 502, 503, 504 or 529 that isn't a proxy, a quota, response protection, or an upstream that answered a stream request with a whole reply, which fails the same however often it is asked (`didNotStream`; the same-one retries of `passing` leave it alone too, `TestStreamlessMemberIsAskedOnce`), or a 429 that is a short rate limit, not a plan or credit), and nothing of the reply has been sent, the members that failed so are asked again in turn after a pause (`replan`). The pause is `retryPause` doubled each round up to `replanLongest()` (30 times `retryPause`, 30s), and never shorter than the soonest Retry-After; a member whose Retry-After ends past the pause is asked after the others. This goes on while the group's `Patience` lasts. A member of a group in the group uses the innermost that sets `Patience` (`innerPatience`, #2410), as FirstToken (#2246) and Sink (#2255) do; unset falls back to the group asked for, and an inner `PatienceOff` skips replan for that member (`TestNestedGroupPatienceThroughOuter`, `TestNestedGroupPatienceInnerOff`, `TestNestedGroupPatienceFallsBackToOuter`). `replanRounds` (12) is only a backstop that never comes first: the pauses alone add up to `PatienceLongest` in 11 rounds (with 6, a group set to 240s gave up after 90s of pauses, real-jacket on #1418; `TestPatienceIsUsedUp`). The budget is the group's `Patience`, counted from the first time every member had failed, when the agent would have had the error (`waitFrom`; `Group.Waits`: 0 is `PatienceDefault`, 60s; -1, `PatienceOff`, turns it off; at most `PatienceLongest`, 240s). A pause that would end past the budget isn't taken, and the agent gets the error; a member the vendor said is back within a second past its budget (read in whole seconds) is asked as the budget ends (`TestReporterResetFitsTheDefaultPatience`). While another member is busy too, the last one isn't first tried again alone (`passing`): the members take turns, and once the budget has begun, the same-one retries aren't taken either. While the budget lasts, the last candidate's failure is held (`newHoldWriter`), and a streaming agent is kept alive through the pause with SSE comments (`pauseAlive`). The try is traced with `Again` (the pause), `Replan` (how many are asked again) and `Patience` (the budget in seconds). The group editor's "Every member busy" row sets it. A plain provider (a `provider/model` request, its accounts and fallbacks the candidates) first takes the same-one retries `passing` gives the last one left: `lastRetries` for a busy vendor, `rateRetries` for a rate limit, each pause `retryPause<<n` or a Retry-After of at most `longestPause` (8s). Past those, or for a Retry-After longer than `longestPause`, it is replanned the same way, its accounts taking turns as members do, for the provider's own `Patience` (`Provider.Patience`, the same values as a group's, set with `magpie provider set <id> patience=2m|off|default`; the provider editor shows no row for it and its save keeps it, `TestProviderSaveKeepsPatience`), unset `singlePatience` (`PatienceDefault`, 60s), counted from when the agent would have had the error, so it works with no setting and the user's value wins either way (`TestSingleProviderOwnPatienceWins`; ChatGPT's reset of a large request, `codexReset`, is left out: Codex is told it at its 503 with what may help, as `codexBusy` leaves it). A provider's own Patience is for a request to it alone: a group it is in, set or unset, keeps the group's (zoecats on Discord: a local relay's short 429 went straight to Claude Code once the few retries were spent). So a 429 whose Retry-After is 20s is waited out, the stream kept alive past `keepHeldAfter`; one of an hour, a quota, credit or plan limit, a 401 or 403, a refusal, response protection's 502 and `didNotStream` are not `busy` or don't fit the budget, and reach the agent at once as the vendor said them. Its tries are traced with `Again` alone, no `Replan` or `Patience`, so the Routing page tells it as the last one left asked again rather than as a group's members (`TestSingleProviderWaitsOutAShortRateLimit`, `TestSingleProviderPassesALongLimitThrough`, `TestSingleProviderAgentGoneInTheWait` in [`single_busy_test.go`](../../internal/gateway/single_busy_test.go)). Codex's own one-account relay (`codexUpstreamOn`, below) doesn't join it: its request is relayed unchanged outside the candidate loop, and the backend's 429 is always the plan's usage limit (`codexBusy` never retries one), so the short rate limit this waits out doesn't arise there; its overloads keep their `lastRetries` and then the subscription's fallbacks. An agent that goes away in either pause (the same-one retry's or a group's replan) ends the request there with 499: nobody is asked again, and the try whose pause it was is marked `Gone` (#1894, heng91: a relay down while its proxy was off, the agent's window closed). The Routing page says the agent canceled the request before the retry and lists it as canceled, rather than ending its story on "tried again in 2s", a retry that never came (`TestAgentGoneInTheRetryPause`, `routing-agent-gone.test.cjs`). A try that answered is recorded (`served`, `answered`) for routing, affinity and usage. A try is added to the route's `Tries` only as it is asked, so a later try is the record that the gateway went on from this one, and the Routing page tells what came of a try from that, never from where it stood in the order (#2281, xishuchkui-code: an Antigravity 502 empty reply that went on to the next account was told as "an error another account wouldn't fix, so Claude Code gets it"). The one case the record can't show is the last try left out of its allowance after an earlier failure that wasn't one, where the agent is told the earlier error: that try is marked `Earlier` (`routing-went-on.test.cjs`).diff --git a/internal/cli/quota_cli.go b/internal/cli/quota_cli.goindex 8a37e72f5..b7138e5d0 100644--- a/internal/cli/quota_cli.go+++ b/internal/cli/quota_cli.go@@ -32,8 +32,8 @@ const quotaUsage = `usage: magpie quota [<provider>…] [--json]starting the account's current windows again (the one Codex is signed in to unlessnamed). It can't be undone, so it asks first; --yes doesn't. quota auto-reset on letsthe account spend one by itself when its weekly window is used up and no other- account can take a request, one a week at most (the five hours running out never- does), and spend the one about to expire about half an hour before it does, if+ account can take a request, or before a request goes on its credits, one a week+ at most (the five hours running out never does), and spend the one about to expire about half an hour before it does, ifthe account's windows have been used, so what they have left can be used untilthen and it isn't lost; at once when the account is held up until after then.week on|off or expiring on|off turns only one of those two times on or off, the@@ -47,7 +47,7 @@ const quotaUsage = `usage: magpie quota [<provider>…] [--json]goes to the other accounts, groups and fallbacks, or is refused with why (withauto-reset on, its week used up and no one else left, it spends a reset first).on, the default, lets the vendor answer on its credits then, so the task goes- on; alone it says which accounts don't spend theirs.+ on (with auto-reset's week on, a reset held is spent before the credits); alone it says which accounts don't spend theirs.quota alert 80 has the magpie app notify when any window of a subscription or planreaches 80% used, once each time the window runs (not windows set aside, such ason-demand spending); --balance 5 when a balance falls to 5 or under, in its own@@ -316,9 +316,9 @@ func quotaAutoResetCmd(args []string) error {}switch week, expiring := provider.CodexAutoResetWhen(user); {case week && expiring:- fmt.Println(green.Render("✓"), user+":", "uses a reset by itself once its week is used up and no other account can answer, one a week at most, and the one about to expire half an hour before it does, or at once when held up past then")+ fmt.Println(green.Render("✓"), user+":", "uses a reset by itself once its week is used up and no other account can answer, or before its credits are spent, one a week at most, and the one about to expire half an hour before it does, or at once when held up past then")case week:- fmt.Println(green.Render("✓"), user+":", "uses a reset by itself once its week is used up and no other account can answer, one a week at most; one about to expire is left to run out")+ fmt.Println(green.Render("✓"), user+":", "uses a reset by itself once its week is used up and no other account can answer, or before its credits are spent, one a week at most; one about to expire is left to run out")case expiring:fmt.Println(green.Render("✓"), user+":", "uses the reset about to expire half an hour before it does, or at once when held up past then; a week used up is waited out")default:diff --git a/internal/gateway/codex_autoreset.go b/internal/gateway/codex_autoreset.goindex 88680b6ba..1b05c8055 100644--- a/internal/gateway/codex_autoreset.go+++ b/internal/gateway/codex_autoreset.go@@ -98,3 +98,48 @@ func unhold(order, left []Weighed, c candidate) ([]Weighed, []Weighed) {w.Unlisted, w.Capped, w.CapBack, w.NoCredits = false, 0, nil, falsereturn append(slices.Clip(order), w), slices.Delete(slices.Clone(left), i, i+1)}++// resetBeforeCredits spends one of c's resets before a request goes to it+// on its credits (tongzhenbao on X): a Codex account set to spend one by+// itself when its week runs out, its week used up by its last reading,+// and let spend its credits. ChatGPT answers such an account on its+// credits, so it never refuses it as out of its allowance, and autoReset,+// which runs on that refusal, never ran: the week's reset was left+// unspent while the credits were. A reset is free and credits cost money,+// so the reset goes first; once none is held, or the week's one is spent,+// the credits go on as before. AutoUseCodexReset reads the week again+// before spending, one a week at most.+func (s *Server) resetBeforeCredits(ctx context.Context, c candidate) (provider.ResetOutcome, bool) {+ a := c.p.Account+ if a == nil || a.User == "" || !provider.AutoResetsWeek(a.Agent, a.User) {+ return provider.ResetOutcome{}, false+ }+ if al, ok := c.allowance(); !ok || !spendsCredits(c.p, al) || !al.WeekUsedUp(time.Now()) {+ return provider.ResetOutcome{}, false+ }+ out, ok := autoResetOf(ctx, a.Agent, a.User)+ if ok {+ s.Unrest(c.restKey())+ }+ return out, ok+}++// resetBeforeCreditsOn is resetBeforeCredits for a turn relayed on on, or+// on Codex's own sign-in when on is nil; who is the account.+func (s *Server) resetBeforeCreditsOn(ctx context.Context, on *provider.Provider) (who string, out provider.ResetOutcome, ok bool) {+ if on != nil {+ if on.Account == nil {+ return "", provider.ResetOutcome{}, false+ }+ out, ok = s.resetBeforeCredits(ctx, candidate{p: *on, rest: on.ID})+ return on.Account.User, out, ok+ }+ who, signed := provider.CodexSignedIn()+ if !signed || !provider.AutoResetsWeek("codex", who) || !relayOnCredits(nil) || !allowances("codex")[who].WeekUsedUp(time.Now()) {+ return "", provider.ResetOutcome{}, false+ }+ if out, ok = autoResetOf(ctx, "codex", who); ok {+ s.Unrest("codex@" + strings.ToLower(who))+ }+ return who, out, ok+}diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.goindex 167fb9c7c..698279585 100644--- a/internal/gateway/codex_backend.go+++ b/internal/gateway/codex_backend.go@@ -1084,6 +1084,16 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st}var sniff *usageSniffervar refusal []byte // what OpenAI said, of a request it turned away+ if rest == "/responses" && base != codexAPIBase {+ // the account goes on its credits, its week used up: a reset it+ // spends by itself when the week runs out goes first+ // (resetBeforeCredits)+ if who, out, ok := s.resetBeforeCreditsOn(r.Context(), on); ok {+ autoReset = true+ s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1].Reset = &AutoReset{Who: who, Text: out.Text()} })+ resetNote = "openai (" + who + "): used one of its resets by itself before its credits (" + out.Text() + ")"+ }+ }for {// the try's own, which a stream that failed before its reply ends// (holdWriter.stop)diff --git a/internal/gateway/codex_reset_before_credits_test.go b/internal/gateway/codex_reset_before_credits_test.gonew file mode 100644index 000000000..48ce94c90--- /dev/null+++ b/internal/gateway/codex_reset_before_credits_test.go@@ -0,0 +1,99 @@+package gateway++import (+ "strings"+ "testing"++ "github.com/yetone/magpie/internal/provider"+)++// tongzhenbao on X: a Codex account set to spend a reset by itself when+// its week runs out (that switch alone on), its week used up, holding a+// reset that runs out after the week starts again, and let spend its+// credits. ChatGPT answers it on its credits, so nothing refuses it as out+// of its allowance, and the reset was never spent while ~10k credits were.+// The reset is spent before the turn goes on the credits, once a week;+// with the week's switch off, the turn goes on the credits as before.+func TestCodexResetBeforeCredits(t *testing.T) {+ reporter := func(t *testing.T, b *resetBackend, user, acct string) {+ t.Helper()+ // answers all the same, on its credits; the reset held runs out+ // 20 days on, past the week's own reset 3 days on+ b.credits[acct] = true+ if err := provider.SetCodexAutoResetCase(user, provider.ResetCaseWeek, true); err != nil {+ t.Fatal(err)+ }+ if w, e := provider.CodexAutoResetWhen(user); !w || e {+ t.Fatalf("set week only: week %v expiring %v", w, e)+ }+ }+ t.Run("relayed", func(t *testing.T) {+ codexSignedIn(t)+ b := newResetBackend(t, "acct-1")+ creditsUsage(t, map[string]float64{"[email protected]": 100}, "[email protected]")+ reporter(t, b, "[email protected]", "acct-1")+ srv := New()+ code, body := resetPost(t, srv)+ if tried, spent := b.seen(); code != 200 || !strings.Contains(body, "pong") || tried != "acct-1" || spent != "acct-1" {+ t.Fatalf("%d %s tried %q spent %q", code, body, tried, spent)+ }+ if got := resetsTraced(srv); len(got) != 1 || got[0] != "[email protected]: 2 windows started again" {+ t.Fatalf("traced %v", got)+ }+ if calls := srv.Recent(); len(calls) == 0 || !strings.Contains(calls[0].Fallback, "before its credits") {+ t.Fatalf("request log %+v", calls)+ }+ // used up again in the same week: the credits go on, no second reset+ b.mu.Lock()+ b.out["acct-1"], b.week["acct-1"], b.held["acct-1"] = true, 100, 1+ b.mu.Unlock()+ if code, _ := resetPost(t, srv); code != 200 {+ t.Fatalf("second time in the week: %d", code)+ }+ if _, spent := b.seen(); spent != "acct-1" {+ t.Fatalf("second time in the week spent %q", spent)+ }+ })+ t.Run("routed", func(t *testing.T) {+ codexSignedIn(t, "[email protected]")+ b := newResetBackend(t, "acct-1", "acct-2")+ b.held["acct-2"] = 0+ // spare used up with no credits: benched, never asked+ creditsUsage(t, map[string]float64{"[email protected]": 100, "[email protected]": 100}, "[email protected]")+ reporter(t, b, "[email protected]", "acct-1")+ srv := New()+ code, body := resetPost(t, srv)+ if tried, spent := b.seen(); code != 200 || !strings.Contains(body, "pong") || tried != "acct-1" || spent != "acct-1" {+ t.Fatalf("%d %s tried %q spent %q", code, body, tried, spent)+ }+ if got := resetsTraced(srv); len(got) != 1 || got[0] != "[email protected]: 2 windows started again" {+ t.Fatalf("traced %v", got)+ }+ })+ t.Run("week's switch off", func(t *testing.T) {+ codexSignedIn(t)+ b := newResetBackend(t, "acct-1")+ b.credits["acct-1"] = true+ creditsUsage(t, map[string]float64{"[email protected]": 100}, "[email protected]")+ if err := provider.SetCodexAutoResetCase("[email protected]", provider.ResetCaseExpiring, true); err != nil {+ t.Fatal(err)+ }+ code, _ := resetPost(t, New())+ if tried, spent := b.seen(); code != 200 || tried != "acct-1" || spent != "" {+ t.Fatalf("%d tried %q spent %q", code, tried, spent)+ }+ })+ t.Run("week not used up", func(t *testing.T) {+ codexSignedIn(t)+ b := newResetBackend(t)+ b.week["acct-1"], b.held["acct-1"], b.credits["acct-1"] = 60, 1, true+ creditsUsage(t, map[string]float64{"[email protected]": 60}, "[email protected]")+ if err := provider.SetCodexAutoResetCase("[email protected]", provider.ResetCaseWeek, true); err != nil {+ t.Fatal(err)+ }+ code, _ := resetPost(t, New())+ if tried, spent := b.seen(); code != 200 || tried != "acct-1" || spent != "" {+ t.Fatalf("%d tried %q spent %q", code, tried, spent)+ }+ })+}diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.goindex 19cf25520..21dd49db9 100644--- a/internal/gateway/gateway.go+++ b/internal/gateway/gateway.go@@ -2637,6 +2637,15 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Procands = cands[:i+1]}}+ if !autoReset && c.onCredits() {+ // going to the account on its credits, its week used up: a+ // reset it spends by itself when the week runs out goes+ // first (resetBeforeCredits)+ if out, ok := s.resetBeforeCredits(r.Context(), c); ok {+ autoReset = true+ resetFirst = &AutoReset{Who: c.p.Account.User, Text: out.Text(), Agent: c.p.Account.Agent}+ }+ }last := i == len(cands)-1// the last one's failure is held too when an earlier one failed,// for its allowance running out to be told as that one's errordiff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.jsindex 4fb7a536d..b4df27501 100644--- a/internal/gui/assets/app.js+++ b/internal/gui/assets/app.js@@ -17385,10 +17385,12 @@ function resetsWords(r, q) {w.title = r.each?.length ? resetsEach(r) : t("The first runs out {when}", { when: at.toLocaleString(intlLang()) });// whether the one that runs out first is kept from going to waste:// with Auto-use on it is used shortly before it does (#624, #719)+ // or, the week's alone, when the week runs out (tongzhenbao on X)if (q && autoResetKept(q)) {- const on = autoResetWhen(q).expiring;- w.append(el("span", "resets-kept" + (on ? " on" : ""), " · " + t(on ? "auto-used before it expires" : "not auto-used")));- w.title += "\n" + t(on ? "Auto-use is on: the reset that runs out first is used about half an hour before it does, if this account's windows have been used, so what they have left can be used until then and it isn't lost; at once if the account is held up until after then."+ const { expiring: x, week } = autoResetWhen(q);+ w.append(el("span", "resets-kept" + (x || week ? " on" : ""), " · " + t(x ? "auto-used before it expires" : week ? "auto-used when the week runs out" : "not auto-used")));+ w.title += "\n" + t(x ? "Auto-use is on: the reset that runs out first is used about half an hour before it does, if this account's windows have been used, so what they have left can be used until then and it isn't lost; at once if the account is held up until after then."+ : week ? "Auto-use is on for a used-up week: a reset is used by itself when this account's week is used up, before its credits are spent. One about to run out is otherwise lost unless it's used by hand or the week runs out before then.": "Auto-use is off: the reset that runs out first is lost unless it's used by hand before then.");}} else if (r.each?.length) w.title = resetsEach(r);diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.jsindex e1c2566a3..b7935d554 100644--- a/internal/gui/assets/i18n.js+++ b/internal/gui/assets/i18n.js@@ -2042,6 +2042,8 @@ const I18N = {"Auto-use: on": "自动用卡:开","Auto-use: off": "自动用卡:关","auto-used before it expires": "到期前自动使用",+ "auto-used when the week runs out": "周额度用完时自动使用",+ "Auto-use is on for a used-up week: a reset is used by itself when this account's week is used up, before its credits are spent. One about to run out is otherwise lost unless it's used by hand or the week runs out before then.": "自动使用已开启(周额度用完时):本账号周额度用完时自动用一张重置卡,先于积分扣费。快到期的卡若未手动使用、也没等到周额度用完,将作废。","Last reset used: {when} · {why}": "上次用卡:{when} · {why}","by itself, its week used up": "自动,周额度用完","by itself, before it expired": "自动,重置卡到期前",@@ -6097,6 +6099,8 @@ const I18N = {"Auto-use: on": "自動用卡:開","Auto-use: off": "自動用卡:關","auto-used before it expires": "到期前自動使用",+ "auto-used when the week runs out": "週額度用完時自動使用",+ "Auto-use is on for a used-up week: a reset is used by itself when this account's week is used up, before its credits are spent. One about to run out is otherwise lost unless it's used by hand or the week runs out before then.": "自動使用已開啟(週額度用完時):本帳號週額度用完時自動用一張重置卡,先於積分扣費。快到期的卡若未手動使用、也沒等到週額度用完,將作廢。","Last reset used: {when} · {why}": "上次用卡:{when} · {why}","by itself, its week used up": "自動,週額度用完","by itself, before it expired": "自動,重置卡到期前",@@ -10129,6 +10133,8 @@ const I18N = {"Auto-use: on": "自動使用:オン","Auto-use: off": "自動使用:オフ","auto-used before it expires": "期限切れ前に自動使用",+ "auto-used when the week runs out": "週の枠を使い切ったら自動使用",+ "Auto-use is on for a used-up week: a reset is used by itself when this account's week is used up, before its credits are spent. One about to run out is otherwise lost unless it's used by hand or the week runs out before then.": "自動使用はオン(週の枠を使い切ったとき):このアカウントの週の枠を使い切ると、クレジットを使う前にリセットを自動で使います。期限が近いリセットは、手動で使うか、それまでに週の枠を使い切らなければ失われます。","Last reset used: {when} · {why}": "前回のリセット使用:{when} · {why}","by itself, its week used up": "自動(週の枠を使い切ったため)","by itself, before it expired": "自動(期限切れの前)",@@ -14191,6 +14197,8 @@ const I18N = {"Auto-use: on": "Automatisch: an","Auto-use: off": "Automatisch: aus","auto-used before it expires": "wird vor Ablauf automatisch eingelöst",+ "auto-used when the week runs out": "wird eingelöst, wenn die Woche aufgebraucht ist",+ "Auto-use is on for a used-up week: a reset is used by itself when this account's week is used up, before its credits are spent. One about to run out is otherwise lost unless it's used by hand or the week runs out before then.": "Automatisches Einlösen ist an, wenn die Woche aufgebraucht ist: Ist die Woche dieses Kontos aufgebraucht, wird ein Reset eingelöst, bevor Credits verbraucht werden. Ein bald ablaufender verfällt sonst, sofern er nicht von Hand eingelöst wird oder die Woche vorher aufgebraucht ist.","Last reset used: {when} · {why}": "Zuletzt Reset eingelöst: {when} · {why}","by itself, its week used up": "automatisch, Woche aufgebraucht","by itself, before it expired": "automatisch, vor dem Ablauf",diff --git a/internal/gui/tests/codex-auto-reset.test.cjs b/internal/gui/tests/codex-auto-reset.test.cjsindex 3cea4f6ef..5a9b7d637 100644--- a/internal/gui/tests/codex-auto-reset.test.cjs+++ b/internal/gui/tests/codex-auto-reset.test.cjs@@ -80,7 +80,7 @@ function serve(lang, posts) {const words = {en: {say: "Auto-use resets:", week: "when its week runs out", expiry: "before one expires",- keptOn: "· auto-used before it expires", keptOff: "· not auto-used",+ keptOn: "· auto-used before it expires", keptOff: "· not auto-used", keptWeek: "· auto-used when the week runs out",brief: "Auto-use", label: "Auto-use resets", on: "On", off: "Off",both: (who) => `${who} uses a reset by itself when its week runs out, or before one expires`,weekOnly: (who) => `${who} uses a reset by itself only when its week runs out`,@@ -90,7 +90,7 @@ const words = {},zh: {say: "自动使用重置卡:", week: "周额度用完时", expiry: "重置卡到期前",- keptOn: "· 到期前自动使用", keptOff: "· 不会自动使用",+ keptOn: "· 到期前自动使用", keptOff: "· 不会自动使用", keptWeek: "· 周额度用完时自动使用",brief: "自动用卡", label: "自动使用重置卡", on: "开启", off: "关闭",both: (who) => `${who} 会在周额度用完时、或重置卡到期前自动使用重置卡`,weekOnly: (who) => `${who} 仅在周额度用完时自动使用重置卡`,@@ -101,7 +101,7 @@ const words = {};const keys = {say: "Auto-use resets:", week: "when its week runs out", expiry: "before one expires",- keptOn: "auto-used before it expires", keptOff: "not auto-used", brief: "Auto-use", label: "Auto-use resets", on: "On", off: "Off",+ keptOn: "auto-used before it expires", keptOff: "not auto-used", keptWeek: "auto-used when the week runs out", brief: "Auto-use", label: "Auto-use resets", on: "On", off: "Off",both: "{who} uses a reset by itself when its week runs out, or before one expires",weekOnly: "{who} uses a reset by itself only when its week runs out",expiryOnly: "{who} uses a reset by itself only before one expires",@@ -116,6 +116,7 @@ const strings = ["Off: a reset that runs out unused is lost. Click to turn it on.","Auto-use is on: the reset that runs out first is used about half an hour before it does, if this account's windows have been used, so what they have left can be used until then and it isn't lost; at once if the account is held up until after then.","Auto-use is off: the reset that runs out first is lost unless it's used by hand before then.",+ "Auto-use is on for a used-up week: a reset is used by itself when this account's week is used up, before its credits are spent. One about to run out is otherwise lost unless it's used by hand or the week runs out before then.","On: a reset is used by itself when this account's week is used up and no other account can answer, one a week at most, and the one about to run out is used about half an hour before it does, if the account has been used, or at once when the account is held up until after then. Otherwise the five hours running out never uses one. Click to turn it off.","Off: this account's resets are used only by hand. Turned on, one is used by itself when its week is used up and no other account can answer, one a week at most, and the one about to run out about half an hour before it does, if the account has been used, or at once when the account is held up until after then. Otherwise the five hours running out never uses one.",];@@ -124,7 +125,7 @@ async function wordsOf(page, lang) {if (words[lang]) return words[lang];const d = await page.evaluate(([lang, keys]) => Object.fromEntries(Object.entries(keys).map(([k, v]) => [k, I18N[lang][v]])), [lang, keys]);const fill = (s) => (who) => s.replace("{who}", who);- return { ...d, keptOn: "· " + d.keptOn, keptOff: "· " + d.keptOff, both: fill(d.both), weekOnly: fill(d.weekOnly), expiryOnly: fill(d.expiryOnly), none: fill(d.none) };+ return { ...d, keptOn: "· " + d.keptOn, keptOff: "· " + d.keptOff, keptWeek: "· " + d.keptWeek, both: fill(d.both), weekOnly: fill(d.weekOnly), expiryOnly: fill(d.expiryOnly), none: fill(d.none) };}for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {@@ -266,7 +267,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",assert.equal((await panel.locator(".pq-resets button").textContent()).trim(), w.useOne);assert.equal((await panel.locator(".pq-resets .resets-kept").textContent()).trim(), w.keptOff);await flip(panel, week(psel), panelPosts, { user: "[email protected]", on: true, when: "week" }, true, w.weekOnly("[email protected]"));- assert.equal((await panel.locator(".pq-resets .resets-kept").textContent()).trim(), w.keptOff, "the week alone doesn't keep the one about to expire");+ // the week alone (tongzhenbao on X): the card says it is used when+ // the week runs out, not "not auto-used" beside that switch on+ assert.equal((await panel.locator(".pq-resets .resets-kept").textContent()).trim(), w.keptWeek, "the week alone says the reset is used when the week runs out");+ assert.equal(await panel.locator(".pq-resets .resets-kept").evaluate((e) => e.classList.contains("on")), true);await flip(panel, expiry(psel), panelPosts, { user: "[email protected]", on: true, when: "expiring" }, true, w.both("[email protected]"));assert.equal((await panel.locator(".pq-resets .resets-kept").textContent()).trim(), w.keptOn);// the switches and their words fit the card: none of it cut off or widerdiff --git a/internal/provider/routing.go b/internal/provider/routing.goindex 8fd04d0f0..49de3640a 100644--- a/internal/provider/routing.go+++ b/internal/provider/routing.go@@ -235,6 +235,18 @@ func (a Allowance) OnCredits() bool {return false}+// WeekUsedUp says whether the allowance's week, a window of a day or more+// that counts every model, is used up at now, as its last reading says:+// weekUsedUp's rule (AutoUseCodexReset) on an allowance, credits or none.+func (a Allowance) WeekUsedUp(now time.Time) bool {+ for _, l := range a {+ if l.Span >= 24*time.Hour && l.Model == "" && l.matches == nil && l.Used >= 100 && l.Resets.After(now) {+ return true+ }+ }+ return false+}+// Restarts is when an auto-used reset starts the account's windows again,// as the Codex reset about to run out is spent (expiringResetSpent):// resetExpiryLead before it runs out, or now when the account is held up