Files
magpie/internal/gateway/served_test.go
T
yetone c816c9f828 routing: a request answered by another model than the one asked for is marked, from the model the vendor's reply names (v on Discord #feedback: 模型路由情况其实有的时候还是想知道的,比如之前 openai 会把 sol 降智到 luna 这样的,现在只有走 s2a 和 newapi 这些网关服务才能明确看到) — magpie read the tokens off each reply but not the model it says answered, so a vendor serving sol's requests with luna looked, on the Routing page, like sol answering. The reply's model is now kept as it goes by, never delayed or changed: on a relayed reply by the usage sniffer, which already reads every event and JSON body (Chat Completions' model in its JSON and each chunk, the Responses API's response.model in response.created/completed and model in its JSON, Anthropic's message.model in message_start and model in its JSON); on a translated one from the decoders' start event, which already carried it (Chat, Responses, Anthropic, and Gemini Code Assist's modelVersion), streamed or collected; on a Claude subscription's from the CLI's message_start; and on Codex's own models relayed to the ChatGPT backend. It goes in Usage.Served (and so the request log), each try's Served and the route's (the last try's, when it answered), with Swapped when it is another model than the one the try sent the vendor. Vendors mostly echo a dated or pinned name, which is the same model: the names are compared without a maker or path prefix (openai/, models/, Bedrock's us.anthropic.), case, and a version at the end — a date (-2025-08-07, -20250929, -06-05), a build number (-0613, -001), Bedrock's -v1:0, -latest, -preview — so gpt-5 answered as gpt-5-2025-08-07 or claude-3-5-sonnet-latest as claude-3-5-sonnet-20241022 is not marked, while gpt-5 as gpt-5-mini, gpt-5 as gpt-5.1, claude-opus-4 as claude-opus-4-1-… and deepseek-v3 as deepseek-v2 are. A reply that names no model marks nothing. The Routing page's Requests list puts an amber "served luna" (实际 luna) tag by the answer, its title saying what it means, and the request's story a line "requested sol · served luna" (请求 sol · 实际 luna) with the same sentence; no border stripe, and picking the request leaves the page where it is. Cursor, Devin, Kiro and Qoder name the model they were asked for themselves, so they are never marked.
Tested with new internal/gateway/served_test.go: TestServedModelRecorded (fake vendors in each protocol, streamed and not, relayed — Anthropic, Chat, Responses — and translated — Chat from Anthropic, Anthropic from Chat, Anthropic from Responses — each answering luna (marked), sol-2026-01-01 and models/SOL (not): the route, its try and the request log keep the name, Swapped as said), TestServedModelUnnamed, TestSwappedModel (the names above), TestSniffServedModel and TestCodexOwnModelServedTraced; and new internal/gui/tests/routing-served.test.cjs in Chromium and WebKit, en and zh (the tag on the swapped request alone, whole and in its row, no left border, its title; the story's line; a click that doesn't move the page; the dated and unnamed ones unmarked). With three requests alone the Routing page above the list jiggles by a few to 70px in WebKit on its own (on main too, with no served model in the fixture), so the fixture lists six. go build -tags nogui (and GOOS=linux, GOOS=windows), go test -tags nogui ./... and all GUI tests (80) pass. Not tested against a real vendor serving another model.
2026-09-29 19:41:29 +08:00

249 lines
11 KiB
Go

package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// servedBy is a vendor that answers in its protocol, streamed when asked,
// naming model as the one that answered.
func servedBy(proto provider.Protocol, model string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
var req struct {
Stream bool `json:"stream"`
}
json.Unmarshal(b, &req)
m, _ := json.Marshal(model)
M := string(m)
if !req.Stream {
w.Header().Set("Content-Type", "application/json")
switch proto {
case provider.Chat:
io.WriteString(w, `{"id":"c1","object":"chat.completion","model":`+M+`,"choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":2}}`)
case provider.Responses:
io.WriteString(w, `{"id":"r1","object":"response","model":`+M+`,"status":"completed","output":[{"type":"message","id":"msg_1","role":"assistant","content":[{"type":"output_text","text":"hi"}]}],"usage":{"input_tokens":5,"output_tokens":2}}`)
default:
io.WriteString(w, `{"id":"msg_1","type":"message","role":"assistant","model":`+M+`,"content":[{"type":"text","text":"hi"}],"stop_reason":"end_turn","usage":{"input_tokens":5,"output_tokens":2}}`)
}
return
}
var events []string
switch proto {
case provider.Chat:
events = []string{
`data: {"id":"c1","model":` + M + `,"choices":[{"index":0,"delta":{"role":"assistant","content":"hi"}}]}`,
`data: {"id":"c1","model":` + M + `,"choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":2}}`,
`data: [DONE]`,
}
case provider.Responses:
events = []string{
"event: response.created\ndata: " + `{"type":"response.created","response":{"id":"r1","model":` + M + `,"status":"in_progress","output":[]}}`,
"event: response.output_item.added\ndata: " + `{"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[]}}`,
"event: response.output_text.delta\ndata: " + `{"type":"response.output_text.delta","item_id":"msg_1","output_index":0,"content_index":0,"delta":"hi"}`,
"event: response.output_item.done\ndata: " + `{"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[{"type":"output_text","text":"hi"}]}}`,
"event: response.completed\ndata: " + `{"type":"response.completed","response":{"id":"r1","model":` + M + `,"status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":2}}}`,
}
default:
events = []string{
"event: message_start\ndata: " + `{"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":` + M + `,"content":[],"usage":{"input_tokens":5,"output_tokens":0}}}`,
"event: content_block_start\ndata: " + `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
"event: content_block_delta\ndata: " + `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}`,
"event: content_block_stop\ndata: " + `{"type":"content_block_stop","index":0}`,
"event: message_delta\ndata: " + `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}`,
"event: message_stop\ndata: " + `{"type":"message_stop"}`,
}
}
w.Header().Set("Content-Type", "text/event-stream")
for _, ev := range events {
io.WriteString(w, ev+"\n\n")
}
}
}
// The model a vendor's reply says answered is kept on the request's
// route, its try and its log entry, whatever the vendor speaks, streamed
// or not, relayed or translated; the route says it was swapped when it is
// another model than the one asked for, and not when it is that model's
// dated name.
func TestServedModelRecorded(t *testing.T) {
bodies := map[string]string{
"/v1/messages": `{"model":"fake/sol","max_tokens":100,"messages":[{"role":"user","content":"hi"}]`,
"/v1/chat/completions": `{"model":"fake/sol","messages":[{"role":"user","content":"hi"}]`,
"/v1/responses": `{"model":"fake/sol","input":"hi"`,
}
type path struct {
name string
proto provider.Protocol // the vendor's
agent string // the agent's endpoint
}
paths := []path{
{"anthropic", provider.Anthropic, "/v1/messages"},
{"chat", provider.Chat, "/v1/chat/completions"},
{"responses", provider.Responses, "/v1/responses"},
{"chat from anthropic", provider.Anthropic, "/v1/chat/completions"},
{"anthropic from chat", provider.Chat, "/v1/messages"},
{"anthropic from responses", provider.Responses, "/v1/messages"},
}
for _, pa := range paths {
for _, stream := range []bool{true, false} {
for _, c := range []struct {
served string
swapped bool
}{
{"luna", true},
{"sol-2026-01-01", false},
{"models/SOL", false},
} {
name := pa.name + "/" + c.served
if stream {
name += "/stream"
}
t.Run(name, func(t *testing.T) {
fresh(t)
up := httptest.NewServer(servedBy(pa.proto, c.served))
t.Cleanup(up.Close)
p := provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"sol"}}
switch pa.proto {
case provider.Chat:
p.Chat = up.URL + "/v1"
case provider.Responses:
p.Responses = up.URL + "/v1"
case provider.Anthropic:
p.Anthropic = up.URL
}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
body := bodies[pa.agent]
if stream {
body += `,"stream":true`
}
s := New()
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", pa.agent, strings.NewReader(body+"}")))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "hi") {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
r := lastRoute(s)
if r.Served != c.served || r.Swapped != c.swapped {
t.Errorf("route served %q swapped %v; want %q %v", r.Served, r.Swapped, c.served, c.swapped)
}
if len(r.Tries) != 1 || r.Tries[0].Model != "sol" || r.Tries[0].Served != c.served || r.Tries[0].Swapped != c.swapped {
t.Errorf("tries %+v", r.Tries)
}
if calls := s.Recent(); len(calls) == 0 || calls[0].Usage.Served != c.served {
t.Errorf("request log: %+v", calls)
}
})
}
}
}
}
// A reply that names no model marks nothing.
func TestServedModelUnnamed(t *testing.T) {
fresh(t)
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"id":"c1","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}]}`)
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"sol"}, Chat: up.URL + "/v1"}); err != nil {
t.Fatal(err)
}
s := New()
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"fake/sol","messages":[{"role":"user","content":"hi"}]}`)))
if r := lastRoute(s); rec.Code != 200 || r.Served != "" || r.Swapped || r.Tries[0].Swapped {
t.Fatalf("%d, route %+v", rec.Code, r)
}
}
// swapped tells another model from the one asked for, and not the same
// one under its dated, pinned or prefixed name.
func TestSwappedModel(t *testing.T) {
for _, c := range []struct {
sent, served string
want bool
}{
{"sol", "luna", true},
{"gpt-5", "gpt-5-mini", true},
{"gpt-5", "gpt-5-mini-2025-08-07", true},
{"gpt-4o", "gpt-4o-mini", true},
{"claude-opus-4", "claude-opus-4-1-20250805", true},
{"deepseek-v3", "deepseek-v2", true},
{"gpt-5", "gpt-5.1", true},
{"gpt-5", "gpt-5-2025-08-07", false},
{"gpt-5", "GPT-5", false},
{"gpt-4", "gpt-4-0613", false},
{"claude-sonnet-4-5", "claude-sonnet-4-5-20250929", false},
{"claude-3-5-sonnet-latest", "claude-3-5-sonnet-20241022", false},
{"claude-sonnet-4-5-20250929", "claude-sonnet-4-5", false},
{"gemini-2.5-pro", "models/gemini-2.5-pro", false},
{"gemini-1.5-pro", "gemini-1.5-pro-002", false},
{"gemini-2.5-pro", "gemini-2.5-pro-preview-06-05", false},
{"openai/gpt-5", "gpt-5-2025-08-07", false},
{"us.anthropic.claude-sonnet-4-20250514-v1:0", "claude-sonnet-4-20250514", false},
{"sol", "", false},
{"", "luna", false},
} {
if got := swapped(c.sent, c.served); got != c.want {
t.Errorf("swapped(%q, %q) = %v, want %v", c.sent, c.served, got, c.want)
}
}
}
// The sniffer reads the model a relayed reply names as it goes by.
func TestSniffServedModel(t *testing.T) {
for _, c := range []struct {
proto provider.Protocol
ct string
body string
}{
{provider.Chat, "text/event-stream", "data: {\"model\":\"luna\",\"choices\":[]}\n\ndata: [DONE]\n\n"},
{provider.Chat, "application/json", `{"model":"luna","choices":[]}`},
{provider.Responses, "text/event-stream", "event: response.created\ndata: {\"type\":\"response.created\",\"response\":{\"model\":\"luna\"}}\n\n"},
{provider.Responses, "application/json", `{"object":"response","model":"luna"}`},
{provider.Anthropic, "text/event-stream", "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"model\":\"luna\"}}\n\n"},
{provider.Anthropic, "application/json", `{"type":"message","model":"luna"}`},
} {
s := newSniffer(c.proto, c.ct)
s.write([]byte(c.body))
if got := s.usage().Served; got != "luna" {
t.Errorf("%s %s: served %q", c.proto, c.ct, got)
}
}
}
// A turn on one of Codex's own models, relayed to the ChatGPT backend,
// keeps the model its reply names as the others do.
func TestCodexOwnModelServedTraced(t *testing.T) {
for _, c := range []struct {
served string
swapped bool
}{{"gpt-5.4-mini", true}, {"gpt-5.5-2026-04-01", false}} {
setup(t, provider.Chat, &fake{t: t})
chatgpt(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(`data: {"type":"response.created","response":{"id":"r1","model":"`+c.served+`"}}`,
`data: {"type":"response.completed","response":{"id":"r1","model":"`+c.served+`","usage":{"input_tokens":9,"output_tokens":2}}}`))
})
s := New()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":"hi"}`))
req.Header.Set("Authorization", "Bearer chatgpt-token")
s.Handler().ServeHTTP(rec, req)
r := lastRoute(s)
if r.Served != c.served || r.Swapped != c.swapped || r.Tries[0].Served != c.served || r.Tries[0].Swapped != c.swapped {
t.Errorf("%s: route %+v", c.served, r)
}
}
}