From 1474b78f19322dc7148668d73dfbcfce8ba8d283 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 1 Oct 2026 17:05:59 +0800 Subject: [PATCH] =?UTF-8?q?gateway:=20GET=20/v1/magpie/route=20tells=20a?= =?UTF-8?q?=20session's=20route=20as=20it=20happens=20(#405:=20a=20status?= =?UTF-8?q?=20bar=20wants=20the=20routed=20model=20and=20effort=20before?= =?UTF-8?q?=20the=20first=20token)=20=E2=80=94=20routing=20decides=20a=20g?= =?UTF-8?q?roup's=20member,=20and=20its=20decision=20model=20the=20effort,?= =?UTF-8?q?=20before=20the=20vendor=20is=20asked,=20but=20an=20agent's=20U?= =?UTF-8?q?I=20only=20learned=20it=20from=20the=20reply.=20A=20route=20now?= =?UTF-8?q?=20remembers=20the=20session=20its=20request=20named=20(X-Magpi?= =?UTF-8?q?e-Session,=20or=20the=20agent's=20own=20session=20header;=20kep?= =?UTF-8?q?t=20out=20of=20the=20trace's=20JSON=20and=20history),=20and=20G?= =?UTF-8?q?ET=20/v1/magpie/route=3Fsession=3D=20answers=20that=20sessi?= =?UTF-8?q?on's=20latest=20route:=20the=20model=20asked,=20the=20group,=20?= =?UTF-8?q?the=20rule=20matched=20(with=20the=20effort=20picked),=20the=20?= =?UTF-8?q?member=20being=20tried=20and=20the=20effort=20it=20was=20sent?= =?UTF-8?q?=20at,=20every=20try=20with=20why=20a=20fallen-over=20one=20fai?= =?UTF-8?q?led,=20then=20done/status/served.=20after=3D&wait=3D=20?= =?UTF-8?q?(up=20to=2060)=20waits=20for=20it=20to=20change.=20Only=20the?= =?UTF-8?q?=20named=20session=20is=20told;=20like=20/v1/magpie/quotas=20it?= =?UTF-8?q?=20answers=20this=20machine,=20and=20another=20only=20with=20th?= =?UTF-8?q?e=20shared=20gateway's=20key.=20TestSessionRoute=20fails=20with?= =?UTF-8?q?out=20the=20change=20(404).=20go=20vet,=20go=20build=20-tags=20?= =?UTF-8?q?nogui=20(darwin,=20GOOS=3Dlinux),=20GOOS=3Dwindows=20go=20build?= =?UTF-8?q?,=20go=20test=20-tags=20nogui=20./...=20pass=20(TestUserPath=20?= =?UTF-8?q?and=20two=20Claude=20account=20tests=20flaked=20under=20load=20?= =?UTF-8?q?and=20pass=20alone).?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 17 +++ internal/gateway/codex_backend.go | 2 +- internal/gateway/gateway.go | 5 +- internal/gateway/session_route.go | 157 +++++++++++++++++++++++++ internal/gateway/session_route_test.go | 143 ++++++++++++++++++++++ internal/gateway/trace.go | 1 + 6 files changed, 322 insertions(+), 3 deletions(-) create mode 100644 internal/gateway/session_route.go create mode 100644 internal/gateway/session_route_test.go diff --git a/README.md b/README.md index 0ca68f81a..f6660c14a 100644 --- a/README.md +++ b/README.md @@ -481,6 +481,23 @@ subscription with several: only it is tried, and an unknown account, one whose plan lacks the model, or one resting is an error rather than another account's reply. The header is not sent on to the vendor. +A status bar can show where a turn went before its first token arrives: +send `X-Magpie-Session: ` with the requests (an agent's own session +header, such as Pi's or Claude Code's, works too) and read +`GET /v1/magpie/route?session=`. It answers the session's latest +request as routing has it so far — `asked` (the model the agent named), +`group`, `rule` (the group's rule that matched, and `rule.pick`, the +effort its decision model picked), `model` and `effort` (the member being +tried now, as `provider/model`, and the reasoning it was sent at), and +`tries`, one per member tried, each failed one a fallback with its `fail` +— then `done`, `status` and `served` once the reply is over; `route` is +`null` before the session has one. The route appears once routing has +decided, before the vendor is asked. `after=&wait=` (up to 60) +holds the answer until the route changes past the `seq` of the last one, +so a UI can follow a turn with one request at a time. Only the session +named is told; like `/v1/magpie/quotas`, it answers this machine, and +another only with the key of a gateway shared on the local network. + The *Gateway* tab in the app has this as copy buttons and ready-made snippets (shell, curl, Python, Node) for each API, the list of model ids, and the recent calls; `MAGPIE_DEBUG=1` logs every call to the terminal. diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index d8e184d60..a5d9f9d7f 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -238,7 +238,7 @@ func (s *Server) codexUpstream(w http.ResponseWriter, r *http.Request, rest stri } model := modelOf(body) seat := Weighed{ID: "codex", Provider: "openai", Name: "OpenAI", Icon: "openai", Who: who, Kind: "account", Agent: "codex", Model: model} - tr = s.trace.begin(Route{Time: start, Agent: agentOf(r), Kind: callKind(r.Header), Model: model, Provider: "openai", + tr = s.trace.begin(Route{Time: start, Agent: agentOf(r), Session: sessionOf(r.Header), Kind: callKind(r.Header), Model: model, Provider: "openai", Order: []Weighed{seat}, Tries: []Try{{ID: seat.ID, Model: model, Start: start}}}) end = func(status int, msg string, tokens, out int) { ms := time.Since(start).Milliseconds() diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 4da0e1ce8..abb245bb9 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -365,6 +365,7 @@ func (s *Server) Handler() http.Handler { writeJSON(w, 200, map[string]any{"name": "magpie", "version": Version}) }) mux.HandleFunc("GET /v1/magpie/quotas", s.quotas) + mux.HandleFunc("GET /v1/magpie/route", s.sessionRoute) mux.HandleFunc("POST /v1/chat/completions", s.handle(provider.Chat)) mux.HandleFunc("POST /chat/completions", s.handle(provider.Chat)) mux.HandleFunc("POST /v1/responses", s.handle(provider.Responses)) @@ -395,7 +396,7 @@ func (s *Server) Handler() http.Handler { func (s *Server) info(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, map[string]any{"name": "magpie", "version": Version, "models": len(provider.Catalog()), "window": Window, - "apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1/magpie/quotas"}}) + "apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1/magpie/quotas", "/v1/magpie/route"}}) } // quotas is what is left of every subscription, plan and key magpie has, @@ -1044,7 +1045,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro if len(cands) == 1 { shown = nil // nobody else to stay away from } - tr := s.trace.begin(Route{Pinned: pin, Time: start, Agent: call.Agent, Kind: call.Kind, For: call.For, Model: call.Model, Effort: requestEffort(from, body), Provider: p.ID, Group: group, Rule: hit, Nested: nested, Affinity: shown, Order: pl.order, Left: pl.left}) + tr := s.trace.begin(Route{Pinned: pin, Time: start, Agent: call.Agent, Session: sessionOf(r.Header), Kind: call.Kind, For: call.For, Model: call.Model, Effort: requestEffort(from, body), Provider: p.ID, Group: group, Rule: hit, Nested: nested, Affinity: shown, Order: pl.order, Left: pl.left}) var skipped []string sent := "" // the reasoning the last try's model was asked for where := "" // the last try's provider.Where, for the usage diff --git a/internal/gateway/session_route.go b/internal/gateway/session_route.go new file mode 100644 index 000000000..4044c96fe --- /dev/null +++ b/internal/gateway/session_route.go @@ -0,0 +1,157 @@ +package gateway + +// GET /v1/magpie/route: where a session's turn went, for an agent's UI to +// show while the reply is still on its way (#405). Routing decides the +// member, and a group's decision model the effort, before the vendor is +// asked; each fallback is in the trace as it happens. This tells one +// session's latest route from the trace, nothing the trace doesn't hold. + +import ( + "context" + "net/http" + "strconv" + "strings" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// routeWaitMax caps how long one ask waits for the route to change. +const routeWaitMax = 60 * time.Second + +// SessionRoute is a session's latest request as routing has it so far. +type SessionRoute struct { + ID int64 `json:"id"` + Time time.Time `json:"time"` + Kind string `json:"kind,omitempty"` // a side call's: a title, a subagent… + Asked string `json:"asked"` // the model as the agent asked + AskedEffort string `json:"asked_effort,omitempty"` // the reasoning it asked for + Group string `json:"group,omitempty"` // the routing group's id, when it asked one + Rule *RuleHit `json:"rule,omitempty"` // the group's rules, as the Routing page has them + Nested []NestedRule `json:"nested,omitempty"` + // Model and Effort: the try under way, or the last, as provider/model + // and the reasoning it was sent at + Model string `json:"model,omitempty"` + Effort string `json:"effort,omitempty"` + Served string `json:"served,omitempty"` // the model the reply says answered + Tries []RouteTry `json:"tries"` + Done bool `json:"done"` + Status int `json:"status,omitempty"` + Error string `json:"error,omitempty"` + Millis int64 `json:"ms,omitempty"` + TTFT int64 `json:"ttft_ms,omitempty"` +} + +// RouteTry is one member trying the request: each failed one was fallen +// over from. +type RouteTry struct { + Model string `json:"model"` // provider/model + Effort string `json:"effort,omitempty"` + Done bool `json:"done"` + Status int `json:"status,omitempty"` + Fail string `json:"fail,omitempty"` // why it failed, as the trace tells it + Millis int64 `json:"ms,omitempty"` +} + +func sessionRouteOf(r Route) SessionRoute { + out := SessionRoute{ID: r.ID, Time: r.Time, Kind: r.Kind, Asked: r.Model, AskedEffort: r.Effort, Rule: r.Rule, Nested: r.Nested, + Served: r.Served, Tries: []RouteTry{}, Done: r.Done, Status: r.Status, Error: r.Error, Millis: r.Millis, TTFT: r.TTFT} + if r.Group != nil { + out.Group = r.Group.ID + } + // a try names its seat, whose provider is in the order weighed + providerOf := func(id string) string { + for _, ws := range [][]Weighed{r.Order, r.Left} { + for _, w := range ws { + if w.ID == id { + return w.Provider + } + } + } + return r.Provider + } + for _, t := range r.Tries { + model := t.Model + if p := providerOf(t.ID); p != "" && model != "" { + model = p + "/" + model + } + out.Tries = append(out.Tries, RouteTry{Model: model, Effort: t.Effort, Done: t.Done, Status: t.Status, Fail: t.Fail, Millis: t.Millis}) + } + if n := len(out.Tries); n > 0 { + out.Model, out.Effort = out.Tries[n-1].Model, out.Tries[n-1].Effort + } + return out +} + +// sessionRoute answers GET /v1/magpie/route?session=, or with the +// session in X-Magpie-Session (or the agent's own session header): the +// session's latest route, null before it has one. With after= and +// wait= it waits, up to a minute, for the route to change past +// seq. Like the quotas, it answers this machine, and another only with the +// shared gateway's key. +func (s *Server) sessionRoute(w http.ResponseWriter, r *http.Request) { + if !local(r) && !sharedWith(r) { + writeError(w, provider.Chat, http.StatusForbidden, "magpie's routes are told to another machine only when magpie is shared on the local network (Settings → Share on local network) and the request carries its API key (Authorization: Bearer or x-api-key: )") + return + } + q := r.URL.Query() + session := strings.TrimSpace(q.Get("session")) + if len(session) > 128 { + session = session[:128] // as sessionOf keeps it + } + if session == "" { + session = sessionOf(r.Header) + } + if session == "" { + writeError(w, provider.Chat, http.StatusBadRequest, "name the session: ?session= or the "+SessionHeader+" header") + return + } + after, _ := strconv.ParseInt(q.Get("after"), 10, 64) + secs, _ := strconv.ParseFloat(q.Get("wait"), 64) + wait := min(time.Duration(secs*float64(time.Second)), routeWaitMax) + seq, route := s.trace.sessionLatest(r.Context(), session, after, wait) + out := map[string]any{"session": session, "seq": seq, "route": nil} + if route != nil { + out["route"] = sessionRouteOf(*route) + } + writeJSON(w, 200, out) +} + +// sessionLatest is a copy of session's latest route, and its seq; with +// wait, it waits up to that long for it to change past after. +func (t *trace) sessionLatest(ctx context.Context, session string, after int64, wait time.Duration) (int64, *Route) { + deadline := time.NewTimer(max(wait, 0)) + defer deadline.Stop() + for { + t.mu.Lock() + var seq int64 + var found *Route + for i := len(t.routes) - 1; i >= 0; i-- { + if r := t.routes[i]; r.Session == session { + c := *r + c.Order = append([]Weighed(nil), r.Order...) + c.Left = append([]Weighed(nil), r.Left...) + c.Tries = append([]Try{}, r.Tries...) + seq, found = r.Seq, &c + break + } + } + // after past the trace's count: the gateway started over since + if wait <= 0 || seq > after || t.seq < after { + t.mu.Unlock() + return seq, found + } + if t.wake == nil { + t.wake = make(chan struct{}) + } + wake := t.wake + t.mu.Unlock() + select { + case <-wake: + case <-deadline.C: + return seq, found + case <-ctx.Done(): + return seq, found + } + } +} diff --git a/internal/gateway/session_route_test.go b/internal/gateway/session_route_test.go new file mode 100644 index 000000000..ce08069e0 --- /dev/null +++ b/internal/gateway/session_route_test.go @@ -0,0 +1,143 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// GET /v1/magpie/route tells an agent's UI where its session's turn went +// while it is under way (#405): the member routing put first, the effort it +// was sent at, and each fallback as it happens — before the reply's first +// token, not after. Only the session asked for is told, and only to this +// machine or one with the shared gateway's key. +func TestSessionRoute(t *testing.T) { + fresh(t) + t.Setenv("MAGPIE_ADDR", "") + limited := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusTooManyRequests) + io.WriteString(w, `{"error":{"message":"rate limited"}}`) + })) + t.Cleanup(limited.Close) + asked, release := make(chan struct{}, 1), make(chan struct{}) + slow := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + asked <- struct{}{} + <-release + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"id":"ok","model":"m","choices":[{"message":{"role":"assistant","content":"hi"}}]}`) + })) + t.Cleanup(slow.Close) + var once sync.Once + let := func() { once.Do(func() { close(release) }) } + t.Cleanup(let) // before slow.Close, cleanups running last first + for _, p := range []provider.Provider{ + {ID: "ra", Name: "RA", Key: "k", Models: []string{"m"}, Chat: limited.URL + "/v1"}, + {ID: "rb", Name: "RB", Key: "k", Models: []string{"m"}, Chat: slow.URL + "/v1"}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + if err := provider.SaveGroup(provider.Group{Name: "R", Members: []string{"ra/m", "rb/m"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + s := New() + h := lanGuard(s.Handler()) + get := func(from, target string, hdr ...string) (int, map[string]any) { + t.Helper() + r := httptest.NewRequest("GET", target, nil) + r.RemoteAddr = from + for i := 0; i+1 < len(hdr); i += 2 { + r.Header.Set(hdr[i], hdr[i+1]) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + var out map[string]any + json.Unmarshal(w.Body.Bytes(), &out) + return w.Code, out + } + const here = "127.0.0.1:5000" + + done := make(chan int, 1) + go func() { + r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"group/r","reasoning_effort":"high","messages":[{"role":"user","content":"hi"}]}`)) + r.RemoteAddr = here + r.Header.Set(SessionHeader, "pi-1") + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + done <- w.Code + }() + select { + case <-asked: + case <-time.After(5 * time.Second): + t.Fatal("the second member was never asked") + } + + // under way: the first member failed over to the second, which has + // not answered yet + code, out := get(here, "/v1/magpie/route", SessionHeader, "pi-1") + if code != 200 || out["session"] != "pi-1" { + t.Fatalf("in flight: %d %v", code, out) + } + rt, _ := out["route"].(map[string]any) + if rt == nil || rt["done"] != false || rt["asked"] != "group/r" || rt["group"] != "r" || rt["model"] != "rb/m" || rt["effort"] != "high" { + t.Fatalf("in flight route: %v", out) + } + tries, _ := rt["tries"].([]any) + if len(tries) != 2 { + t.Fatalf("tries: %v", rt["tries"]) + } + first, second := tries[0].(map[string]any), tries[1].(map[string]any) + if first["model"] != "ra/m" || first["status"] != float64(429) || first["fail"] == nil || second["model"] != "rb/m" || second["done"] != false { + t.Fatalf("tries: %v", tries) + } + seq := int64(out["seq"].(float64)) + + // a long poll hears the turn end + polled := make(chan map[string]any, 1) + go func() { + _, o := get(here, "/v1/magpie/route?session=pi-1&wait=5&after="+strconv.FormatInt(seq, 10)) + polled <- o + }() + time.Sleep(50 * time.Millisecond) + let() + if c := <-done; c != 200 { + t.Fatal("the turn got", c) + } + o := <-polled + if rt, _ := o["route"].(map[string]any); rt == nil || rt["done"] != true || rt["status"] != float64(200) || rt["model"] != "rb/m" { + t.Fatalf("polled: %v", o) + } + + // another session hears nothing of this one + if code, out := get(here, "/v1/magpie/route?session=other"); code != 200 || out["route"] != nil { + t.Fatalf("other session: %d %v", code, out) + } + if code, _ := get(here, "/v1/magpie/route"); code != http.StatusBadRequest { + t.Fatal("no session got", code) + } + // another machine needs the shared gateway's key, as the quotas do + key, none := "sk-magpie-k", "" + t.Cleanup(func() { lanKey.Store(&none) }) + lanKey.Store(&key) + if code, _ := get("192.168.1.9:5000", "/v1/magpie/route?session=pi-1"); code != http.StatusUnauthorized { + t.Fatal("no key got", code) + } + if code, out := get("192.168.1.9:5000", "/v1/magpie/route?session=pi-1", "Authorization", "Bearer "+key); code != 200 || out["route"] == nil { + t.Fatalf("with the key: %d %v", code, out) + } + lanKey.Store(&none) + t.Setenv("MAGPIE_ADDR", "0.0.0.0:3425") + if code, _ := get("192.168.1.9:5000", "/v1/magpie/route?session=pi-1"); code != http.StatusForbidden { + t.Fatal("MAGPIE_ADDR, not shared, got", code) + } +} diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index a09f59aa8..f034a5cca 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -27,6 +27,7 @@ type Route struct { ID int64 `json:"id"` Time time.Time `json:"time"` Agent string `json:"agent"` + Session string `json:"-"` // the session it named (sessionOf), for GET /v1/magpie/route alone Kind string `json:"kind,omitempty"` // what the call is for, as Call's For *CallFor `json:"for,omitempty"` // the request it was made for, as Call's Model string `json:"model"` // as the agent asked