gateway, gui: a request an aggregator passed on says which provider answered it behind it, "Upstream: DeepInfra" (leslie_luo on Discord: 像 CPA 那样指出实际供应商) — through OpenRouter a request was only "OpenRouter · deepseek/deepseek-chat", with no word of the provider (DeepInfra, StreamLake, Novita…) OpenRouter had sent it on to. OpenRouter names it in its replies, as tried with the owner's real key: Chat's body and every chunk of its stream have a top-level "provider", Messages' body has one and its stream's message_start a message.provider; its Responses replies and every reply's headers name none. The gateway now reads it (upstreamOf) from a body relayed as it came and from each event of one it translated, Chat, Messages or Responses, streamed or not, and keeps it on the request's try and route (upstream) and in the usage ledger (Record.Upstream; the CSV export's last column, searched as the rest). The Routing page's Requests list says Upstream: DeepInfra beside where it went, giving way after the provider's name when short of room, with its story saying the aggregator passed it on; a request's details on the Usage page have Upstream provider. A reply naming none says nothing. zh, ja, de strings. ClinePass and Cline weren't tried (no account); Vercel's gateway documents no such field in its replies, and a vendor whose reply has a top-level "provider" string is read the same way. In a sandbox magpie with the owner's real OpenRouter key: Chat, Messages and Responses (translated to Chat), streamed and not, all six said StreamLake in the trace, the ledger and on the Routing page. TestUpstreamRecorded (6 paths × streamed or not: the route, its try, Recent and the ledger) fails on the old code, TestUpstreamOf; routing-upstream.test.cjs (Chromium and WebKit, en and zh: the tag inside its row, the story, the Usage details, a click moves nothing, no left-border accent) fails on the old assets. ledger-hscroll, request-archive-usage, usage-ledger and usage-ledger-detail pass on WebKit; routing-served fails the same on origin/main (its swap wording). go vet, builds (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass but for TestTranslatedStreamKeepsClientAlive, which passes alone 5 times here and on origin/main.

This commit is contained in:
yetone
2026-10-05 14:08:08 +08:00
parent bbb9729748
commit e5981040dc
15 changed files with 395 additions and 20 deletions
+6 -3
View File
@@ -1613,7 +1613,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
call.Error = refusedError(c.p, c.model, hw.failMsg)
}
try := Try{ID: c.rest, Model: c.model, Effort: sent, Picked: picked, Fixed: fixed, Fast: fast, Start: began, Done: true, Status: call.Status, Millis: time.Since(began).Milliseconds(), Error: call.Error, Queued: queued,
Served: call.Usage.Served, Auto: autoPicked()}
Served: call.Usage.Served, Upstream: call.Usage.Upstream, Auto: autoPicked()}
asName := provider.SentNameOnIn(wiresOf(r.Context()), c.p.ID, accountAgent(c.p), c.model, sent)
try.Swapped, try.Routed = swapped(asName, call.Usage.Served), usage.GroupRouted(asName, call.Usage.Served)
try.TTFT, try.FirstText = hw.first.ms()
@@ -1725,7 +1725,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, Upstream: call.Usage.Upstream,
Input: call.Usage.Input, Output: call.Usage.Output, CacheRead: call.Usage.CacheRead,
CacheWrite: call.Usage.CacheWrite, Reasoning: call.Usage.Reasoning, Effort: sent, Millis: time.Since(began).Milliseconds(), Status: call.Status,
TTFT: try.TTFT, FirstText: try.FirstText, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind,
@@ -1991,13 +1991,14 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
t.Output, t.TTFT, t.FirstText = call.Usage.Output, call.TTFT, call.FirstText
if n := len(t.Tries); n > 0 && call.Status < 400 {
t.Served, t.Swapped, t.Routed = t.Tries[n-1].Served, t.Tries[n-1].Swapped, t.Tries[n-1].Routed
t.Upstream = t.Tries[n-1].Upstream
}
})
s.record(call)
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,
Requested: call.Model, Served: call.Usage.Served, Upstream: call.Usage.Upstream,
Input: call.Usage.Input, Output: call.Usage.Output, CacheRead: call.Usage.CacheRead,
CacheWrite: call.Usage.CacheWrite, Reasoning: call.Usage.Reasoning, Effort: sent, Millis: call.Millis, Status: call.Status,
TTFT: call.TTFT, FirstText: call.FirstText, Sent: sentMs, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind,
@@ -3308,6 +3309,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
})
see, held := written(see)
serr := readSSEAlive(rd, func(_, data string) error {
u.add(Usage{Upstream: upstreamOf([]byte(data))})
return dec(data, see)
}, func() {
// the provider's keepalives aren't events to translate: while
@@ -3343,6 +3345,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
var col collector
see, held := written(zenSee(zen, col.add))
err = readSSE(rd, func(_, data string) error {
u.add(Usage{Upstream: upstreamOf([]byte(data))})
return dec(data, see)
})
held()
+6
View File
@@ -200,6 +200,9 @@ type Usage struct {
// Served: the model the vendor's reply says answered, when it named
// one — which may not be the one it was asked for
Served string `json:"served,omitempty"`
// Upstream: the provider an aggregator says answered behind it
// (OpenRouter's "provider": DeepInfra, Novita …), when it says one
Upstream string `json:"upstream,omitempty"`
// RequestID: the id the vendor gave the request, from its reply's
// headers (Claude Code's own for a subscription); ErrType: what a
// failed request's error body called the error
@@ -235,6 +238,9 @@ func (u *Usage) add(v Usage) {
if v.Served != "" {
u.Served = v.Served
}
if v.Upstream != "" {
u.Upstream = v.Upstream
}
if v.RequestID != "" {
u.RequestID = v.RequestID
}
+3
View File
@@ -124,6 +124,9 @@ func (s *usageSniffer) parse(b []byte) {
s.u.ErrType = provider.ErrorType(body)
}
}
if up := upstreamOf(b); up != "" {
s.u.Upstream = up
}
switch s.proto {
case provider.Gemini:
// Factory's generateContent chunks, the same usageMetadata Code
+9 -4
View File
@@ -67,6 +67,8 @@ type Route struct {
Served string `json:"served,omitempty"`
Swapped bool `json:"swapped,omitempty"`
Routed bool `json:"routed,omitempty"`
// Upstream: the provider an aggregator said answered behind it
Upstream string `json:"upstream,omitempty"`
}
// RouteUsage is one billable attempt's pricing inputs, kept in routing history.
@@ -235,10 +237,13 @@ type Try struct {
Served string `json:"served,omitempty"`
Swapped bool `json:"swapped,omitempty"`
Routed bool `json:"routed,omitempty"`
Fail string `json:"fail,omitempty"` // why it failed, as rest tells it
Error string `json:"error,omitempty"`
Rest *Rest `json:"rest,omitempty"` // how long it now sits out; none when it was the last to try
Again int64 `json:"again,omitempty"` // ms waited before it was tried again, the last one left
// Upstream: the provider an aggregator said answered behind it
// (OpenRouter's DeepInfra, Novita …)
Upstream string `json:"upstream,omitempty"`
Fail string `json:"fail,omitempty"` // why it failed, as rest tells it
Error string `json:"error,omitempty"`
Rest *Rest `json:"rest,omitempty"` // how long it now sits out; none when it was the last to try
Again int64 `json:"again,omitempty"` // ms waited before it was tried again, the last one left
// Queued: ms it waited for one of its key's or account's slots, the
// provider's MaxConcurrency out already (concurrency.go)
Queued int64 `json:"queued,omitempty"`
+40
View File
@@ -0,0 +1,40 @@
package gateway
import (
"bytes"
"encoding/json"
"strings"
)
// upstreamOf is the provider an aggregator's reply (a JSON body, or one
// event of its stream) says answered behind it, "" when it says none.
// OpenRouter names it in a top-level "provider" — a Chat body and every
// chunk of its stream, an Anthropic Messages body — and in a Messages
// stream's message_start, as message.provider (seen 2026-10-05: DeepInfra,
// StreamLake). Its Responses replies name none.
func upstreamOf(b []byte) string {
if !bytes.Contains(b, []byte(`"provider"`)) {
return ""
}
var v struct {
Provider json.RawMessage `json:"provider"`
Message struct {
Provider json.RawMessage `json:"provider"`
} `json:"message"`
Response struct {
Provider json.RawMessage `json:"provider"`
} `json:"response"`
}
if json.Unmarshal(b, &v) != nil {
return ""
}
for _, raw := range []json.RawMessage{v.Provider, v.Message.Provider, v.Response.Provider} {
var s string // a request's provider options echoed back are an object
if json.Unmarshal(raw, &s) == nil {
if s = strings.TrimSpace(s); s != "" && len(s) <= 64 {
return s
}
}
}
return ""
}
+139
View File
@@ -0,0 +1,139 @@
package gateway
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// orAnswers is an aggregator that answers as OpenRouter does (seen
// 2026-10-05): a Chat body and every chunk of its stream say the
// provider behind it in a top-level "provider", an Anthropic body too, and
// an Anthropic stream in message_start's message.
func orAnswers(proto provider.Protocol, upstream string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
stream := strings.Contains(string(b), `"stream":true`)
P := `"provider":"` + upstream + `"`
if !stream {
w.Header().Set("Content-Type", "application/json")
if proto == provider.Chat {
io.WriteString(w, `{"id":"gen-1","object":"chat.completion","model":"deepseek/deepseek-chat",`+P+`,"choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":2}}`)
} else {
io.WriteString(w, `{"id":"gen-1","type":"message","role":"assistant","model":"deepseek/deepseek-chat","content":[{"type":"text","text":"hi"}],"stop_reason":"end_turn","usage":{"input_tokens":5,"output_tokens":2},`+P+`}`)
}
return
}
var events []string
if proto == provider.Chat {
events = []string{
`data: {"id":"gen-1","model":"deepseek/deepseek-chat",` + P + `,"choices":[{"index":0,"delta":{"role":"assistant","content":"hi"}}]}`,
`data: {"id":"gen-1","model":"deepseek/deepseek-chat",` + P + `,"choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":2}}`,
`data: [DONE]`,
}
} else {
events = []string{
"event: message_start\ndata: " + `{"type":"message_start","message":{"id":"gen-1","type":"message","role":"assistant","model":"deepseek/deepseek-chat","content":[],"usage":{"input_tokens":5,"output_tokens":0},` + P + `}}`,
"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 provider an aggregator says answered behind it (leslie_luo on
// Discord: "指出实际供应商" for ClinePass, OpenRouter) is kept on the
// request's route, its try, the request log and the usage ledger, relayed
// or translated, streamed or not.
func TestUpstreamRecorded(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"`,
}
for _, pa := range []struct {
name string
proto provider.Protocol // the aggregator's
agent string
}{
{"chat", provider.Chat, "/v1/chat/completions"},
{"anthropic", provider.Anthropic, "/v1/messages"},
{"anthropic from chat", provider.Chat, "/v1/messages"},
{"responses from chat", provider.Chat, "/v1/responses"},
{"chat from anthropic", provider.Anthropic, "/v1/chat/completions"},
{"responses from anthropic", provider.Anthropic, "/v1/responses"},
} {
for _, stream := range []bool{true, false} {
name := pa.name
if stream {
name += "/stream"
}
t.Run(name, func(t *testing.T) {
fresh(t)
up := httptest.NewServer(orAnswers(pa.proto, "DeepInfra"))
t.Cleanup(up.Close)
p := provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"sol"}}
if pa.proto == provider.Chat {
p.Chat = up.URL + "/v1"
} else {
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.Upstream != "DeepInfra" || len(r.Tries) != 1 || r.Tries[0].Upstream != "DeepInfra" {
t.Errorf("route upstream %q, tries %+v", r.Upstream, r.Tries)
}
if calls := s.Recent(); len(calls) == 0 || calls[0].Usage.Upstream != "DeepInfra" {
t.Errorf("request log: %+v", calls)
}
if u := usage.Load(time.Time{}); len(u) != 1 || u[0].Upstream != "DeepInfra" {
t.Errorf("usage %+v", u)
}
})
}
}
}
// Only a name is an upstream: a reply without one, or one echoing a
// request's provider options (an object), says none.
func TestUpstreamOf(t *testing.T) {
for in, want := range map[string]string{
`{"id":"c1","provider":"Novita","choices":[]}`: "Novita",
`{"type":"message_start","message":{"provider":"StreamLake"}}`: "StreamLake",
`{"id":"c1","choices":[]}`: "",
`{"provider":{"order":["deepseek"]},"choices":[]}`: "",
`{"provider":" "}`: "",
`{"choices":[{"delta":{"content":"the \"provider\" field"}}]}`: "",
`not json "provider"`: "",
`{"type":"response.created","response":{"provider":"Baseten"}}`: "Baseten",
} {
if got := upstreamOf([]byte(in)); got != want {
t.Errorf("upstreamOf(%s) = %q; want %q", in, got, want)
}
}
}
+2
View File
@@ -12924,6 +12924,8 @@ function ledDetail(r, cols) {
if (ledRowSpeed(r)) add("Speed", t("{n} tok/s", { n: ledNum(Math.round(ledRowSpeed(r))) }));
add("Request ID", r.rid);
add("Endpoint", r.ep);
// the provider an aggregator (OpenRouter …) said answered behind it
add("Upstream provider", r.upstream);
add("Session ID", r.session);
// a call that isn't a turn of the conversation says what it was for, as
// the agent named it: a subagent's, a title, an approval check… — a
+9
View File
@@ -2597,6 +2597,9 @@ const I18N = {
"{n} tok/s": "{n} token/秒",
"requested {sent} · served {served}": "请求 {sent} · 实际 {served}",
"served {served}": "实际 {served}",
"Upstream: {upstream}": "上游:{upstream}",
"The aggregator passed the request on to {upstream}, as its reply says: the provider that actually answered it.": "聚合供应商把这条请求转给了 {upstream},由它实际作答(聚合供应商的回复里写明)。",
"Upstream provider": "上游",
"{sent} is a routing group of the remote magpie, and it routed the request to {served}: the group picking one of its models, not the vendor swapping the model.": "{sent} 是远程 magpie 的路由组,请求被路由给 {served}:这是路由组选择了组内模型,并非服务商替换了模型。",
"Open Routing": "打开路由",
"The vendor was asked for {sent}, but its reply says {served} answered: likely another model. The same model under a dated name or spelled otherwise isn't marked.": "向服务商请求的是 {sent},但回复说是 {served} 作答,很可能换成了别的模型。(同一模型只是带了日期或写法不同,不会这样标出。)",
@@ -5722,6 +5725,9 @@ const I18N = {
"{n} tok/s": "{n} トークン/秒",
"requested {sent} · served {served}": "リクエスト {sent} · 応答 {served}",
"served {served}": "応答 {served}",
"Upstream: {upstream}": "上流:{upstream}",
"The aggregator passed the request on to {upstream}, as its reply says: the provider that actually answered it.": "アグリゲーターはこのリクエストを {upstream} に回したと応答に書いています。実際に応答したプロバイダーです。",
"Upstream provider": "上流プロバイダー",
"{sent} is a routing group of the remote magpie, and it routed the request to {served}: the group picking one of its models, not the vendor swapping the model.": "{sent} はリモート magpie のルーティンググループで、リクエストを {served} にルーティングしました。グループがモデルを選んだもので、ベンダーがモデルを差し替えたのではありません。",
"Open Routing": "ルーティングを開く",
"The vendor was asked for {sent}, but its reply says {served} answered: likely another model. The same model under a dated name or spelled otherwise isn't marked.": "ベンダーには {sent} をリクエストしましたが、応答では {served} が答えたとあり、別のモデルに替えられた可能性があります。(同じモデルに日付が付いただけ、または表記が違うだけなら表示しません。)",
@@ -8847,6 +8853,9 @@ const I18N = {
"{n} tok/s": "{n} Token/s",
"requested {sent} · served {served}": "angefragt {sent} · geliefert {served}",
"served {served}": "geliefert {served}",
"Upstream: {upstream}": "Upstream: {upstream}",
"The aggregator passed the request on to {upstream}, as its reply says: the provider that actually answered it.": "Der Aggregator hat die Anfrage laut seiner Antwort an {upstream} weitergegeben: der Anbieter, der sie tatsächlich beantwortet hat.",
"Upstream provider": "Upstream-Anbieter",
"{sent} is a routing group of the remote magpie, and it routed the request to {served}: the group picking one of its models, not the vendor swapping the model.": "{sent} ist eine Weiterleitungsgruppe des entfernten magpie und hat die Anfrage an {served} weitergeleitet: Die Gruppe wählt eines ihrer Modelle, nicht der Anbieter tauscht das Modell.",
"Open Routing": "Weiterleitung öffnen",
"The vendor was asked for {sent}, but its reply says {served} answered: likely another model. The same model under a dated name or spelled otherwise isn't marked.": "Beim Anbieter wurde {sent} angefragt, laut Antwort hat aber {served} geantwortet – wahrscheinlich ein anderes Modell. (Dasselbe Modell mit Datum oder anderer Schreibweise wird nicht markiert.)",
+3
View File
@@ -197,6 +197,9 @@
.rt-req .to .swap { flex: none; max-width: 70%; }
.rt-req .to .routed, .pr-to .routed { flex: none; max-width: 45%; overflow: hidden; text-overflow: ellipsis; font-size: 10.5px; line-height: 16px; color: var(--muted); white-space: nowrap; }
.rt-steps li.swap::before { background: var(--amber); }
/* short of room, where it went gives way down to the provider's name, then this does */
.rt-req .to:has(.upstream) .said { min-width: min(10em, 45%); }
.rt-req .to .upstream, .pr-to .upstream { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; font-size: 10.5px; line-height: 16px; color: var(--muted); white-space: nowrap; }
.rt-req .meta { color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; text-align: right; }
.rt-req .meta .cost { display: inline-block; margin-left: 10px; color: var(--fg-2); }
.rt-session { grid-column: 1 / -1; display: flex; align-items: center; flex-wrap: wrap; gap: 4px 8px; min-width: 0; padding: 9px 8px; margin-top: 4px; font: inherit; font-size: 12px; text-align: left; color: var(--fg-2); background: var(--card-2); border: 1px solid var(--line); border-radius: 8px; }
+12 -1
View File
@@ -1187,6 +1187,7 @@
if (tr.done && tryOk(tr) && tr.swapped) items.push([swapWhy(tr), "swap", tr]);
// another magpie's routing group named the member it routed to
else if (tr.done && tryOk(tr) && tr.routed) items.push([routedWhy(tr), "aside", tr]);
if (tr.done && tryOk(tr) && tr.upstream) items.push([upstreamWhy(tr), "aside upstream-said", tr]);
});
if (r.done && !r.tries.length) items.push([t("Nothing was tried: {error}", { error: r.error || r.status }), "bad"]);
const key = JSON.stringify([r.kind, items.map(([s, c, tr]) => [s, c, tr?.model, tr?.served]), r.order.map(logoOf)]);
@@ -1289,6 +1290,14 @@
}
const routedWhy = (tr) => t("{sent} is a routing group of the remote magpie, and it routed the request to {served}: the group picking one of its models, not the vendor swapping the model.", { sent: tr.model, served: tr.served });
window.routedWhy = routedWhy;
// the provider an aggregator (OpenRouter …) said answered behind it:
// DeepInfra, Novita… (leslie_luo on Discord)
function upstreamTag(tr) {
const k = el("span", "upstream", t("Upstream: {upstream}", { upstream: tr.upstream }));
k.title = upstreamWhy(tr);
return k;
}
const upstreamWhy = (tr) => t("The aggregator passed the request on to {upstream}, as its reply says: the provider that actually answered it.", { upstream: tr.upstream });
function kindWhy(r) {
const agent = agentName(r.agent);
if (KIND[r.kind] === "Subagent") return r.group
@@ -1562,7 +1571,7 @@
// all the row says, and its titles
const title = reqTitle(r, how, tr);
const sig = JSON.stringify([lang, said, how, title, r.time, r.agent, agentName(r.agent), ag?.icon, r.model, r.provider, r.kind, r.effort,
tr?.effort, tr?.picked, tr?.fixed, tr?.fast, tr?.swapped && tr.done && tryOk(tr) ? [tr.model, tr.served] : 0, tr?.routed && tr.done && tryOk(tr) ? tr.served : 0, meta, routeCost(r)]);
tr?.effort, tr?.picked, tr?.fixed, tr?.fast, tr?.swapped && tr.done && tryOk(tr) ? [tr.model, tr.served] : 0, tr?.routed && tr.done && tryOk(tr) ? tr.served : 0, tr?.done && tryOk(tr) ? tr.upstream : 0, meta, routeCost(r)]);
ids.add(r.id);
let x = reqRows.get(r.id);
if (!x || x.sig !== sig) {
@@ -1623,6 +1632,7 @@
}
if (tr?.swapped && tr.done && tryOk(tr)) to.append(swapTag(tr, true)); // beside the model asked for
else if (tr?.routed && tr.done && tryOk(tr)) to.append(routedTag(tr));
if (tr?.upstream && tr.done && tryOk(tr)) to.append(upstreamTag(tr));
const info = el("span", "meta");
info.append(el("span", "", meta.join(" · ")), el("span", "cost", routeCost(r)));
info.lastChild.title = r.priced ? costNote() : t("No known price or token counts for this request");
@@ -3652,6 +3662,7 @@
if (model) to.append(el("span", "pr-m", model));
if (tr?.swapped && tr.done) to.append(swapTag(tr, true));
else if (tr?.routed && tr.done) to.append(routedTag(tr));
if (tr?.upstream && tr.done) to.append(upstreamTag(tr));
}
const meta = [];
if (r.tries.length > 1) meta.push(t("{n} tries", { n: r.tries.length }));
@@ -0,0 +1,151 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// The provider an aggregator says answered behind it (leslie_luo on
// Discord: 指出实际供应商, as CPA does, for ClinePass and OpenRouter): a
// request OpenRouter passed on to DeepInfra says "Upstream: DeepInfra" in
// the Routing page's Requests list, whole and inside its row, its story
// says so, and a request's details on the Usage page name it; one whose
// reply named none says nothing. No click moves the page, no left-border
// accent. English and Chinese; 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: "openrouter", provider: "openrouter", name: "OpenRouter", kind: "provider", model: "deepseek/deepseek-chat" };
// newest first: one passed on to DeepInfra, then ones that named none
const ups = ["DeepInfra", "", "", "", "", ""];
const routes = ups.map((u, i) => ({
id: 100 - i, seq: 100 - i, time: at(i), agent: "codex", model: "openrouter/deepseek/deepseek-chat", provider: "openrouter",
order: [key], tries: [{ id: key.id, model: "deepseek/deepseek-chat", start: at(i), done: true, status: 200, ms: 900, served: "deepseek/deepseek-chat", ...(u ? { upstream: u } : {}) }],
done: true, status: 200, ms: 900, tokens: 1200, served: "deepseek/deepseek-chat", ...(u ? { upstream: u } : {}),
}));
const ledRow = (i, u) => ({
t: at(i), agent: "codex", agentName: "Codex", icon: "codex-color", provider: "openrouter", providerName: "OpenRouter",
req: "openrouter/deepseek/deepseek-chat", model: "deepseek/deepseek-chat", served: "deepseek/deepseek-chat", in: 300, out: 40, ms: 2000, status: 200, rid: "gen-" + i, ep: "/v1/chat/completions",
...(u ? { upstream: u } : {}),
});
const ROWS = [ledRow(0, "DeepInfra"), 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: { tag: "Upstream: DeepInfra", story: /passed the request on to DeepInfra/, dt: "Upstream provider" },
zh: { tag: "上游:DeepInfra", story: /把这条请求转给了 DeepInfra/, dt: "上游" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
test(`${engine} ${lang}: the provider behind an aggregator 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);
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}-upstream.png`), fullPage: true });
}
await browser.close();
});
await page.goto("http://magpie.test/?view=routing");
// a browser started cold draws the days late
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(ups.length - 1).waitFor();
// the list: the one passed on says where, whole, inside its row
const tags = await page.locator(".rt-req").evaluateAll((rows) => rows.map((r) => r.querySelector(".to .upstream")?.textContent || ""));
assert.deepEqual(tags, [want[lang].tag, "", "", "", "", ""]);
const look = await page.locator(".rt-req .to .upstream").evaluate((e) => {
const row = e.closest(".rt-req").getBoundingClientRect(), b = e.getBoundingClientRect(), cs = getComputedStyle(e);
return { inRow: b.left >= row.left && b.right <= row.right + 0.5 && b.width > 0, full: e.clientWidth >= e.scrollWidth, border: cs.borderLeftWidth, title: e.title };
});
assert(look.inRow && look.full, JSON.stringify(look));
assert.equal(look.border, "0px");
assert.match(look.title, want[lang].story);
// its story says so, and the click leaves the row where it is
const row = page.locator(".rt-req").nth(0);
const was = await row.evaluate((e) => e.getBoundingClientRect().top);
const scrolled = await page.evaluate(() => [scrollX, scrollY, document.scrollingElement.scrollTop]);
await row.click();
await page.waitForTimeout(600);
assert(Math.abs((await row.evaluate((e) => e.getBoundingClientRect().top)) - was) <= 1, "picking the request moved the page");
assert.deepEqual(await page.evaluate(() => [scrollX, scrollY, document.scrollingElement.scrollTop]), scrolled);
const story = page.locator(".rt-steps li.upstream-said");
assert.equal(await story.count(), 1);
assert.match(await story.textContent(), want[lang].story);
if (process.env.ARTIFACT_DIR) await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-upstream-routing.png`) });
await page.locator(".rt-req").nth(1).click();
await page.waitForTimeout(300);
assert.equal(await page.locator(".rt-steps li.upstream-said").count(), 0);
// the Usage page's Requests: a request's details name it
await page.locator('[data-view="usage"]').first().click();
await page.locator("#usageTab .opt").nth(1).click();
const rows = page.locator(".led tbody tr.led-row");
await rows.nth(1).waitFor();
const top = () => page.locator("#view-usage").evaluate((v) => v.scrollTop);
const dd = async (i) => {
// brought into view by the wheel; the click itself moves nothing
await reader.inView(page, rows.nth(i));
const was = await top();
await rows.nth(i).click();
await page.waitForTimeout(200);
assert.equal(await top(), was, "a click moved the page");
const box = page.locator(".led-detail").nth(i);
await box.waitFor();
return box.evaluate((b, dt) => [...b.querySelectorAll("dt")].find((d) => d.textContent === dt)?.nextElementSibling?.textContent || "", want[lang].dt);
};
assert.equal(await dd(0), "DeepInfra");
assert.equal(await dd(1), "");
const border = await page.evaluate(() => [...document.querySelectorAll(".rt-req .upstream, .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", "ja", "de"]) {
const missing = await page.evaluate((l) => ["Upstream: {upstream}", "Upstream provider",
"The aggregator passed the request on to {upstream}, as its reply says: the provider that actually answered it."].filter((k) => !I18N[l][k]), l);
assert.deepEqual(missing, [], `every string has its ${l}`);
}
assert.deepEqual(errors, []);
});
}
}
+3 -3
View File
@@ -109,7 +109,7 @@ func (f Filter) keeps(r Record) bool {
return false
}
if q := strings.ToLower(strings.TrimSpace(f.Query)); q != "" {
return slices.ContainsFunc([]string{r.Requested, r.Model, r.Served, r.Provider, r.Host, r.Session, r.Effort, r.SessionProvider, r.SessionAccount, r.ProviderKeyID, r.ProviderKeyName, r.Account(), r.CallerKeyID, r.CallerKeyName}, func(s string) bool {
return slices.ContainsFunc([]string{r.Requested, r.Model, r.Served, r.Upstream, r.Provider, r.Host, r.Session, r.Effort, r.SessionProvider, r.SessionAccount, r.ProviderKeyID, r.ProviderKeyName, r.Account(), r.CallerKeyID, r.CallerKeyName}, func(s string) bool {
return strings.Contains(strings.ToLower(s), q)
})
}
@@ -390,7 +390,7 @@ func NewPricer() func([]Record) Totals {
var CSVHeader = []string{"time", "agent", "requested_model", "provider", "host", "model", "served_model", "swapped",
"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"}
"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"}
// WriteCSV writes rows as CSV, a header first: times in RFC 3339 with
// their offset, the cost in USD at the effective price (empty when unknown), error
@@ -416,7 +416,7 @@ func WriteCSV(w io.Writer, rows []Row) error {
cw.Write([]string{r.Time.Format(time.RFC3339), r.Agent, r.Requested, r.Provider, r.Host, r.Model, r.Served,
strconv.FormatBool(r.Swapped), r.Effort, n(r.Input), n(r.Output), n(r.CacheWrite), n(r.CacheRead), n(r.Reasoning),
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.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})
}
cw.Flush()
return cw.Error()
+3 -3
View File
@@ -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,,,\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,,,\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,,,,\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,,,,\n"
if b.String() != want {
t.Fatalf("csv:\n%s\nwant:\n%s", b.String(), want)
}
@@ -260,7 +260,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,,,\n", ",true,s2,,,,,,req_lim,,You've hit your limit,rate_limit,log,false,,,false,,,\n"} {
for _, want := range []string{",req_log,,,,log,false,,,false,,,,\n", ",true,s2,,,,,,req_lim,,You've hit your limit,rate_limit,log,false,,,false,,,,\n"} {
if !strings.Contains(b.String(), want) {
t.Fatalf("csv lacks %q:\n%s", want, b.String())
}
+4 -4
View File
@@ -51,7 +51,7 @@ type RequestPage struct {
type packedRow struct {
Time time.Time
Text [27]uint32
Text [28]uint32
Tokens [5]int64
Millis, TTFT, FirstText, Order int64
Sent int64
@@ -76,10 +76,10 @@ type rowChunk struct {
}
// rowMsg is the Text of a row's Claude message id, after rowText's
const rowMsg = 26
const rowMsg = 27
func rowText(r *Row) [26]*string {
return [26]*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}
func rowText(r *Row) [27]*string {
return [27]*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}
}
func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
if c.dict == nil {
+5 -2
View File
@@ -51,8 +51,11 @@ type Record struct {
// routing group, provider/model…), and Served the model the vendor's
// reply says answered, when it named one: a ledger to set beside the
// vendor's own bill. Neither is in a record written before they were.
Requested string `json:"req,omitempty"`
Served string `json:"served,omitempty"`
Requested string `json:"req,omitempty"`
Served string `json:"served,omitempty"`
// Upstream: the provider an aggregator (OpenRouter …) said answered
// behind it — DeepInfra, Novita — when its reply named one
Upstream string `json:"upstream,omitempty"`
Input int `json:"in"`
Output int `json:"out"`
CacheRead int `json:"cache_read,omitempty"`