fatcutegg's patch (fatcutegg/magpie 40ceb22df). The routing trace is held
by the process that serves the gateway. A second magpie on this computer
(`magpie web`, or the app while a launchd `magpie serve` holds the port)
showed none of it. Now its console reads the serving magpie's
GET /v1/magpie/trace (and /v1/magpie/concurrency for the lanes) over
loopback, and plays that trace as its own. The heading names which magpie
is routing ("serve (pid N) is routing").
Reviewed as a community change. A trace names accounts and emails, session
ids, a folder's last two parts and error text. It holds no prompt text and
no key. The endpoint answers local(r) alone: a request from another address
gets 403, and so does a loopback request carrying a proxy or Tailscale
header, or a LAN request while the gateway is shared, whatever key it holds.
lanGuard and corsGuard stop rebinding Hosts, Origin: null and *.localhost
first, as on every route.
Changed on top of the patch:
- A gateway key held to a budget, models or accounts is refused with
KeyHeldCode (refuseHeld), as concurrency and quotas refuse it.
- The console reads loopback alone (ownerURL). A non-loopback MAGPIE_ADDR is
never asked, and 0.0.0.0, :port, [::] and localhost are read at
127.0.0.1.
- OwnerTrace lets a hung magpie go at wait+5s (was +20s). OwnerLanes waits
700ms like ServedBy (was 2s) and is asked only when a magpie answers.
- `/` tells pid and serves to a loopback request alone. A plain `magpie`
that opens the TUI reports itself as "tui".
- Takeover: in the real two-instance run, after B took the gateway over the
hub still read "serve (pid A) is routing", from the providers state. Now
the trace carries `by` (pid, serves), and the page names the router from
it. When `by` changes, the page drops its routes and reads the new
magpie's whole trace, so route ids from two magpies never mix. The
label's full text is in its title, because the node cuts it with an
ellipsis.
- Trace's doc comment, which the patch had orphaned, is back on it. Docs
(gateway-routing.md, gui-shell.md) say all of the above. Issue
references are #2606 (were #110).
- Tests: a proxy-header subtest, TestOwnerReadOnLoopbackAlone, the trace
added to TestHeldKeyToldNoAccounts, and `by` / pid / serves asserted in
both packages' peer tests.
Run:
- Each guarantee broken by hand, and its test went red: refuseHeld removed,
ownerURL returning MAGPIE_ADDR, local(r) replaced by a RemoteAddr check,
pid/serves dropped from the answer, `by` dropped in OwnerTrace, and the
console's OwnerTrace fallback turned off.
- A real sandbox (own HOME, ports 3591-3593, fake upstream on 3564):
- A `magpie serve`, B `magpie web`. B's Routing page played A's routes
live (the long poll counted 3 requests through A).
- Probes of A's /v1/magpie/trace. 200 from plain loopback. 403 for
evil Origin, Origin: null, evil.localhost, a rebound Host with and
without Origin, x.localhost Host, X-Forwarded-For and
Tailscale-User-Login.
- A LAN-shared instance answered 403 from 10.0.0.111 even with a valid
key, and gave no pid on `/`.
- Killed A: B took over in ~11s. The hub dropped the "is routing" label,
and the next request through B showed as a fresh trace (1 request).
- Chromium and WebKit screenshots at 1280 and 390 wide, in en, zh and ja.
No horizontal scroll.
- gofmt -l clean. go vet darwin, GOOS=linux -tags nogui and GOOS=windows
pass, and all three builds pass.
- go test -timeout 45m ./... at this tree (sandbox HOME, load 250-400):
every package ok except four.
- agent, gateway and library hit 45m in TestClaudeTierPickedAsTheMainModelStays,
TestQueuedStreamKeptAliveOnceSentToItsVendor and TestWellKnownKitGrouped.
- plugin failed TestGatewayHookMixedPiPackage (#2865).
- Rerun alone with -p 1: plugin ok (464s). gateway finished in 45m with
one red, TestRequestBuildsProvidersOnce, a 900ms/1s timing window under
load. It is 8/8 green alone here and on origin/main f73378365. Filed as
#2965.
- agent ok (2162s) and library ok (377s), each run alone.
- GUI suite, whole, Chromium (playwright 1.62.0, 8 at a time, load
~300): 5608 of 5661 pass. The 15 red files were run alone at this tree
and at origin/main f73378365. The fails are the same set, give or take
load (136 of 162 pass here, 137 of 162 on main), and each already has
an issue: routing-bodies #2559, segs-glide #2683, lightweight #2638,
codex-predictions #2624, routing-model-rest #2115, routing-keys-fold
#1612/#2658, quota-count-wrap #2228/#2399, sidebar-overlay-scrollbar
#1863. routing-keys-fold's live fold test, which plays a live trace, is
3 of 3 green alone both here and on main.
- WebKit: the whole pass was cut short at ~1576 tests by load (nothing
routing-related red in it). The 9 files that drive the hub or the live
trace (routing-js, routing-keys-fold, routing-group-fold,
routing-held-dot, routing-held-member, routing-answered-still,
routing-weight-chip, routing-mode-goes, claude-subagent-tag) are 108 of
108 in WebKit here.
Co-authored-by: fatcutegg <29221285+fatcutegg@users.noreply.github.com>
314 lines
10 KiB
Go
314 lines
10 KiB
Go
package gui
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/url"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/gateway"
|
|
"github.com/yetone/magpie/internal/sessions"
|
|
"github.com/yetone/magpie/internal/usage"
|
|
)
|
|
|
|
// traceJSON is the gateway's routing trace since the page last asked.
|
|
type traceJSON struct {
|
|
gateway.TraceState
|
|
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"`
|
|
}
|
|
|
|
type routeJSON struct {
|
|
gateway.Route
|
|
SessionTitle string `json:"sessionTitle,omitempty"`
|
|
Cost float64 `json:"cost"`
|
|
Priced bool `json:"priced"`
|
|
Unpriced int `json:"unpriced"`
|
|
}
|
|
|
|
// Name polling reuses the history evidence already loaded by this view. Never
|
|
// reread a day's routing log every 15 seconds just to notice a title write.
|
|
var titleHistory struct {
|
|
sync.Mutex
|
|
days map[string][]gateway.Route
|
|
}
|
|
|
|
func rememberTitleHistory(day string, rows []gateway.Route) {
|
|
if day == "" {
|
|
return
|
|
}
|
|
evidence := make([]gateway.Route, 0, len(rows))
|
|
for _, r := range rows {
|
|
if r.Agent != "codex" || (r.TitleLink == nil && r.ParentSession == "") {
|
|
continue
|
|
}
|
|
failed := ""
|
|
if r.Error != "" {
|
|
failed = "failed"
|
|
}
|
|
evidence = append(evidence, gateway.Route{ID: r.ID, Agent: r.Agent, Session: r.Session,
|
|
ParentSession: r.ParentSession, Kind: r.Kind, Time: r.Time, Millis: r.Millis,
|
|
Done: r.Done, Status: r.Status, Error: failed, TitleLink: r.TitleLink})
|
|
}
|
|
titleHistory.Lock()
|
|
defer titleHistory.Unlock()
|
|
if titleHistory.days == nil {
|
|
titleHistory.days = map[string][]gateway.Route{}
|
|
}
|
|
if _, exists := titleHistory.days[day]; !exists && len(titleHistory.days) >= 4 {
|
|
for key := range titleHistory.days {
|
|
delete(titleHistory.days, key)
|
|
break
|
|
}
|
|
}
|
|
titleHistory.days[day] = evidence
|
|
}
|
|
|
|
func recalledTitleHistory(day string) []gateway.Route {
|
|
titleHistory.Lock()
|
|
defer titleHistory.Unlock()
|
|
return titleHistory.days[day] // immutable after publication
|
|
}
|
|
|
|
func pricedRoutes(routes []gateway.Route) []routeJSON {
|
|
gw := served.Load()
|
|
if gw == nil {
|
|
gw = &gateway.Server{}
|
|
}
|
|
routes = gw.ResolveTitleParents(routes)
|
|
out := make([]routeJSON, 0, len(routes))
|
|
priceOf := usage.NewPricer()
|
|
ids := make([]string, 0, len(routes))
|
|
for _, r := range routes {
|
|
if r.Agent == "codex" {
|
|
id := r.Session
|
|
if r.ParentSession != "" {
|
|
id = r.ParentSession
|
|
}
|
|
ids = append(ids, id)
|
|
}
|
|
}
|
|
titles := sessions.CodexTitles(ids)
|
|
for _, r := range routes {
|
|
recs := make([]usage.Record, len(r.Usage))
|
|
for i, u := range r.Usage {
|
|
recs[i] = u.PricingRecord()
|
|
}
|
|
sum := priceOf(recs)
|
|
// Old history and calls without token counts stay unknown, not free.
|
|
priced := sum.Calls > sum.Unpriced && sum.Input+sum.Output > 0
|
|
name := ""
|
|
if r.Agent == "codex" {
|
|
id := r.Session
|
|
if r.ParentSession != "" {
|
|
id = r.ParentSession
|
|
}
|
|
name = titles[id]
|
|
}
|
|
out = append(out, routeJSON{Route: r, SessionTitle: name, Cost: sum.Cost, Priced: priced, Unpriced: sum.Unpriced})
|
|
}
|
|
return out
|
|
}
|
|
|
|
// mainView is the tab the window is asked to open on, as the page's view
|
|
// parameter: the Routing page on one request (req, its id) when the tray
|
|
// panel's Routing tab asks for it, or the Usage page's Requests on one
|
|
// provider or agent when its Usage tab does, its Overview (the allowances)
|
|
// when a menu-bar cell's click does. Anything but an id, or a name of the
|
|
// kind a provider or an agent has, is dropped.
|
|
func mainView(q url.Values) string {
|
|
view := q.Get("view")
|
|
switch view {
|
|
case "routing":
|
|
if id, err := strconv.ParseInt(q.Get("req"), 10, 64); err == nil && id > 0 {
|
|
view += "&req=" + strconv.FormatInt(id, 10)
|
|
}
|
|
case "usage":
|
|
if tab := q.Get("tab"); tab == "requests" || tab == "usage" {
|
|
view += "&tab=" + tab
|
|
}
|
|
if card := q.Get("card"); q.Get("tab") == "usage" && card != "" {
|
|
view += "&card=" + url.QueryEscape(card)
|
|
}
|
|
for _, k := range []string{"provider", "agent"} {
|
|
if v := q.Get(k); mainName.MatchString(v) {
|
|
view += "&" + k + "=" + url.QueryEscape(v)
|
|
}
|
|
}
|
|
}
|
|
// the panel's picker making a routing group of a model kept for groups
|
|
// and in none: the window opens on a new group of it
|
|
if m := q.Get("newgroup"); view == "routing" && m != "" {
|
|
view += "&newgroup=" + url.QueryEscape(m)
|
|
}
|
|
return view
|
|
}
|
|
|
|
// mainName is the id of a provider or an agent.
|
|
var mainName = regexp.MustCompile(`^[A-Za-z0-9._@:/ -]{1,80}$`)
|
|
|
|
// mainURL is the window's page for a view as mainView gives it, the
|
|
// request's id kept as its own parameter (the panel's link to one request,
|
|
// which escaping the whole of it lost).
|
|
func mainURL(view, query string) string { return "/?view=" + view + query }
|
|
|
|
// argView is a tab named on the command line (`magpie gui settings`, a
|
|
// restart to update) as ShowMain takes it: a name, never parameters.
|
|
func argView(s string) string { return url.QueryEscape(s) }
|
|
|
|
// quotaView opens the Usage overview at a provider/account card, or at
|
|
// the period of one of magpie's own totals (trayTotal). Invalid provider
|
|
// names fall back to the overview without a target.
|
|
func quotaView(id string) string {
|
|
view := "usage&tab=usage"
|
|
if p, ok := trayTotalPeriod(id); ok {
|
|
// magpie's own total: the Requests tab at its period, which sums
|
|
// what the total does (trayTotalSum)
|
|
return "usage&tab=requests&period=" + string(p)
|
|
}
|
|
provider, _, hasAccount := strings.Cut(id, "|")
|
|
if mainName.MatchString(provider) {
|
|
view += "&provider=" + url.QueryEscape(provider)
|
|
if hasAccount {
|
|
view += "&card=" + url.QueryEscape(id)
|
|
}
|
|
}
|
|
return view
|
|
}
|
|
|
|
// traceRoutes serves the routing trace for the Gateway view to play: it
|
|
// waits up to 25 s for something to change after the seq it is given, so
|
|
// the page hears of a request as it happens.
|
|
func traceRoutes(mux *http.ServeMux) {
|
|
// Names can arrive or change after a route finishes, independently of the
|
|
// trace sequence. Read only the IDs the page currently lists.
|
|
mux.HandleFunc("POST /api/gateway/session-titles", func(rw http.ResponseWriter, r *http.Request) {
|
|
var in struct {
|
|
IDs []string `json:"ids"`
|
|
Groups bool `json:"groups"`
|
|
RouteIDs []int64 `json:"routeIds"`
|
|
Day string `json:"day"`
|
|
// Sessions are other agents' sessions as agent:id, named
|
|
// from their own files (sessions.Titles) rather than Codex's
|
|
// index (#1293)
|
|
Sessions []string `json:"sessions"`
|
|
}
|
|
r.Body = http.MaxBytesReader(rw, r.Body, 256<<10)
|
|
if json.NewDecoder(r.Body).Decode(&in) != nil || len(in.IDs) > 2000 || len(in.RouteIDs) > 2000 || len(in.Sessions) > 2000 {
|
|
http.Error(rw, "invalid session IDs", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if len(in.Sessions) > 0 && len(in.IDs) == 0 {
|
|
writeJSON(rw, map[string]any{"titles": sessions.Titles(in.Sessions)})
|
|
return
|
|
}
|
|
if !in.Groups {
|
|
writeJSON(rw, sessions.CodexTitles(in.IDs))
|
|
return
|
|
}
|
|
var rows []gateway.Route
|
|
gw := served.Load()
|
|
if in.Day != "" {
|
|
if _, err := time.Parse("2006-01-02", in.Day); err != nil {
|
|
http.Error(rw, "invalid route day", http.StatusBadRequest)
|
|
return
|
|
}
|
|
rows = recalledTitleHistory(in.Day)
|
|
} else if gw != nil {
|
|
rows = gw.Trace(r.Context(), 0, 0).Routes
|
|
}
|
|
if gw == nil {
|
|
gw = &gateway.Server{}
|
|
}
|
|
rows = gw.ResolveTitleParents(rows)
|
|
wanted := make(map[int64]bool, len(in.RouteIDs))
|
|
for _, id := range in.RouteIDs {
|
|
wanted[id] = true
|
|
}
|
|
parents := map[int64]string{}
|
|
matched := map[int64]bool{}
|
|
for _, row := range rows {
|
|
if !wanted[row.ID] || row.Agent != "codex" {
|
|
continue
|
|
}
|
|
parents[row.ID], matched[row.ID] = row.ParentSession, row.ParentMatched
|
|
if row.ParentSession != "" {
|
|
in.IDs = append(in.IDs, row.ParentSession)
|
|
}
|
|
}
|
|
writeJSON(rw, map[string]any{"names": sessions.CodexTitles(in.IDs), "parents": parents, "matched": matched,
|
|
"resetInferred": in.Day != "" && rows == nil})
|
|
})
|
|
mux.HandleFunc("GET /api/gateway/route", func(rw http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.ParseInt(r.URL.Query().Get("id"), 10, 64)
|
|
if err != nil || id <= 0 {
|
|
http.Error(rw, "invalid route id", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if gw := served.Load(); gw != nil {
|
|
for _, route := range gw.Trace(r.Context(), 0, 0).Routes {
|
|
if route.ID == id {
|
|
writeJSON(rw, pricedRoutes([]gateway.Route{route})[0])
|
|
return
|
|
}
|
|
}
|
|
}
|
|
day, err := time.Parse("2006-01-02", r.URL.Query().Get("day"))
|
|
if err != nil {
|
|
http.Error(rw, "invalid route day", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if route, ok := gateway.HistoryRoute(id, day); ok {
|
|
writeJSON(rw, pricedRoutes([]gateway.Route{route})[0])
|
|
return
|
|
}
|
|
http.Error(rw, "route history is no longer available", http.StatusNotFound)
|
|
})
|
|
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 {
|
|
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)
|
|
writeJSON(rw, out)
|
|
})
|
|
// the routes of a day gone by, from the history the gateway keeps on
|
|
// disk — read whichever magpie serves the gateway
|
|
mux.HandleFunc("GET /api/gateway/history", func(rw http.ResponseWriter, r *http.Request) {
|
|
day := r.URL.Query().Get("day")
|
|
days, routes, cut := gateway.History(day)
|
|
rememberTitleHistory(day, routes)
|
|
writeJSON(rw, map[string]any{"days": days, "routes": pricedRoutes(routes), "cut": cut})
|
|
})
|
|
// an account's rest lifted by hand: verified with its vendor, say
|
|
mux.HandleFunc("POST /api/gateway/unrest", func(rw http.ResponseWriter, r *http.Request) {
|
|
var in struct {
|
|
Key string `json:"key"`
|
|
}
|
|
gw := served.Load()
|
|
if json.NewDecoder(r.Body).Decode(&in) != nil || in.Key == "" || gw == nil {
|
|
http.Error(rw, "nothing to lift", http.StatusBadRequest)
|
|
return
|
|
}
|
|
writeJSON(rw, map[string]bool{"lifted": gw.Unrest(in.Key)})
|
|
})
|
|
}
|