providers: a provider of the user's can be set never to rest for a limit
zoecats (Discord #feedback, 10-25): a local aggregator answers "quota
exhausted" (429 insufficient_quota) for the moment it switches
upstreams, and magpie set its key aside for 30 minutes, answering every
request itself ("out of its allowance: not asked again before …").
A provider the user added now has, under the editor's Advanced fold,
"Set it aside when out of quota or rate limited" (Rests), ticked by
default, with a note. Unticked (provider.LimitRestOff, limitRestOff in
providers.json), restAfterMarked rests nothing, counts no failure and
sinks nothing for a refusal it reads as out of quota, credit or rate
limited, or any 429: by "off", and the next request is sent to it as
usual. restDrawer rests no image model of it either. A 401, a model not
served and a plain failure still rest it. The default is as before. The
editor offers it only to a provider the user added (custom); a Save that
leaves it out keeps it. A checkbox (tick), no native select; strings in
zh, zh-TW, ja and de. app.js's budget (and the core's) are raised by the
576 bytes the row adds, with no room, after the comment was cut.
Run on origin/main 75e78a5a0 plus these two commits:
- gofmt -l clean; node --check app.js, i18n.js; go vet ./... on darwin
and GOOS=linux/windows -tags nogui: ok.
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/gui/
./internal/provider/ (suite lock): gateway ok 417.9s, provider ok
114.4s, gui red only on TestCoreScriptBudget (741 over); after the
trim and the raise, TestCoreScriptBudget, TestProviderSaveLimitRestOff
and TestI18n* ok.
- GUI, chromium and webkit: provider-limit-rest (new; en, zh, zh-TW, ja,
de at 1100 and 420), provider-insecure-tls, i18n-keys, fallback-more:
128/128. Every provider*, every file opening Advanced, i18n-keys,
routing-lifted-elsewhere, rest-try-now, rate-limited-sink (58 files):
1053 of 1055 (on the pre-trim app.js, the trim only a comment and an
unused class): providers-last-known webkit zh-TW (filed #3565) and
tencent-access-key webkit en (#2733) red at load ~130; each passes
alone in WebKit on this tree and on origin/main 5b2b3d3f5.
After the trim: provider-limit-rest, i18n-keys, provider-insecure-tls
124/124.
- Sandbox HOME, a dev build of this tree, fake upstream answering 429
insufficient_quota "quota exhausted": by default the second request was
magpie's own "not asked again before 13:17" (1 upstream hit). Saved
limitRestOff:true through /api/provider/save and lifted the rest:
three requests, three upstream hits, each the vendor's 429; then 429
rate_limit_error: no rest on the key (each request still asked again
after 1s, 2s, 4s within itself, as a lone candidate always is); the
upstream back, 200 at once.
Broken by hand, each red, then restored:
- the check in restAfterMarked off: TestLimitRestOffKeepsAsking ("1
rests set after the refusal, want none") and
TestLimitRestOffRestsNothingForALimit ("rests 29m59s by credit").
- the save's keep-when-left-out branch removed: TestProviderSaveLimitRestOff
("a Save that left it out turned rests back on").
- app.js's save line removed: provider-limit-rest's first two tests red
in webkit zh-TW 420.
Not tried: zoecats' own aggregator; the in-request retries on a rate
limit (1s, 2s, 4s) are left as they are, as they are not a rest.
Again after rebasing on origin/main 1b039a3c7 (which changed app.js,
client.js and gateway.go): gofmt, node --check, vet on three OSes ok;
go test ./internal/gui/ ok (the budgets set to this head's sizes);
go test -run 'TestTryNow|TestRenewed|TestLimitRestOff|TestRestCapOff|
TestOwnRestCap|Sink|Unrest|Rest' ./internal/gateway/ ok; GUI, both engines: provider-limit-rest,
i18n-keys, provider-insecure-tls, routing-lifted-elsewhere, rest-try-now,
rate-limited-sink, routing-model-rest, routing-rest-off, routing-rule-drag,
routing-rule-models, view-trackpad-coast, fallback-more: 272/272.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -215,6 +215,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
|
||||
- Every request to the ChatGPT backend (`CodexBase`'s host) goes over HTTP/1.1, as Codex itself speaks to it: each transport [`netproxy.Dispatch`](../../internal/netproxy/netproxy.go) makes (`http.DefaultClient`'s, the gateway's) sends a request `netproxy.HTTP1` names through an HTTP/1.1 copy of itself whose TLS hello offers no h2, and the provider package sets `HTTP1` to `codexBackend` ([codex_http1.go](../../internal/provider/codex_http1.go)). That covers the gateway's turns, the models list, the warm-up, the allowance, its resets and spending one, through the proxy in force, an account's own included. Every other vendor is still offered HTTP/2.
|
||||
- A streamed turn to the ChatGPT backend (POST `CodexBase`/responses with `"stream":true`) goes over the backend's WebSocket, as Codex's own client sends it, and comes back as the server-sent events the HTTP route answers with (`codexSocket` in [codex_socket.go](../../internal/gateway/codex_socket.go), first in the gateway's `upstreamTransport`, so Codex's own sign-in passed through and magpie's ChatGPT accounts both take it, through the proxy in force). On some networks a streamed HTTP reply from chatgpt.com is cut at about 120 s, before `response.completed`, while the WebSocket runs to the end (brickhao on Discord). The handshake carries the turn's headers with `OpenAI-Beta: responses_websockets=2026-02-06`, without `x-codex-turn-state` and the responses-lite header, which go in the message's `client_metadata` as Codex puts them; the message is the body with `"type":"response.create"` ahead of it (a zstd body is decoded first). `codex.rate_limits` and `codex.response.metadata`, read ahead of the reply, are also told as the `x-codex-*` and `x-codex-turn-state` headers the HTTP route carries; `responsesapi.websocket_timing` is dropped. An `error` frame ahead of the reply is that status with its error as the body; `websocket_connection_limit_reached`, a refused handshake or a body that isn't a streamed turn goes over HTTP instead, and a host that refused the handshake (other than 401, 429 or 5xx) is spoken HTTP for 10 minutes (`codexSocketShun`). A socket that ends, or won't take the message, before any frame of the reply was handed on (any close status, a dropped connection, a normal close with no reply) sends the same body over HTTP (`codexSocketEnded`): Lamrfu's long conversation was closed 1009 (message too big) by chatgpt.com and got a 502. magpie opens a socket per turn and sends the whole body, where Codex's own client sends a delta after `previous_response_id` on a kept socket. A message at least as big as one a host closed 1009 goes to it over HTTP for 10 minutes (`codexTooBig`). A socket closed after the reply began reads as a cut stream (`io.ErrUnexpectedEOF`), and is not asked again. Codex still speaks HTTP to magpie: magpie answers its WebSocket handshake 426, and Codex falls back for the session; only the leg to the vendor changed. The gateway's tests turn it off in TestMain (`codexSocketOff`); codex_socket_test's fakes speak it.
|
||||
- A provider the user added may have its certificate left unchecked (`InsecureTLS`, the editor's Certificate row, #2383: a vLLM on the LAN, Ollama behind a self-signed cert, a company CA). Only one with a base URL of the user's own takes it (`TakesInsecureTLS`: no account, no preset, not Vertex, not a subscription's or plugin's id); `Save` refuses it on any other, and one written into providers.json by hand is ignored. `Provider.Via` then adds `netproxy.WithUncheckedTLS` with the hosts of its own base URLs (`UncheckedHosts`: Chat, Responses, Anthropic, Gemini, Decide), so every request made on its behalf through a `Dispatch` transport (the gateway's turns, count_tokens, models, test and detect, balance) skips the check for those hosts alone, on a transport kept apart for each (`route.unchecked`). A redirect or a models, balance or image URL on another host is checked, and `netproxy.With` drops the leave for a request made for another provider. An `https://` proxy would be dialled with the same TLS config, so its certificate would go unchecked too: such a request is refused (`ErrUncheckedOverHTTPSProxy`); an `http://` or `socks5://` proxy is taken. Backup, export and sync carry the field with the provider; an import link doesn't.
|
||||
- A provider the user added may be set never to rest for a limit (`LimitRestOff`, `limitRestOff`; the editor's Advanced fold, "Set it aside when out of quota or rate limited", ticked by default; zoecats on Discord: a local aggregator's "quota exhausted" while it switches upstreams). Off, a quota, credit or rate refusal and any 429 rest none of its keys and the next request is sent to it as usual (`restAfterMarked` in the gateway, see [gateway routing](gateway-routing.md)). The editor offers it only to a provider the user added (`custom`); a save that leaves it out keeps it (`TestProviderSaveLimitRestOff`, `provider-limit-rest.test.cjs`).
|
||||
- The Copilot account the editors and CLI keep is read by `copilotLogin` ([account.go](../../internal/provider/account.go)): an editor's github.com sign-in in `~/.config/github-copilot/apps.json` or `hosts.json` first, then the Copilot CLI's, then an editor's on GHE.com. When GitHub refuses the editor token's trade for a session token (401 or 403, `copilotRefusals`, retried after an hour), the CLI's sign-in of the same login on the same host takes its place, sent as the CLI sends it, from that request on and on the Usage card (`copilotStandIn`); a CLI signed in to another account is never used for it, and the error names the editors' file (#1238). A sign-in from magpie of the account whose editor token is refused is kept and stands for it (`copilotProbeEditor`, `addCopilotLogin`); while the editor token works, it is let go as the agent's own, as before.
|
||||
- A keychain read that may have shown the user a dialog is not asked again for ten minutes after it was refused (`keychainDeniedTTL` in [account.go](../../internal/provider/account.go)): Copilot's token read backs a denial off (`copilotCLISecret`), and the Cursor token (`cursorKeychainToken`) and Claude Code's item (`readClaudeKeychainItem`, through `claudeCredential`'s cache) do too (#2408). 44, the item not being there, is no refusal and keeps the short TTL, so a sign-in made in the agent is still seen within it; a sign-in or out in magpie reads afresh (`forgetCursorStatus`, `forgetClaudeCredential`), backoff or not.
|
||||
- An unreadable `providers.json` is an error, never an empty list. Saving over an empty list would lose every provider.
|
||||
|
||||
@@ -911,9 +911,10 @@ func (s *Server) drawOnAccounts(ctx context.Context, r *http.Request, p provider
|
||||
// still have it first (restLast in candidates), and a chat on that image
|
||||
// model goes past it too, where before every drawing asked the spent
|
||||
// account first again (01huadalang on Discord). A failure of any other
|
||||
// kind rests nothing, as before: a key, a request refused, a vendor down.
|
||||
// kind rests nothing, as before: a key, a request refused, a vendor down;
|
||||
// nor does any on a provider set never to rest for a limit (LimitRestOff).
|
||||
func restDrawer(c candidate, code int, msg string) {
|
||||
if c.p.Account == nil || c.model == "" || failure(code, []byte(msg)) != failQuota {
|
||||
if c.p.Account == nil || c.p.LimitRestOff || c.model == "" || failure(code, []byte(msg)) != failQuota {
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// zoecats on Discord: a local aggregator says "quota exhausted" for a
|
||||
// moment while it switches upstreams, and the half hour magpie rested its
|
||||
// one key for it held every request back, answered "out of its allowance"
|
||||
// without asking. With rests on quota and 429 turned off for the provider
|
||||
// (LimitRestOff), the refusal goes to the agent as it came, nothing is set
|
||||
// aside, and the next request is sent to the aggregator, which answers.
|
||||
func TestLimitRestOffKeepsAsking(t *testing.T) {
|
||||
noRests()
|
||||
t.Cleanup(noRests)
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
var calls, failing atomic.Int32
|
||||
failing.Store(1)
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
io.Copy(io.Discard, r.Body)
|
||||
calls.Add(1)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if failing.Load() == 1 {
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
io.WriteString(w, `{"error":{"message":"quota exhausted","type":"insufficient_quota"}}`)
|
||||
return
|
||||
}
|
||||
io.WriteString(w, `{"id":"x","object":"chat.completion","model":"m1","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`)
|
||||
}))
|
||||
t.Cleanup(up.Close)
|
||||
p := provider.Provider{ID: "agg", Name: "Agg", Key: "k", Models: []string{"m1"}, Chat: up.URL + "/v1", LimitRestOff: true}
|
||||
if err := provider.Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := `{"model":"agg/m1","messages":[{"role":"user","content":"hi"}]}`
|
||||
code, body := post(t, "/v1/chat/completions", req)
|
||||
if code != http.StatusTooManyRequests || !strings.Contains(body, "quota exhausted") {
|
||||
t.Fatalf("first: %d %s", code, body)
|
||||
}
|
||||
restingUntil.Lock()
|
||||
n := len(restingUntil.m)
|
||||
restingUntil.Unlock()
|
||||
if n != 0 {
|
||||
t.Fatalf("%d rests set after the refusal, want none", n)
|
||||
}
|
||||
before := calls.Load()
|
||||
// refused again: asked again, never answered from a rest
|
||||
code, body = post(t, "/v1/chat/completions", req)
|
||||
if code != http.StatusTooManyRequests || strings.Contains(body, "not asked again") || calls.Load() == before {
|
||||
t.Fatalf("second, still refusing: %d %s, upstream asked %d times", code, body, calls.Load()-before)
|
||||
}
|
||||
failing.Store(0)
|
||||
code, body = post(t, "/v1/chat/completions", req)
|
||||
if code != http.StatusOK || !strings.Contains(body, `"hi"`) {
|
||||
t.Fatalf("third, upstream back: %d %s", code, body)
|
||||
}
|
||||
}
|
||||
|
||||
// The switch covers every refusal it names, and only those: out of quota
|
||||
// or credit and rate limited, at any status, and any 429, rest nothing,
|
||||
// count toward no backoff and sink nothing; a refused key still rests.
|
||||
// Off by default: the same refusals rest a provider without it.
|
||||
func TestLimitRestOffRestsNothingForALimit(t *testing.T) {
|
||||
s := &Server{}
|
||||
limits := []struct {
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
{429, `{"error":{"message":"quota exhausted","type":"insufficient_quota"}}`},
|
||||
{429, `{"error":{"message":"Too many requests","type":"rate_limit_error"}}`},
|
||||
{429, `{"error":{"message":"busy"}}`},
|
||||
{403, `{"error":{"message":"Your quota has been exhausted","type":"insufficient_quota"}}`},
|
||||
{402, `{"error":{"message":"Insufficient balance","type":"insufficient_balance"}}`},
|
||||
}
|
||||
for _, off := range []bool{true, false} {
|
||||
c := candidate{p: provider.Provider{ID: "lim", Key: "k", LimitRestOff: off}, model: "m", rest: "lim#k"}
|
||||
id := c.restKey()
|
||||
clean := func() {
|
||||
clearRest(id)
|
||||
clearRest(c.restID())
|
||||
routed.Lock()
|
||||
delete(routed.failures, id)
|
||||
delete(routed.failures, c.restID())
|
||||
routed.Unlock()
|
||||
sunk.Lock()
|
||||
delete(sunk.m, id)
|
||||
sunk.Unlock()
|
||||
}
|
||||
clean()
|
||||
t.Cleanup(clean)
|
||||
for _, k := range limits {
|
||||
clean()
|
||||
r := s.restAfter(c, k.status, http.Header{}, []byte(k.body))
|
||||
if off && (r.By != "off" || r.Until.After(time.Now()) || resting(c)) {
|
||||
t.Fatalf("off, %d %s: rests %v by %s (%s), want none", k.status, k.body, time.Until(r.Until), r.By, r.Why)
|
||||
}
|
||||
if !off && (r.By == "off" || !resting(c)) {
|
||||
t.Fatalf("on, %d %s: not rested (%s by %s)", k.status, k.body, r.Why, r.By)
|
||||
}
|
||||
routed.Lock()
|
||||
f := routed.failures[id]
|
||||
routed.Unlock()
|
||||
sunk.Lock()
|
||||
_, sank := sunk.m[id]
|
||||
sunk.Unlock()
|
||||
if off && (f != 0 || sank) {
|
||||
t.Fatalf("off, %d: %d failures counted, sunk %v", k.status, f, sank)
|
||||
}
|
||||
}
|
||||
if off {
|
||||
clean()
|
||||
r := s.restAfter(c, 401, http.Header{}, []byte(`{"error":{"message":"invalid api key"}}`))
|
||||
if r.By == "off" || !resting(c) {
|
||||
t.Fatalf("a refused key isn't rested: %s by %s", r.Why, r.By)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -929,6 +929,16 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo
|
||||
// the account is as good as it was; the proxy is the user's to start
|
||||
return r
|
||||
}
|
||||
if c.p.LimitRestOff && (why == failQuota || why == failCredit || why == failRate || status == http.StatusTooManyRequests) {
|
||||
// the user set it never to rest for a limit (provider.LimitRestOff;
|
||||
// zoecats on Discord: a local aggregator says "quota exhausted"
|
||||
// for the moment it switches upstreams, and the next request goes
|
||||
// through): not set aside, sunk or counted, and asked as ever. A
|
||||
// key refused, a model not served or a plain failure rests it as
|
||||
// before
|
||||
r.By, r.Until = "off", now
|
||||
return r
|
||||
}
|
||||
if why == failCredit || why == failQuota {
|
||||
// the vendor's words, for quotaHeld to give again
|
||||
r.said = provider.APIError(body, http.StatusText(status))
|
||||
|
||||
@@ -7998,7 +7998,7 @@ function advancedSet(d, p) {
|
||||
return (d.headers || []).some(([k]) => (k || "").trim()) || !!(d.extraBody || "").trim() ||
|
||||
!!d.proxyMode || Object.values(d.accountProxies || {}).some((x) => x?.mode) ||
|
||||
[d.concurrency, d.queueLimit, d.queueWait, d.maxRPM, d.priceRate, d.contexts, d.outputs, d.compacts].some((v) => String(v ?? "").trim()) ||
|
||||
!!(d.searches || d.authHeader || d.passUserAgent || d.unredacted || d.pinUpstream || d.nativeCompaction || d.balanceToken) ||
|
||||
!!(d.searches || d.authHeader || d.passUserAgent || d.unredacted || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff) ||
|
||||
!!d.fallback?.length || !!p?.balanceToken?.set;
|
||||
}
|
||||
function priceRateError(ed) {
|
||||
@@ -9033,7 +9033,7 @@ function baseAPIOf(p) {
|
||||
|
||||
// draftOf is a saved provider as its editor's form holds it.
|
||||
function draftOf(p) {
|
||||
return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, searches: !!p.searches, unredacted: !!p.unredacted, insecureTLS: !!p.insecureTLS, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p) };
|
||||
return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, searches: !!p.searches, unredacted: !!p.unredacted, insecureTLS: !!p.insecureTLS, limitRestOff: !!p.limitRestOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p) };
|
||||
}
|
||||
|
||||
// duplicateProvider opens the Add form on a copy of p (#268): its URLs,
|
||||
@@ -9644,6 +9644,12 @@ function drawEditor(p, presetID) {
|
||||
showTLS();
|
||||
ed.append(...row);
|
||||
}
|
||||
// off, a 429 or quota refusal rests none of its keys (LimitRestOff, zoecats)
|
||||
if (custom) {
|
||||
const [rtk, rcb] = tick(t("Set it aside when out of quota or rate limited"), !draft.limitRestOff);
|
||||
rcb.onchange = () => { draft.limitRestOff = !rcb.checked; };
|
||||
advIn.append(...field(t("Rests"), rtk, t("Off: a 429 or an out-of-quota refusal doesn't rest its keys, and the next request is sent to it as usual. For a relay whose limits pass in a moment.")));
|
||||
}
|
||||
|
||||
// a vendor that tells the whole account's balance only to a token of its
|
||||
// own (AiHubMix's system access token), where a key knows just its own
|
||||
@@ -9992,6 +9998,7 @@ function drawEditor(p, presetID) {
|
||||
if (twoKeyHeaders()) body.authHeader = draft.authHeader || "";
|
||||
body.unredacted = !!draft.unredacted && onLAN();
|
||||
if (tlsTakes()) body.insecureTLS = !!draft.insecureTLS && onHTTPS();
|
||||
if (custom) body.limitRestOff = !!draft.limitRestOff;
|
||||
if (!decideOnly(p || pr)) body.nativeCompaction = !!draft.nativeCompaction && carriesCompaction();
|
||||
body.passUserAgent = !!draft.passUserAgent && uaPassable();
|
||||
const cx = parseContexts(draft.contexts || "");
|
||||
|
||||
@@ -3456,6 +3456,9 @@ const I18N = {
|
||||
"Redaction": "脱敏",
|
||||
"Send requests unmasked": "请求不脱敏",
|
||||
"Don't check its certificate": "不校验它的证书",
|
||||
"Set it aside when out of quota or rate limited": "额度用完或被限流时暂停它",
|
||||
"Rests": "暂停",
|
||||
"Off: a 429 or an out-of-quota refusal doesn't rest its keys, and the next request is sent to it as usual. For a relay whose limits pass in a moment.": "关闭后:429 或额度用完的拒绝不会让它的密钥暂停,下一个请求照常发给它。适合限额很快就会恢复的中转。",
|
||||
"Certificate": "证书",
|
||||
"For your own server with a self-signed certificate or one from your company's CA. magpie then can't tell it from another machine answering at its address: turn it on only on a network you trust.": "用于你自己的服务器,证书是自签名的或来自公司内部 CA。开启后 magpie 无法分辨应答的是它本身还是同一地址上的另一台机器:只在你信任的网络中开启。",
|
||||
"Codex compacts on this provider": "Codex 在此服务商上原生压缩",
|
||||
@@ -7388,6 +7391,9 @@ const I18N = {
|
||||
"Redaction": "脫敏",
|
||||
"Send requests unmasked": "請求不脫敏",
|
||||
"Don't check its certificate": "不驗證它的憑證",
|
||||
"Set it aside when out of quota or rate limited": "額度用完或被限流時暫停它",
|
||||
"Rests": "暫停",
|
||||
"Off: a 429 or an out-of-quota refusal doesn't rest its keys, and the next request is sent to it as usual. For a relay whose limits pass in a moment.": "關閉後:429 或額度用完的拒絕不會讓它的金鑰暫停,下一個請求照常送給它。適合限額很快就會恢復的中轉。",
|
||||
"Certificate": "憑證",
|
||||
"For your own server with a self-signed certificate or one from your company's CA. magpie then can't tell it from another machine answering at its address: turn it on only on a network you trust.": "用於你自己的伺服器,憑證是自簽的或來自公司內部 CA。開啟後 magpie 無法分辨應答的是它本身還是同一位址上的另一台機器:只在你信任的網路中開啟。",
|
||||
"Codex compacts on this provider": "Codex 在此服務商上原生壓縮",
|
||||
@@ -11337,6 +11343,9 @@ const I18N = {
|
||||
"Redaction": "マスク",
|
||||
"Send requests unmasked": "リクエストをマスクしない",
|
||||
"Don't check its certificate": "証明書を検証しない",
|
||||
"Set it aside when out of quota or rate limited": "クォータ切れやレート制限で一時的に外す",
|
||||
"Rests": "一時停止",
|
||||
"Off: a 429 or an out-of-quota refusal doesn't rest its keys, and the next request is sent to it as usual. For a relay whose limits pass in a moment.": "オフ:429 やクォータ切れで拒否されてもキーを休ませず、次のリクエストはいつも通り送られます。制限がすぐ解けるリレー向けです。",
|
||||
"Certificate": "証明書",
|
||||
"For your own server with a self-signed certificate or one from your company's CA. magpie then can't tell it from another machine answering at its address: turn it on only on a network you trust.": "自己署名証明書や社内 CA の証明書を使う自分のサーバー向けです。オンにすると、magpie はそのアドレスで応答しているのが本物か別のマシンかを見分けられません。信頼できるネットワークでのみオンにしてください。",
|
||||
"Codex compacts on this provider": "Codex のコンパクションをこのプロバイダーで行う",
|
||||
@@ -15300,6 +15309,9 @@ const I18N = {
|
||||
"Redaction": "Maskierung",
|
||||
"Send requests unmasked": "Anfragen unmaskiert senden",
|
||||
"Don't check its certificate": "Zertifikat nicht prüfen",
|
||||
"Set it aside when out of quota or rate limited": "Bei aufgebrauchtem Kontingent oder Ratenlimit pausieren",
|
||||
"Rests": "Pausen",
|
||||
"Off: a 429 or an out-of-quota refusal doesn't rest its keys, and the next request is sent to it as usual. For a relay whose limits pass in a moment.": "Aus: Ein 429 oder eine Ablehnung wegen aufgebrauchtem Kontingent pausiert seine Schlüssel nicht, die nächste Anfrage geht wie gewohnt an ihn. Für ein Relay, dessen Limits gleich wieder vorbei sind.",
|
||||
"Certificate": "Zertifikat",
|
||||
"For your own server with a self-signed certificate or one from your company's CA. magpie then can't tell it from another machine answering at its address: turn it on only on a network you trust.": "Für Ihren eigenen Server mit selbstsigniertem Zertifikat oder einem Ihrer Firmen-CA. magpie kann ihn dann nicht von einem anderen Rechner unterscheiden, der unter seiner Adresse antwortet: nur in einem Netzwerk einschalten, dem Sie vertrauen.",
|
||||
"Codex compacts on this provider": "Codex kompaktiert bei diesem Anbieter",
|
||||
|
||||
@@ -15,8 +15,8 @@ import (
|
||||
// so a page can't quietly grow back into the core; a change that needs more
|
||||
// raises them and says why in its commit.
|
||||
const (
|
||||
appScriptBudget = 1_321_424 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397); 1,269,083 with Free first's option in the provider editor's ROUTINGS, which the Routing page reads too, plus 1.5%; 1,272,726 with the Providers page drawing its last list at once (#1519), the core's page, and the Routing trace's account names read without Object.entries (#1481), plus 1.5%; a dialog growing out of the row that opened it and folding back into it, the core's own since every page's dialogs open through it (10-20); Codex's and Claude Code's own settings moved from Settings into the agent's row on the Agents page, the core's own since the tray panel and the window both draw them (10-20); 1,314,432 with Settings › Privacy's record of what was masked (its summary, the records view and the local model's controls), which belongs to Settings, the core's own, plus 1.5%; 1,336,481 with a provider's Names & levels saying Provider in model names is Settings' and opening it there (joe), and Settings' Image recognition saying where a custom provider's model is marked (nexnull), both in the core's own pages, with no room added (10-23); 1,337,633 with Settings › Models › Replies' Intent classifier timeout (#2934, reyoung), Settings' own row, drawn by waitRow, which the Image generation timeout's row now shares, with no room added; 1,337,735 with the provider editor's link naming a partner's page by its own host (siteHost) instead of usemagpie.ai's /go link, the core's own editor, with no room added (10-23); 1,338,084 with Check in now saying what the press came to (claimed +credits, already today, not available yet) where it said "refreshed" (#3326), the check-in row the tray panel draws too, the core's own, with no room added (10-23); 1,338,929 with a new partner's tile keeping a small dot until it is opened, in the add sheet, the core's own, with no room added (10-23); 1,343,324 with the sidebar's open-page row marked by one shape that moves on a spring (navTopGo), the window's own shell, which every page sits beside, with no room added (10-23); 1,343,465 with a dialog kept centred while its content comes in, until it is pressed (holdModal, every page's dialogs), the core's own, with no room added (10-24); 1,317,486 with what masking did moved out to Insights › Masking (plugins/redact), the budget lowered to it (10-24); 1,321,336 with Codex's one subagent model, its card's square saying plainly what each choice does and a row with a name in its sheet, where two squares read alike (the owner), the Agents page's, which the tray panel draws too, the core's own, with no room added (10-24); 1,321,424 with Settings › Models' Image generation MCP server row beside Image recognition's (JonahFu on X), the two drawn by one helper (mcpRow), Settings' own, with no room added (10-25)
|
||||
coreScriptBudget = 1_528_972 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25)
|
||||
appScriptBudget = 1_321_994 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397); 1,269,083 with Free first's option in the provider editor's ROUTINGS, which the Routing page reads too, plus 1.5%; 1,272,726 with the Providers page drawing its last list at once (#1519), the core's page, and the Routing trace's account names read without Object.entries (#1481), plus 1.5%; a dialog growing out of the row that opened it and folding back into it, the core's own since every page's dialogs open through it (10-20); Codex's and Claude Code's own settings moved from Settings into the agent's row on the Agents page, the core's own since the tray panel and the window both draw them (10-20); 1,314,432 with Settings › Privacy's record of what was masked (its summary, the records view and the local model's controls), which belongs to Settings, the core's own, plus 1.5%; 1,336,481 with a provider's Names & levels saying Provider in model names is Settings' and opening it there (joe), and Settings' Image recognition saying where a custom provider's model is marked (nexnull), both in the core's own pages, with no room added (10-23); 1,337,633 with Settings › Models › Replies' Intent classifier timeout (#2934, reyoung), Settings' own row, drawn by waitRow, which the Image generation timeout's row now shares, with no room added; 1,337,735 with the provider editor's link naming a partner's page by its own host (siteHost) instead of usemagpie.ai's /go link, the core's own editor, with no room added (10-23); 1,338,084 with Check in now saying what the press came to (claimed +credits, already today, not available yet) where it said "refreshed" (#3326), the check-in row the tray panel draws too, the core's own, with no room added (10-23); 1,338,929 with a new partner's tile keeping a small dot until it is opened, in the add sheet, the core's own, with no room added (10-23); 1,343,324 with the sidebar's open-page row marked by one shape that moves on a spring (navTopGo), the window's own shell, which every page sits beside, with no room added (10-23); 1,343,465 with a dialog kept centred while its content comes in, until it is pressed (holdModal, every page's dialogs), the core's own, with no room added (10-24); 1,317,486 with what masking did moved out to Insights › Masking (plugins/redact), the budget lowered to it (10-24); 1,321,336 with Codex's one subagent model, its card's square saying plainly what each choice does and a row with a name in its sheet, where two squares read alike (the owner), the Agents page's, which the tray panel draws too, the core's own, with no room added (10-24); 1,321,424 with Settings › Models' Image generation MCP server row beside Image recognition's (JonahFu on X), the two drawn by one helper (mcpRow), Settings' own, with no room added (10-25); 1,321,994 with a provider of the user's set never to rest for a limit (zoecats), the provider editor's Advanced row, the core's own editor, with no room added (10-25)
|
||||
coreScriptBudget = 1_529_542 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25)
|
||||
)
|
||||
|
||||
func TestCoreScriptBudget(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// zoecats (Discord, 10-25): the editor's "Set it aside when out of quota or
|
||||
// rate limited" tick is saved on a provider of the user's, opens as
|
||||
// saved, and is kept by a Save that leaves it out.
|
||||
func TestProviderSaveLimitRestOff(t *testing.T) {
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
t.Setenv("USERPROFILE", os.Getenv("HOME"))
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
mux := http.NewServeMux()
|
||||
providerRoutes(mux, nil)
|
||||
post := func(body string) {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/provider/save", strings.NewReader(body)))
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("%d %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
off := func() bool {
|
||||
t.Helper()
|
||||
p, err := provider.Find("agg")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info := providerInfo(*p, nil); info.LimitRestOff != p.LimitRestOff {
|
||||
t.Fatalf("the editor is shown %v, saved %v", info.LimitRestOff, p.LimitRestOff)
|
||||
}
|
||||
return p.LimitRestOff
|
||||
}
|
||||
const edit = `{"id":"agg","from":"agg","name":"Aggregator","chat":"http://127.0.0.1:8317/v1","icon":"generic","models":[],"headers":{}`
|
||||
|
||||
post(`{"id":"agg","name":"Aggregator","key":"sk-a","chat":"http://127.0.0.1:8317/v1","icon":"generic","new":true}`)
|
||||
if off() {
|
||||
t.Fatal("added without it, saved never resting")
|
||||
}
|
||||
post(edit + `,"limitRestOff":true}`)
|
||||
if !off() {
|
||||
t.Fatal("unticked, still rests")
|
||||
}
|
||||
post(edit + `}`)
|
||||
if !off() {
|
||||
t.Fatal("a Save that left it out turned rests back on")
|
||||
}
|
||||
post(edit + `,"limitRestOff":false}`)
|
||||
if off() {
|
||||
t.Fatal("ticked again, still never rests")
|
||||
}
|
||||
post(`{"id":"agg2","name":"Aggregator 2","key":"sk-b","chat":"http://127.0.0.1:8318/v1","icon":"generic","new":true,"limitRestOff":true}`)
|
||||
if p, _ := provider.Find("agg2"); p == nil || !p.LimitRestOff {
|
||||
t.Fatal("added unticked, saved resting")
|
||||
}
|
||||
}
|
||||
@@ -104,6 +104,9 @@ type providerJSON struct {
|
||||
// may be, being the user's own and not a preset's or a sign-in's
|
||||
InsecureTLS bool `json:"insecureTLS"`
|
||||
TakesInsecureTLS bool `json:"takesInsecureTLS"`
|
||||
// asked as usual after a quota refusal or a 429, never set aside for
|
||||
// it (provider.LimitRestOff)
|
||||
LimitRestOff bool `json:"limitRestOff"`
|
||||
// Codex's compaction asked of it as Codex sent it, its sealed item
|
||||
// back as it came (provider.NativeCompaction, #1099); CarriesCompaction: its
|
||||
// wire can carry it, so the editor offers it
|
||||
@@ -594,7 +597,7 @@ func providerInfoWith(p provider.Provider, agents []agentUse, desktop map[string
|
||||
ID: p.ID, Name: p.Name, Icon: p.Icon, Preset: p.Preset, Host: p.Host(),
|
||||
Chat: p.Chat, Responses: p.Responses, Anthropic: p.Anthropic, Gemini: p.Gemini, Decide: p.Decide, BaseAPI: p.BaseAPI, ModelTest: p.ModelTest(), TestsAs: p.TestClients(), DecideTest: p.AsksDecideModels(), MarksKinds: p.MarksKinds(),
|
||||
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, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL,
|
||||
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), LimitRestOff: p.LimitRestOff, NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL,
|
||||
Ready: p.Ready(), Chosen: p.Picks(), Models: []modelJSON{}, Agents: []providerAgent{},
|
||||
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, Unlisted: p.Unlisted, NoModels: p.ServesNone(), Off: p.Off, Contexts: p.Contexts,
|
||||
MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), PriceRate: p.PriceRate,
|
||||
@@ -1154,6 +1157,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
// host is taken unchecked (#2383); a save that leaves it out
|
||||
// keeps it
|
||||
InsecureTLS *bool `json:"insecureTLS"`
|
||||
// LimitRestOff is whether a quota refusal or a 429 leaves it
|
||||
// asked as usual; a save that leaves it out keeps it
|
||||
LimitRestOff *bool `json:"limitRestOff"`
|
||||
// MaxConcurrency is how many requests each of its keys or
|
||||
// accounts has out at once: a number (0 none), null for what
|
||||
// its plugin says or none; a save that leaves it out keeps it
|
||||
@@ -1476,6 +1482,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
if req.InsecureTLS != nil {
|
||||
in.InsecureTLS = *req.InsecureTLS
|
||||
}
|
||||
if req.LimitRestOff != nil {
|
||||
in.LimitRestOff = *req.LimitRestOff
|
||||
}
|
||||
add := provider.Add
|
||||
if req.CopyOf != "" {
|
||||
add = func(p provider.Provider) (string, error) { return provider.AddCopy(p, req.CopyOf) }
|
||||
@@ -1508,6 +1517,11 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
} else if old != nil {
|
||||
in.InsecureTLS = old.InsecureTLS
|
||||
}
|
||||
if req.LimitRestOff != nil {
|
||||
in.LimitRestOff = *req.LimitRestOff
|
||||
} else if old != nil {
|
||||
in.LimitRestOff = old.LimitRestOff
|
||||
}
|
||||
if keepCC && old != nil {
|
||||
in.MaxConcurrency = old.MaxConcurrency
|
||||
}
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// zoecats (Discord #feedback, 10-25): a local aggregator answers "quota
|
||||
// exhausted" for the moment it switches upstreams, and magpie set its key
|
||||
// aside for half an hour. A provider the user added has, under Advanced,
|
||||
// "Set it aside when out of quota or rate limited", ticked by default and
|
||||
// with a note. Unticked and saved, it posts limitRestOff: true; one saved
|
||||
// so opens unticked, with Advanced open, and ticked again posts false. A
|
||||
// preset's and a signed-in account have no such row, and a preset's Save
|
||||
// sends none. A checkbox, never a native select. Every language, wide and
|
||||
// narrow.
|
||||
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 base = {
|
||||
icon: "generic", chat: "", responses: "", anthropic: "", catalog: "",
|
||||
models: [{ id: "glm-5", name: "glm-5", on: true }], agents: [], fallback: [], headers: {},
|
||||
key: { set: true, masked: "sk-…agg" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", searches: false,
|
||||
};
|
||||
const agg = { ...base, id: "agg", name: "Local Aggregator", chat: "http://127.0.0.1:8317/v1", limitRestOff: false };
|
||||
const kept = { ...base, id: "kept", name: "Kept Relay", chat: "http://127.0.0.1:8318/v1", limitRestOff: true };
|
||||
const openai = { ...base, id: "openai", name: "OpenAI", preset: "openai", chat: "https://api.openai.example/v1" };
|
||||
const codex = {
|
||||
id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "",
|
||||
models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [],
|
||||
account: { agent: "codex", agentName: "Codex", user: "me@example.com", plan: "PLUS", logins: [{ user: "me@example.com", plan: "PLUS", active: true, on: true }] },
|
||||
proxy: "",
|
||||
};
|
||||
|
||||
function serve(lang, posts) {
|
||||
const providers = {
|
||||
providers: [agg, kept, openai, codex],
|
||||
presets: [{ id: "openai", name: "OpenAI", kind: "vendor", icon: "openai", chat: "https://api.openai.example/v1", added: true }],
|
||||
excluded: [], gateway: { running: true, window: true },
|
||||
};
|
||||
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json(state);
|
||||
if (url.pathname === "/api/providers") return json(providers);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname.startsWith("/api/provider/") && route.request().method() === "POST") {
|
||||
posts.push({ action: url.pathname.slice("/api/provider/".length), body: route.request().postDataJSON() });
|
||||
return json(providers);
|
||||
}
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const strings = [
|
||||
"Rests", "Set it aside when out of quota or rate limited",
|
||||
"Off: a 429 or an out-of-quota refusal doesn't rest its keys, and the next request is sent to it as usual. For a relay whose limits pass in a moment.",
|
||||
];
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
for (const width of [1100, 420]) {
|
||||
const open = async (t, name) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
let page;
|
||||
t.after(async () => {
|
||||
if (process.env.ARTIFACT_DIR && page) {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-${name}-limit-rest.png`), fullPage: true });
|
||||
}
|
||||
await browser.close();
|
||||
});
|
||||
page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const posts = [];
|
||||
await page.route("**/*", serve(lang, posts));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
const w = await page.evaluate(([lang, ks]) => Object.fromEntries(ks.map((k) => [k, (I18N[lang] || {})[k] || k])), [lang, [...strings, "Save"]]);
|
||||
await page.locator(".row.provider", { hasText: name }).click();
|
||||
await page.locator(".editor .bar").waitFor();
|
||||
return { page, errors, posts, w };
|
||||
};
|
||||
const adv = (page) => page.locator(".editor details.advanced");
|
||||
const unfold = async (page) => {
|
||||
await adv(page).waitFor({ state: "attached" });
|
||||
if (!(await adv(page).evaluate((d) => d.open))) await adv(page).locator(":scope > summary").click();
|
||||
};
|
||||
const row = (page, w) => page.locator(".editor label.tick", { hasText: w["Set it aside when out of quota or rate limited"] });
|
||||
const box = (page, w) => row(page, w).locator("input[type=checkbox]");
|
||||
const save = async (page, posts, w) => {
|
||||
const n = posts.length;
|
||||
await page.locator(".editor .bar").getByRole("button", { name: w.Save, exact: true }).click();
|
||||
for (let i = 0; i < 50 && posts.length === n; i++) await page.waitForTimeout(50);
|
||||
return posts.at(-1);
|
||||
};
|
||||
|
||||
test(`${engine} ${lang} ${width}: a provider of the user's rests for a limit by default, and is saved not to`, async (t) => {
|
||||
const { page, errors, posts, w } = await open(t, "Local Aggregator");
|
||||
if (lang !== "en") {
|
||||
const missing = await page.evaluate(([lang, ks]) => ks.filter((k) => !(I18N[lang] || {})[k]), [lang, strings]);
|
||||
assert.deepEqual(missing, [], `every string has its ${lang}`);
|
||||
}
|
||||
assert.equal(await adv(page).evaluate((d) => d.open), false, "Advanced stays folded while it is as by default");
|
||||
await unfold(page);
|
||||
assert.equal(await row(page, w).isVisible(), true);
|
||||
assert.equal(await box(page, w).isChecked(), true, "ticked by default");
|
||||
assert.equal(await page.locator(".editor select").count(), 0, "no native select");
|
||||
await box(page, w).scrollIntoViewIfNeeded();
|
||||
const r = await row(page, w).boundingBox();
|
||||
assert.ok(r.width > 60 && r.x >= 0 && r.x + r.width <= width, `the row fits: ${JSON.stringify(r)}`);
|
||||
assert.ok(await page.locator(".editor", { hasText: w[strings[2]] }).count() > 0, "the note is shown");
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true, "no sideways scroll");
|
||||
await box(page, w).uncheck();
|
||||
const saved = await save(page, posts, w);
|
||||
assert.equal(saved.action, "save");
|
||||
assert.equal(saved.body.id, "agg");
|
||||
assert.equal(saved.body.limitRestOff, true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang} ${width}: one saved not to rest opens unticked with Advanced open, and ticked is saved to rest`, async (t) => {
|
||||
const { page, errors, posts, w } = await open(t, "Kept Relay");
|
||||
assert.equal(await adv(page).evaluate((d) => d.open), true, "Advanced opens with it set");
|
||||
assert.equal(await box(page, w).isChecked(), false);
|
||||
await box(page, w).scrollIntoViewIfNeeded();
|
||||
await box(page, w).check();
|
||||
const saved = await save(page, posts, w);
|
||||
assert.equal(saved.body.id, "kept");
|
||||
assert.equal(saved.body.limitRestOff, false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang} ${width}: a preset's and a sign-in's have no row, and a preset's Save sends none`, async (t) => {
|
||||
{
|
||||
const { page, errors, posts, w } = await open(t, "OpenAI");
|
||||
await unfold(page);
|
||||
assert.equal(await row(page, w).count(), 0);
|
||||
const saved = await save(page, posts, w);
|
||||
assert.equal(saved.action, "save");
|
||||
assert.equal("limitRestOff" in saved.body, false, `a preset's Save sends none: ${JSON.stringify(saved.body)}`);
|
||||
assert.deepEqual(errors, []);
|
||||
}
|
||||
const { page, errors, w } = await open(t, "Codex");
|
||||
await unfold(page);
|
||||
assert.equal(await row(page, w).count(), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -195,6 +195,12 @@ type Provider struct {
|
||||
// still stands over it. RestCapOff (-1): no rest at all after a
|
||||
// failure that says nothing of why, a rate limit's as the gateway's own.
|
||||
RestCap int `json:"restCap,omitempty"`
|
||||
// LimitRestOff keeps its keys and accounts asked when the vendor says
|
||||
// they are out of quota or answers 429 (zoecats on Discord: a local
|
||||
// aggregator says "quota exhausted" for a moment while it switches
|
||||
// upstreams, and a rest of half an hour held every request back until
|
||||
// magpie restarted). Off by default: such a refusal rests it as ever.
|
||||
LimitRestOff bool `json:"limitRestOff,omitempty"`
|
||||
|
||||
// PriceRate is what the provider charges against the official price
|
||||
// (ITea312, #819): a relay that bills 0.8× or 1.5× of it. It scales the
|
||||
|
||||
Reference in New Issue
Block a user