routing: a provider set to Use first goes ahead of the others Smart weighs it with
hzh_1119 on Discord: ChatGPT Pro and Business now come with monthly API credit, and they want an OpenAI API key spent before the ChatGPT subscription where both serve a model, the subscription taking over after. Smart had no way to say so: an API key tells no allowance, so it went after every account with room, in every model's found group (auto/<model>). The only way round was a group set to In order with its members dragged, one group at a time, which nothing pointed to. A provider row's right-click has Use first (provider/usefirst, provider.SetUseFirst, Provider.UseFirst, copied onto its accounts by accountSettings, kept by the editor's Save). Its keys and accounts are routes.Seat.Lead, and Smart (leadFirst) puts those not all but used up ahead of every other seat, each side in Smart's own order. A resting one is passed over as before, so a 429 insufficient_quota (out of credit) or a failure moves the request on to the subscription. Off by default; within one provider nothing changes. The Routing page says why the first went first (Weighed.UseFirst, firstWhy) and doesn't call the one behind it "renewing later" (behindWhy). The menu shows a tick when it is on. Free quota by expiry orders its paid seats with Smart and so follows it; other strategies don't read it. The core's script budget is met by cutting three Providers-page comments in app.js, no raise. Run (on mote via mote-run, atda548b454= origin/main): - go test ./internal/routes ./internal/provider: ok. ./internal/gui: ok but TestMainWindowCorners/macOS_26_SDK, red the same on a fresh origin/mainda548b454checkout (#3949, macOS 27). - go test -run 'TestUseFirstLeadsTheGroup|TestRoutingGroups' ./internal/gateway: ok. - node --test use-first.test.cjs (new: 40 cases, Chromium and WebKit, 1100 and 420 wide, en zh zh-TW ja de) and provider-find.test.cjs (its menu now lists Use first): 52 pass. - i18n-keys, i18n-en-no-cjk, routing-behind-why: pass but i18n-keys' "a plugin's words are its own", red the same on origin/main (#5327, #5426, #5482; none of its keys are this change's). - GOOS=linux and GOOS=windows go vet -tags nogui ./...: ok. gofmt -l: none. Broken by hand: - Lead left out of weighRouted's seat: TestUseFirstLeadsTheGroup red (served from ksub with api set to Use first). - Smart without leadFirst: TestSmartLeadFirst red ([plus pro api ...], want api first). - firstWhy's Use first case off: use-first.test.cjs's Routing cases red in every language. Not tried: a real ChatGPT account beside a real OpenAI key with API credit; the 429 insufficient_quota fallthrough is from the fake vendor's body (carriedQuotaBody). The full suite runs after the push. Reported-by: hzh_1119
This commit is contained in:
@@ -232,6 +232,7 @@ recorded as a prediction failure (`noPrediction`).
|
||||
- A ChatGPT account that holds credits answers past its windows on them; the vendor spends them. That is the default. Set not to spend them (Usage card's *Use credits*, `magpie quota credits <account> off`), the account is held at 100% of a window till it renews, by magpie's latest reading of its windows (`provider.Allowances`, refreshed about every minute), so the other accounts, groups and fallbacks take the request. A cap set on the account (1–99%) takes precedence. Unlike a cap, the hold is at the vendor's own 100%, so an account allowed to spend its resets spends one there, both when every candidate is held and after the last one is refused. A reset made forgets the account's cached allowance (`renewedNow`), so neither hold outlives the windows it started again. One let spend its credits, and holding some by its last `/wham/usage` (`credits.has_credits` with a balance over 0, or `unlimited`; `QuotaWindow.Credits`, `Limit.Credits`, `Allowance.OnCredits`), is not out when a window fills (豆子 and Zhenzhen on Discord): ChatGPT may answer the turn that uses the window up 429 `usage_limit_reached` before it spends the credits, and the next turn on them. So that 429 is asked again at once, once a request, on the same account, before a reset is looked at, on the routed path (`creditsAgain`, `creditsAsked`, `Try.Credits`) and on Codex's own sign-in's relay (`relayOnCredits`), rather than ended for the agent, which ended a running session while a new one worked. Refused again, it rests `fallbackCooldown` (`Rest.By` `credits`) and is read again, not until its window renews, and its full windows rest it nowhere else (`full` is zero for it, `spendsCredits`). Smart, Pace and Least used put such an account first of the spent tier (`routes.Seat.Credits`, `spentBefore`): after those with allowance left, ahead of those used up with nothing to go on with (`Weighed.Credits`, told on the Routing page). Switching to credits early, at a few percent left, was weighed and not done: the vendor spends credits only once the allowance is used up, so it would only waste what is left. `TestCodexCreditsAskedAgainAtTheEdge`, `TestCodexCreditsNoLongRest`, `TestCodexCreditsFirstOfTheSpent`, `TestCreditsFirstOfTheSpent`, `routing-codex-credits-again.test.cjs`.
|
||||
- A third way, set per account, spends the credits only after everything else (gokoshiki on Discord: a Codex subscription, then an OpenAI API key, then the subscription's credits): *Only after every other account, key and fallback* under the Usage card's *Use credits*, `magpie quota credits <account> last`, `settings.CodexCreditsLast` (`provider.CodexCreditsLast`, `SetCodexCreditsMode`; on or off clears it, and an account never in it keeps its place, so a setting saved before keeps its order). Such an account is `creditsLast` while it goes on on its credits (`spendsCredits`) and a window for the model is used up where *off* would hold it (`Allowance.CapHeld` at `WindowCaps{Credits: true}`; a call ChatGPT counts in no window, `freeOnChatGPT`, stays). `restLast` then puts it behind every candidate of the plan, the provider's fallbacks and groups included: ready, then resting, then the credits-last ones in their own order (`Weighed.CreditsLast`). Affinity doesn't keep a conversation on one while one not on its credits leads (`Affinity.Why` `credits`, `lastBehind`), within a turn too, and In turn's next pick and Smart/Pace/Least used's spreading of new sessions never bring one forward (`after`, `leastHeld`, `readyForNew`). Strict affinity keeps it, as a rule, an `X-Magpie-Account` pin and a sealed task's lead (`leadFirst`) still put theirs first. A reset is still spent before its credits when the try reaches it (`resetBeforeCredits`). Codex's own sign-in's relay has the one account and nothing to put first, so there it is as *on*. The Routing page tells each: behind the rest, first when every one is, and the conversation moved. `TestCodexCreditsLastAfterTheOthers`, `TestCodexCreditsLastAfterTheFallback`, `TestCodexCreditsLastNotKept`, `TestCodexCreditsLastMode`, `codex-credits-last.test.cjs`.
|
||||
- A fourth, set per account, spends the credits before moving to another account (jojonas_xyz on X: the account ran out, magpie moved to another by itself, and no setting kept the first one's credits in use). *On* alone lets the vendor answer on credits, but Smart and Pace still put an account at `LowShare` (90%) or `SpentShare` (98%) behind every account with room (`tier`), Drain counts it used up at `SpentShareOf(Drain)`, and `NextLogin` moves Codex's own sign-in at the spent share, credits or not. *Before moving to another account* under *Use credits* (the Usage card, the menu bar panel, and the account's ⋯ in its provider's editor), `magpie quota credits <account> first`, `settings.CodexCreditsFirst` (`provider.CodexCreditsFirst`; one of first and last at most, on or off clears it) makes an account that spends credits (`spendsCredits`) a `routes.Seat.First`: Smart, Pace and Fastest weigh it at tier 0 (`seatTier`), Drain doesn't count it spent, affinity doesn't move a conversation off it as `spent`, and `readyForNew`/`standsInFor` treat it as having room (`Weighed.CreditsFirst`). `NextLogin` keeps Codex signed in to it while one of its windows says it holds credits (`spendsFirst`); with the credits gone it moves as before. The account magpie moved Codex off says where the setting is, on its *First again once it has room* tag. `TestCodexCreditsFirstKeepsItsPlace`, `TestCodexCreditsFirstDrainStays`, `TestCodexCreditsFirstMode`, `TestCodexStaysOnAnAccountSpendingCreditsFirst`, `codex-credits-first.test.cjs`.
|
||||
- A provider can be set to be used first (hzh_1119 on Discord: ChatGPT Pro and Business come with monthly API credit, to be spent on an OpenAI API key before the subscription where both serve a model). *Use first* on a provider row's right-click (GUI `provider/usefirst`, `provider.SetUseFirst`, `Provider.UseFirst`, copied onto its accounts by `accountSettings`) makes its keys and accounts `routes.Seat.Lead`, and Smart (`leadFirst`) puts those under the spent tier (`seatTier` below 2) ahead of every other seat it weighs, each side in Smart's own order. Without it an API key, which tells no allowance, goes after every account with room. It counts where Smart weighs several providers together: a model's found group (`auto/<model>`) or a user's group routed Smart; within one provider every seat shares it, so nothing changes. One resting is passed over as any is, so a 429 `insufficient_quota` (out of credit, a half-hour rest) or a failure moves the request on to the others. Free quota by expiry orders its paid seats with Smart and so honours it too; the other strategies don't read it. Affinity still keeps a conversation on the one that answered it. The Routing page says why (`Weighed.UseFirst`, `firstWhy`), and `behindWhy` doesn't call one behind it renewing later. `TestSmartLeadFirst`, `TestUseFirstLeadsTheGroup`, `use-first.test.cjs`.
|
||||
- Different failures are classified separately: out of credit, out of quota, rate limit and other errors rest for different lengths. A fix must not merge them into one bucket (see #873).
|
||||
- A refusal of where the request comes from (`regionWords`: Google's 400 "User location is not supported for the API use.", as Antigravity and Code Assist pass it on, and OpenAI's `unsupported_country_region_territory` / "Country, region, or territory not supported"; `regionRefused`) is the network's and the edge's the connection reached, not the account's. It rests no account and counts no failure (`restAfterMarked` returns `Rest.By` `off`, `Until` now), and the next try goes out on a new connection: `regionFresh` (in `upstreamTransport`, around each of its three transports, so under every request the gateway sends through `s.client`) reads the head of each failed reply, and when it matches it closes the transport's idle connections as the body closes and again before the next request (`pending`), so the HTTP/2 or keep-alive connection that drew the refusal isn't reused. The last candidate is asked again after `retryPause` (`passing`). Refused a second time for the same provider and model within a request (`regionAsked` in the serve loop), it is the place, not a connection: Google serves some models to no request from where the user is while the same account's other models answer (taoxiaoxin, #5182: Antigravity's gemini-3.8-flash refused, its Claude models answered). Then none of the provider's other accounts is asked that model (`notMates`), the last isn't asked again (`protected`), another provider or model left is, and the agent is told the vendor's words with `regionNote` (through `explained`, beside `Provider.Explain`): the vendor doesn't serve that model to requests from that region, it is no account's fault, other models may answer, and a proxy in a served region or another provider gets past it. So a refused model costs two asks a request, not one per account and retries. Before, every Antigravity account was asked on the one kept-alive connection, each refused the same and rested, and the agent got a 400, while a new connection answered 12 seconds on (#5182, ggdayup; `TestRegionRefusalDropsItsConnection`, `TestAntigravityRegionRefusalAsksTheNextOnANewConnection`, `TestAntigravityRegionRefusalAsksTheLastAgain`, `TestRegionRefusalRestsNoAccount`, `TestRegionRefusalOfTheModelEndsAfterOneMoreAsk`, `TestRegionNote`). Not covered: an HTTP/2 connection carrying another stream at that moment outlives the close until it is idle, and the close drops other vendors' idle connections too (one handshake each). A user whose region is refused gets the refusal after the one more ask, a moment later than before.
|
||||
- One of Codex's own models on the backend path with no routing to do (`codexAccounts` false: one ChatGPT account, no usage cap, no key holds, nothing pinned, and the sign-in not known to be out of its allowance, `provider.CodexUsedUpKnown`, which routes the turn as `codex/<model>` as a restarted Codex's goes) is relayed as Codex sent it, on Codex's own sign-in, its bytes and headers unchanged and its reply streamed as it comes (`codexUpstreamOn` with no account): routing was built for more than one account, and that path also keeps the turn's native compaction with the backend. Before, nothing was asked again on it, so an overload went straight to Codex, which doesn't retry the backend's `server_is_overloaded` itself (夜松云 on Discord). Now a transient overload (`codexBusy`: what `busy` calls busy, a 529, a 503 saying overloaded, the backend's in-stream `response.failed` with `server_is_overloaded` (#1418); never a 429, a usage limit, an edge's drop of the connection (`edgeSaidDrop`) or a reset (`codexReset`)) is asked again of the same account, the same body and headers, up to `lastRetries` times after `retryPause<<n`, as the accounts loop asks its last account, and only before any of the reply has reached Codex. A stream is held for it through a `holdWriter` with its reasoning let through (`thinkingShown`), kept alive past `keepHeldAfter` across the tries (one `keptAlive`), so Codex sees the stream's headers and comments, never a failed try's frames. Nothing rests for an overload. Once the retries are spent, a turn whose codex subscription has fallbacks (`codexFallsBack`; never a compaction) goes on to them (`codexFallBack`: the turn served as `codex/<model>` with the account left out of the candidates, `fallbacksOnly`, and the same keepalive carried in `handedOnKey`); without fallbacks Codex gets the last try's failure as the backend said it. The account out of its allowance goes on to the same fallbacks at once, after the credits retry and the automatic reset are looked at (`codexAccountOut`: a quota, credit or rate refusal, as a status or as a stream's failure before any reply, and a 403 `usage_not_included`; never a 401, which Codex renews its sign-in on). Before that, Codex was handed the 429 with its fallbacks unused (adorable_piglet on Discord, `TestCodexOneAccountSpentFallsBack`); with none set it still is (`TestCodexOneAccountSpentNoFallbackRelayed`). Each try is a `HandedOn` usage record and a try in the trace. The reply's `x-codex-*` windows are kept as the sign-in's usage and a `usage_limit_reached` refusal has it read again at once (`heardCodexLimits`, `codexMayBeUsedUp`), as on the accounts path. A success is relayed as before, with nothing held when no retry or fallback is left (`TestCodexOneAccountOverloadAskedAgain`, `…StreamOverloadAskedAgain`, `…OverloadBounded`, `…OverloadFallsBack`, `…OverloadKeptAlive`, `…RefusalNotAskedAgain` in [`codex_one_account_overload_test.go`](../../internal/gateway/codex_one_account_overload_test.go)).
|
||||
|
||||
@@ -17,7 +17,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
|
||||
| Part | Responsibility | Source |
|
||||
| --- | --- | --- |
|
||||
| Provider | `Provider` holds the endpoint bases for each `Protocol` (Chat, Responses, Anthropic, Gemini), the keys, `Fallback`, `Routing`, `Sink`, `Affinity`, concurrency and queue limits, `Headers`, `Proxy`, models, and balance settings. `BaseAPI` is the API a custom provider's editor shows its Base URL as: the one the user picked and saved, while it has a URL, so a provider with a chat URL beside its Responses one isn't shown as OpenAI compatible after Responses was picked. Requests go by which URLs are set; `Native`, the API agents' model files ask a model on, takes `BaseAPI` where it serves the model, after the OpenAI-model and Claude-on-Messages rules (nb5p on Discord: dsh asked a Responses relay's GPTs on Chat). A custom provider's `Gemini` URL is the base of Google's Gemini API, or of one that answers as it does (#1346): `GeminiBase` keeps it as the base (…/v1beta added to a bare host, a pasted endpoint or model list cut back), requests go to `models/{model}:streamGenerateContent?alt=sse` under it (`GeminiPath`) signed with `x-goog-api-key` (`AuthHeaders`), and its models are listed by `catalog.FetchGemini` (paged, only those serving generateContent). Factory's sign-in alone keeps its own `/generate` route and token (`FactoryGemini`). `Account` is set only for a subscription and is never saved (`json:"-"`). | [`provider.go`](../../internal/provider/provider.go) |
|
||||
| Provider | `Provider` holds the endpoint bases for each `Protocol` (Chat, Responses, Anthropic, Gemini), the keys, `Fallback`, `Routing`, `Sink`, `UseFirst` (Smart puts it ahead of the other providers it weighs it with, [gateway routing](gateway-routing.md)), `Affinity`, concurrency and queue limits, `Headers`, `Proxy`, models, and balance settings. `BaseAPI` is the API a custom provider's editor shows its Base URL as: the one the user picked and saved, while it has a URL, so a provider with a chat URL beside its Responses one isn't shown as OpenAI compatible after Responses was picked. Requests go by which URLs are set; `Native`, the API agents' model files ask a model on, takes `BaseAPI` where it serves the model, after the OpenAI-model and Claude-on-Messages rules (nb5p on Discord: dsh asked a Responses relay's GPTs on Chat). A custom provider's `Gemini` URL is the base of Google's Gemini API, or of one that answers as it does (#1346): `GeminiBase` keeps it as the base (…/v1beta added to a bare host, a pasted endpoint or model list cut back), requests go to `models/{model}:streamGenerateContent?alt=sse` under it (`GeminiPath`) signed with `x-goog-api-key` (`AuthHeaders`), and its models are listed by `catalog.FetchGemini` (paged, only those serving generateContent). Factory's sign-in alone keeps its own `/generate` route and token (`FactoryGemini`). `Account` is set only for a subscription and is never saved (`json:"-"`). | [`provider.go`](../../internal/provider/provider.go) |
|
||||
| Rate windows | A provider bills the hours it says at its own rate (#2463): `RateWindows`, each a span `HH:MM`–`HH:MM` on this computer's clock whose end may pass its start over midnight, the days it is on (`Days`, `time.Weekday`'s numbers, none for every day), and a rate from just over 0 to 1000 at three decimals. The first window that holds a call's time multiplies the price again, on top of `PriceRate` — a price the user set for a model included, which the price rate alone leaves as set — and outside every window the price rate alone counts. A call is priced at its own time wherever a cost is counted call by call — the Usage page and its CSV, a gateway key's cost limit, the gateway's sessions in Usage — by `EffectivePriceAt`, which `EffectivePriceIn` is at `time.Now()`, and its record's time is read on this computer's clock whatever zone it was written in (a call reported as `…Z`); the Sessions page sums a session's calls by model, not by time, so it prices them without any window (`BasePriceIn` in `sessions.priceOf`), the same at every hour it is read; the ledger's `Pricer` holds each provider's base price and windows once and reads each record's rate at the record's own time, so a window that opens mid-page prices only the calls inside it; a gateway block's rows (`blockPricer`, the Requests tab) take their price from a memo asked with no time, which `RateAt` reads as no window, and each row is put at its own window's rate there (`atWindow` before `Price.In`). A list price billed double at peak (`Peak`, DeepSeek's, Ollama Cloud's two DeepSeek models' and the relays `PeakOf` names) is part of the base: the final price is that base, peak included, times the window's rate, so a provider with a `Peak` needs no window for the same hours: the order is the spec (the author, YangHonghang), so a 0.8 window on a shared DeepSeek key takes 0.8 off the peak price at peak, and a window set over the official peak hours would double them twice, which the editor's hint says under the windows. `/v1/models` prices its list at now (`EntryPricer`); the model list magpie writes into an agent's own config (`AgentPricer`, Pi's and omp's cost) leaves every window out, since nothing rewrites that file as a window opens or closes. `CheckRateWindows` says what is wrong with a set; the editor keeps the windows under Advanced, drawn by `ratewindows.js`, which app.js imports when an editor draws the field (`rateWindowsField`) so it adds nothing to the core's scripts — until it has loaded, a save leaves `rateWindows` out, which keeps them. A provider with windows shows what it bills at now on its row (`rateNow` in `/api/providers`, `rateNowOf` in the GUI's `providers.go`: `RateAt` on the server's clock, which calls are counted on, never the browser's); one with a price rate alone shows nothing new. Windows are kept with the provider: a save that leaves them out keeps them, null or an empty list clears them, and a signed-in account's survive its `Save` — the account branch and `withPicks` both go through one list, `accountSettings`, beside its `PriceRate`, or the editor's Save would quietly drop what it shows (#4738: two lists drifted, and `additionalTools`, extraBody, reply headers, its rests, `limitRestOff` and patience were each lost one way; `TestAccountSettingsKept`). | [`ratewindow.go`](../../internal/provider/ratewindow.go), [`models.go`](../../internal/provider/models.go), [`ledger.go`](../../internal/usage/ledger.go) (`Pricer`), [`app.js`](../../internal/gui/assets/app.js) (`rateWindowsField`), [`ratewindows.js`](../../internal/gui/assets/ratewindows.js), [`gui/providers.go`](../../internal/gui/providers.go) (`rateNowOf`) |
|
||||
| Anthropic key header | A provider of the user's own on a third-party Anthropic API is sent its key as both `x-api-key` and `Authorization: Bearer` (`AuthHeaders`); Anthropic's own API, Bedrock, Azure, Vertex and every subscription account have their own and never this choice (`BothAuth` is false). Some services refuse the two together with a 401 (Aloha on Discord: "鉴权 header, x-api-key 和 Authorization 不可以同时存在"), so `Provider.AuthHeader` (`authHeader`: empty for both, `x-api-key` or `bearer`; anything else is read as empty) sends one alone, picked in the editor's Key header row (shown while `bothAuth` is true, or a custom provider's Anthropic URL is a third party's). Left at both, a 401 whose body `catalog.BothAuthRefused` tells as that refusal (it names both headers and says they can't be together, in Chinese or English) is asked once more with x-api-key alone, then Bearer alone (`RetryOneAuth`, in the gateway's `forwardOnce` and the provider test's `probe`; `catalog.fetchOne` for the model list through `listAuth`); the first not answered 401 or 403 is kept with `LearnAuthHeader`, which never changes a pick the user made. A request carrying the user's own `Authorization` or `x-api-key` header is never retried. | [`authheader.go`](../../internal/provider/authheader.go), [`test.go`](../../internal/provider/test.go), [`catalog/authheader.go`](../../internal/catalog/authheader.go), [`catalog/live.go`](../../internal/catalog/live.go) |
|
||||
| GLM Coding Plan key at pay as you go | Zhipu's and Z.ai's presets offer Pay as you go first (`/api/paas/v4`) and the Coding Plan (`/api/coding/paas/v4`, Responses at `/api/v1`); both share `/api/anthropic`, which bills the plan, so a plan's key left at Pay as you go worked in Claude Code and was refused 429 code 1113 "余额不足或无可用资源包" in Codex (@cleverpigo on X). Nothing in the key tells the two apart, so a Chat request to `open.bigmodel.cn` or `api.z.ai` at `/api/paas/v4` refused 1113 is asked once more at `/api/coding/paas/v4` (`RetryZhipuCoding`, in the gateway's `forwardOnce` and the provider test's `probe`). Served there, `LearnZhipuCoding` moves a saved provider with that one key, still at that URL, to the plan's OpenAI URL (and the preset's plan Responses URL when it has none); one with other keys stays and is asked again each time. Refused there too, the 1113 body keeps its code and gets both URLs and what to change in its message (`ZhipuNoBalanceHint`). A pay-as-you-go key with a balance is never answered 1113 and never sent to the plan's endpoint. | [`zhipu_coding.go`](../../internal/provider/zhipu_coding.go), [`test.go`](../../internal/provider/test.go) |
|
||||
|
||||
@@ -2344,7 +2344,7 @@ func weighRouted(p provider.Provider, cs []candidate, model string, from provide
|
||||
}
|
||||
seats[i] = routes.Seat{Key: c.rest, Account: c.p.Account != nil, Known: known, Learns: learns(c, wg.lefts),
|
||||
Used: l.used, WeekLow: l.weekLow, Soon: l.soon, Lapse: l.lapse, Pace: pace, Weight: keyWeight(c), Resting: resting(c), Tokens: routed.used[c.restKey()].now(now), Credits: l.credits, First: l.first,
|
||||
Left: l.bal, LeftIn: l.balIn, Spent: spentRest(c)}
|
||||
Left: l.bal, LeftIn: l.balIn, Spent: spentRest(c), Lead: c.p.UseFirst}
|
||||
}
|
||||
routed.Unlock()
|
||||
if st.ByUse {
|
||||
|
||||
@@ -352,6 +352,9 @@ type Weighed struct {
|
||||
Speaks provider.Protocol `json:"speaks,omitempty"` // a key made for one protocol only
|
||||
Rest *Rest `json:"rest,omitempty"` // resting after a failure, when the request came
|
||||
Unlisted bool `json:"unlisted,omitempty"`
|
||||
// UseFirst: its provider is set to be used first, which Smart puts
|
||||
// ahead of the other providers' (provider.Provider.UseFirst)
|
||||
UseFirst bool `json:"useFirst,omitempty"`
|
||||
// Window: left out as the request is longer than this, its model's
|
||||
// context window (roomy), unless every one with room is out of its
|
||||
// allowance (#3749)
|
||||
@@ -561,7 +564,7 @@ type planned struct {
|
||||
|
||||
func weighed(c candidate, p provider.Provider, wg weighing, fallback bool, from provider.Protocol) Weighed {
|
||||
w := Weighed{ID: c.rest, Provider: p.ID, Name: p.Name, Icon: p.Icon, Preset: p.Preset, Model: c.model, Fixed: c.effort, Fast: c.fast,
|
||||
Routing: p.Routing, Fallback: fallback, Shared: c.rest != p.ID, Rank: c.rank, NoURL: c.noURL, Reserve: c.reserve}
|
||||
Routing: p.Routing, Fallback: fallback, Shared: c.rest != p.ID, Rank: c.rank, NoURL: c.noURL, Reserve: c.reserve, UseFirst: c.p.UseFirst}
|
||||
switch {
|
||||
case c.p.Account != nil:
|
||||
w.Kind, w.Who, w.Agent, w.Plan = "account", c.p.Account.User, c.p.Account.Agent, c.p.Account.Plan
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// quotaKeyed answers from the key each request came with, or, once out,
|
||||
// with OpenAI's 429 insufficient_quota.
|
||||
type quotaKeyed struct {
|
||||
mu sync.Mutex
|
||||
tried []string
|
||||
out bool
|
||||
}
|
||||
|
||||
func (k *quotaKeyed) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
io.ReadAll(r.Body)
|
||||
key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
k.mu.Lock()
|
||||
k.tried = append(k.tried, key)
|
||||
out := k.out
|
||||
k.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if out {
|
||||
w.WriteHeader(429)
|
||||
io.WriteString(w, carriedQuotaBody)
|
||||
return
|
||||
}
|
||||
io.WriteString(w, `{"id":"x","choices":[{"index":0,"message":{"role":"assistant","content":"from `+key+`"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}`)
|
||||
}
|
||||
|
||||
// A provider set to be used first takes a model's group's requests ahead
|
||||
// of the one listed before it, under Smart (hzh_1119 on Discord: an API
|
||||
// key's monthly credit before the subscription), and once it answers 429
|
||||
// insufficient_quota the request goes on to the other.
|
||||
func TestUseFirstLeadsTheGroup(t *testing.T) {
|
||||
fresh(t)
|
||||
sub, api := "aKeyed{}, "aKeyed{}
|
||||
serveOn(t, "sub", "ksub", []string{"m"}, sub)
|
||||
serveOn(t, "api", "kapi", []string{"m"}, api)
|
||||
s := New()
|
||||
ask := func(n string) string {
|
||||
t.Helper()
|
||||
code, body := postAs(t, s, "", `{"model":"auto/m","messages":[{"role":"user","content":"`+n+`"}]}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("%s: %d %s", n, code, body)
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
if body := ask("listed order"); !strings.Contains(body, "from ksub") {
|
||||
t.Fatalf("none set: %s, want the first listed", body)
|
||||
}
|
||||
if err := provider.SetUseFirst("api", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body := ask("use first"); !strings.Contains(body, "from kapi") {
|
||||
t.Fatalf("api set to be used first: %s", body)
|
||||
}
|
||||
r := s.trace.routes[len(s.trace.routes)-1]
|
||||
if len(r.Order) != 2 || r.Order[0].Provider != "api" || !r.Order[0].UseFirst || r.Order[1].UseFirst {
|
||||
t.Fatalf("trace: %+v", r.Order)
|
||||
}
|
||||
|
||||
api.mu.Lock()
|
||||
api.out = true
|
||||
api.mu.Unlock()
|
||||
if body := ask("out of credit"); !strings.Contains(body, "from ksub") {
|
||||
t.Fatalf("api out of quota: %s", body)
|
||||
}
|
||||
if got := strings.Join(api.tried, ","); got != "kapi,kapi" {
|
||||
t.Fatalf("api tried %s", got)
|
||||
}
|
||||
}
|
||||
@@ -6339,11 +6339,8 @@ function providerHandle(p, row) {
|
||||
return b;
|
||||
}
|
||||
|
||||
// The ids of the providers that are on, in their order, and of those a
|
||||
// search shows. While searching, a provider moves among the ones shown:
|
||||
// Alt+↑ puts it just above the one shown above it, a drop puts it where the
|
||||
// row dropped on was; the ones hidden keep their order among themselves.
|
||||
// Move to Top and Move to Bottom go to the top or the bottom of them all.
|
||||
// The providers on, in order, and those a search shows: while searching, one
|
||||
// moves among those shown; the hidden keep their order.
|
||||
const onProviderIds = () => providers.providers.filter((x) => !x.off).map((x) => x.id);
|
||||
const shownProviderIds = () => [...$("#providers").children].filter((r) => r.classList.contains("provider") && !r.hidden).map((r) => r.dataset.id);
|
||||
const shownToOn = (id) => (id ? onProviderIds().indexOf(id) : -1);
|
||||
@@ -6353,9 +6350,8 @@ function stepProvider(id, by, keyboard) {
|
||||
arrangeProvider(id, shownToOn(shown[i + by]), keyboard);
|
||||
}
|
||||
|
||||
// openProviderMenu: a provider row's right-click, the quick way through a
|
||||
// long list (#1614): Move to Top and Move to Bottom beside one step up or
|
||||
// down, each with its keys.
|
||||
// openProviderMenu: a row's right-click (#1614), and Use first, which Smart
|
||||
// tries first (hzh_1119 on Discord)
|
||||
function openProviderMenu(anchor, p) {
|
||||
if (!anchor) return;
|
||||
const again = agentMenu?.anchor === anchor;
|
||||
@@ -6369,18 +6365,14 @@ function openProviderMenu(anchor, p) {
|
||||
{ name: "Move up", icon: MOVE_UP, key: ALT + "↑", off: k <= 0, run: () => stepProvider(p.id, -1) },
|
||||
{ name: "Move down", icon: MOVE_DOWN, key: ALT + "↓", off: k < 0 || k >= shown.length - 1, run: () => stepProvider(p.id, 1) },
|
||||
{ name: "Move to bottom", icon: MOVE_BOTTOM, key: ALT + SHIFT + "↓", off: i === on.length - 1, run: () => arrangeProvider(p.id, on.length - 1) },
|
||||
{ name: "Use first", icon: p.useFirst ? CHECK : "", sep: !0, run: () => accountAction("provider/usefirst", { id: p.id, useFirst: !p.useFirst }, t(p.useFirst ? "{name} takes its turn with the others" : "{name} is used first", { name: p.name })) },
|
||||
...magpie.actions?.("provider", { provider: { id: p.id, name: p.name } }) || [],
|
||||
]);
|
||||
}
|
||||
|
||||
// Providers' search (#1614, ququdu: "供应商很多,然后经常需要翻找"): the
|
||||
// words typed keep the rows that say them all, on and off alike, matched on
|
||||
// the row's own text and on what it doesn't show: its id, preset, addresses,
|
||||
// each account's user and plan, and the keys' names. The words it doesn't
|
||||
// say are one model's it serves, separators aside ("opus 5.5" finds
|
||||
// claude-opus-5-5), named under the row (frankdeng, Neo). The ones turned
|
||||
// off show unfolded while searching. Escape or clearing the box brings back
|
||||
// every row, the fold as it was.
|
||||
// Providers' search (#1614): the rows saying every word, on and off, by their
|
||||
// text, ids, addresses, users and keys; a word they don't say is a model's
|
||||
// they serve, named under the row (frankdeng, Neo).
|
||||
let pvQuery = "";
|
||||
function providerText(p, row) {
|
||||
const a = p.account;
|
||||
|
||||
@@ -3266,6 +3266,9 @@ const I18N = {
|
||||
"Serves {models}": "提供 {models}",
|
||||
"Move to top": "移到顶部",
|
||||
"Move to bottom": "移到底部",
|
||||
"Use first": "优先使用",
|
||||
"{name} is used first": "{name} 优先使用",
|
||||
"{name} takes its turn with the others": "{name} 和其他供应商照常排序",
|
||||
"right-click to move it to the top or the bottom": "右键可移到顶部或底部",
|
||||
"Resume": "继续",
|
||||
"Resume command": "继续会话的命令",
|
||||
@@ -7917,6 +7920,9 @@ const I18N = {
|
||||
"Serves {models}": "提供 {models}",
|
||||
"Move to top": "移到頂部",
|
||||
"Move to bottom": "移到底部",
|
||||
"Use first": "優先使用",
|
||||
"{name} is used first": "{name} 優先使用",
|
||||
"{name} takes its turn with the others": "{name} 和其他供應商照常排序",
|
||||
"right-click to move it to the top or the bottom": "按右鍵可移到頂部或底部",
|
||||
"Resume": "繼續",
|
||||
"Resume command": "繼續會話的命令",
|
||||
@@ -12571,6 +12577,9 @@ const I18N = {
|
||||
"Serves {models}": "{models} を提供",
|
||||
"Move to top": "一番上へ移動",
|
||||
"Move to bottom": "一番下へ移動",
|
||||
"Use first": "優先して使う",
|
||||
"{name} is used first": "{name} を優先して使います",
|
||||
"{name} takes its turn with the others": "{name} は他と同じ順番に戻りました",
|
||||
"right-click to move it to the top or the bottom": "右クリックで一番上・一番下へ移動",
|
||||
"Resume": "再開",
|
||||
"Resume command": "再開コマンド",
|
||||
@@ -17236,6 +17245,9 @@ const I18N = {
|
||||
"Serves {models}": "Bietet {models}",
|
||||
"Move to top": "Ganz nach oben",
|
||||
"Move to bottom": "Ganz nach unten",
|
||||
"Use first": "Zuerst verwenden",
|
||||
"{name} is used first": "{name} wird zuerst verwendet",
|
||||
"{name} takes its turn with the others": "{name} reiht sich wieder bei den anderen ein",
|
||||
"right-click to move it to the top or the bottom": "Rechtsklick, um ihn ganz nach oben oder unten zu verschieben",
|
||||
"Resume": "Fortsetzen",
|
||||
"Resume command": "Befehl zum Fortsetzen",
|
||||
|
||||
@@ -911,6 +911,11 @@ function routingPage(part) {
|
||||
if (f.kind === "key" && !someKnown) return t("Use before expiry: {who} served the fewest tokens lately — {n}.", { who: w, n: tokens(f.tokens || 0) });
|
||||
return t("Use before expiry: {who} goes first.", { who: w });
|
||||
}
|
||||
// its provider set to be used first (Provider.UseFirst, routes.Seat.Lead):
|
||||
// Smart puts it ahead of the others it weighs it with, whatever they
|
||||
// have left (hzh_1119 on Discord)
|
||||
if (f.useFirst && peers.some((p) => !p.useFirst)) return restedTo(t("its provider is set to be used first."))
|
||||
|| t("{who} goes first: its provider is set to be used first.", { who: w });
|
||||
// keys that read their own windows (a sub2api key's limits) are
|
||||
// weighed by them, as accounts are, and one not read yet beside them
|
||||
// too: told below as one
|
||||
@@ -950,7 +955,7 @@ function routingPage(part) {
|
||||
if (!f || !x || x === f || f.rest || f.fallback || x.fallback || x.routing || !x.known || group(x) !== "fine") return null;
|
||||
if (!weighedWith(r, x).includes(f) || memberSplit(r, f, x)) return null;
|
||||
if (["session", "turn", "cache"].includes(r.affinity?.why)) return "kept";
|
||||
if (r.sealedTask || ruleWhy(r, true) || f.learns || !f.known || group(f) !== "fine") return null;
|
||||
if (r.sealedTask || ruleWhy(r, true) || f.learns || !f.known || group(f) !== "fine" || f.useFirst && !x.useFirst) return null;
|
||||
return cmpRenews(f, x).c < 0 ? "sooner" : null;
|
||||
}
|
||||
|
||||
|
||||
@@ -466,6 +466,8 @@ magpie.strings({
|
||||
"{who} goes first: it's made for {api}, the API {model} is at home in, so nothing is translated.": "{who} 排第一:它专为 {api} 而设,正是 {model} 的原生 API,无需转换。",
|
||||
"{who} goes first: keys go in their order, those that suit the request first.": "{who} 排第一:Key 按顺序排,适合此请求的在前。",
|
||||
"{who} goes first.": "{who} 排第一。",
|
||||
"its provider is set to be used first.": "它的供应商设为优先使用。",
|
||||
"{who} goes first: its provider is set to be used first.": "{who} 排第一:它的供应商设为优先使用。",
|
||||
"The vendor hasn't said yet what these accounts have left, so they go in their order: {who} first.": "厂商尚未告知这些账号的剩余额度,按顺序排:{who} 第一。",
|
||||
"Every account is at 90% or more of its allowance, so the one with the most left goes first: {who}, at {n}.": "所有账号均已用到 90% 以上,剩余最多的排第一:{who},已用 {n}。",
|
||||
"Every key and account here is at 90% or more of its allowance, so the one with the most left goes first: {who}, at {n}.": "这里的密钥和账号均已用到 90% 以上,剩余最多的排第一:{who},已用 {n}。",
|
||||
@@ -1133,6 +1135,8 @@ magpie.strings({
|
||||
"{who} goes first: it's made for {api}, the API {model} is at home in, so nothing is translated.": "{who} 排第一:它專為 {api} 而設,正是 {model} 的原生 API,無需轉換。",
|
||||
"{who} goes first: keys go in their order, those that suit the request first.": "{who} 排第一:Key 按順序排,適合此請求的在前。",
|
||||
"{who} goes first.": "{who} 排第一。",
|
||||
"its provider is set to be used first.": "它的供應商設為優先使用。",
|
||||
"{who} goes first: its provider is set to be used first.": "{who} 排第一:它的供應商設為優先使用。",
|
||||
"The vendor hasn't said yet what these accounts have left, so they go in their order: {who} first.": "廠商尚未告知這些帳號的剩餘額度,按順序排:{who} 第一。",
|
||||
"Every account is at 90% or more of its allowance, so the one with the most left goes first: {who}, at {n}.": "所有帳號均已用到 90% 以上,剩餘最多的排第一:{who},已用 {n}。",
|
||||
"Every key and account here is at 90% or more of its allowance, so the one with the most left goes first: {who}, at {n}.": "這裡的金鑰和帳號均已用到 90% 以上,剩餘最多的排第一:{who},已用 {n}。",
|
||||
@@ -1798,6 +1802,8 @@ magpie.strings({
|
||||
"{who} goes first: it's made for {api}, the API {model} is at home in, so nothing is translated.": "{who} が先です:{model} 本来の API である {api} 用なので、変換は不要です。",
|
||||
"{who} goes first: keys go in their order, those that suit the request first.": "{who} が先です:キーは設定順で、リクエストに合うものが先です。",
|
||||
"{who} goes first.": "{who} が先です。",
|
||||
"its provider is set to be used first.": "そのプロバイダが優先して使う設定です。",
|
||||
"{who} goes first: its provider is set to be used first.": "{who} が先です:そのプロバイダが優先して使う設定です。",
|
||||
"The vendor hasn't said yet what these accounts have left, so they go in their order: {who} first.": "ベンダーはこれらのアカウントの残りをまだ知らせていないため、設定順です:{who} が先頭。",
|
||||
"Every account is at 90% or more of its allowance, so the one with the most left goes first: {who}, at {n}.": "すべてのアカウントが利用枠の 90% 以上を使っているため、残りが最も多いものが先です:{who}({n})。",
|
||||
"Every key and account here is at 90% or more of its allowance, so the one with the most left goes first: {who}, at {n}.": "ここのキーとアカウントはすべて利用枠の 90% 以上を使っているため、残りが最も多いものが先です:{who}({n})。",
|
||||
@@ -2465,6 +2471,8 @@ magpie.strings({
|
||||
"{who} goes first: it's made for {api}, the API {model} is at home in, so nothing is translated.": "{who} kommt zuerst: Es ist für {api} gedacht, die native API von {model}, daher wird nichts übersetzt.",
|
||||
"{who} goes first: keys go in their order, those that suit the request first.": "{who} kommt zuerst: Schlüssel gehen in ihrer Reihenfolge, die zur Anfrage passenden zuerst.",
|
||||
"{who} goes first.": "{who} kommt zuerst.",
|
||||
"its provider is set to be used first.": "sein Anbieter ist auf „Zuerst verwenden“ gestellt.",
|
||||
"{who} goes first: its provider is set to be used first.": "{who} kommt zuerst: sein Anbieter ist auf „Zuerst verwenden“ gestellt.",
|
||||
"The vendor hasn't said yet what these accounts have left, so they go in their order: {who} first.": "Der Anbieter hat noch nicht mitgeteilt, was diese Konten übrig haben, daher gehen sie in ihrer Reihenfolge: {who} zuerst.",
|
||||
"Every account is at 90% or more of its allowance, so the one with the most left goes first: {who}, at {n}.": "Jedes Konto liegt bei 90 % oder mehr seines Kontingents, daher kommt das mit dem größten Rest zuerst: {who}, bei {n}.",
|
||||
"Every key and account here is at 90% or more of its allowance, so the one with the most left goes first: {who}, at {n}.": "Jeder Schlüssel und jedes Konto hier liegt bei 90 % oder mehr seines Kontingents, daher kommt das mit dem größten Rest zuerst: {who}, bei {n}.",
|
||||
|
||||
@@ -255,6 +255,9 @@ type providerJSON struct {
|
||||
// Sink: a key or account rate limited with quota left goes to the
|
||||
// back of the order (provider.Provider.Sink)
|
||||
Sink bool `json:"sink,omitempty"`
|
||||
// UseFirst: Smart puts it ahead of the other providers serving the
|
||||
// same model (provider.Provider.UseFirst), set on its own with usefirst
|
||||
UseFirst bool `json:"useFirst,omitempty"`
|
||||
// KeepLogin: magpie keeps Codex or Claude Code signed in to the first
|
||||
// account rather than moving it on when that runs low (#524)
|
||||
KeepLogin bool `json:"keepLogin,omitempty"`
|
||||
@@ -738,7 +741,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs
|
||||
Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL,
|
||||
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, LimitRestOff: p.LimitRestOff, ImageFilesOff: p.ImageFilesOff, TakesImageFiles: p.TakesImageFiles(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), PassErrors: p.PassErrors, TakesPassErrors: p.TakesPassErrors(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL,
|
||||
Ready: p.Ready(), Chosen: p.PicksOf(avail), Agents: make([]providerAgent, 0, len(agents)),
|
||||
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, RestartApp: p.RestartApp, Self: p.SelfAnswered(), KeepSelf: p.KeepSelf, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts,
|
||||
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, UseFirst: p.UseFirst, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, RestartApp: p.RestartApp, Self: p.SelfAnswered(), KeepSelf: p.KeepSelf, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts,
|
||||
MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate,
|
||||
RateWindows: p.RateWindows, RateNow: rateNowOf(p, time.Now()),
|
||||
AccountConcurrency: p.AccountConcurrency, AccountWeights: p.AccountWeights, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM,
|
||||
@@ -2106,6 +2109,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
in.SwitchOnly, in.RestartApp = old.SwitchOnly, old.RestartApp // switchonly, restartapp
|
||||
in.KeepSelf = old.KeepSelf // keepself
|
||||
in.CapStop, in.CapCareful = old.CapStop, old.CapCareful // capstop, capcareful
|
||||
in.UseFirst = old.UseFirst // usefirst
|
||||
in.Off = old.Off // and this with off and on
|
||||
if in.Contexts == nil {
|
||||
in.Contexts = old.Contexts // a save that doesn't say
|
||||
@@ -2395,6 +2399,13 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
case "usefirst":
|
||||
// ahead of the other providers where Smart weighs them
|
||||
// together (hzh_1119 on Discord)
|
||||
if err := provider.SetUseFirst(in.ID, in.UseFirst); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
case "delete":
|
||||
var err error
|
||||
if moved, err = agent.Reseat(func() error { return provider.Delete(in.ID) }); err != nil {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
// account's user and the rest, the ones turned off too (their fold opens
|
||||
// while searching); nothing found says so; Escape clears it and puts the
|
||||
// fold back. A row's right-click has Move to Top, Move Up, Move Down and
|
||||
// Move to Bottom, Alt+Shift+↑/↓ go to the top or the bottom from the
|
||||
// Move to Bottom, then Use first, Alt+Shift+↑/↓ go to the top or the bottom from the
|
||||
// keyboard. While searching, a row moves among the ones shown (Alt+↑/↓, a
|
||||
// drag) and the ones hidden keep their order. Nothing scrolls, and in a
|
||||
// narrow window nothing runs off to the side. Every language, Chromium and
|
||||
@@ -177,8 +177,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
const menu = page.locator(".pop.row-menu");
|
||||
await menu.waitFor();
|
||||
const names = await menu.locator(".rm-name").allTextContents();
|
||||
assert.deepEqual(names, [await tr("Move to top"), await tr("Move up"), await tr("Move down"), await tr("Move to bottom")]);
|
||||
assert.deepEqual(await menu.locator(".rm-item").evaluateAll((bs) => bs.map((b) => b.disabled)), [false, false, true, true]);
|
||||
assert.deepEqual(names, [await tr("Move to top"), await tr("Move up"), await tr("Move down"), await tr("Move to bottom"), await tr("Use first")]);
|
||||
assert.deepEqual(await menu.locator(".rm-item").evaluateAll((bs) => bs.map((b) => b.disabled)), [false, false, true, true, false]);
|
||||
await menu.locator(".rm-item").first().click();
|
||||
await page.waitForFunction(() => document.querySelector("#providers > .row.provider").dataset.id === "zhipu");
|
||||
assert.deepEqual(f.posted.at(-1), ["zhipu", "openai", "relay-two", "relay-one", "anthropic", "relay-three", "deepseek", "moonshot", "relay-off"]);
|
||||
@@ -187,8 +187,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
// the first one's: Move to Bottom
|
||||
await page.locator('#providers > .row.provider[data-id="zhipu"] .name').click({ button: "right" });
|
||||
await menu.waitFor();
|
||||
assert.deepEqual(await menu.locator(".rm-item").evaluateAll((bs) => bs.map((b) => b.disabled)), [true, true, false, false]);
|
||||
await menu.locator(".rm-item").last().click();
|
||||
assert.deepEqual(await menu.locator(".rm-item").evaluateAll((bs) => bs.map((b) => b.disabled)), [true, true, false, false, false]);
|
||||
await menu.locator(".rm-item").nth(3).click();
|
||||
await page.waitForFunction(() => [...document.querySelectorAll("#providers > .row.provider")].at(-1).dataset.id === "zhipu");
|
||||
assert.deepEqual(f.posted.at(-1), ["openai", "relay-two", "relay-one", "anthropic", "relay-three", "deepseek", "moonshot", "zhipu", "relay-off"]);
|
||||
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// hzh_1119 on Discord: an OpenAI API key's monthly credit spent before the
|
||||
// ChatGPT subscription where both serve a model. A provider row's
|
||||
// right-click has Use first: it posts provider/usefirst, and once on the
|
||||
// item shows a tick and posts it off again. On the Routing page, a request
|
||||
// whose first went first for it says so, not that its allowance renews
|
||||
// sooner. The page doesn't move. Every language, Chromium and WebKit, at
|
||||
// 1100 and 420 wide; no backend, the API is faked here.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const CHECK = "m3.5 8.5 3 3 6-7";
|
||||
const now = new Date();
|
||||
const ago = (minutes) => new Date(now.getTime() - minutes * 60e3).toISOString();
|
||||
const prov = (id, name, extra = {}) => ({
|
||||
id, name, icon: "generic", host: id + ".example.com", chat: "https://" + id + ".example.com/v1", responses: "", anthropic: "", catalog: "",
|
||||
models: [{ id: "gpt-5.5", name: "GPT-5.5", on: true }], agents: [], fallback: [], headers: {},
|
||||
key: { set: true, masked: "sk-…" + id }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", ...extra,
|
||||
});
|
||||
const order = [
|
||||
{ id: "openai#k", provider: "openai", name: "OpenAI", who: "OpenAI", kind: "key", model: "gpt-5.5", routing: "", useFirst: true },
|
||||
{ id: "codex#u", provider: "codex", name: "Codex", who: "me@example.com", kind: "account", model: "gpt-5.5", routing: "", known: true, used: 10,
|
||||
windows: [{ used: 10, resets: new Date(now.getTime() + 2 * 3600e3).toISOString() }] },
|
||||
];
|
||||
|
||||
function serve(lang, posts) {
|
||||
let list = [prov("codex", "Codex"), prov("openai", "OpenAI")];
|
||||
const providers = () => ({ providers: list, presets: [], excluded: [], gateway: { running: true, window: true } });
|
||||
const route = {
|
||||
id: 1, seq: 1, time: ago(1), agent: "codex", model: "auto/gpt-5.5", provider: "openai", done: true, status: 200, ms: 900, tokens: 1200, order,
|
||||
tries: [{ id: "openai#k", model: "gpt-5.5", start: ago(1), done: true, status: 200, ms: 900 }],
|
||||
};
|
||||
return async (request) => {
|
||||
const url = new URL(request.request().url());
|
||||
const json = (data) => request.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return request.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return request.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } });
|
||||
if (url.pathname === "/api/providers") return json(providers());
|
||||
if (url.pathname === "/api/provider/usefirst") {
|
||||
const body = request.request().postDataJSON();
|
||||
posts.push(body);
|
||||
list = list.map((p) => p.id === body.id ? { ...p, useFirst: body.useFirst } : p);
|
||||
return json(providers());
|
||||
}
|
||||
if (url.pathname === "/api/gateway/trace") {
|
||||
if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes
|
||||
return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 1 }, routes: [route] });
|
||||
}
|
||||
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
await request.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const strings = [
|
||||
"Use first",
|
||||
"{name} is used first",
|
||||
"{name} takes its turn with the others",
|
||||
"{who} goes first: its provider is set to be used first.",
|
||||
"its provider is set to be used first.",
|
||||
];
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const width of [1100, 420]) {
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
const open = async (t, view) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [], posts = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, posts));
|
||||
await page.goto("http://magpie.test/?view=" + view);
|
||||
const say = (key, vars = {}) => page.evaluate(([lang, key, vars]) => {
|
||||
const s = (lang !== "en" && I18N[lang]?.[key]) || key;
|
||||
return s.replace(/\{(\w+)\}/g, (_, k) => vars[k] ?? `{${k}}`);
|
||||
}, [lang, key, vars]);
|
||||
return { page, errors, posts, say };
|
||||
};
|
||||
|
||||
test(`${engine} ${width} ${lang}: a provider's right-click turns Use first on and off`, async (t) => {
|
||||
const { page, errors, posts, say } = await open(t, "providers");
|
||||
await page.locator(".row.provider").first().waitFor();
|
||||
if (lang === "en") {
|
||||
const missing = await page.evaluate((ks) => ["zh", "zh-TW", "ja", "de"].flatMap((l) => ks.filter((k) => !I18N[l][k]).map((k) => `${l}: ${k}`)), strings);
|
||||
assert.deepEqual(missing, [], "every string has its translations");
|
||||
}
|
||||
const scrollers = () => page.evaluate(() => [...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => e.scrollTop).concat(document.scrollingElement.scrollTop));
|
||||
const before = await scrollers();
|
||||
const row = page.locator('#providers > .row.provider[data-id="openai"]');
|
||||
const menu = page.locator(".pop.row-menu");
|
||||
const item = menu.locator(".rm-item", { hasText: await say("Use first") });
|
||||
await row.locator(".name").click({ button: "right" });
|
||||
await menu.waitFor();
|
||||
assert.equal(await item.count(), 1);
|
||||
assert.notEqual(await item.locator("path").getAttribute("d"), CHECK, "off, no tick");
|
||||
const box = await menu.boundingBox();
|
||||
assert.ok(box.x >= 0 && box.x + box.width <= width, `the menu fits across ${width}`);
|
||||
await item.click();
|
||||
await page.waitForFunction(() => !document.querySelector(".pop.row-menu"));
|
||||
assert.deepEqual(posts, [{ id: "openai", useFirst: true }]);
|
||||
assert.equal(await page.locator("#providers > .row.provider.selected").count(), 0, "the right-click opened the row");
|
||||
|
||||
await row.locator(".name").click({ button: "right" });
|
||||
await menu.waitFor();
|
||||
assert.equal(await item.locator("path").getAttribute("d"), CHECK, "on, a tick");
|
||||
await item.click();
|
||||
await page.waitForFunction(() => !document.querySelector(".pop.row-menu"));
|
||||
assert.deepEqual(posts, [{ id: "openai", useFirst: true }, { id: "openai", useFirst: false }]);
|
||||
|
||||
await page.locator('#providers > .row.provider[data-id="codex"] .name').click({ button: "right" });
|
||||
await menu.waitFor();
|
||||
assert.notEqual(await item.locator("path").getAttribute("d"), CHECK, "another provider is off");
|
||||
await page.keyboard.press("Escape");
|
||||
assert.deepEqual(await scrollers(), before, "the page doesn't move");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${width} ${lang}: the Routing page says the first went first for Use first`, async (t) => {
|
||||
const { page, errors, say } = await open(t, "routing");
|
||||
const req = page.locator(".rt-req").first();
|
||||
await req.waitFor();
|
||||
if (await req.getAttribute("aria-pressed") !== "true") await req.click();
|
||||
const why = page.locator(".rt-steps li.why").first();
|
||||
await why.waitFor();
|
||||
assert.equal((await why.textContent()).trim(), await say("{who} goes first: its provider is set to be used first.", { who: "OpenAI" }));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -142,6 +142,16 @@ type Provider struct {
|
||||
// goes round already. See gateway.sink.
|
||||
Sink bool `json:"sink,omitempty"`
|
||||
|
||||
// UseFirst puts its keys or accounts ahead of the other providers'
|
||||
// where Smart weighs them together: a group of several providers'
|
||||
// models (hzh_1119 on Discord: an OpenAI API key's monthly credit
|
||||
// spent before the ChatGPT subscription serving the same models). One
|
||||
// resting after a failure, out of credit or out of quota (a 429
|
||||
// insufficient_quota) is passed over as ever, and one all but used up
|
||||
// goes with the others that are. Off, the default, Smart goes as it
|
||||
// always has (routes.Seat.Lead).
|
||||
UseFirst bool `json:"useFirst,omitempty"`
|
||||
|
||||
// Affinity is how long a conversation stays with the key or account
|
||||
// that answered it, so the vendor's prompt cache it filled is read
|
||||
// again rather than lost (see Affinities): "" auto, "session",
|
||||
@@ -984,6 +994,7 @@ func accountSettings(a, pk Provider) Provider {
|
||||
a.Proxy, a.AccountProxies, a.AccountModels, a.AccountModelsAll = pk.Proxy, pk.AccountProxies, pk.AccountModels, pk.AccountModelsAll
|
||||
a.AccountCaps, a.AccountWindowCaps = pk.AccountCaps, pk.AccountWindowCaps
|
||||
a.CapStop, a.CapCareful = pk.CapStop, pk.CapCareful
|
||||
a.UseFirst = pk.UseFirst
|
||||
a.AccountNames = pk.AccountNames
|
||||
a.MaxConcurrency, a.PinUpstream = pk.MaxConcurrency, pk.PinUpstream
|
||||
a.MaxAccounts = pk.MaxAccounts
|
||||
|
||||
@@ -105,6 +105,18 @@ func SetSink(id string, sink bool) error {
|
||||
return Save(*p)
|
||||
}
|
||||
|
||||
// SetUseFirst puts a provider's keys or accounts ahead of the other
|
||||
// providers' where Smart weighs them together, or back in Smart's own
|
||||
// order (Provider.UseFirst).
|
||||
func SetUseFirst(id string, on bool) error {
|
||||
p, err := Find(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.UseFirst = on
|
||||
return Save(*p)
|
||||
}
|
||||
|
||||
// SetCapStop has a subscription answer 429 while every account is held at
|
||||
// its usage cap, rather than go on to its fallbacks (Provider.CapStop), or
|
||||
// go on to them again.
|
||||
|
||||
@@ -75,6 +75,10 @@ type Seat struct {
|
||||
// out never put it behind the others (seatTier), so it keeps the
|
||||
// place an account with room has.
|
||||
First bool
|
||||
// Lead: its provider is set to be used first (provider.Provider.
|
||||
// UseFirst). Smart puts such seats ahead of the others while they have
|
||||
// quota (seatTier below 2), in Smart's own order among themselves.
|
||||
Lead bool
|
||||
// TTFT is how long it took lately to the first of its reply, in ms,
|
||||
// for the model this seat would be asked for: a decayed average of its
|
||||
// recent streamed answers, 0 when it hasn't answered one lately.
|
||||
|
||||
@@ -237,3 +237,30 @@ func TestCreditsFirstOfTheSpent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A seat whose provider is set to be used first (Seat.Lead) goes ahead of
|
||||
// the others Smart weighs it with: an API key's monthly credit before a
|
||||
// subscription with room, which renews soonest (hzh_1119 on Discord). One
|
||||
// all but used up goes with the others that are, and with none set to
|
||||
// lead, Smart goes as it did.
|
||||
func TestSmartLeadFirst(t *testing.T) {
|
||||
now := time.Now()
|
||||
s := []Seat{
|
||||
{Key: "plus", Used: 10, Soon: []time.Time{now.Add(2 * time.Hour)}},
|
||||
{Key: "pro", Used: 40, Soon: []time.Time{now.Add(24 * time.Hour)}},
|
||||
{Key: "api", Lead: true},
|
||||
{Key: "api-spent", Lead: true, Used: 99},
|
||||
{Key: "spent", Used: 98},
|
||||
}
|
||||
got := keys(s, Apply(Smart, "p", s))
|
||||
if want := []string{"api", "plus", "pro", "spent", "api-spent"}; !slices.Equal(got, want) {
|
||||
t.Fatalf("Smart with a lead: %v, want %v", got, want)
|
||||
}
|
||||
for i := range s {
|
||||
s[i].Lead = false
|
||||
}
|
||||
got = keys(s, Apply(Smart, "p", s))
|
||||
if want := []string{"plus", "pro", "api", "spent", "api-spent"}; !slices.Equal(got, want) {
|
||||
t.Fatalf("Smart with none set: %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,9 +184,29 @@ var Smart = Strategy{Order: func(_ string, seats []Seat) []int {
|
||||
})
|
||||
sort.SliceStable(low, func(i, j int) bool { return seats[low[i]].Used < seats[low[j]].Used })
|
||||
sort.SliceStable(spent, func(i, j int) bool { return spentBefore(seats[spent[i]], seats[spent[j]]) })
|
||||
return append(append(fine, low...), spent...)
|
||||
return leadFirst(seats, append(append(fine, low...), spent...))
|
||||
}}
|
||||
|
||||
// leadFirst is order with the seats of a provider set to be used first
|
||||
// (Seat.Lead) ahead of the rest, each side in order's own order: a key's
|
||||
// monthly credit spent before a subscription that serves the same model
|
||||
// (hzh_1119 on Discord). One all but used up stays with the others that
|
||||
// are, and one resting is passed over by the gateway as any is.
|
||||
func leadFirst(seats []Seat, order []int) []int {
|
||||
var lead, rest []int
|
||||
for _, i := range order {
|
||||
if seats[i].Lead && seatTier(seats[i]) < 2 {
|
||||
lead = append(lead, i)
|
||||
} else {
|
||||
rest = append(rest, i)
|
||||
}
|
||||
}
|
||||
if len(lead) == 0 {
|
||||
return order
|
||||
}
|
||||
return append(lead, rest...)
|
||||
}
|
||||
|
||||
// spentBefore orders two seats all but used up: one that goes on on its
|
||||
// credits first (a Codex account holding them answers past its allowance;
|
||||
// one with nothing left is refused), then the one with the most left.
|
||||
|
||||
Reference in New Issue
Block a user