copilot: a model the plan refuses is remembered and Auto falls back (#371, #256) — Copilot answers a model the account's plan doesn't carry (Student, Free) with 400 model_not_supported; magpie kept offering and picking it. Such a model is now marked refused for that token for 6h, left out of the models listed and of Auto's picks, and the request is retried on the next model (fallback, then default, then non-premium such as gpt-4.1). TestCopilotRefused* fail without the change.

This commit is contained in:
yetone
2026-10-01 11:28:41 +08:00
parent eb89665d98
commit 7d0f33d702
9 changed files with 505 additions and 41 deletions
+82
View File
@@ -0,0 +1,82 @@
package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// #256: on a Copilot Student account, copilot/auto answered 400 "Copilot:
// The requested model is not supported." — Auto's session picked a model
// Copilot then refused the account (#371: claude-haiku-4.5, policy enabled
// and all). The gateway sends the request again with another model Auto
// offers, and the agent is answered.
func TestCopilotAutoRefusedThroughGateway(t *testing.T) {
fresh(t)
cfg := os.Getenv("XDG_CONFIG_HOME")
os.MkdirAll(filepath.Join(cfg, "github-copilot"), 0o755)
os.WriteFile(filepath.Join(cfg, "github-copilot", "apps.json"), mustJSON(map[string]any{
"github.com:Iv1.x": map[string]any{"user": "student", "oauth_token": "gho_student371"},
}), 0o600)
var mu sync.Mutex
var asked []string // "<model> <session token>"
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
defer mu.Unlock()
switch r.URL.Path {
case "/models":
io.WriteString(w, `{"data":[
{"id":"claude-haiku-4.5","name":"Claude Haiku 4.5","model_picker_enabled":true,"policy":{"state":"enabled"},"supported_endpoints":["/chat/completions","/v1/messages"],"capabilities":{"type":"chat"}},
{"id":"gpt-4.1","name":"GPT-4.1","model_picker_enabled":true,"is_chat_default":true,"is_chat_fallback":true,"policy":{"state":"enabled"},"supported_endpoints":["/chat/completions"],"capabilities":{"type":"chat"}}]}`)
case "/models/session":
io.WriteString(w, `{"session_token":"auto-tok","selected_model":"claude-haiku-4.5","available_models":["claude-haiku-4.5","gpt-4.1"],"expires_at":`+
mustString(time.Now().Add(time.Hour).Unix())+`}`)
default:
m := modelOf(b)
asked = append(asked, m+" "+r.Header.Get("Copilot-Session-Token"))
if m != "gpt-4.1" {
w.WriteHeader(400)
io.WriteString(w, `{"error":{"message":"The requested model is not supported.","code":"model_not_supported","param":"model","type":"invalid_request_error"}}`)
return
}
io.WriteString(w, `{"id":"c1","model":"gpt-4.1","choices":[{"index":0,"message":{"role":"assistant","content":"hello from gpt-4.1"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":3}}`)
}
}))
defer api.Close()
gh := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/token") {
json.NewEncoder(w).Encode(map[string]any{"token": "sess", "expires_at": time.Now().Add(time.Hour).Unix(), "endpoints": map[string]string{"api": api.URL}})
return
}
io.WriteString(w, `{"copilot_plan":"individual","access_type_sku":"free_educational_quota"}`)
}))
defer gh.Close()
oldTok, oldUser := provider.CopilotTokenURL, provider.CopilotUserURL
provider.CopilotTokenURL, provider.CopilotUserURL = gh.URL+"/token", gh.URL+"/user"
defer func() { provider.CopilotTokenURL, provider.CopilotUserURL = oldTok, oldUser }()
s := New()
for range 2 {
code, body := postAs(t, s, "", `{"model":"copilot/auto","messages":[{"role":"user","content":"hi"}]}`)
if code != 200 || !strings.Contains(body, "hello from gpt-4.1") {
t.Fatalf("copilot/auto: %d %s", code, body)
}
}
mu.Lock()
defer mu.Unlock()
// the refused model is asked once, then passed over
if strings.Join(asked, "|") != "claude-haiku-4.5 auto-tok|gpt-4.1 auto-tok|gpt-4.1 auto-tok" {
t.Fatalf("Copilot was asked %q", asked)
}
}
+14 -9
View File
@@ -1359,19 +1359,24 @@ func markOpenRouterSharedPool(w http.ResponseWriter) {
// provider that turns away betas it doesn't know by name (Bedrock's: 400
// Unexpected value(s) `x` for the `anthropic-beta` header) is asked again
// once without them, and they're left out for it from then on. An account's
// 403 it can mend (Provider.Retry) is asked once more.
// 403 or 400 it can mend (Provider.Retry) is asked again, a few times at most.
func (s *Server) forward(ctx context.Context, p provider.Provider, to provider.Protocol, path string, body []byte, in http.Header) (*http.Response, error) {
res, err := s.forwardOnce(ctx, p, to, path, body, in)
if err == nil && res.StatusCode == http.StatusForbidden && p.Retries() {
if err == nil && (res.StatusCode == http.StatusForbidden || res.StatusCode == http.StatusBadRequest) && p.Retries() {
// an account that can mend what the refusal names (a Factory org
// the server won't take) is asked once more
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
res.Body.Close()
res.Body = io.NopCloser(bytes.NewReader(b))
if p.Retry(ctx, res.StatusCode, b) {
return s.forwardOnce(ctx, p, to, path, body, in)
// the server won't take; a model Copilot's Auto picked that the
// account is refused, for which Auto picks another) is asked again
for range 3 {
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
res.Body.Close()
res.Body = io.NopCloser(bytes.NewReader(b))
if !p.Retry(ctx, body, res.StatusCode, b) {
break
}
if res, err = s.forwardOnce(ctx, p, to, path, body, in); err != nil || res.StatusCode != http.StatusForbidden && res.StatusCode != http.StatusBadRequest {
return res, err
}
}
return res, nil
}
if err != nil || to != provider.Anthropic || res.StatusCode != http.StatusBadRequest {
return res, err
+44 -15
View File
@@ -73,10 +73,14 @@ type Account struct {
// the model it picks for the account (copilot_auto.go).
auto func(ctx context.Context) (copilotAutoSession, error)
// retry is asked about a refusal the backend answered: true when the
// account has put right what it names and the request is worth
// sending once more (a Factory org the server can't reach, factory.go).
retry func(ctx context.Context, status int, body []byte) bool
// retry is asked about a refusal the backend answered to a request for
// model: true when the account has put right what it names and the
// request is worth sending once more (a Factory org the server can't
// reach, factory.go; another model for Copilot's Auto, copilot_refused.go).
retry func(ctx context.Context, model string, status int, body []byte) bool
// unusable is set on a Copilot account: whether a model its list offers
// is one the account was refused (copilot_refused.go).
unusable func(model string) bool
// explain adds what the user can do about a refusal the account's
// backend answered, "" when there is nothing to add (factory.go).
explain func(status int, body []byte) string
@@ -170,13 +174,13 @@ func (p Provider) Sign(ctx context.Context, req *http.Request, proto Protocol, b
// refusal's body is worth reading before it is passed on.
func (p Provider) Retries() bool { return p.Account != nil && p.Account.retry != nil }
// Retry is whether a request the backend refused with status and body is
// worth sending once more, the account having mended what it named.
func (p Provider) Retry(ctx context.Context, status int, body []byte) bool {
// Retry is whether a request (sent) the backend refused with status and
// body is worth sending once more, the account having mended what it named.
func (p Provider) Retry(ctx context.Context, sent []byte, status int, body []byte) bool {
if p.Account == nil || p.Account.retry == nil {
return false
}
return p.Account.retry(p.Via(ctx), status, body)
return p.Account.retry(p.Via(ctx), bodyModel(sent), status, body)
}
// Explain is the error a refusal is passed on as: msg, with what the
@@ -1138,6 +1142,10 @@ func copilotProvider(app copilotApp, plan string) Provider {
}
return copilotAutoResolve(ctx, app, false)
}
acct.retry = func(ctx context.Context, model string, status int, body []byte) bool {
return copilotRefused(ctx, app, model, status, body)
}
acct.unusable = func(model string) bool { return copilotRefuses(app.Token, model) }
acct.fetch = func(ctx context.Context) ([]catalog.Model, error) {
ms, err := copilotModels(ctx, app)
if err != nil {
@@ -1247,7 +1255,7 @@ var copilotInternal = regexp.MustCompile(`^(copilot-search|exec-agent|trajectory
var (
copilotTermsMu sync.Mutex
copilotTerms = map[string]map[string]bool{} // by GitHub token: models whose terms wait
copilotPicks = map[string][]string{} // by GitHub token: models it may pick by hand, in the list's order
copilotPicks = map[string][]string{} // by GitHub token: models it may pick by hand, the likeliest served first
)
// copilotAccept enables model for the account when its terms still wait.
@@ -1322,12 +1330,17 @@ func copilotModels(ctx context.Context, app copilotApp) ([]catalog.Model, error)
b, _ := io.ReadAll(io.LimitReader(res.Body, 4<<20))
var v struct {
Data []struct {
ID string `json:"id"`
Name string `json:"name"`
Vendor string `json:"vendor"`
Picker bool `json:"model_picker_enabled"`
Category string `json:"model_picker_category"`
Endpoints []string `json:"supported_endpoints"`
ID string `json:"id"`
Name string `json:"name"`
Vendor string `json:"vendor"`
Picker bool `json:"model_picker_enabled"`
Category string `json:"model_picker_category"`
Default bool `json:"is_chat_default"`
Fallback bool `json:"is_chat_fallback"`
Endpoints []string `json:"supported_endpoints"`
Billing *struct {
Premium bool `json:"is_premium"`
} `json:"billing"`
Capabilities struct {
Type string `json:"type"`
Supports struct {
@@ -1345,6 +1358,7 @@ func copilotModels(ctx context.Context, app copilotApp) ([]catalog.Model, error)
}
var out []catalog.Model
var picks []string
rank := map[string]int{} // how early a pick stands in for Auto
waiting := map[string]bool{}
copilotSeenMu.Lock()
for _, m := range v.Data {
@@ -1364,6 +1378,20 @@ func copilotModels(ctx context.Context, app copilotApp) ([]catalog.Model, error)
switch {
case m.Policy != nil && m.Policy.State == "enabled", m.Policy == nil && m.Picker:
picks = append(picks, m.ID)
// Copilot's base model (VS Code's copilot-base: the list's
// is_chat_fallback), then its default, then one billed to no
// premium allowance: what a plan that may pick little (a
// Student's) is likeliest to be served
switch {
case m.Fallback:
rank[m.ID] = 0
case m.Default:
rank[m.ID] = 1
case m.Billing != nil && !m.Billing.Premium:
rank[m.ID] = 2
default:
rank[m.ID] = 3
}
case m.Policy != nil && m.Policy.Terms != "":
waiting[m.ID] = true
default:
@@ -1375,6 +1403,7 @@ func copilotModels(ctx context.Context, app copilotApp) ([]catalog.Model, error)
// it lists, and the only choice a Student plan has: an account whose
// list leaves it nothing to pick by hand still has it
out = append(out, copilotAutoModel)
slices.SortStableFunc(picks, func(a, b string) int { return rank[a] - rank[b] })
copilotTermsMu.Lock()
copilotTerms[app.Token] = waiting
copilotPicks[app.Token] = picks
+28 -10
View File
@@ -24,6 +24,7 @@ import (
"errors"
"io"
"net/http"
"slices"
"strings"
"sync"
"time"
@@ -55,11 +56,12 @@ var (
type copilotAutoKey struct{}
// copilotAutoResolve is the account's Auto session, asked again a couple of
// minutes before it expires or when fresh is set.
// minutes before it expires, when fresh is set or once the account was
// refused its model.
func copilotAutoResolve(ctx context.Context, app copilotApp, fresh bool) (copilotAutoSession, error) {
copilotAutoMu.Lock()
defer copilotAutoMu.Unlock()
if a, ok := copilotAutoSessions[app.Token]; ok && !fresh && (a.ExpiresAt == 0 || time.Until(time.Unix(a.ExpiresAt, 0)) > 2*time.Minute) {
if a, ok := copilotAutoSessions[app.Token]; ok && !fresh && (a.ExpiresAt == 0 || time.Until(time.Unix(a.ExpiresAt, 0)) > 2*time.Minute) && !copilotRefuses(app.Token, a.Model) {
return a, nil
}
s, err := app.session(ctx)
@@ -107,11 +109,16 @@ func copilotAutoResolve(ctx context.Context, app copilotApp, fresh bool) (copilo
json.Unmarshal(v.Selected, &m)
model = m.ID
}
// one the account was refused is passed over for another available
if model != "" && copilotRefuses(app.Token, model) {
model = ""
}
available := slices.DeleteFunc(slices.Clone(v.Available), func(id string) bool { return copilotRefuses(app.Token, id) })
// none named: the first available the account's list served, as VS
// Code picks among the models it knows
if model == "" {
copilotSeenMu.Lock()
for _, id := range v.Available {
for _, id := range available {
if _, ok := copilotSeen[id]; ok {
model = id
break
@@ -119,8 +126,13 @@ func copilotAutoResolve(ctx context.Context, app copilotApp, fresh bool) (copilo
}
copilotSeenMu.Unlock()
}
if model == "" && len(available) > 0 {
model = available[0]
}
if model == "" && len(v.Available) > 0 {
model = v.Available[0]
// every model Auto offers the account was refused it: the one it
// may pick by hand, as when it has no Auto
return copilotAutoFallback(ctx, app, "every model Copilot Auto offers was refused")
}
if model == "" {
return copilotAutoSession{}, errors.New("Copilot Auto picked no model")
@@ -131,8 +143,9 @@ func copilotAutoResolve(ctx context.Context, app copilotApp, fresh bool) (copilo
}
// copilotAutoFallback stands in for an Auto session Copilot has none of for
// the account (404): the first model it may pick by hand, sent without a
// session, for a while; with none, an error that says so.
// the account (404): the model it may pick by hand likeliest served (see
// copilotModels) and not refused it, sent without a session, for a while;
// with none, an error that says so.
func copilotAutoFallback(ctx context.Context, app copilotApp, why string) (copilotAutoSession, error) {
copilotTermsMu.Lock()
picks, known := copilotPicks[app.Token]
@@ -143,8 +156,9 @@ func copilotAutoFallback(ctx context.Context, app copilotApp, why string) (copil
picks = copilotPicks[app.Token]
copilotTermsMu.Unlock()
}
picks = slices.DeleteFunc(slices.Clone(picks), func(id string) bool { return copilotRefuses(app.Token, id) })
if len(picks) == 0 {
return copilotAutoSession{}, errors.New("Copilot doesn't offer Auto to this account (" + why + "), and lists no model it may pick by hand; check the plan at github.com/settings/copilot")
return copilotAutoSession{}, errors.New("Copilot doesn't offer Auto to this account (" + why + "), and lists no model it may pick by hand that it serves; check the plan at github.com/settings/copilot")
}
a := copilotAutoSession{Model: picks[0], ExpiresAt: time.Now().Add(10 * time.Minute).Unix()}
copilotAutoSessions[app.Token] = a
@@ -171,16 +185,20 @@ func (p Provider) ResolveAuto(ctx context.Context, model string) (context.Contex
// swapped for the one picked.
func copilotAutoSign(ctx context.Context, app copilotApp, req *http.Request, body []byte) (model string, err error) {
model = bodyModel(body)
if a, ok := ctx.Value(copilotAutoKey{}).(copilotAutoSession); ok && a.Model == model {
a, auto := ctx.Value(copilotAutoKey{}).(copilotAutoSession)
auto = auto && a.Model == model
if auto && !copilotRefuses(app.Token, model) {
if a.Token != "" {
req.Header.Set("Copilot-Session-Token", a.Token)
}
return model, nil
}
if model != CopilotAuto {
// Auto's pick sent again once the account was refused it
// (copilotRefused) goes as Auto's next pick
if model != CopilotAuto && !auto {
return model, nil
}
a, err := copilotAutoResolve(ctx, app, false)
a, err = copilotAutoResolve(ctx, app, false)
if err != nil {
return model, err
}
+82
View File
@@ -0,0 +1,82 @@
package provider
// A model Copilot's /models offers an account that the account still can't
// call. A Copilot Student plan (#371, #256) is listed models it is answered
// 400 "The requested model is not supported." (code model_not_supported)
// for, policy "enabled" or not: of the seven its list had enabled, gpt-4.1
// alone was served. Neither its policy nor anything else in the list tells
// them apart, so Copilot's answer does: a model refused so is left out of
// the account's models for a while, an agent's pick of it too, and Auto,
// whose pick it was, picks another and the request is sent again.
import (
"context"
"regexp"
"sync"
"time"
)
// copilotRefusedFor is how long a refused model stays left out: a plan
// changed (a Student account upgraded) is seen again within it.
const copilotRefusedFor = 6 * time.Hour
var (
copilotRefusedMu sync.Mutex
copilotRefusedAt = map[string]map[string]time.Time{} // by GitHub token: model → when refused
)
// copilotNotServed is how Copilot says the account may not call the model —
// not that it is asked on the wrong endpoint ("not accessible via the
// /chat/completions endpoint", unsupported_api_for_model), which the
// gateway takes to another of the model's endpoints.
var copilotNotServed = regexp.MustCompile(`(?i)"model_not_supported"|requested model is not supported`)
// copilotRefused notes a refusal of model for the account, and says whether
// the request is worth sending again: when Auto picked the model, as Auto
// then picks another.
func copilotRefused(ctx context.Context, app copilotApp, model string, status int, body []byte) bool {
if status != 400 || !copilotNotServed.Match(body) {
return false
}
a, ok := ctx.Value(copilotAutoKey{}).(copilotAutoSession)
// Auto's: the request the gateway resolved for it, or a model test
// asking for "auto" itself
auto := ok && a.Model == model || model == CopilotAuto
if auto && (model == CopilotAuto || copilotRefuses(app.Token, model)) {
// sent as the pick asked for in its stead (copilotAutoSign)
copilotAutoMu.Lock()
cur, ok := copilotAutoSessions[app.Token]
copilotAutoMu.Unlock()
if !ok {
return false
}
model = cur.Model
}
if model == "" || model == CopilotAuto {
return false
}
copilotRefusedMu.Lock()
if copilotRefusedAt[app.Token] == nil {
copilotRefusedAt[app.Token] = map[string]time.Time{}
}
copilotRefusedAt[app.Token][model] = time.Now()
copilotRefusedMu.Unlock()
if !auto {
return false
}
// Auto's session, or the model standing in for it, is asked anew
copilotAutoMu.Lock()
if cur, ok := copilotAutoSessions[app.Token]; ok && cur.Model == model {
delete(copilotAutoSessions, app.Token)
}
copilotAutoMu.Unlock()
return true
}
// copilotRefuses reports whether the account was refused model lately.
func copilotRefuses(token, model string) bool {
copilotRefusedMu.Lock()
defer copilotRefusedMu.Unlock()
at, ok := copilotRefusedAt[token][model]
return ok && time.Since(at) < copilotRefusedFor
}
+235
View File
@@ -0,0 +1,235 @@
package provider
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/catalog"
)
// copilot371Models is a Copilot Student account's /models as #371 measured
// it: each model's policy.state, and whether /chat/completions served it.
// The issue gave no more of the list; its endpoints, picker flags, billing
// and gpt-4.1 standing as Copilot's base model are the list's usual ones.
func copilot371Models() string {
var data []string
add := func(id, extra string) {
data = append(data, fmt.Sprintf(`{"id":%q,"name":%q,"model_picker_enabled":true,"supported_endpoints":["/chat/completions"],"capabilities":{"type":"chat"}%s}`, id, id, extra))
}
// policy enabled: only gpt-4.1 served
for _, id := range []string{"claude-haiku-4.5", "gpt-5.6-luna", "gpt-5.4-mini", "kimi-k3", "mai-code-1.1-flash"} {
add(id, `,"policy":{"state":"enabled"},"billing":{"is_premium":true,"multiplier":0.33}`)
}
add("gpt-5-mini", `,"policy":{"state":"enabled"},"billing":{"is_premium":false,"multiplier":0}`)
add("gpt-4.1", `,"policy":{"state":"enabled"},"is_chat_default":true,"is_chat_fallback":true,"billing":{"is_premium":false,"multiplier":0}`)
// policy disabled, with terms to accept: none served
for _, id := range []string{"claude-opus-5", "claude-sonnet-5.5", "claude-fable-5.1", "gemini-3.5-flash", "gemini-3.6-flash", "gemini-3.7-flash", "gemini-3.8-flash", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-6-sol", "gpt-6.1-sol", "gpt-6-astra"} {
add(id, `,"policy":{"state":"disabled","terms":"Enable access to the latest models."},"billing":{"is_premium":true,"multiplier":1}`)
}
// no policy: served
add("gpt-4o", `,"billing":{"is_premium":false,"multiplier":0}`)
return `{"data":[` + strings.Join(data, ",") + `]}`
}
// copilot371Served is what #371 found /chat/completions served the account.
var copilot371Served = []string{"gpt-4.1", "gpt-4o", "gpt-4o-mini", "gpt-3.5-turbo"}
// student371 stands in for Copilot's API for #371's account: the models
// above, refused as Copilot refuses them, and Auto's session (#256), when
// it has one, picking a model the account is refused.
type student371 struct {
mu sync.Mutex
auto bool // whether /models/session gives a session; 404 when not
asked []string // "<model> <Copilot-Session-Token> <status>"
}
func (c *student371) ServeHTTP(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
c.mu.Lock()
defer c.mu.Unlock()
switch r.URL.Path {
case "/models":
io.WriteString(w, copilot371Models())
case "/models/gpt-5.6-sol/policy", "/models/gpt-5.6-terra/policy":
// terms accepted, as they are for any account: the model is no
// more served for it
io.WriteString(w, `{"state":"enabled"}`)
case "/models/session":
if !c.auto {
w.WriteHeader(404)
io.WriteString(w, `{"error":{"message":"Not Found"}}`)
return
}
io.WriteString(w, `{"session_token":"auto-tok","selected_model":"claude-haiku-4.5","available_models":["claude-haiku-4.5","gpt-5-mini","gpt-4.1"],"expires_at":`+fmt.Sprint(time.Now().Add(time.Hour).Unix())+`}`)
default:
m := bodyModel(b)
status := 200
if !slices.Contains(copilot371Served, m) {
status = 400
}
c.asked = append(c.asked, fmt.Sprintf("%s %s %d", m, r.Header.Get("Copilot-Session-Token"), status))
w.WriteHeader(status)
if status == 400 {
io.WriteString(w, `{"error":{"message":"The requested model is not supported.","code":"model_not_supported","param":"model","type":"invalid_request_error"}}`)
return
}
io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"ok"}}]}`)
}
}
func student371Provider(t *testing.T, auto bool) (Provider, *student371) {
t.Helper()
signIn(t)
up := &student371{auto: auto}
api := httptest.NewServer(up)
t.Cleanup(api.Close)
tokens := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]any{"token": "sess", "expires_at": time.Now().Add(time.Hour).Unix(), "endpoints": map[string]string{"api": api.URL}})
}))
t.Cleanup(tokens.Close)
old := CopilotTokenURL
CopilotTokenURL = tokens.URL
t.Cleanup(func() { CopilotTokenURL = old })
copilotSessions = map[string]copilotSession{}
copilotAutoSessions = map[string]copilotAutoSession{}
copilotTerms = map[string]map[string]bool{}
copilotPicks = map[string][]string{}
copilotRefusedAt = map[string]map[string]time.Time{}
p, _ := find(All(), "copilot")
if _, err := p.Fetch(context.Background()); err != nil {
t.Fatal(err)
}
return p, up
}
// send has p's backend answer body as the gateway sends it: once more when
// the account says the request is worth it.
func (s *student371) send(t *testing.T, ctx context.Context, p Provider, body string) int {
t.Helper()
for range 3 {
req, _ := http.NewRequest("POST", p.Chat+"/chat/completions", strings.NewReader(body))
if err := p.Sign(ctx, req, Chat, []byte(body)); err != nil {
t.Fatal(err)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(res.Body)
res.Body.Close()
if res.StatusCode != 400 || !p.Retry(ctx, []byte(body), res.StatusCode, b) {
return res.StatusCode
}
}
return 0
}
func modelIDs(ms []catalog.Model) []string {
var out []string
for _, m := range ms {
out = append(out, m.ID)
}
return out
}
// #371: a Copilot Student account's list offers models Copilot then
// refuses it (400 "The requested model is not supported."), policy enabled
// or not, and magpie exposed the four picked for it — one of them not even
// in the list — every one refused. A pick the list no longer has is left
// out; a model the account was refused leaves its models and its picks.
func TestCopilotRefusedLeavesModels(t *testing.T) {
p, up := student371Provider(t, false)
p.Models = []string{"gpt-6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna"}
if got := modelIDs(p.Exposed()); !slices.Equal(got, []string{"gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna"}) {
t.Fatalf("exposed %q: gpt-6-luna isn't in the account's list", got)
}
for _, m := range p.Models[1:] {
if code := up.send(t, context.Background(), p, `{"model":"`+m+`","messages":[]}`); code != 400 {
t.Fatalf("%s: %d", m, code)
}
}
// a model named by hand is sent once: the refusal is the agent's to see
if len(up.asked) != 3 {
t.Fatalf("asked %q", up.asked)
}
avail := modelIDs(p.Available())
for _, m := range p.Models {
if slices.Contains(avail, m) {
t.Fatalf("%s still listed after Copilot refused it: %q", m, avail)
}
}
exposed := modelIDs(p.Exposed())
if len(exposed) == 0 || slices.ContainsFunc(exposed, func(id string) bool { return slices.Contains(p.Models, id) }) {
t.Fatalf("exposed %q: none of the picks is served, so as if none were picked", exposed)
}
if !slices.Contains(exposed, "gpt-4.1") || !slices.Contains(exposed, CopilotAuto) {
t.Fatalf("exposed %q", exposed)
}
// another account's refusals are its own
if copilotRefuses("gho_other", "gpt-5.6-luna") || !copilotRefuses("gho_x", "gpt-5.6-luna") {
t.Fatal("refusals are kept by account")
}
// a refusal is forgotten after a while: a plan may change
copilotRefusedMu.Lock()
copilotRefusedAt["gho_x"]["gpt-5.6-luna"] = time.Now().Add(-copilotRefusedFor)
copilotRefusedMu.Unlock()
if !slices.Contains(modelIDs(p.Available()), "gpt-5.6-luna") {
t.Fatal("gpt-5.6-luna not listed again once its refusal is old")
}
}
// #256: Copilot Auto for a Student account with no Auto session (404)
// stood in with the first enabled model of the list — claude-haiku-4.5,
// refused it. It takes Copilot's base model (is_chat_fallback), and passes
// over a model the account was refused.
func TestCopilotAutoFallbackServed(t *testing.T) {
p, up := student371Provider(t, false)
ctx, model, err := p.ResolveAuto(context.Background(), CopilotAuto)
if err != nil || model != "gpt-4.1" {
t.Fatalf("Auto stood in with %q, %v; want Copilot's base model gpt-4.1", model, err)
}
if code := up.send(t, ctx, p, `{"model":"gpt-4.1","messages":[]}`); code != 200 {
t.Fatalf("auto: %d %q", code, up.asked)
}
// once refused that one too, the next it may pick
copilotRefused(ctx, copilotApp{Token: "gho_x"}, "gpt-4.1", 400, []byte(`{"error":{"code":"model_not_supported"}}`))
if _, model, _ := p.ResolveAuto(context.Background(), CopilotAuto); model != "gpt-5-mini" {
t.Fatalf("after gpt-4.1 was refused, Auto picked %q", model)
}
}
// #256 (v0.1.498 on): Auto's session picks a model Copilot then refuses the
// account. The request is sent again with another model Auto offers, in
// the same session, and Auto passes the refused model over from then on.
func TestCopilotAutoRefusedPicksAnother(t *testing.T) {
p, up := student371Provider(t, true)
ctx, model, err := p.ResolveAuto(context.Background(), CopilotAuto)
if err != nil || model != "claude-haiku-4.5" {
t.Fatalf("resolve: %q %v", model, err)
}
if code := up.send(t, ctx, p, `{"model":"claude-haiku-4.5","messages":[]}`); code != 200 {
t.Fatalf("auto: %d %q", code, up.asked)
}
want := []string{"claude-haiku-4.5 auto-tok 400", "gpt-5-mini auto-tok 400", "gpt-4.1 auto-tok 200"}
if !slices.Equal(up.asked, want) {
t.Fatalf("asked %q, want %q", up.asked, want)
}
if _, model, _ := p.ResolveAuto(context.Background(), CopilotAuto); model != "gpt-4.1" {
t.Fatalf("next Auto request picked %q", model)
}
// a refusal that isn't one of the model (the wrong endpoint) is the
// gateway's to mend, not noted
if copilotRefused(ctx, copilotApp{Token: "gho_x"}, "gpt-4o", 400, []byte(`{"error":{"message":"model gpt-4o is not accessible via the /chat/completions endpoint","code":"unsupported_api_for_model"}}`)) || copilotRefuses("gho_x", "gpt-4o") {
t.Fatal("a wrong endpoint taken for a refused model")
}
}
+1 -1
View File
@@ -664,7 +664,7 @@ func factoryProvider(a factoryLogin) Provider {
}
return nil
}
acct.retry = func(ctx context.Context, status int, body []byte) bool {
acct.retry = func(ctx context.Context, _ string, status int, body []byte) bool {
return factoryMendOrg(ctx, user, status, body)
}
acct.explain = factoryExplain
+4 -4
View File
@@ -424,7 +424,7 @@ func factorySend(t *testing.T, p Provider) (int, string) {
return res.StatusCode, b
}
code, b := send()
if code == 403 && p.Retry(context.Background(), code, b) {
if code == 403 && p.Retry(context.Background(), nil, code, b) {
code, b = send()
}
return code, string(b)
@@ -550,8 +550,8 @@ func TestFactoryOrgRefused(t *testing.T) {
if c := factoryKept(t, "cy"); c.Active != "fac_A" {
t.Fatalf("cy kept active %q", c.Active)
}
if p.Retry(context.Background(), 403, []byte(`{"error":{"message":"model not allowed"}}`)) ||
p.Retry(context.Background(), 401, []byte(`Requested active organization is not accessible`)) {
if p.Retry(context.Background(), nil, 403, []byte(`{"error":{"message":"model not allowed"}}`)) ||
p.Retry(context.Background(), nil, 401, []byte(`Requested active organization is not accessible`)) {
t.Fatal("retried an unrelated refusal")
}
}
@@ -636,7 +636,7 @@ func TestFactoryForbiddenWithoutOrg(t *testing.T) {
return res.StatusCode, b
}
code, b := do()
if code == 403 && p.Retry(context.Background(), code, b) {
if code == 403 && p.Retry(context.Background(), nil, code, b) {
code, b = do()
}
return code, string(b)
+15 -2
View File
@@ -44,6 +44,11 @@ func (p Provider) Available() []catalog.Model {
}
}
if live, _, ok := p.live(); ok {
if p.Account != nil && p.Account.unusable != nil {
// a model the list offers that the account was refused
// (Copilot's, copilot_refused.go)
live = slices.DeleteFunc(slices.Clone(live), func(m catalog.Model) bool { return p.Account.unusable(m.ID) })
}
switch p.ID {
case "cursor":
live = withoutCursorCapacity(collapseCursorModels(withCursorContexts(live)))
@@ -430,8 +435,16 @@ func (p Provider) Exposed() []catalog.Model {
}
return out
}
if len(p.Models) > 0 {
return pick(p.Models)
picks := p.Models
if _, _, ok := p.live(); ok && p.Account != nil && p.Account.unusable != nil {
// A Copilot account is served what its list offers it, less what
// it was refused: a pick its list doesn't have (#371: gpt-6-luna,
// not in a Student plan's) or that it was refused is left out;
// with none left, as if none were picked.
picks = slices.DeleteFunc(slices.Clone(picks), func(id string) bool { _, ok := byID[id]; return !ok })
}
if len(picks) > 0 {
return pick(picks)
}
// another magpie's list is already the models its user exposed
if len(avail) <= manyModels || p.IsRemoteMagpie() {