Files
magpie/internal/gateway/media_route_test.go
T
yetone 5f6a46630a gateway: images, videos and embeddings are listed on Routing (zzzkl3994)
zzzkl3994 on Discord: a video made through the magpie-image MCP was in
Usage → Requests but never on Routing → Requests. The MCP's requests do
go through the gateway, but `images`, `videosCreate` and `retrieve`
(embeddings, rerank, audio transcriptions) wrote their usage row and
began no route, so the routing trace never had them. Only the chat
path, the Codex backend, titles and System One began routes.

Each now begins one route (media_route.go, sideRoute) with the caller's
agent and session, the model as asked, the provider and the routing
group. Each key, account or group member asked is a try, put in Order
so the page finds its seat. The route ends with the status, error and
tokens, and the usage row names it in RouteID. Route.Usage is for
display and is not a second ledger row, so nothing is counted twice.
An image's accounts are tried in drawOnAccounts, which gets the route
through the request's context. A video's polls and its download are the
same generation; they add no route, as they add no usage row. A video
turned away before any vendor was asked ends its route as failed.
Route.Kind stays empty.

Run:
- New tests (media_route_test.go): TestImageIsOnRouting,
  TestFailedImageIsOnRouting, TestVideoIsOnRoutingOnce (create, three
  polls and the download give one route and one usage row),
  TestRefusedVideoIsOnRouting and TestEmbeddingAndRerankAreOnRouting.
  All are red at 5d24bc6cc without the fix ("Routing lists 0 routes")
  and green with it (wsl-run). Their neighbours pass too:
  TestVideoIsStartedPolledAndFetched, TestImageGroupMovesOnToTheNextMember,
  TestCallerUsageVideos and TestEmbeddingsGoToTheModelsProvider.
- Broken by hand. With RouteID dropped from the image's usage row, both
  image tests go red ("isn't the one the usage row names (0)"). With
  sideRoute.end always writing status 200, TestRefusedVideoIsOnRouting
  goes red.
- Full suite at 5d24bc6cc plus this change (wsl-run, `go test -tags
  nogui ./... -timeout 45m -count=1`): 77 packages ok. internal/agent
  has 4 reds (TestInstalledVersion, TestGrokInstalled,
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI and
  TestOmpDetectedWithPiDir), all already filed for the WSL box at main
  in #4033.
- GOOS=windows and GOOS=linux `go vet ./internal/gateway` (mote): ok.
- Rebased on 4d9058a98, then on 95b40fb2f (redact and library only).
  internal/gateway and internal/imagemcp at the 4d9058a98
  head (mote-run) are still running when this is pushed.

Not tried:
- A real generate_video through the MCP in the GUI. The Routing page's
  GUI suite wasn't run, as no GUI file changed; the route has the shape
  the page already reads (Order, Tries, Kind "").
2026-10-29 15:58:20 +08:00

168 lines
6.0 KiB
Go

