Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

gateway, gui: a console shows the routing of the magpie that serves the gateway (#2606, fatcutegg)

!am9a09eef655acb40b2
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index 01090d794..a68498097 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -178,6 +178,28 @@ recorded as a prediction failure (`noPrediction`).
## Remote magpie APIs
+`GET /v1/magpie/trace` answers the routing this gateway has decided, for a
+magpie on the same computer that does not serve it, whose console plays it as
+its own Routing page (#2606). A trace names accounts and their emails, what
+they served, session ids, a folder's last two parts and why accounts rest; it
+holds no prompt text and no key. So it answers `local(r)` alone: a request
+from another address is refused 403, and so is one from loopback that carries
+a proxy's forwarding header (a tunnel or Tailscale Serve here), or a LAN
+request while the gateway is shared, whatever key it holds. Rebinding,
+`Origin: null` and `*.localhost` pages are stopped before it by `lanGuard` and
+`corsGuard`, as on every route. A gateway key held to a budget, models or
+accounts is refused with `KeyHeldCode`, as `/v1/magpie/concurrency` and
+`/v1/magpie/quotas` refuse it. It answers what `Server.Trace` holds, plus
+this process's `pid` and `serves` (the command that started it, `Serves`), so
+a caller long-polls it with `after` and `wait` the way the page's own
+`/api/gateway/trace` does. `/` adds `pid` and `serves` too, to a loopback
+request alone. `Server.gatewayTrace` in
+[`trace.go`](../../internal/gateway/trace.go), and
+`TestGatewayTraceIsLoopbackOnly` in
+[`trace_peer_test.go`](../../internal/gateway/trace_peer_test.go) and
+`TestHeldKeyToldNoAccounts` in
+[`quotas_held_key_test.go`](../../internal/gateway/quotas_held_key_test.go).
+
A remote provider serves the conversation, token-counting, System One,
embeddings, rerank, speech-to-text, image generation/edit and video
creation/status/content APIs. Gemini clients enter through the local Gemini adapter and follow the
diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md
index 7039c52d1..563b7412e 100644
--- a/docs/subsystems/gui-shell.md
+++ b/docs/subsystems/gui-shell.md
@@ -397,6 +397,38 @@ leaving suggested plugin cards in place so a click begun before the answer still
opens the intended plugin. `plugin-market.test.cjs` holds the search response
between pointerdown and pointerup to check this in Chromium and WebKit.
+### Routing shown by the magpie that serves the gateway
+
+A magpie on this computer that does not serve the gateway shows the serving
+one's routing in its Routing page, instead of the notice that its routing
+cannot be watched here (#2606). The trigger is `served.Load()` being nil while
+a magpie answers at the gateway's address. Then `/api/gateway/trace` reads
+the serving magpie's `GET /v1/magpie/trace` over loopback
+([`OwnerTrace`](../../internal/gateway/trace.go)) and answers with it as its
+own (`mine` true, so the page plays it), and `/api/lanes` reads
+`GET /v1/magpie/concurrency` ([`OwnerLanes`](../../internal/gateway/trace.go))
+so a provider's rows show the same pills. Both are read on loopback alone
+(`ownerURL`): a gateway address on another interface or host is never asked,
+whatever `MAGPIE_ADDR` says, and one listening everywhere is read at
+127.0.0.1. `OwnerTrace` lets a hung magpie go 5s past the 25s long poll, or
+when the page stops asking; `OwnerLanes` waits 700ms, as `ServedBy` does, and
+is asked only when a magpie answers. The state read carries the serving
+magpie's `serves` and `pid` ([`gatewayJSON`](../../internal/gui/providers.go)),
+and the trace carries them as `by`. The Routing page's heading names the
+magpie from `by` ("serve (pid 49217) is routing · 127.0.0.1:3525"), so the
+name goes with the trace: when the page's trace comes from another magpie
+than before (a takeover, either way), it drops the routes it had and reads
+the new one's whole trace. Nothing is written; serving and takeover are
+unchanged. A
+magpie that serves the gateway keeps its own trace, and one older than the
+endpoint keeps the notice as before (a refused or unreadable read is unknown,
+never empty: `OwnerTrace` says so with its second result). See
+`TestConsoleShowsTheServingMagpiesRouting` and
+`TestConsoleKeepsTheNoticeFromAnOlderGateway` in
+[`trace_peer_test.go`](../../internal/gui/trace_peer_test.go), and
+`TestGatewayTraceIsLoopbackOnly` in
+[`trace_peer_test.go`](../../internal/gateway/trace_peer_test.go).
+
## Verification
The session readers include Cursor CLI chat stores, Cursor editor project
diff --git a/internal/cli/main.go b/internal/cli/main.go
index 7a06ebb50..72ed5448f 100644
--- a/internal/cli/main.go
+++ b/internal/cli/main.go
@@ -292,6 +292,7 @@ func run(args []string) error {
if hasGUI {
return runGUI(true, "")
}
+ gateway.Serves = "tui"
return runTUI()
}
// a magpie:// link the system handed over (Windows, Linux): the app
@@ -302,6 +303,14 @@ func run(args []string) error {
}
return runGUI(false, args[0])
}
+ // how this process was started, for the Routing page of another magpie on
+ // this computer to name the one that serves the gateway (#2606)
+ switch args[0] {
+ case "tui", "web", "serve", "tray":
+ gateway.Serves = args[0]
+ case "app", "gui", "panel", "-Embedding":
+ gateway.Serves = "app"
+ }
switch args[0] {
case "tui":
return runTUI()
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index 95b5961d0..8f950d314 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -242,6 +242,11 @@ func URL() string {
// not magpie serve, which has none. Set by the gui.
var Window bool
+// Serves says how this process was started (app, tray, web, serve or tui):
+// the Routing page of another magpie on this computer, which shows this
+// one's routing, names it (#2606). Set by the cli.
+var Serves = "app"
+
// Running reports whether a gateway answers at the address.
func Running() bool {
running, _ := Serving()
@@ -262,6 +267,8 @@ type Served struct {
Running bool // a magpie gateway answers
Window bool // its routing can be watched in its window (#110)
Version string // its version; "" from one that doesn't say
+ Pid int // its process id; 0 from one that doesn't say
+ Serves string // how it was started: app, tray, web, serve or tui; "" from one that doesn't say
}
// ServedBy asks the address which magpie answers there. Another magpie can
@@ -282,11 +289,13 @@ func ServedBy() Served {
Name string `json:"name"`
Version string `json:"version"`
Window bool `json:"window"`
+ Pid int `json:"pid"`
+ Serves string `json:"serves"`
}
if decodeJSON(b, &info) != nil || info.Name != "magpie" {
return Served{Running: bytes.Contains(b, []byte(`"magpie"`)), Window: bytes.Contains(b, []byte(`"window":true`))}
}
- return Served{Running: true, Window: info.Window, Version: info.Version}
+ return Served{Running: true, Window: info.Window, Version: info.Version, Pid: info.Pid, Serves: info.Serves}
}
// Taken reports whether anything accepts connections at the gateway's
@@ -641,6 +650,7 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("GET "+provider.RemoteCardsPath, s.quotaCards)
mux.HandleFunc("POST "+provider.RemoteRefreshPath, s.quotaCardsRefresh)
mux.HandleFunc("GET /v1/magpie/route", s.sessionRoute)
+ mux.HandleFunc("GET /v1/magpie/trace", s.gatewayTrace)
mux.HandleFunc("GET /v1/magpie/concurrency", s.concurrency)
mux.HandleFunc("GET /v1/magpie/limit", s.keyLimit)
// a heap profile of this process, for magpie heap (loopback only)
@@ -713,8 +723,14 @@ func responsesOverHTTP(w http.ResponseWriter, r *http.Request) {
}
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/embeddings", "/v1/rerank", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", SearchMCPPath, VisionMCPPath, ToolsMCPPath}})
+ out := 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/embeddings", "/v1/rerank", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", "/v1/magpie/trace", SearchMCPPath, VisionMCPPath, ToolsMCPPath}}
+ // which process serves, for another magpie on this computer to name it
+ // on its Routing page (#2606); not told to another machine
+ if local(r) {
+ out["pid"], out["serves"] = os.Getpid(), Serves
+ }
+ writeJSON(w, 200, out)
}
// quotas is what is left of every subscription, plan and key magpie has,
diff --git a/internal/gateway/quotas_held_key_test.go b/internal/gateway/quotas_held_key_test.go
index d09cd734b..82ea7923f 100644
--- a/internal/gateway/quotas_held_key_test.go
+++ b/internal/gateway/quotas_held_key_test.go
@@ -110,6 +110,14 @@ func TestHeldKeyToldNoAccounts(t *testing.T) {
if r := route(from, s, other); (i == 0) != (r != nil) {
t.Errorf("%s from %s: another key's session %s: %v", name, from, other, r)
}
+ // the whole trace (#2606), every key's routes: this computer
+ // alone, and never a held key, even from here
+ c, b := do("GET", "/v1/magpie/trace", from, s)
+ if want := i == 0 && from == "127.0.0.1:5000"; want != (c == 200) {
+ t.Errorf("%s from %s: the trace: %d %s", name, from, c, b)
+ } else if i > 0 && from == "127.0.0.1:5000" && !strings.Contains(b, provider.KeyHeldCode) {
+ t.Errorf("%s from %s: the trace refused without saying the key is held: %d %s", name, from, c, b)
+ }
}
}
}
diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go
index cee51083e..b3d695d6f 100644
--- a/internal/gateway/trace.go
+++ b/internal/gateway/trace.go
@@ -10,8 +10,13 @@ package gateway
import (
"context"
+ "io"
+ "net"
"net/http"
+ "net/url"
+ "os"
"slices"
+ "strconv"
"strings"
"sync"
"time"
@@ -480,6 +485,16 @@ type TraceState struct {
Seq int64 `json:"seq"`
Routes []Route `json:"routes"`
Totals Totals `json:"totals"`
+ // By is the magpie whose routing this is, when it is another magpie's
+ // (OwnerTrace): the console names it from here, so the name follows the
+ // trace when another magpie takes the gateway over (#2606)
+ By *TraceBy `json:"by,omitempty"`
+}
+
+// TraceBy names the magpie a trace was read from.
+type TraceBy struct {
+ Pid int `json:"pid"`
+ Serves string `json:"serves"`
}
func (t *trace) changed() {
@@ -637,6 +652,131 @@ func (t *trace) update(r *Route, f func(r *Route)) {
r.Seq = t.seq
}
+// gatewayTrace tells this gateway's routing to another magpie on the same
+// computer, which does not serve the gateway and so has no trace of its own
+// (#2606, fatcutegg: the trace is the serving process's, and a second magpie
+// showed none of it). Its console reads this to show the same Routing page.
+// This computer alone, and never to a held key: the trace names accounts,
+// what they served, folders and why accounts rest. A request through a proxy
+// or tunnel on this computer isn't local, nor is a LAN one while shared.
+func (s *Server) gatewayTrace(w http.ResponseWriter, r *http.Request) {
+ if !local(r) {
+ writeError(w, provider.Chat, http.StatusForbidden, "magpie's routing is told to this computer alone")
+ return
+ }
+ if refuseHeld(w, r, heldRefused) {
+ return
+ }
+ after, _ := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64)
+ var wait time.Duration
+ if r.URL.Query().Get("wait") != "" {
+ wait = 25 * time.Second
+ }
+ st := s.Trace(r.Context(), after, wait)
+ writeJSON(w, 200, map[string]any{"object": "trace", "now": time.Now(), "seq": st.Seq, "routes": st.Routes, "totals": st.Totals, "pid": os.Getpid(), "serves": Serves})
+}
+
+// ownerURL is the gateway's address on loopback, where the magpie serving
+// it is read by another magpie on this computer (OwnerTrace, OwnerLanes).
+// An address on another interface, or another host, gives "": the trace is
+// read from this computer alone, never from wherever MAGPIE_ADDR points.
+func ownerURL() string {
+ h, p, err := net.SplitHostPort(Addr())
+ if err != nil {
+ return ""
+ }
+ ip := net.ParseIP(strings.Trim(h, "[]"))
+ switch {
+ case h == "", strings.EqualFold(h, "localhost"), ip != nil && ip.IsUnspecified():
+ return "http://" + net.JoinHostPort("127.0.0.1", p)
+ case ip != nil && ip.IsLoopback():
+ return "http://" + net.JoinHostPort(ip.String(), p)
+ }
+ return ""
+}
+
+// OwnerTrace reads the routing the magpie serving the gateway's address has
+// decided, for a magpie on this computer that doesn't serve it: its console
+// reads this and shows the same Routing page (#2606: the trace is the
+// serving process's alone, so a second magpie showed none of it). ok is
+// false when nothing answers there, or a magpie too old to tell its trace,
+// or one that refuses: unknown, never an empty trace.
+func OwnerTrace(ctx context.Context, after int64, wait time.Duration) (TraceState, bool) {
+ base := ownerURL()
+ if base == "" {
+ return TraceState{}, false
+ }
+ q := url.Values{}
+ if after > 0 {
+ q.Set("after", strconv.FormatInt(after, 10))
+ }
+ if wait > 0 {
+ q.Set("wait", "1")
+ }
+ // the serving magpie holds a long poll up to 25s; a hung one is let go
+ // a few seconds past that, and at once when the page stops asking
+ c := &http.Client{Timeout: wait + 5*time.Second}
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/v1/magpie/trace?"+q.Encode(), nil)
+ if err != nil {
+ return TraceState{}, false
+ }
+ res, err := c.Do(req)
+ if err != nil {
+ return TraceState{}, false
+ }
+ defer res.Body.Close()
+ if res.StatusCode != http.StatusOK {
+ return TraceState{}, false
+ }
+ b, err := io.ReadAll(io.LimitReader(res.Body, 8<<20))
+ if err != nil {
+ return TraceState{}, false
+ }
+ var out struct {
+ Object string `json:"object"`
+ Seq int64 `json:"seq"`
+ Routes []Route `json:"routes"`
+ Totals Totals `json:"totals"`
+ Pid int `json:"pid"`
+ Serves string `json:"serves"`
+ }
+ if decodeJSON(b, &out) != nil || out.Object != "trace" || out.Routes == nil {
+ return TraceState{}, false
+ }
+ return TraceState{Seq: out.Seq, Routes: out.Routes, Totals: out.Totals, By: &TraceBy{Pid: out.Pid, Serves: out.Serves}}, true
+}
+
+// OwnerLanes reads the lanes of the magpie serving the gateway's address, for
+// a console that doesn't serve it (the providers' rows show the same pills
+// wherever the gateway runs). ok is false when nothing answers there. It is
+// asked on every state read, so it waits no longer than ServedBy does.
+func OwnerLanes() (map[string]Lane, bool) {
+ base := ownerURL()
+ if base == "" {
+ return nil, false
+ }
+ c := &http.Client{Timeout: 700 * time.Millisecond}
+ res, err := c.Get(base + "/v1/magpie/concurrency")
+ if err != nil {
+ return nil, false
+ }
+ defer res.Body.Close()
+ if res.StatusCode != http.StatusOK {
+ return nil, false
+ }
+ b, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
+ if err != nil {
+ return nil, false
+ }
+ var out struct {
+ Data map[string]Lane `json:"data"`
+ }
+ if decodeJSON(b, &out) != nil || out.Data == nil {
+ return nil, false
+ }
+ return out.Data, true
+}
+
// Trace is the routes changed after seq, oldest first. With none, it waits
// up to wait for one.
func (s *Server) Trace(ctx context.Context, after int64, wait time.Duration) TraceState {
diff --git a/internal/gateway/trace_peer_test.go b/internal/gateway/trace_peer_test.go
new file mode 100644
index 000000000..4b9a71df6
--- /dev/null
+++ b/internal/gateway/trace_peer_test.go
@@ -0,0 +1,99 @@
+package gateway
+
+import (
+ "encoding/json"
+ "net/http/httptest"
+ "os"
+ "testing"
+)
+
+// The routing is this process's own, so a magpie on this computer that does
+// not serve the gateway reads it here to show the same Routing page (#2606).
+// It answers this computer alone: the trace names accounts and what they
+// served, and the magpie that reads it is on the same machine.
+func TestGatewayTraceIsLoopbackOnly(t *testing.T) {
+ h := New().Handler()
+
+ t.Run("this computer", func(t *testing.T) {
+ w := httptest.NewRecorder()
+ r := httptest.NewRequest("GET", "/v1/magpie/trace", nil)
+ r.RemoteAddr = "127.0.0.1:50123"
+ h.ServeHTTP(w, r)
+ if w.Code != 200 {
+ t.Fatalf("%d %s", w.Code, w.Body)
+ }
+ var got struct {
+ Object string `json:"object"`
+ Seq int64 `json:"seq"`
+ Routes []json.RawMessage `json:"routes"`
+ Pid int `json:"pid"`
+ Serves string `json:"serves"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
+ t.Fatal(err)
+ }
+ if got.Object != "trace" || got.Routes == nil {
+ t.Fatalf("object %q routes %v", got.Object, got.Routes)
+ }
+ // the console names the magpie routing from the trace it plays
+ if got.Pid != os.Getpid() || got.Serves != Serves {
+ t.Errorf("the trace doesn't name its magpie: pid %d serves %q", got.Pid, got.Serves)
+ }
+ })
+
+ // a proxy or tunnel on this computer (cloudflared, Tailscale serve)
+ // hands on someone else's request from loopback
+ t.Run("through a proxy here", func(t *testing.T) {
+ for _, hdr := range []string{"X-Forwarded-For", "Cf-Connecting-IP", "Tailscale-User-Login"} {
+ w := httptest.NewRecorder()
+ r := httptest.NewRequest("GET", "/v1/magpie/trace", nil)
+ r.RemoteAddr = "127.0.0.1:50123"
+ r.Header.Set(hdr, "203.0.113.7")
+ h.ServeHTTP(w, r)
+ if w.Code != 403 {
+ t.Fatalf("a request a proxy handed on (%s) reached the trace: %d %s", hdr, w.Code, w.Body)
+ }
+ }
+ })
+
+ t.Run("another machine", func(t *testing.T) {
+ w := httptest.NewRecorder()
+ r := httptest.NewRequest("GET", "/v1/magpie/trace", nil)
+ r.RemoteAddr = "192.168.0.9:50123"
+ h.ServeHTTP(w, r)
+ if w.Code != 403 {
+ t.Fatalf("another machine reached the trace: %d %s", w.Code, w.Body)
+ }
+ })
+}
+
+// Another magpie's trace is read from this computer alone (#2606): an
+// address on another interface or host is never asked, whatever
+// MAGPIE_ADDR says, and one listening everywhere is read on loopback.
+func TestOwnerReadOnLoopbackAlone(t *testing.T) {
+ for addr, want := range map[string]string{
+ "127.0.0.1:3561": "http://127.0.0.1:3561",
+ "0.0.0.0:3561": "http://127.0.0.1:3561",
+ ":3561": "http://127.0.0.1:3561",
+ "[::]:3561": "http://127.0.0.1:3561",
+ "localhost:3561": "http://127.0.0.1:3561",
+ "[::1]:3561": "http://[::1]:3561",
+ "127.0.0.2:3561": "http://127.0.0.2:3561",
+ "192.168.1.9:3561": "",
+ "10.0.0.5:3561": "",
+ "example.com:3561": "",
+ "magpie.tail:3561": "",
+ } {
+ t.Setenv("MAGPIE_ADDR", addr)
+ if got := ownerURL(); got != want {
+ t.Errorf("MAGPIE_ADDR %s: read at %q, want %q", addr, got, want)
+ }
+ }
+ t.Setenv("MAGPIE_ADDR", "192.0.2.1:3561")
+ if _, ok := OwnerTrace(t.Context(), 0, 0); ok {
+ t.Error("a trace read from another host")
+ }
+ if _, ok := OwnerLanes(); ok {
+ t.Error("lanes read from another host")
+ }
+}
diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js
index 307be3923..cdb5ef0d8 100644
--- a/internal/gui/assets/i18n.js
+++ b/internal/gui/assets/i18n.js
@@ -2236,6 +2236,7 @@ const I18N = {
// gateway
"running": "运行中",
"running · served by another magpie": "运行中 · 由另一个 magpie 提供",
+ "{serves} (pid {pid}) is routing": "{serves}(pid {pid})正在路由",
"running · served by magpie {v}, older than this one": "运行中 · 由更旧的 magpie {v} 提供",
"Agents' requests go through magpie {v} and are sent as it sends them, without this version's fixes. Quit it here and this one serves the gateway at once.": "Agent 的请求经 magpie {v} 发出,不含当前版本的修复。在这里关闭它,当前版本会立即接管网关。",
"Quit magpie {v} and take over": "关闭 magpie {v} 并接管网关",
@@ -5930,6 +5931,7 @@ const I18N = {
"no key is on for this endpoint": "這個位址沒有啟用的金鑰",
"running": "執行中",
"running · served by another magpie": "執行中 · 由另一個 magpie 提供",
+ "{serves} (pid {pid}) is routing": "{serves}(pid {pid})正在路由",
"running · served by magpie {v}, older than this one": "執行中 · 由更舊的 magpie {v} 提供",
"Agents' requests go through magpie {v} and are sent as it sends them, without this version's fixes. Quit it here and this one serves the gateway at once.": "Agent 的請求經 magpie {v} 發出,不含目前版本的修復。在這裡關閉它,目前版本會立即接管閘道。",
"Quit magpie {v} and take over": "關閉 magpie {v} 並接管閘道",
@@ -9645,6 +9647,7 @@ const I18N = {
"no key is on for this endpoint": "このエンドポイントで有効なキーがありません",
"running": "実行中",
"running · served by another magpie": "実行中 · 別の magpie が提供",
+ "{serves} (pid {pid}) is routing": "{serves}(pid {pid})がルーティング中",
"running · served by magpie {v}, older than this one": "実行中 · これより古い magpie {v} が提供",
"Agents' requests go through magpie {v} and are sent as it sends them, without this version's fixes. Quit it here and this one serves the gateway at once.": "エージェントのリクエストは magpie {v} を経由し、そのバージョンの方法で送られるため、このバージョンの修正が反映されません。ここで終了すると、すぐにこちらがゲートウェイを引き継ぎます。",
"Quit magpie {v} and take over": "magpie {v} を終了して引き継ぐ",
@@ -13370,6 +13373,7 @@ const I18N = {
"no key is on for this endpoint": "für diesen Endpunkt ist kein Schlüssel aktiv",
"running": "läuft",
"running · served by another magpie": "läuft · bereitgestellt von einem anderen magpie",
+ "{serves} (pid {pid}) is routing": "{serves} (pid {pid}) routet",
"running · served by magpie {v}, older than this one": "läuft · bereitgestellt von magpie {v}, älter als diese Version",
"Agents' requests go through magpie {v} and are sent as it sends them, without this version's fixes. Quit it here and this one serves the gateway at once.": "Anfragen der Agenten laufen über magpie {v} und werden so gesendet, wie es sie sendet – ohne die Korrekturen dieser Version. Beenden Sie es hier, dann übernimmt diese Version den Zugangspunkt sofort.",
"Quit magpie {v} and take over": "magpie {v} beenden und übernehmen",
diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js
index da334c7a3..82608dd9f 100644
--- a/internal/gui/assets/plugins/routing/client.js
+++ b/internal/gui/assets/plugins/routing/client.js
@@ -1057,7 +1057,7 @@ function routingPage(part) {
// ---------- state ----------
const routes = new Map(); // id → the latest of each route
- let seq = 0, mine = true, loaded = false, daysAt = 0;
+ let seq = 0, mine = true, loaded = false, daysAt = 0, by = null;
let traceTotals = { requests: 0, rerouted: 0, errors: 0 };
let offMsg = ""; // why the trace can't be watched here, when it can't
// the request the window was opened on (?req=), from the tray panel
@@ -3385,6 +3385,11 @@ function routingPage(part) {
noteAccounts(d);
skew = at(d.now) - Date.now();
mine = d.mine;
+ // another magpie took the gateway over (#2606): its routes and seq
+ // are its own, so the page starts again from its whole trace
+ const fromOther = loaded && (d.by?.pid || 0) !== (by?.pid || 0);
+ by = d.by || null;
+ if (fromOther) { routes.clear(); seq = 0; loaded = false; hubText(); continue; }
hubText();
traceTotals = d.totals || traceTotals;
if (!mine) {
@@ -3460,7 +3465,17 @@ function routingPage(part) {
}
}
- function hubText() { setText(hubSub, (providers?.gateway?.url || "").replace(/^https?:\/\//, "") || t("gateway")); }
+ function hubText() {
+ const g = providers?.gateway;
+ // which magpie is routing, when it isn't this one (#2606): this page plays
+ // that magpie's routing, and its window is the other place it shows. It
+ // is named by the trace the page plays, so it goes with a takeover at once
+ const who = mine && by?.serves
+ ? t("{serves} (pid {pid}) is routing", { serves: by.serves, pid: by.pid }) + " · "
+ : "";
+ setText(hubSub, who + ((g?.url || "").replace(/^https?:\/\//, "") || t("gateway")));
+ hubSub.title = who ? hubSub.textContent : ""; // whole, where the node cuts it short
+ }
// labels in the page's language, and again when it changes
function words() {
diff --git a/internal/gui/providers.go b/internal/gui/providers.go
index 93dbe096f..4e20ad723 100644
--- a/internal/gui/providers.go
+++ b/internal/gui/providers.go
@@ -434,10 +434,15 @@ type gatewayJSON struct {
// Version is another magpie's, serving it, and Older says it is older
// than this one: agents' requests are then sent as that version sends
// them, without this one's fixes (#506)
- Version string `json:"version,omitempty"`
- Older bool `json:"older,omitempty"`
- Models int `json:"models"`
- Calls []gateway.Call `json:"calls"`
+ Version string `json:"version,omitempty"`
+ Older bool `json:"older,omitempty"`
+ // Pid and Serves are the serving magpie's own: which process it is and
+ // how it was started, for the Routing page to name the one that is
+ // routing (#2606)
+ Pid int `json:"pid,omitempty"`
+ Serves string `json:"serves,omitempty"`
+ Models int `json:"models"`
+ Calls []gateway.Call `json:"calls"`
// Lanes are the keys and accounts with requests out or waiting under
// a limit on requests at once (#892), by provider#keyid or
// provider@account
@@ -936,6 +941,15 @@ func providersState() providersJSON {
o := gateway.ServedBy()
s.Gateway.Running, s.Gateway.Window, s.Gateway.Version = o.Running, o.Window, o.Version
s.Gateway.Older = o.Running && update.Newer(gateway.Version, o.Version)
+ // the process that is routing, for the Routing page to name it
+ // (#2606): another magpie on this computer, whose routing this
+ // console shows through OwnerTrace, and its lanes for the rows
+ s.Gateway.Pid, s.Gateway.Serves = o.Pid, o.Serves
+ if o.Running {
+ if l, ok := gateway.OwnerLanes(); ok {
+ s.Gateway.Lanes = l
+ }
+ }
}
s.Gateway.Archive = archiveState()
s.CodexDaemon = provider.CodexDaemonStale()
@@ -985,6 +999,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
lanes := map[string]gateway.Lane{}
if gw := served.Load(); gw != nil {
lanes = gw.Lanes()
+ } else if l, ok := gateway.OwnerLanes(); ok {
+ // another magpie on this computer serves the gateway: its lanes
+ // are the ones to show (the rows read the same wherever it runs)
+ lanes = l
}
writeJSON(rw, lanes)
})
diff --git a/internal/gui/trace.go b/internal/gui/trace.go
index 757604025..8ed061c60 100644
--- a/internal/gui/trace.go
+++ b/internal/gui/trace.go
@@ -18,7 +18,7 @@ import (
// traceJSON is the gateway's routing trace since the page last asked.
type traceJSON struct {
gateway.TraceState
- Mine bool `json:"mine"` // this magpie serves the gateway: another's trace isn't here
+ Mine bool `json:"mine"` // the trace here is live: this magpie serves the gateway, or this console reads the magpie that does (#2606)
Now time.Time `json:"now"`
Routes []routeJSON `json:"routes"`
}
@@ -272,13 +272,19 @@ func traceRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/gateway/trace", func(rw http.ResponseWriter, r *http.Request) {
gw := served.Load()
out := traceJSON{TraceState: gateway.TraceState{Routes: []gateway.Route{}}, Mine: gw != nil}
+ after, _ := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64)
+ var wait time.Duration
+ if r.URL.Query().Get("wait") != "" {
+ wait = 25 * time.Second
+ }
if gw != nil {
- after, _ := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64)
- var wait time.Duration
- if r.URL.Query().Get("wait") != "" {
- wait = 25 * time.Second
- }
out.TraceState = gw.Trace(r.Context(), after, wait)
+ } else if st, ok := gateway.OwnerTrace(r.Context(), after, wait); ok {
+ // another magpie on this computer serves the gateway: show the
+ // routing it decides here too, live, and let the page name the
+ // process that is routing (#2606)
+ out.TraceState = st
+ out.Mine = true
}
out.Now = time.Now()
out.Routes = pricedRoutes(out.TraceState.Routes)
diff --git a/internal/gui/trace_peer_test.go b/internal/gui/trace_peer_test.go
new file mode 100644
index 000000000..c23476c20
--- /dev/null
+++ b/internal/gui/trace_peer_test.go
@@ -0,0 +1,124 @@
+package gui
+
+import (
+ "encoding/json"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "testing"
+)
+
+// A magpie here that does not serve the gateway shows the routing of the one
+// that does (#2606), and names it: the console reads the serving magpie's
+// trace over loopback and plays it as its own, and its state carries how that
+// magpie was started and its pid.
+func TestConsoleShowsTheServingMagpiesRouting(t *testing.T) {
+ h := t.TempDir()
+ t.Setenv("HOME", h)
+ t.Setenv("USERPROFILE", h)
+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
+ t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
+ t.Setenv("XDG_DATA_HOME", filepath.Join(h, ".local", "share"))
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("MAGPIE_ADDR", ln.Addr().String())
+ other := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ switch r.URL.Path {
+ case "/":
+ w.Write([]byte(`{"name":"magpie","version":"0.1.1257","models":3,"window":true,"serves":"serve","pid":4321,"apis":[]}`))
+ case "/v1/magpie/trace":
+ w.Write([]byte(`{"object":"trace","seq":7,"pid":4321,"serves":"serve","routes":[{"id":1,"model":"ollama/gemma4:e4b","provider":"ollama","status":200}]}`))
+ default:
+ http.NotFound(w, r)
+ }
+ })}
+ go other.Serve(ln)
+ defer other.Close()
+ served.Store(nil)
+
+ mux := http.NewServeMux()
+ traceRoutes(mux)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/gateway/trace", nil))
+ if w.Code != 200 {
+ t.Fatalf("%d %s", w.Code, w.Body)
+ }
+ var got struct {
+ Mine bool `json:"mine"`
+ By *struct {
+ Pid int `json:"pid"`
+ Serves string `json:"serves"`
+ } `json:"by"`
+ Routes []struct {
+ Model string `json:"model"`
+ Status int `json:"status"`
+ } `json:"routes"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
+ t.Fatal(err)
+ }
+ if !got.Mine || len(got.Routes) != 1 || got.Routes[0].Model != "ollama/gemma4:e4b" || got.Routes[0].Status != 200 {
+ t.Fatalf("the serving magpie's routing was not shown: mine %v routes %+v", got.Mine, got.Routes)
+ }
+ // the trace names the magpie it came from, so the page's name for it
+ // changes with the trace when another magpie takes the gateway over
+ if got.By == nil || got.By.Pid != 4321 || got.By.Serves != "serve" {
+ t.Errorf("the trace doesn't name the magpie it came from: %+v", got.By)
+ }
+
+ // the state names it, for the page's heading to say which one is routing
+ g := providersState().Gateway
+ if !g.Running || g.Mine || g.Serves != "serve" || g.Pid != 4321 {
+ t.Errorf("state: running %v mine %v serves %q pid %d", g.Running, g.Mine, g.Serves, g.Pid)
+ }
+}
+
+// One that doesn't tell its trace (older than the endpoint, or a refusal) is
+// unknown, not empty: the page keeps the notice it had, and never plays
+// another magpie's routing as its own.
+func TestConsoleKeepsTheNoticeFromAnOlderGateway(t *testing.T) {
+ h := t.TempDir()
+ t.Setenv("HOME", h)
+ t.Setenv("USERPROFILE", h)
+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
+ t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
+ t.Setenv("XDG_DATA_HOME", filepath.Join(h, ".local", "share"))
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("MAGPIE_ADDR", ln.Addr().String())
+ other := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if r.URL.Path == "/" {
+ w.Write([]byte(`{"name":"magpie","version":"0.1.550","models":3,"window":true,"apis":[]}`))
+ return
+ }
+ http.NotFound(w, r)
+ })}
+ go other.Serve(ln)
+ defer other.Close()
+ served.Store(nil)
+
+ mux := http.NewServeMux()
+ traceRoutes(mux)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/gateway/trace", nil))
+ if w.Code != 200 {
+ t.Fatalf("%d %s", w.Code, w.Body)
+ }
+ var got struct {
+ Mine bool `json:"mine"`
+ Routes json.RawMessage `json:"routes"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
+ t.Fatal(err)
+ }
+ if got.Mine {
+ t.Fatalf("an older gateway's routing was played as this console's own: %s", w.Body)
+ }
+}