diff --git a/docs/reference.md b/docs/reference.md index 2957caf94..23167fb3b 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -470,11 +470,16 @@ whether Fast ran or not, so from it those are left empty too. The JSON log keeps them as `tier_asked`, `tier_sent` and `tier_served`, and each try in `/v1/magpie/route` has `tier` and `tier_served`. A request's row on the Requests page shows them as Service tier (asked, sent when it -differs, answered). The last column, -`upstream_stop`, is why the upstream said its reply ended, in its own +differs, answered). Then +`upstream_stop`, why the upstream said its reply ended, in its own words (`stop`, `tool_calls`, `end_turn`, a Responses reply's -`completed`), empty when it said none. A request's row on the Requests -page shows it as Upstream stop reason. +`completed`), empty when it said none; a request's row on the Requests +page shows it as Upstream stop reason. After `credits`, the last column, +`sent_model`, is the model id the request went out to the vendor under, +when it is another than `model`: a name set for the model upstream, or the +variant a plugin picked for the effort (Antigravity's +`gemini-3.1-pro-high` for `gemini-3.1-pro` at high). A request's row shows it +as Sent, and each try in `/v1/magpie/route` has it as `wire`. **Output speed** (tok/s on the Usage and Routing pages, `magpie usage`) is all output tokens the vendor counted, reasoning and tool calls included, over diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 4b53869d9..b96c741cf 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3648,6 +3648,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro sent := "" // the reasoning the last try's model was asked for wentAt := "" // and the level that went, once translated (wireEffort, #1636) wentTier := "" // the service tier the last try went out at (noteWireTier, #1784) + wentAs := "" // the model id the last try went out under, when another than its model (wireName) where := "" // the last try's provider.Where, for the usage again := 0 // times the last one left has been tried again planAgain := 0 // times a group's member was asked again in place for the Qwen Token Plan's concurrency 429 (qwenPlanBusy) @@ -4683,6 +4684,8 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro try.Reset, resetFirst = resetFirst, nil } asName := provider.SentNameOnIn(wiresOf(r.Context()), c.p.ID, accountAgent(c.p), c.model, sent) + wentAs = wireName(c.model, at.model, asName) + try.Wire = wentAs try.Entry, try.EntryWhy = entryOf() try.Swapped, try.Routed = swapped(asName, call.Usage.Served) && !usage.ListedAs(c.p.ID, c.model, call.Usage.Served), usage.GroupRouted(asName, call.Usage.Served) try.TTFT, try.FirstText = hw.first.ms() @@ -4716,7 +4719,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } rec := usage.Record{RouteID: tr.ID, Time: began, Agent: call.Agent, Via: call.Via, Provider: call.Provider, Host: where, Model: c.model, ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: providerAccount, - Requested: call.Model, Served: call.Usage.Served, Upstream: call.Usage.Upstream, + Requested: call.Model, Served: call.Usage.Served, Wire: wentAs, Upstream: call.Usage.Upstream, Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, CacheWrite1h: u.CacheWrite1h, CacheUnknown: u.cacheNotCounted(), Reasoning: u.Reasoning, Credits: call.Usage.Credits, Effort: wentAt, Millis: try.Millis, Status: call.Status, TierAsked: tierAsked, TierSent: wentTier, TierServed: call.Usage.Tier, @@ -4974,7 +4977,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro if call.To != "" { rec := usage.Record{RouteID: tr.ID, Time: began, Agent: call.Agent, Via: call.Via, Provider: call.Provider, Host: where, Model: c.model, ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: providerAccount, - Requested: call.Model, Served: call.Usage.Served, Upstream: call.Usage.Upstream, + Requested: call.Model, Served: call.Usage.Served, Wire: wentAs, Upstream: call.Usage.Upstream, Input: call.Usage.billed().Input, Output: call.Usage.billed().Output, CacheRead: call.Usage.billed().CacheRead, CacheWrite: call.Usage.billed().CacheWrite, CacheWrite1h: call.Usage.billed().CacheWrite1h, CacheUnknown: call.Usage.billed().cacheNotCounted(), Reasoning: call.Usage.billed().Reasoning, Credits: call.Usage.Credits, Effort: wentAt, Millis: try.Millis, Status: call.Status, TierAsked: tierAsked, TierSent: wentTier, TierServed: call.Usage.Tier, @@ -5019,7 +5022,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro if call.To != "" { rec := usage.Record{RouteID: tr.ID, Time: began, Agent: call.Agent, Via: call.Via, Provider: call.Provider, Host: where, Model: c.model, ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: providerAccount, - Requested: call.Model, Served: call.Usage.Served, + Requested: call.Model, Served: call.Usage.Served, Wire: wentAs, Input: call.Usage.billed().Input, Output: call.Usage.billed().Output, CacheRead: call.Usage.billed().CacheRead, CacheWrite: call.Usage.billed().CacheWrite, CacheWrite1h: call.Usage.billed().CacheWrite1h, CacheUnknown: call.Usage.billed().cacheNotCounted(), Reasoning: call.Usage.billed().Reasoning, Credits: call.Usage.Credits, Effort: wentAt, Millis: try.Millis, Status: call.Status, TierAsked: tierAsked, TierSent: wentTier, TierServed: call.Usage.Tier, @@ -5914,7 +5917,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro if call.To != "" { rec := usage.Record{RouteID: tr.ID, Time: start, Agent: call.Agent, Via: call.Via, Provider: call.Provider, Host: where, Model: model, ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: providerAccount, - Requested: call.Model, Served: call.Usage.Served, Upstream: call.Usage.Upstream, + Requested: call.Model, Served: call.Usage.Served, Wire: wentAs, Upstream: call.Usage.Upstream, Input: call.Usage.billed().Input, Output: call.Usage.billed().Output, CacheRead: call.Usage.billed().CacheRead, CacheWrite: call.Usage.billed().CacheWrite, CacheWrite1h: call.Usage.billed().CacheWrite1h, CacheUnknown: call.Usage.billed().cacheNotCounted(), Reasoning: call.Usage.billed().Reasoning, Credits: call.Usage.Credits, Effort: wentAt, Millis: call.Millis, Status: call.Status, TierAsked: tierAsked, TierSent: wentTier, TierServed: call.Usage.Tier, @@ -6261,6 +6264,7 @@ func (s *Server) forward(ctx context.Context, p provider.Provider, to provider.P defer func() { if err == nil { heardReply(ctx, p, res) + noteWireModel(ctx, p, res) heardNet() // the network is up (offline.go) } }() diff --git a/internal/gateway/sent_model_test.go b/internal/gateway/sent_model_test.go new file mode 100644 index 000000000..e5ad31ff6 --- /dev/null +++ b/internal/gateway/sent_model_test.go @@ -0,0 +1,197 @@ +package gateway + +import ( + "bytes" + "context" + "encoding/csv" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/testenv" + "github.com/yetone/magpie/internal/usage" +) + +// The model id a request went out to the vendor under, when it is another +// than the model magpie asked the provider for, is kept with the try and the +// ledger's row, and named in the CSV: a name the user gave the model +// upstream goes out in place of magpie's (daoche_wuzui on X asked to see +// whether a request went out as a model with a suffix). A request that went +// out as the model keeps none, and a vendor saying a sent model in magpie's +// header is not taken at its word: only a plugin says what it sent. +func TestUpstreamNameSentIsKept(t *testing.T) { + fresh(t) + + var seen asked + relay := asking(t, &seen) + other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var b struct { + Model string `json:"model"` + } + json.NewDecoder(r.Body).Decode(&b) + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set(provider.SentModelHeader, "spoofed") + io.WriteString(w, `data: {"id":"x","model":"`+b.Model+`","choices":[{"index":0,"delta":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],`+ + `"usage":{"prompt_tokens":5,"completion_tokens":3}}`+"\n\n") + io.WriteString(w, "data: [DONE]\n\n") + })) + t.Cleanup(other.Close) + + for _, p := range []provider.Provider{ + {ID: "relay-b", Name: "Relay B", Key: "k", Models: []string{"model-2"}, Chat: relay.URL}, + {ID: "other", Name: "Other", Key: "k", Models: []string{"model-2"}, Chat: other.URL}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + if err := provider.SetUpstreamName("relay-b/model-2", "vendor-c/model-2-preview"); err != nil { + t.Fatal(err) + } + + s := New() + ask := func(model string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/messages", strings.NewReader( + `{"model":"`+model+`","max_tokens":1024,"stream":true,`+ + `"messages":[{"role":"user","content":"hi"}]}`)) + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("%s: status %d: %s", model, rec.Code, rec.Body.String()) + } + return rec + } + + ask("relay-b/model-2") + if got := seen.all(); len(got) != 1 || got[0] != "vendor-c/model-2-preview" { + t.Fatalf("the relay was asked for %v; want the upstream name", got) + } + if tr := lastRoute(s).Tries; len(tr) != 1 || tr[0].Wire != "vendor-c/model-2-preview" || tr[0].Model != "model-2" { + t.Errorf("the try keeps %+v; want model-2 sent as vendor-c/model-2-preview", tr) + } + + rec := ask("other/model-2") + if got := rec.Header().Get(provider.SentModelHeader); got != "" { + t.Errorf("the agent was told the sent model %q", got) + } + if tr := lastRoute(s).Tries; len(tr) != 1 || tr[0].Wire != "" { + t.Errorf("a try that went out as its model keeps %+v; want no sent name, and none a vendor said", tr) + } + + rows := usage.Load(time.Time{}) + wire := map[string]string{} + for _, r := range rows { + wire[r.Provider] = r.Wire + } + if len(rows) != 2 || wire["relay-b"] != "vendor-c/model-2-preview" || wire["other"] != "" { + t.Fatalf("the ledger keeps %v; want relay-b's sent name alone", wire) + } + + var buf bytes.Buffer + var led []usage.Row + for _, r := range rows { + led = append(led, usage.Row{Record: r}) + } + if err := usage.WriteCSV(&buf, led); err != nil { + t.Fatal(err) + } + recs, err := csv.NewReader(&buf).ReadAll() + if err != nil { + t.Fatal(err) + } + col := slices.Index(recs[0], "sent_model") + pcol := slices.Index(recs[0], "provider") + if col < 0 { + t.Fatalf("the CSV has no sent_model column: %v", recs[0]) + } + for _, r := range recs[1:] { + want := map[string]string{"relay-b": "vendor-c/model-2-preview"}[r[pcol]] + if r[col] != want { + t.Errorf("the CSV's %s row says sent_model %q, want %q", r[pcol], r[col], want) + } + } +} + +// A plugin that sends the vendor another id than the model it was asked for +// — Antigravity's sends a family as the variant the effort picks from the +// account's own list — says so in provider.SentModelHeader, and the try and +// the ledger keep it. The header is magpie's: the agent never sees it. +func TestPluginSentModelIsKept(t *testing.T) { + bun := testenv.Bun(t) + fresh(t) + t.Setenv("MAGPIE_BUN", bun) + t.Cleanup(plugin.Settle) + + say := "fake-1-high" + up := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + w.Header().Set("Content-Type", "text/event-stream") + if say != "" { + w.Header().Set(provider.SentModelHeader, say) + } + fmt.Fprint(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{"role":"assistant","content":"hi there"},"finish_reason":null}]}`+"\n\n") + fmt.Fprint(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":3}}`+"\n\ndata: [DONE]\n\n") + })) + defer up.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + abs, _ := filepath.Abs("../plugin/testdata/fake/index.js") + if _, err := plugin.Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + st, err := provider.StartPluginSignIn("fakeco", 1, map[string]string{"where": "work", "team": "full"}) + if err != nil { + t.Fatal(err) + } + if err := provider.SubmitSignInCallback(st.ID, "good"); err != nil { + t.Fatal(err) + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + + s := New() + for _, c := range []struct{ said, want string }{ + {"fake-1-high", "fake-1-high"}, + // a plugin saying the model it was asked for sent nothing else + {"fake-1", ""}, + {"", ""}, + } { + say = c.said + for _, stream := range []bool{false, true} { + body := `{"model":"fakeco/fake-1","messages":[{"role":"user","content":"hello"}]` + if stream { + body += `,"stream":true` + } + req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(body+"}")) + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "hi there") { + t.Fatalf("said %q, stream %v: %d %s", c.said, stream, rec.Code, rec.Body) + } + if got := rec.Header().Get(provider.SentModelHeader); got != "" { + t.Errorf("said %q, stream %v: the agent was told the sent model %q", c.said, stream, got) + } + if tr := lastRoute(s).Tries; len(tr) != 1 || tr[0].Wire != c.want { + t.Errorf("said %q, stream %v: the try keeps %+v; want sent as %q", c.said, stream, tr, c.want) + } + rows := usage.Load(time.Time{}) + if len(rows) == 0 || rows[len(rows)-1].Wire != c.want { + t.Errorf("said %q, stream %v: the ledger's last row keeps %q; want %q", c.said, stream, rows[len(rows)-1].Wire, c.want) + } + } + } +} diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index 57c36f64b..e80f50483 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -530,6 +530,10 @@ type Try struct { Served string `json:"served,omitempty"` Swapped bool `json:"swapped,omitempty"` Routed bool `json:"routed,omitempty"` + // Wire: the model id it went out to the vendor under, when that is + // another than Model (usage.Record.Wire): a name the user gave the + // model upstream, or the variant a plugin picked + Wire string `json:"wire,omitempty"` // Upstream: the provider an aggregator said answered behind it // (OpenRouter's DeepInfra, Novita …) Upstream string `json:"upstream,omitempty"` diff --git a/internal/gateway/wire_effort.go b/internal/gateway/wire_effort.go index 19ae13d8a..f48401104 100644 --- a/internal/gateway/wire_effort.go +++ b/internal/gateway/wire_effort.go @@ -1,7 +1,10 @@ package gateway import ( + "cmp" "context" + "net/http" + "strings" "github.com/yetone/magpie/internal/provider" ) @@ -26,6 +29,9 @@ type wireAt struct { // tier: the service tier the try's request went out at, whichever // path sent it (noteWireTier) tier string + // model: the model id the plugin the try went to said it sent its + // vendor (noteWireModel) + model string } type wireAtKey struct{} @@ -68,3 +74,30 @@ func wireEffort(to provider.Protocol, req *Request) (string, bool) { } return "", false } + +// noteWireModel leaves, where the request's context has a place for it, the +// model id a plugin's answer res says it sent its vendor +// (provider.SentModelHeader). Only a plugin is taken at its word: a vendor +// or a relay naming one is not what magpie sent. +func noteWireModel(ctx context.Context, p provider.Provider, res *http.Response) { + if res == nil || !p.IsPlugin() { + return + } + m := strings.TrimSpace(res.Header.Get(provider.SentModelHeader)) + res.Header.Del(provider.SentModelHeader) + w, _ := ctx.Value(wireAtKey{}).(*wireAt) + if w == nil || m == "" || len(m) > 200 { + return + } + w.model = m +} + +// wireName is the model id a try went out under, when it is another than +// model, the id magpie asked it for: what the plugin said it sent, else the +// name the user gave the model upstream (sentAs, provider.SentNameOnIn). +func wireName(model, plugin, sentAs string) string { + if w := cmp.Or(plugin, sentAs); w != model { + return w + } + return "" +} diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index 03c535bf0..7b5b1f5e0 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -3800,6 +3800,10 @@ function routingPage(part) { as.forEach((a, i) => items.push([a, "aside", undefined, as.about[i]])); r.tries.forEach((tr, i) => { items.push([tryWhy(r, i), tr.done ? (tryOk(tr) ? "ok" : "bad") : "wait", undefined, tried(r, tr)]); + // the id it went out under, when another than its model's: the + // variant a plugin picked for the effort (Antigravity's …-high), a + // name set for the model upstream + if (tr.wire) items.push([t("Sent to the vendor as {model}", { model: tr.wire }), "aside wire-said"]); // where its time went, once it is done: the first try's has the // request's masking before it const timed = i === 0 && r.masking > 0 ? { ...tr, masking: r.masking } : tr; diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js index 75a845dd6..6f64882b8 100644 --- a/internal/gui/assets/plugins/routing/i18n.js +++ b/internal/gui/assets/plugins/routing/i18n.js @@ -631,6 +631,7 @@ magpie.strings({ "{agent} checked that magpie answers, as it does when it starts and from its Test connection. It names this check's model itself, from the names in its model list ({model}), not the model chosen in the conversation, and only reads whether an answer comes back; magpie sends it to the model chosen in {agent}'s model menu, or to its first listed model when none is. Not a turn of the conversation.": "{agent} 在检查 magpie 能否应答(启动时和在 Test connection 里都会发)。这次检查的模型由它自己按模型列表里的名字选出({model}),不是对话里选的模型,它也只看有没有回应;magpie 会把它发给 {agent} 模型菜单里选的模型,没选时发给列表里的第一个模型。不属于对话轮次。", "Nothing was tried: {error}": "没有尝试任何账号:{error}", "{agent} asked for {model}: {name} serves it, and the vendor is asked for {sent}": "{agent} 请求 {model}:由 {name} 提供,向厂商请求的模型是 {sent}", + "Sent to the vendor as {model}": "以 {model} 发给厂商", "the last {n} the gateway keeps": "网关保留的最近 {n} 个", "Accounts and keys": "账号与密钥", "over those requests": "统计自这些请求", @@ -1397,6 +1398,7 @@ magpie.strings({ "{agent} checked that magpie answers, as it does when it starts and from its Test connection. It names this check's model itself, from the names in its model list ({model}), not the model chosen in the conversation, and only reads whether an answer comes back; magpie sends it to the model chosen in {agent}'s model menu, or to its first listed model when none is. Not a turn of the conversation.": "{agent} 在檢查 magpie 能否回應(啟動時和在 Test connection 裡都會發)。這次檢查的模型由它自己依模型清單裡的名稱選出({model}),不是對話裡選的模型,它也只看有沒有回應;magpie 會把它送給 {agent} 模型選單裡選的模型,沒選時送給清單裡的第一個模型。不屬於對話輪次。", "Nothing was tried: {error}": "沒有嘗試任何帳號:{error}", "{agent} asked for {model}: {name} serves it, and the vendor is asked for {sent}": "{agent} 請求 {model}:由 {name} 提供,向廠商請求的模型是 {sent}", + "Sent to the vendor as {model}": "以 {model} 發給廠商", "the last {n} the gateway keeps": "閘道保留的最近 {n} 個", "Accounts and keys": "帳號與金鑰", "over those requests": "統計自這些請求", @@ -2161,6 +2163,7 @@ magpie.strings({ "{agent} checked that magpie answers, as it does when it starts and from its Test connection. It names this check's model itself, from the names in its model list ({model}), not the model chosen in the conversation, and only reads whether an answer comes back; magpie sends it to the model chosen in {agent}'s model menu, or to its first listed model when none is. Not a turn of the conversation.": "{agent} が magpie の応答を確かめるチェックです(起動時と Test connection で送られます)。このチェックのモデルはモデル一覧の名前から自分で選んだもの({model})で、会話で選んだモデルではなく、応答があるかだけを見ます。magpie はこれを {agent} のモデルメニューで選ばれたモデルへ、未選択なら一覧の先頭のモデルへ送ります。会話のターンではありません。", "Nothing was tried: {error}": "何も試行されませんでした:{error}", "{agent} asked for {model}: {name} serves it, and the vendor is asked for {sent}": "{agent} が {model} をリクエスト:{name} が提供し、ベンダーには {sent} をリクエスト", + "Sent to the vendor as {model}": "ベンダーには {model} として送信", "the last {n} the gateway keeps": "ゲートウェイが保持する直近 {n} 件", "Accounts and keys": "アカウントとキー", "over those requests": "これらのリクエストの集計", @@ -2927,6 +2930,7 @@ magpie.strings({ "{agent} checked that magpie answers, as it does when it starts and from its Test connection. It names this check's model itself, from the names in its model list ({model}), not the model chosen in the conversation, and only reads whether an answer comes back; magpie sends it to the model chosen in {agent}'s model menu, or to its first listed model when none is. Not a turn of the conversation.": "{agent} prüft, ob magpie antwortet, beim Start und über „Test connection“. Das Modell dieser Prüfung wählt es selbst nach den Namen in seiner Modellliste ({model}), nicht das im Gespräch gewählte, und liest nur, ob eine Antwort kommt; magpie schickt sie an das in {agent}s Modellmenü gewählte Modell oder, wenn keins gewählt ist, an das erste der Liste. Kein Zug des Gesprächs.", "Nothing was tried: {error}": "Nichts wurde versucht: {error}", "{agent} asked for {model}: {name} serves it, and the vendor is asked for {sent}": "{agent} verlangte {model}: {name} stellt es bereit, beim Anbieter wird {sent} angefragt", + "Sent to the vendor as {model}": "Beim Anbieter als {model} gesendet", "the last {n} the gateway keeps": "die letzten {n}, die der Zugangspunkt aufbewahrt", "Accounts and keys": "Konten und Schlüssel", "over those requests": "über diese Anfragen", diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index 352b0ad49..b8647f7c1 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -2229,7 +2229,9 @@ function ledDetail(r) { } // the subscription account that answered, or the key it was sent with if (r.source !== "log") add("Account", r.providerAccount || r.providerKeyName); - add("Sent", r.model); + // the id it went out under, when another than the model's (a variant a + // plugin picked for the effort, a name set upstream): the model's on hover + add("Sent", r.wire || r.model, r.wire ? "led-wire" : "", r.wire ? r.model + " → " + r.wire : ""); if (r.served) add("Served", ledServed(r)); add("Effort", r.effort); add("Service tier", ledTierText(r)); @@ -3934,7 +3936,7 @@ function renderLedger() { if (badges.childElementCount) wc.append(badges); // the model sent is what the gateway sent the vendor: a session file has none // The log names a model, but does not capture the outbound HTTP request. - td(r.model || "—", "model " + (r.model ? "model-value" : "faint"), r.source === "log" && r.model ? t("Model recorded in the local session log; the outbound HTTP request was not captured.") : r.model); + td(r.wire || r.model || "—", "model " + (r.model ? "model-value" : "faint"), r.source === "log" && r.model ? t("Model recorded in the local session log; the outbound HTTP request was not captured.") : r.wire ? r.model + " → " + r.wire : r.model); td(ledServed(r), "model"); td(r.effort || "—", r.effort ? "" : "faint"); td(fmtN(r.in || 0), "n", exactN(r.in)); diff --git a/internal/gui/tests/sent-model.test.cjs b/internal/gui/tests/sent-model.test.cjs new file mode 100644 index 000000000..b8e167507 --- /dev/null +++ b/internal/gui/tests/sent-model.test.cjs @@ -0,0 +1,141 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The model id a request went out to the vendor under, when it is another +// than the model's (daoche_wuzui on X: was it routed to a model with a +// suffix?): Antigravity's plugin sends gemini-3.1-pro at high as +// gemini-3.1-pro-high. The Usage page's Requests say that id in the Sent +// column and in a request's details, the model's own on hover; the Routing +// page's story of the try says it went out under it. A request that went out +// as its model says nothing more. No left-border accent; every language; the +// API is faked. +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 reader = require("./reader.cjs"); + +const assets = path.resolve(__dirname, "../assets"); +const now = new Date(); +const day = [now.getFullYear(), now.getMonth() + 1, now.getDate()].map((n) => String(n).padStart(2, "0")).join("-"); +const at = (i) => new Date(now.getTime() - (i + 1) * 60e3).toISOString(); +const key = { id: "antigravity", provider: "antigravity", name: "Antigravity", kind: "provider", model: "gemini-3.1-pro" }; +// newest first: one sent as the variant, then ones sent as the model +const wires = ["gemini-3.1-pro-high", "", "", ""]; +const routes = wires.map((w, i) => ({ + id: 100 - i, seq: 100 - i, time: at(i), agent: "codex", model: "antigravity/gemini-3.1-pro", provider: "antigravity", + order: [key], tries: [{ id: key.id, model: "gemini-3.1-pro", effort: "high", start: at(i), done: true, status: 200, ms: 900, served: "gemini-3.1-pro", ...(w ? { wire: w } : {}) }], + done: true, status: 200, ms: 900, tokens: 1200, served: "gemini-3.1-pro", +})); +const ledRow = (i, w) => ({ + t: at(i), agent: "codex", agentName: "Codex", icon: "codex-color", provider: "antigravity", providerName: "Antigravity", + req: "antigravity/gemini-3.1-pro", model: "gemini-3.1-pro", served: "gemini-3.1-pro", effort: "high", in: 300, out: 40, ms: 2000, status: 200, rid: "r-" + i, ep: "/v1/chat/completions", + ...(w ? { wire: w } : {}), +}); +const ROWS = [ledRow(0, "gemini-3.1-pro-high"), ledRow(1, "")]; + +function serve(lang) { + const state = { agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], 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/gateway/trace") { + if (url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3)); + return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname === "/api/gateway/history") { + const d = url.searchParams.get("day"); + return json({ cut: false, days: [{ day, requests: routes.length }], routes: d ? routes : [] }); + } + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/usage/requests") return json({ period: url.searchParams.get("period"), rows: ROWS, offset: 0, total: 2, calls: 2, errors: 0, input: 600, output: 80, cache_read: 0, cache_write: 0, reasoning: 0, cost: 0, unpriced: 2, agents: [{ id: "codex", name: "Codex", icon: "codex-color" }] }); + if (url.pathname === "/api/usage/requests/content") return json({ found: false, why: "read" }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/usage") return json({ calls: 2, errors: 0, input: 600, output: 80, cache_read: 0, cache_write: 0, reasoning: 0, unpriced: 2, cost: 0, bucket: "day", series: [], agents: [], models: [], path: "~/.config/magpie/usage.jsonl" }); + if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] }); + if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} }); + 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 want = { + en: { story: "Sent to the vendor as gemini-3.1-pro-high", dt: "Sent" }, + zh: { story: "以 gemini-3.1-pro-high 发给厂商", dt: "发送模型" }, + "zh-TW": { story: "以 gemini-3.1-pro-high 發給廠商", dt: "傳送模型" }, + ja: { story: "ベンダーには gemini-3.1-pro-high として送信", dt: "送信したモデル" }, + de: { story: "Beim Anbieter als gemini-3.1-pro-high gesendet", dt: "Gesendet" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(want)) { + test(`${engine} ${lang}: the id a request went out under is named`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const context = await browser.newContext({ viewport: { width: 1100, height: 760 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-sent-model.png`), fullPage: true }); + } + await browser.close(); + }); + + // Routing: the try's story says the id it went out under + await page.goto("http://magpie.test/?view=routing"); + await page.locator(".rt-day").nth(1).waitFor({ state: "visible", timeout: 15000 }); + await page.locator(".rt-day").nth(1).click(); + await page.locator(".rt-req").nth(wires.length - 1).waitFor(); + await page.locator(".rt-req").nth(0).click(); + const said = page.locator(".rt-steps li.wire-said"); + await said.waitFor(); + assert.equal(await said.count(), 1); + assert.equal((await said.textContent()).trim(), want[lang].story); + if (process.env.ARTIFACT_DIR) await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-sent-model-routing.png`) }); + await page.locator(".rt-req").nth(1).click(); + await page.waitForTimeout(300); + assert.equal(await page.locator(".rt-steps li.wire-said").count(), 0); + + // Usage's Requests: the Sent column and a request's details + await page.locator('[data-view="usage"]').first().click(); + await page.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click(); + const rows = page.locator(".led tbody tr.led-row"); + await rows.nth(1).waitFor(); + const cells = await rows.evaluateAll((rs) => rs.map((r) => { + const c = r.querySelector("td.model.model-value"); + return [c?.textContent || "", c?.title || ""]; + })); + assert.deepEqual(cells, [["gemini-3.1-pro-high", "gemini-3.1-pro → gemini-3.1-pro-high"], ["gemini-3.1-pro", "gemini-3.1-pro"]]); + const sent = async (i) => { + await reader.inView(page, rows.nth(i)); + const box = await reader.openRequest(page, rows.nth(i)); + const got = await box.evaluate((b, dt) => { + const dd = [...b.querySelectorAll("dt")].find((d) => d.textContent === dt)?.nextElementSibling; + return dd ? [dd.textContent, dd.title, getComputedStyle(dd).borderLeftWidth] : null; + }, want[lang].dt); + await reader.closeRequest(page); + return got; + }; + assert.deepEqual(await sent(1), ["gemini-3.1-pro", "", "0px"]); + assert.deepEqual(await sent(0), ["gemini-3.1-pro-high", "gemini-3.1-pro → gemini-3.1-pro-high", "0px"]); + const border = await page.evaluate(() => [...document.querySelectorAll(".rt-steps li, .led-detail dd")].map((e) => getComputedStyle(e).borderLeftWidth).filter((b) => parseFloat(b) > 1)); + assert.deepEqual(border, [], "no left-border accent"); + for (const l of ["zh", "zh-TW", "ja", "de"]) { + const missing = await page.evaluate((l) => ["Sent to the vendor as {model}", "Sent"].filter((k) => !I18N[l][k]), l); + assert.deepEqual(missing, [], `every string has its ${l}`); + } + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/provider/migrate_antigravity.go b/internal/provider/migrate_antigravity.go index dd6677ea0..361d2b3e7 100644 --- a/internal/provider/migrate_antigravity.go +++ b/internal/provider/migrate_antigravity.go @@ -16,7 +16,7 @@ import ( func init() { movers["antigravity"] = &mover{ pkg: "@magpie-community/opencode-antigravity-auth", - min: "0.2.1", // 0.2.1 serves again as 0.1.18 did, for the users who have it, and is withdrawn for anyone new (plugin.WithdrawnOf; owner, 11-15: 正在使用的继续正常,加个提示,新用户不让下载); 0.2.0 retired it, sending nothing; 0.1.18 a variant at xhigh (Gemini 4 Hydrogen) is asked at xhigh (plugins#1169); 0.1.14: Gemini 4's late INVALID_ARGUMENT, a bare line in the stream, is asked again and says it isn't a region block (0.1.13 Codex's GPT-5 line reworded in a user's turn, 0.1.12 rewords instead of zero-width, 0.1.11 omp's "key words", 0.1.0 ported the built-in) + min: "0.2.4", // 0.2.4 says the id a request went out under (x-magpie-sent-model), the variant the effort picked, for the ledger and Routing; 0.2.3 Claude Code's identity line goes as "You're …" (#1151); 0.2.1 serves again as 0.1.18 did, for the users who have it, and is withdrawn for anyone new (plugin.WithdrawnOf; owner, 11-15: 正在使用的继续正常,加个提示,新用户不让下载); 0.2.0 retired it, sending nothing; 0.1.18 a variant at xhigh (Gemini 4 Hydrogen) is asked at xhigh (plugins#1169); 0.1.14: Gemini 4's late INVALID_ARGUMENT, a bare line in the stream, is asked again and says it isn't a region block (0.1.13 Codex's GPT-5 line reworded in a user's turn, 0.1.12 rewords instead of zero-width, 0.1.11 omp's "key words", 0.1.0 ported the built-in) agents: []string{"antigravity"}, out: func() ([]Moving, error) { var out []Moving diff --git a/internal/provider/plugins.go b/internal/provider/plugins.go index d2f4804bd..8feb5fdb5 100644 --- a/internal/provider/plugins.go +++ b/internal/provider/plugins.go @@ -835,6 +835,14 @@ func pluginRequestBase(pp plugin.Provider, m plugin.Model, loader string) string // clears the mark. const SignInHeader = "X-Magpie-Sign-In" +// SentModelHeader is how a plugin says the model id it sent the vendor, +// when it picks one magpie can't: Antigravity's plugin sends a family as +// the variant of it the effort picks from the account's own list +// (gemini-3.1-pro at high goes as gemini-3.1-pro-high). The gateway keeps +// it as the try's and the ledger row's Wire, read from a plugin's answer +// only; like every X-Magpie- header it never reaches the agent. +const SentModelHeader = "X-Magpie-Sent-Model" + // ModelUnserved are how a vendor says the model isn't one it serves this // key, or this way — words another provider, or key, may not answer with // (the gateway's unservedWords, read decoded: catalog.Words): ModelScope's diff --git a/internal/usage/ledger.go b/internal/usage/ledger.go index a802ebeca..f6705863f 100644 --- a/internal/usage/ledger.go +++ b/internal/usage/ledger.go @@ -795,7 +795,7 @@ var CSVHeader = []string{"time", "agent", "requested_model", "provider", "host", "effort", "input_tokens", "output_tokens", "cache_write_tokens", "cache_read_tokens", "reasoning_tokens", "cost_usd", "duration_ms", "ttft_ms", "status", "error", "session", "kind", "provider_key_id", "provider_key_name", "provider_account", "route_id", "request_id", "endpoint", "error_message", "error_type", "source", "rejected", "session_provider", "session_account", "session_official_login", "caller_key_id", "caller_key_name", "response_id", "upstream", - "cache_write_5m_tokens", "cache_write_1h_tokens", "tries", "handed_on", "tier_asked", "tier_sent", "tier_served", "upstream_stop", "credits"} + "cache_write_5m_tokens", "cache_write_1h_tokens", "tries", "handed_on", "tier_asked", "tier_sent", "tier_served", "upstream_stop", "credits", "sent_model"} // WriteCSV writes rows as CSV, a header first (cache_write_tokens is every // cache write, as it always was, and the last two columns split it into @@ -811,7 +811,8 @@ var CSVHeader = []string{"time", "agent", "requested_model", "provider", "host", // asked for, the one sent on the row's try and the one the reply said it // ran at, each empty when there was none (Record.TierAsked). credits is // what the reply said the call cost in its plan's credits, empty when it -// said none (Record.Credits). +// said none (Record.Credits). sent_model is the model id the request went +// out to the vendor under, empty when it went as model (Record.Wire). func WriteCSV(w io.Writer, rows []Row) error { cw := csv.NewWriter(w) cw.Write(CSVHeader) @@ -842,7 +843,7 @@ func WriteCSV(w io.Writer, rows []Row) error { cost, strconv.FormatInt(r.Millis, 10), ttft, n(r.Status), strconv.FormatBool(r.Failed()), r.Session, r.Kind, r.ProviderKeyID, r.ProviderKeyName, r.Account(), routeID, r.RequestID, r.Endpoint, r.Error, r.ErrType, r.Source, strconv.FormatBool(r.IsRejected()), r.SessionProvider, r.SessionAccount, strconv.FormatBool(r.SessionOfficialLogin), r.CallerKeyID, r.CallerKeyName, r.ResponseID, r.Upstream, n(r.CacheWrite - min(r.CacheWrite1h, r.CacheWrite)), n(min(r.CacheWrite1h, r.CacheWrite)), tries, strconv.FormatBool(r.HandedOn), - r.TierAsked, r.TierSent, r.TierServed, r.Stop, credits}) + r.TierAsked, r.TierSent, r.TierServed, r.Stop, credits, r.Wire}) } cw.Flush() return cw.Error() diff --git a/internal/usage/ledger_test.go b/internal/usage/ledger_test.go index a147ede25..cc3701869 100644 --- a/internal/usage/ledger_test.go +++ b/internal/usage/ledger_test.go @@ -90,8 +90,8 @@ func TestLedger(t *testing.T) { t.Fatal(err) } want := strings.Join(CSVHeader, ",") + "\n" + - rows[1].Time.Format(time.RFC3339) + ",codex,relay/sol,relay,relay.example,sol,sol-2026-01-01,false,,10,1,0,0,0,0.000028,100,,200,false,,,,,,,,,,,,false,,,false,,,,,0,0,,false,,,,,\n" + - rows[2].Time.Format(time.RFC3339) + ",codex,fast,relay,relay.example,sol,luna,true,high,2000,500,1000,4000,0,0.012500,3200,400,200,false,s1,,,,,123,,,,,,false,,,false,,,,,1000,0,,false,,,,,\n" + rows[1].Time.Format(time.RFC3339) + ",codex,relay/sol,relay,relay.example,sol,sol-2026-01-01,false,,10,1,0,0,0,0.000028,100,,200,false,,,,,,,,,,,,false,,,false,,,,,0,0,,false,,,,,,\n" + + rows[2].Time.Format(time.RFC3339) + ",codex,fast,relay,relay.example,sol,luna,true,high,2000,500,1000,4000,0,0.012500,3200,400,200,false,s1,,,,,123,,,,,,false,,,false,,,,,1000,0,,false,,,,,,\n" if b.String() != want { t.Fatalf("csv:\n%s\nwant:\n%s", b.String(), want) } @@ -261,7 +261,7 @@ func TestLedgerWithSessionLogCalls(t *testing.T) { if err := WriteCSV(&b, rows[2:4]); err != nil { t.Fatal(err) } - for _, want := range []string{",req_log,,,,log,false,,,false,,,,,500,0,,false,,,,,\n", ",true,s2,,,,,,req_lim,,You've hit your limit,rate_limit,log,false,,,false,,,,,0,0,,false,,,,,\n"} { + for _, want := range []string{",req_log,,,,log,false,,,false,,,,,500,0,,false,,,,,,\n", ",true,s2,,,,,,req_lim,,You've hit your limit,rate_limit,log,false,,,false,,,,,0,0,,false,,,,,,\n"} { if !strings.Contains(b.String(), want) { t.Fatalf("csv lacks %q:\n%s", want, b.String()) } diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go index 778095163..3fbd4f84b 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -293,13 +293,13 @@ type rowChunk struct { // rowMsg is the Text of a row's Claude message id, after rowText's, and // rowError its error's const ( - rowMsg = 36 + rowMsg = 37 rowError = 9 // rowClient is the Text of the client's own name, when the user counts // it as another agent (Row.Client, #1958) rowClient = 33 // rowTexts is how many strings a row has: rowText's and the message id - rowTexts = 37 + rowTexts = 38 ) // rowVaried are the strings that differ call by call: the error, the @@ -365,8 +365,8 @@ func (c *rowChunk) shape(t [rowTexts]uint32) uint32 { // reason ("Upstream stop reason", #1927) and the service tiers (#1784) // among them: a string left out comes back empty from the cache, in the // page and in /v1/magpie/usage/requests (TestRowTextHoldsEveryString) -func rowText(r *Row) [36]*string { - return [36]*string{&r.Agent, &r.Provider, &r.Host, &r.SessionProvider, &r.SessionAccount, &r.Model, &r.Requested, &r.Served, &r.Effort, &r.Error, &r.ErrType, &r.RequestID, &r.Endpoint, &r.Session, &r.NativeSession, &r.Kind, &r.Source, &r.Via, &r.ProviderKeyID, &r.ProviderKeyName, &r.CallerKeyID, &r.CallerKeyName, &r.Archive, &r.Operation, &r.ProviderAccount, &r.ResponseID, &r.Upstream, &r.Subagent, &r.ParentAgent, &r.Stop, &r.TierAsked, &r.TierSent, &r.TierServed, &r.Client, &r.CallerIssuerID, &r.ClientIP} +func rowText(r *Row) [37]*string { + return [37]*string{&r.Agent, &r.Provider, &r.Host, &r.SessionProvider, &r.SessionAccount, &r.Model, &r.Requested, &r.Served, &r.Effort, &r.Error, &r.ErrType, &r.RequestID, &r.Endpoint, &r.Session, &r.NativeSession, &r.Kind, &r.Source, &r.Via, &r.ProviderKeyID, &r.ProviderKeyName, &r.CallerKeyID, &r.CallerKeyName, &r.Archive, &r.Operation, &r.ProviderAccount, &r.ResponseID, &r.Upstream, &r.Subagent, &r.ParentAgent, &r.Stop, &r.TierAsked, &r.TierSent, &r.TierServed, &r.Client, &r.CallerIssuerID, &r.ClientIP, &r.Wire} } func (c *rowChunk) add(r Row, msg string, order int64, failed bool) { if c.dict == nil { diff --git a/internal/usage/usage.go b/internal/usage/usage.go index 1235a66d1..2332a0afd 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -62,6 +62,13 @@ type Record struct { // vendor's own bill. Neither is in a record written before they were. Requested string `json:"req,omitempty"` Served string `json:"served,omitempty"` + // Wire is the model id the request went out to the vendor under, when + // it is another than Model: a name the user gave the model upstream + // (ModelWires), or the variant a plugin picked for the effort, which + // the plugin says (provider.SentModelHeader) — Antigravity's + // gemini-…-high for gemini-… at high. "" when it went as Model, and in + // a record written before it was kept. + Wire string `json:"wire,omitempty"` // Upstream: the provider an aggregator (OpenRouter …) said answered // behind it — DeepInfra, Novita — when its reply named one Upstream string `json:"upstream,omitempty"`