Files
magpie/internal/gateway/use_first_test.go
T
yetone 8e350155b6 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, at da548b454 = origin/main):
- go test ./internal/routes ./internal/provider: ok. ./internal/gui: ok
  but TestMainWindowCorners/macOS_26_SDK, red the same on a fresh
  origin/main da548b454 checkout (#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
2026-11-07 07:15:40 +08:00

80 lines
2.3 KiB
Go

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 := &quotaKeyed{}, &quotaKeyed{}
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)
}
}