package gateway
import (
"context"
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/usage"
)
// usageRows waits for n usage rows of op, and answers those there are.
func usageRows(t *testing.T, op string, n int) []usage.Record {
t.Helper()
var got []usage.Record
for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) {
got = got[:0]
for _, r := range usage.Load(time.Time{}) {
if r.Operation == op {
got = append(got, r)
}
}
if len(got) >= n {
break
}
}
return got
}
// oneSideRoute is the one route s has, done, which the one usage row of op
// names: what Routing lists of a request Usage lists.
func oneSideRoute(t *testing.T, s *Server, op string) (Route, usage.Record) {
t.Helper()
rows := usageRows(t, op, 1)
if len(rows) != 1 {
t.Fatalf("%d usage rows of %s, want 1: %+v", len(rows), op, rows)
}
routes := s.Trace(context.Background(), 0, 0).Routes
if len(routes) != 1 {
t.Fatalf("Routing lists %d routes, want the request's one: %+v", len(routes), routes)
}
tr := routes[0]
if !tr.Done || tr.ID == 0 || tr.ID != rows[0].RouteID {
t.Fatalf("route %d (done %v) isn't the one the usage row names (%d)", tr.ID, tr.Done, rows[0].RouteID)
}
if tr.Kind != "" {
t.Fatalf("route kind %q: the page would call it an unrecognized purpose", tr.Kind)
}
if tr.Agent == "" || tr.Agent != rows[0].Agent || tr.Session != rows[0].Session || tr.Status != rows[0].Status {
t.Fatalf("route %+v doesn't say what its usage row does: %+v", tr, rows[0])
}
// each try has its seat in the order, as the page finds it
for _, try := range tr.Tries {
found := false
for _, w := range tr.Order {
found = found || w.ID == try.ID && w.Model == try.Model
}
if !found || !try.Done {
t.Fatalf("try %+v (seated %v) in order %+v", try, found, tr.Order)
}
}
return tr, rows[0]
}
// zzzkl3994 on Discord: a video the magpie-image MCP made was in Usage's
// requests and not on Routing's. Every request magpie sends is listed on
// Routing: an image, a video's start (once, however often it is polled
// and fetched) and an embedding, as a chat is, with its one usage row.
func TestImageIsOnRouting(t *testing.T) {
s, _ := easeled(t)
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/images/generations", strings.NewReader(`{"model":"art/gpt-image-1","prompt":"a magpie"}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "claude-code/2.1.0 "+DrawAgent)
req.Header.Set("X-Magpie-Session", "draw-session")
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
tr, row := oneSideRoute(t, s, "generate_content")
if tr.Provider != "art" || tr.Model != "art/gpt-image-1" || tr.Status != 200 || tr.Session != "draw-session" || tr.Error != "" {
t.Fatalf("route %+v", tr)
}
if len(tr.Tries) != 1 || tr.Tries[0].ID != "art" || tr.Tries[0].Model != "gpt-image-1" || tr.Tries[0].Status != 200 {
t.Fatalf("tries %+v", tr.Tries)
}
if tr.Tokens != row.Input+row.Output || len(tr.Usage) == 0 {
t.Fatalf("route tokens %d usage %+v, row %+v", tr.Tokens, tr.Usage, row)
}
}
func TestFailedImageIsOnRouting(t *testing.T) {
grokSignedIn(t)
newGrokMedia(t)
s := New()
code, _, raw := postImages(t, s, "/v1/images/generations", "application/json", `{"model":"grok/grok-imagine-image","prompt":"REFUSED"}`)
if code != 400 {
t.Fatalf("%d %s", code, raw)
}
tr, _ := oneSideRoute(t, s, "generate_content")
if tr.Provider != "grok" || tr.Status != 400 || !strings.Contains(tr.Error, "moderation") || len(tr.Tries) != 1 || tr.Tries[0].ID != "grok" || tr.Tries[0].Status != 400 {
t.Fatalf("route %+v", tr)
}
}
func TestVideoIsOnRoutingOnce(t *testing.T) {
grokSignedIn(t)
newGrokMedia(t)
s := New()
code, obj, raw, _ := request(t, s, "POST", "/v1/videos", "application/json", `{"model":"grok/grok-imagine-video","prompt":"a kite sways"}`)
if code != 200 {
t.Fatalf("%d %s", code, raw)
}
id, _ := obj["id"].(string)
// generate_video's polls and its download are the same video
for range 3 {
if code, _, raw, _ = request(t, s, "GET", "/v1/videos/"+id, "", ""); code != 200 {
t.Fatalf("poll %d %s", code, raw)
}
}
if code, _, raw, _ = request(t, s, "GET", "/v1/videos/"+id+"/content", "", ""); code != 200 {
t.Fatalf("content %d %s", code, raw)
}
tr, _ := oneSideRoute(t, s, "generate_content")
if tr.Provider != "grok" || tr.Model != "grok/grok-imagine-video" || tr.Status != 200 || len(tr.Tries) != 1 || tr.Tries[0].ID != "grok" || tr.Tries[0].Model != "grok-imagine-video" {
t.Fatalf("route %+v", tr)
}
}
func TestRefusedVideoIsOnRouting(t *testing.T) {
grokSignedIn(t)
newGrokMedia(t)
s := New()
code, _, raw, _ := request(t, s, "POST", "/v1/videos", "application/json", `{"model":"grok/grok-imagine-video","prompt":"TOOLONG"}`)
if code != 400 {
t.Fatalf("%d %s", code, raw)
}
tr, _ := oneSideRoute(t, s, "generate_content")
if tr.Status != 400 || !strings.Contains(tr.Error, "Duration") || len(tr.Tries) != 1 || tr.Tries[0].Status != 400 {
t.Fatalf("route %+v", tr)
}
}
func TestEmbeddingAndRerankAreOnRouting(t *testing.T) {
for _, tc := range []struct{ path, op, body, model string }{
{"/v1/embeddings", "embeddings", `{"model":"lib/embed-1","input":["hello"]}`, "embed-1"},
{"/v1/rerank", "rerank", `{"model":"lib/rerank-1","query":"q","documents":["a","b"]}`, "rerank-1"},
} {
t.Run(tc.op, func(t *testing.T) {
s, _ := shelved(t)
if code, raw := postRetrieval(t, s, tc.path, tc.body); code != 200 {
t.Fatalf("%d %s", code, raw)
}
tr, row := oneSideRoute(t, s, tc.op)
var asked struct{ Model string }
json.Unmarshal([]byte(tc.body), &asked)
if tr.Provider != "lib" || tr.Model != asked.Model || tr.Status != 200 || len(tr.Tries) != 1 || tr.Tries[0].ID != "lib" || tr.Tries[0].Model != tc.model {
t.Fatalf("route %+v", tr)
}
if tr.Tokens == 0 || tr.Tokens != row.Input+row.Output {
t.Fatalf("route tokens %d, row %+v", tr.Tokens, row)
}
})
}
}