diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index 4927ab8cd..57c335283 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -55,6 +55,13 @@ func (c candidate) label() string { // OpenAI one for a GPT model, else the key that speaks what the agent // spoke, so nothing is translated that needn't be. func perKey(p provider.Provider, model string, from provider.Protocol) []candidate { + out, _ := perKeyOf(p, model, from) + return out +} + +// perKeyOf is perKey, and the accounts or keys it left out as not listing +// the model. +func perKeyOf(p provider.Provider, model string, from provider.Protocol) (out, left []candidate) { if p.Account != nil { all := []candidate{{p, model, p.ID}} for _, q := range p.AlsoOn() { @@ -62,19 +69,20 @@ func perKey(p provider.Provider, model string, from provider.Protocol) []candida } // an account whose plan lacks the model (a Free one behind a Plus) // would only answer 400; it is tried only when none lists it - var out []candidate for _, c := range all { if c.p.Account.Lists(model) { out = append(out, c) + } else { + left = append(left, c) } } if len(out) == 0 { - return all + return all, nil } - return out + return out, left } keys := p.KeysOn() - var out, unlisted []candidate + var unlisted []candidate for _, k := range keys { q := p.WithKey(k) if len(q.Speaks()) == 0 { @@ -92,13 +100,13 @@ func perKey(p provider.Provider, model string, from provider.Protocol) []candida out = append(out, candidate{q, model, rest}) } if len(out) == 0 { - out = unlisted // no key lists it: try them all the same + out, unlisted = unlisted, nil // no key lists it: try them all the same } if len(out) == 0 { - return []candidate{{p, model, p.ID}} + return []candidate{{p, model, p.ID}}, nil } sort.SliceStable(out, func(i, j int) bool { return keyFit(out[i].p, model, from) < keyFit(out[j].p, model, from) }) - return out + return out, unlisted } // keyFit ranks how well a key suits a request, best first: 0 fits, 1 needs @@ -145,7 +153,30 @@ func modelFamily(model string) provider.Protocol { // or accounts as its routing orders them, those resting after a recent // failure moved behind the rest. func (s *Server) candidates(p provider.Provider, model string, from provider.Protocol) []candidate { - out := route(p, perKey(p, model, from), model, from) + out, _ := s.plan(p, model, from) + return out +} + +// plan is candidates, and for the routing trace what each stood where it +// did by, and those left out. +func (s *Server) plan(p provider.Provider, model string, from provider.Protocol) ([]candidate, planned) { + var pl planned + add := func(q provider.Provider, m string, fallback bool) []candidate { + cs, left := perKeyOf(q, m, from) + cs, wg := weigh(q, cs, m, from) + for i, c := range cs { + w := weighed(c, q, wg, fallback, from) + w.Turn = i == 0 && q.Routing == provider.Rotate && len(cs) > 1 + pl.order = append(pl.order, w) + } + for _, c := range left { + w := weighed(c, q, weighing{}, fallback, from) + w.Unlisted = true + pl.left = append(pl.left, w) + } + return cs + } + out := add(p, model, false) seen := map[string]bool{p.ID + "/" + model: true} for _, id := range p.Fallback { fp, fm, ok := provider.Resolve(id) @@ -153,37 +184,50 @@ func (s *Server) candidates(p provider.Provider, model string, from provider.Pro continue } seen[fp.ID+"/"+fm] = true - out = append(out, route(fp, perKey(fp, fm, from), fm, from)...) + out = append(out, add(fp, fm, true)...) } if len(out) == 1 { - return out + if r, ok := restOf(out[0].rest); ok { + pl.order[0].Rest = &r // tried all the same: there is no other + } + return out, pl } var ready, resting []candidate - for _, c := range out { - if s.resting(c.rest) { - resting = append(resting, c) + var wReady, wResting []Weighed + for i, c := range out { + if r, ok := restOf(c.rest); ok { + pl.order[i].Rest = &r + resting, wResting = append(resting, c), append(wResting, pl.order[i]) } else { - ready = append(ready, c) + ready, wReady = append(ready, c), append(wReady, pl.order[i]) } } - return append(ready, resting...) + pl.order = append(wReady, wResting...) + return append(ready, resting...), pl } var restingUntil = struct { sync.Mutex - m map[string]time.Time -}{m: map[string]time.Time{}} + m map[string]time.Time + note map[string]Rest // why each rests +}{m: map[string]time.Time{}, note: map[string]Rest{}} func (s *Server) resting(id string) bool { - restingUntil.Lock() - defer restingUntil.Unlock() - return time.Now().Before(restingUntil.m[id]) + _, ok := restOf(id) + return ok } -func (s *Server) rest(id string) { +// restOf is why a candidate is resting, while it is. +func restOf(id string) (Rest, bool) { restingUntil.Lock() - restingUntil.m[id] = time.Now().Add(fallbackCooldown) - restingUntil.Unlock() + defer restingUntil.Unlock() + until := restingUntil.m[id] + if !time.Now().Before(until) { + return Rest{}, false + } + r := restingUntil.note[id] + r.Until = until + return r, true } // quotaWords are how vendors say "out of quota" or "slow down" when their diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 8cea8a7d8..fce825250 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -85,6 +85,7 @@ type Server struct { responseOnly map[string]bool subscription *subscriptionBridge debug bool + trace trace // what routing did with each request, for the Gateway view } // New makes a gateway. @@ -363,15 +364,21 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } // the primary, then its fallbacks while it can't take the request and // nothing has been sent yet - cands := s.candidates(p, model, from) + cands, pl := s.plan(p, model, from) + tr := s.trace.begin(Route{Time: start, Agent: call.Agent, Model: call.Model, Provider: p.ID, Order: pl.order, Left: pl.left}) var skipped []string for i, c := range cands { last := i == len(cands)-1 || r.Context().Err() != nil hw := newHoldWriter(w, !last) call.Provider, call.To, call.Usage = c.p.ID, "", Usage{} + began := time.Now() + s.trace.update(tr, func(t *Route) { t.Tries = append(t.Tries, Try{ID: c.rest, Start: began}) }) call.Status, call.Error = s.attempt(hw, r, from, c.p, c.model, body, &call) + try := Try{ID: c.rest, Start: began, Done: true, Status: call.Status, Millis: time.Since(began).Milliseconds(), Error: call.Error} if !last && hw.failed() { - s.restAfter(c, hw.status, hw.header, hw.held.Bytes()) + rest := s.restAfter(c, hw.status, hw.header, hw.held.Bytes()) + try.Fail, try.Rest = rest.Why, &rest + s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try }) skipped = append(skipped, c.label()+": "+call.Error) continue } @@ -379,7 +386,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro model = c.model if call.Status < 400 { served(c.rest, call.Usage.Input+call.Usage.Output+call.Usage.CacheRead+call.Usage.CacheWrite) + } else { + try.Fail = failure(call.Status, []byte(call.Error)) } + s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try }) break } if len(skipped) > 0 { @@ -387,6 +397,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } call.Millis = time.Since(start).Milliseconds() finishCapture() + s.trace.update(tr, func(t *Route) { + t.Done, t.Status, t.Error, t.Millis = true, call.Status, call.Error, call.Millis + t.Tokens = call.Usage.Input + call.Usage.Output + call.Usage.CacheRead + call.Usage.CacheWrite + }) s.record(call) if call.To != "" { usage.Append(usage.Record{Time: start, Agent: call.Agent, Provider: call.Provider, Model: model, @@ -479,6 +493,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. if res.StatusCode >= 400 { b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) msg := p.Name + ": " + provider.APIError(b, res.Status) + keepRetry(w.Header(), res.Header) return writeError(w, proto, res.StatusCode, msg), msg } rd, sse := eventStream(res) @@ -621,6 +636,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr if res.StatusCode >= 400 { b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) msg := p.Name + ": " + provider.APIError(b, res.Status) + keepRetry(w.Header(), res.Header) return writeError(w, from, res.StatusCode, msg), msg } dec := decoder(actual) diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index ae82d68eb..883565bc8 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -93,47 +93,64 @@ func failure(status int, body []byte) string { return failOther } +// Rest is why a candidate sits out after a failure, and until when. +type Rest struct { + Why string `json:"why"` // failCredit, failQuota, failRate, failOther + Status int `json:"status"` // what it answered + Until time.Time `json:"until"` + // By is what set how long: "credit" (half an hour), "retry-after" (the + // vendor's own headers), "resets" (the time Claude Code gave), "window" + // (the allowance window it filled renews), "quota" (no word of when), + // "cooldown" (a minute), "backoff" (longer each time it fails again). + By string `json:"by"` + Failures int `json:"failures,omitempty"` // in a row, for a backoff +} + // restAfter sets a failed candidate aside for as long as its failure says. -func (s *Server) restAfter(c candidate, status int, header http.Header, body []byte) { +func (s *Server) restAfter(c candidate, status int, header http.Header, body []byte) Rest { now := time.Now() d := fallbackCooldown why := failure(status, body) + r := Rest{Why: why, Status: status, By: "cooldown"} switch why { case failCredit: - d = creditRest + d, r.By = creditRest, "credit" case failQuota: - d = quotaRest + d, r.By = quotaRest, "quota" if w := retryAfter(header, now); w > 0 { - d = w + d, r.By = w, "retry-after" } else if m := resetsWords.FindSubmatch(body); m != nil { if n, _ := strconv.ParseInt(string(m[1]), 10, 64); time.Unix(n, 0).After(now) { - d = time.Unix(n, 0).Sub(now) + d, r.By = time.Unix(n, 0).Sub(now), "resets" } } else if t := c.full(now); !t.IsZero() { - d = t.Sub(now) + d, r.By = t.Sub(now), "window" } case failRate: if w := retryAfter(header, now); w > 0 { - d = w + d, r.By = w, "retry-after" } default: routed.Lock() routed.failures[c.rest]++ n := routed.failures[c.rest] routed.Unlock() - d = min(fallbackCooldown< traceKeep { + t.routes = t.routes[len(t.routes)-traceKeep:] + } + t.changed() + rp.Seq = t.seq + return rp +} + +// update changes a route under the lock. +func (t *trace) update(r *Route, f func(r *Route)) { + if r == nil { + return + } + t.mu.Lock() + defer t.mu.Unlock() + done := r.Done + f(r) + if r.Done && !done { + t.totals.Requests++ + for _, try := range r.Tries { + if try.Rest != nil { + t.totals.Rerouted++ + } + } + if r.Status >= 400 { + t.totals.Errors++ + } + } + t.changed() + r.Seq = t.seq +} + +// 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 { + t := &s.trace + deadline := time.NewTimer(wait) + defer deadline.Stop() + for { + t.mu.Lock() + if t.seq < after { + after = 0 // the gateway started over since + } + st := TraceState{Seq: t.seq, Routes: []Route{}, Totals: t.totals} + for _, r := range t.routes { + if r.Seq > after { + c := *r + c.Order = append([]Weighed(nil), r.Order...) + c.Left = append([]Weighed(nil), r.Left...) + c.Tries = append([]Try{}, r.Tries...) + st.Routes = append(st.Routes, c) + } + } + if len(st.Routes) > 0 || wait <= 0 { + t.mu.Unlock() + return st + } + if t.wake == nil { + t.wake = make(chan struct{}) + } + wake := t.wake + t.mu.Unlock() + select { + case <-wake: + case <-deadline.C: + return st + case <-ctx.Done(): + return st + } + } +} diff --git a/internal/gateway/trace_test.go b/internal/gateway/trace_test.go new file mode 100644 index 000000000..1ce86e9d7 --- /dev/null +++ b/internal/gateway/trace_test.go @@ -0,0 +1,104 @@ +package gateway + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// The trace tells what routing did as it did it: who was to answer in what +// order, each try and what it answered, and how long one that failed rests. +func TestTraceTellsTheRoute(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + restingUntil.Lock() + restingUntil.m = map[string]time.Time{} + restingUntil.Unlock() + up := &byKey{limited: map[string]bool{"k-personal": true}} + srv := httptest.NewServer(up) + defer srv.Close() + p := provider.Provider{ID: "plan", Name: "Plan", Chat: srv.URL + "/v1", Models: []string{"m1"}, + Key: "k-personal", KeyName: "Personal", Keys: []provider.KeyAccount{{Name: "Team", Key: "k-team"}}} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + s := New() + send := func() { + s.Handler().ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(chatReq))) + } + + // one waiting for a route hears of it + got := make(chan []Route, 1) + go func() { + got <- s.Trace(context.Background(), 0, 5*time.Second).Routes + }() + time.Sleep(50 * time.Millisecond) + send() + if rs := <-got; len(rs) != 1 { + t.Fatalf("waiting: %d routes", len(rs)) + } + + st := s.Trace(context.Background(), 0, 0) + r := st.Routes[len(st.Routes)-1] + if !r.Done || r.Status != 200 || r.Provider != "plan" || len(r.Order) != 2 || r.Order[0].Who != "Personal" || r.Order[1].Kind != "key" { + t.Fatalf("route %+v", r) + } + if len(r.Tries) != 2 || r.Tries[0].Status != 429 || r.Tries[0].Fail != failRate || r.Tries[0].Rest == nil || + r.Tries[0].Rest.By != "cooldown" || r.Tries[1].Status != 200 || r.Tries[1].Rest != nil { + t.Fatalf("tries %+v", r.Tries) + } + + // the next finds the limited key resting, and says why + send() + st = s.Trace(context.Background(), st.Seq, 0) + r = st.Routes[len(st.Routes)-1] + if r.Order[0].Who != "Team" || r.Order[1].Rest == nil || r.Order[1].Rest.Status != 429 || len(r.Tries) != 1 { + t.Fatalf("resting %+v", r) + } + if st.Totals != (Totals{Requests: 2, Rerouted: 1}) { + t.Fatalf("totals %+v", st.Totals) + } +} + +// A vendor's Retry-After reaches routing through a failed request: the +// account rests as long as it says, and the trace says so. +func TestRetryAfterRests(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + restingUntil.Lock() + restingUntil.m = map[string]time.Time{} + restingUntil.Unlock() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.Header.Get("Authorization") == "Bearer k-slow" { + w.Header().Set("Retry-After", "300") + w.WriteHeader(429) + io.WriteString(w, `{"error":{"message":"Too many requests"}}`) + return + } + io.WriteString(w, `{"id":"x","choices":[]}`) + })) + defer srv.Close() + p := provider.Provider{ID: "ra", Name: "RA", Chat: srv.URL + "/v1", Models: []string{"m1"}, + Key: "k-slow", KeyName: "Slow", Keys: []provider.KeyAccount{{Name: "Fast", Key: "k-fast"}}} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + s := New() + s.Handler().ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("POST", "/v1/chat/completions", + strings.NewReader(`{"model":"ra/m1","messages":[{"role":"user","content":"hi"}]}`))) + rs := s.Trace(context.Background(), 0, 0).Routes + if len(rs) != 1 || len(rs[0].Tries) != 2 || rs[0].Tries[0].Rest == nil { + t.Fatalf("%+v", rs) + } + r := rs[0].Tries[0].Rest + if r.By != "retry-after" || time.Until(r.Until).Round(time.Minute) != 5*time.Minute { + t.Fatalf("rest %+v", r) + } +} diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 5e76e5762..06737af4e 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -450,6 +450,104 @@ const I18N = { "Path": "路径", "the address every agent is pointed at": "各 Agent 指向的地址", "Saved": "已保存", + // Gateway: routing, live + "live, as the gateway decides": "实时 · 网关正在做的决定", + "Least used": "最少使用", + "requests": "请求", + "rerouted": "改道", + "errors your agent saw": "Agent 收到的错误", + "rate limited": "限流", + "out of credit": "余额不足", + "quota used up": "额度用尽", + "failed": "失败", + "fallback": "备用", + "gateway": "网关", + "your agent": "你的 Agent", + "Recent": "最近", + "Back to live": "回到实时", + "How the last request was routed": "最近一个请求是怎么路由的", + "How the request at {time} was routed": "{time} 的请求是怎么路由的", + "Waiting for a request": "等待请求", + "No request yet": "还没有请求", + "Send one from any agent routed through magpie and it plays here as it happens: who routing put first and why, each try, and what each answered.": "任何经由 magpie 的 Agent 发出请求,这里就实时播放:路由把谁排在第一、为什么,每一次尝试,以及各自的回应。", + "Every request an agent sends to magpie shows up here, routed for real.": "Agent 发给 magpie 的每个请求都会出现在这里——真实的路由。", + "Another magpie serves the gateway; its routing plays live in that magpie's window.": "网关由另一个 magpie 提供,它的路由在那个 magpie 的窗口里实时播放。", + "The gateway isn't running, so nothing is routed.": "网关没有运行,因此没有任何路由。", + "Smart: of the accounts with quota to spare, the one whose allowance renews soonest goes first — what it has left would be lost at the reset. One at 90% or more waits until the others can't answer; one resting after a failure goes last.": "智能:在还有余量的账号里,额度最先重置的排第一——它剩下的额度到重置时就作废了。用到 90% 以上的账号等其他账号都答不了时才用;失败后正在休息的排最后。", + "Smart: keys that suit the request go first — one made for the model's own API — then in their order. One resting after a failure goes last.": "智能:适合这个请求的 Key 排前面——专为该模型原生 API 的 Key 优先——其余按顺序。失败后正在休息的排最后。", + "In order: the first answers everything until it can't; then the next.": "按顺序:第一个处理所有请求,直到它不行了,再换下一个。", + "In turn: each request starts one account further along.": "轮流:每个请求从下一个账号开始。", + "Least used first: the account with the most of its allowance left goes first; a key by the tokens magpie sent it lately.": "最少使用优先:剩余额度最多的账号排第一;Key 按 magpie 最近发给它的 token 数排。", + "Nothing could take {model}.": "没有谁能处理 {model}。", + "{who} is the only one, so it's tried though it is resting.": "只有 {who} 一个,所以虽然它在休息,也还是会试。", + "{who} is the only account on for {model} — nothing to choose between.": "{who} 是 {model} 唯一启用的账号——无需选择。", + "{name} has one key on — nothing to choose between.": "{name} 只启用了一个 Key——无需选择。", + "Every one is resting after a failure, so {who}, first in line, is tried all the same.": "所有账号都在失败后休息,所以排在第一的 {who} 照样会试。", + "{name} is resting, so its fallback {fb} goes first.": "{name} 正在休息,所以它的备用 {fb} 排第一。", + "In order: {who} is first, and answers everything while it can.": "按顺序:{who} 排第一,只要能答就由它答。", + "In turn: it's {who}'s turn — each request starts one further along.": "轮流:这次轮到 {who}——每个请求从下一个开始。", + "Least used first: {who} has the most of its allowance left — {n} used.": "最少使用优先:{who} 剩余额度最多——已用 {n}。", + "Least used first: {who} served the fewest tokens lately — {n}.": "最少使用优先:{who} 最近处理的 token 最少——{n}。", + "Least used first: {who} goes first.": "最少使用优先:{who} 排第一。", + "{who} goes first: it's made for {api}, the API {model} is at home in, so nothing is translated.": "{who} 排第一:它专为 {api} 而设,正是 {model} 的原生 API,无需转换。", + "{who} goes first: keys go in their order, those that suit the request first.": "{who} 排第一:Key 按顺序排,适合这个请求的在前。", + "{who} goes first.": "{who} 排第一。", + "The vendor hasn't said yet what these accounts have left, so they go in their order: {who} first.": "厂商还没告知这些账号还剩多少,所以按顺序排:{who} 第一。", + "Every account is at 90% or more of its allowance, so the one with the most left goes first: {who}, at {n}.": "所有账号都用到了 90% 以上,所以剩余最多的排第一:{who},已用 {n}。", + "{who} goes first: it has quota to spare, and the others are kept for last.": "{who} 排第一:它还有余量,其他账号留到最后。", + "{who} goes first: of those with quota to spare, its allowance renews soonest — in {d} — and what it has left then is lost. {other} renews later and keeps its own.": "{who} 排第一:在还有余量的账号里,它的额度最先重置——{d}后——剩下的届时就作废了。{other} 重置得晚,额度先留着。", + "{who} goes first: its allowance renews in the same hour as {other}'s, and its shorter one sooner — in {d}.": "{who} 排第一:它和 {other} 的额度在同一小时重置,而它较短的那个窗口更早——{d}后。", + "{who} and {other} renew within the same hour, so the order given stays — and the vendor's prompt cache stays warm.": "{who} 和 {other} 在同一小时内重置,所以保持原有顺序——厂商的 prompt 缓存也保持命中。", + "{who} goes first, in the order given: when its allowance renews isn't known.": "{who} 按原有顺序排第一:不知道它的额度何时重置。", + "{who} is resting — {why}, {when} — so it waits at the back.": "{who} 正在休息——{why},{when}——所以排在最后。", + "{who} is at {n} — all but used up, it answers only when nothing else can.": "{who} 已用 {n}——几乎用尽,只在别的都不行时才用它。", + "{who} is at {n} — kept for when the others can't.": "{who} 已用 {n}——留给其他账号都不行的时候。", + "{who}: what it has left isn't known yet, so it goes after those known.": "{who}:还不知道它剩多少,所以排在已知的之后。", + "{who} is left out: its plan doesn't list {model}.": "{who} 不参与:它的套餐不包含 {model}。", + "{who} is answering…": "{who} 正在回答…", + "{n} tokens": "{n} token", + "{who} answered in {ms}{tk}. {agent} got one clean reply and never saw the {n} that failed first.": "{who} 用 {ms} 完成回答{tk}。{agent} 收到一个干净的回复,完全没看到之前失败的 {n} 次。", + "{who} answered in {ms}{tk}.": "{who} 用 {ms} 完成回答{tk}。", + "{who} answered {status} · {fail}. {how}; the request goes on to {next} before any of the reply reaches {agent}.": "{who} 返回 {status} · {fail}。{how};在任何回复到达 {agent} 之前,请求就转给了 {next}。", + "{who} answered {status} and nobody is left to try, so {agent} gets the error.": "{who} 返回 {status},已经没有别的可试,所以 {agent} 收到了这个错误。", + "{who} answered {status} — an error another account wouldn't fix, so {agent} gets it.": "{who} 返回 {status}——换个账号也解决不了的错误,所以 {agent} 收到了它。", + "the next": "下一个", + "It rests {d}, as the vendor's Retry-After says": "按厂商 Retry-After 的要求,它休息 {d}", + "It sits out half an hour, until someone tops it up": "它先休息半小时,等人充值", + "Its allowance is used up: it rests until that renews, at {time}": "它的额度用尽了:休息到额度在 {time} 重置", + "It rests until {time}, when Claude Code says the limit resets": "它休息到 {time},Claude Code 说那时额度重置", + "It rests 15 minutes: out of quota, with no word of when it resets": "它休息 15 分钟:额度用尽,但没说何时重置", + "It has failed {n} times in a row: it rests {d}, longer each time": "它已连续失败 {n} 次:休息 {d},每次更久", + "It rests {d}, longer if it fails again": "它休息 {d},再失败就更久", + "It rests {d}": "它休息 {d}", + "It cools down {d}: the vendor didn't say for how long": "它冷却 {d}:厂商没说要多久", + "With {rested} resting after a failure, {who} goes first: ": "{rested} 失败后正在休息,{who} 排第一:", + "the others go in their order.": "其余按顺序排。", + "In order: with {rested} resting after a failure, {who} is the first that can answer.": "按顺序:{rested} 失败后正在休息,{who} 是第一个能答的。", + "{agent} asked for {model}": "{agent} 请求 {model}", + "Nothing was tried: {error}": "没有尝试任何账号:{error}", + "rerouted {n}×": "改道 {n} 次", + "back in {d}": "{d}后恢复", + "back at {time}": "{time} 恢复", + "its plan doesn't list {model}": "套餐不包含 {model}", + "answering…": "回答中…", + "answered this request": "回答了这个请求", + "{status} · {fail} · passed to {agent}": "{status} · {fail} · 已交给 {agent}", + "{n} used · all but used up": "已用 {n} · 几乎用尽", + "{n} used · kept for last": "已用 {n} · 留到最后", + "{n} used · renews in {d}": "已用 {n} · {d}后重置", + "{n} used": "已用 {n}", + "what's left not known yet": "剩余额度未知", + "{n} tokens lately": "最近 {n} token", + "{api} only": "仅 {api}", + "one on": "启用 1 个", + "{n} on": "启用 {n} 个", + "{n} s": "{n} 秒", + "{n} ms": "{n} 毫秒", + "{n} min": "{n} 分钟", + "{h} h {m} min": "{h} 小时 {m} 分钟", + "{n} h": "{n} 小时", + "{n} d": "{n} 天", }, }; diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index 83f41877a..81951ee4e 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -5,6 +5,7 @@ magpie +
@@ -57,6 +58,8 @@
+
Routinglive, as the gateway decides
+
Connect
Models
@@ -137,5 +140,6 @@ + diff --git a/internal/gui/assets/routing.css b/internal/gui/assets/routing.css new file mode 100644 index 000000000..f7b432e0e --- /dev/null +++ b/internal/gui/assets/routing.css @@ -0,0 +1,107 @@ +/* Routing, live: the Gateway view's stage for what routing does with each + request (routing.js). The same stage as the site's Model Routing, only + played by the gateway's own trace. */ +.rt { container-type: inline-size; background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 14px 16px 12px; margin: 0 0 18px; } +.rt-top { display: flex; flex-direction: column; gap: 3px; } +.rt-what { font-size: 13px; color: var(--muted); } +.rt-what b { color: var(--fg); font-weight: 600; } +.rt-mode { margin: 0; font-size: 12.5px; color: var(--fg-2); line-height: 1.45; } +.rt-stage { position: relative; display: grid; grid-template-columns: 124px 124px minmax(0, 1fr); column-gap: 56px; align-items: center; padding: 22px 2px; } +.rt-wires { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; pointer-events: none; } +.rt-wires path { fill: none; stroke: var(--line); stroke-width: 1.5; transition: opacity .3s; } +.rt-wires path.live { stroke: var(--muted); stroke-dasharray: 3 5; animation: rtflow .7s linear infinite; } +.rt-wires path.rest { stroke-dasharray: 2 6; opacity: .45; } +@keyframes rtflow { to { stroke-dashoffset: -8; } } +.rt-wires .pkt { fill: var(--fg); filter: drop-shadow(0 0 3px var(--muted)); } +.rt-wires .pkt.back { fill: var(--card); stroke: var(--fg); stroke-width: 2; } +.rt-wires .pkt.err { stroke: var(--red); } +.rt-node { position: relative; z-index: 1; min-width: 0; display: flex; flex-direction: column; align-items: center; gap: 2px; padding: 12px 8px 10px; background: var(--card); border: 1px solid var(--line); border-radius: 12px; text-align: center; } +.rt-node .rt-ic .ic, .rt-node .rt-bird { width: 26px; height: 26px; margin-bottom: 3px; } +.rt-node .rt-ic .ic img, .rt-node .rt-ic .ic svg { width: 26px; height: 26px; } +.rt-node b { font-size: 13px; font-weight: 600; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.rt-node small { font-size: 11px; color: var(--muted); max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.rt-hub { border-color: var(--fg); box-shadow: 0 0 0 4px var(--card-2); } +.rt-hub i { font-style: normal; font-size: 10.5px; font-weight: 560; margin-top: 5px; padding: 1px 8px; border-radius: 999px; background: var(--fg); color: var(--card); } +.rt-hub.tick, .rt-src.tick { animation: rttick .4s ease-out; } +@keyframes rttick { 40% { transform: scale(1.04); } } +.rt-accts { position: relative; z-index: 1; list-style: none; margin: 0; padding: 0; display: grid; gap: 7px; min-width: 0; container-type: inline-size; } +.rt-accts li { position: relative; display: grid; grid-template-columns: 10px minmax(0, 1fr) auto; align-items: center; column-gap: 10px; row-gap: 6px; padding: 9px 12px; background: var(--card); border: 1px solid var(--line); border-radius: 10px; font-size: 13px; transition: opacity .3s, border-color .3s, transform .5s cubic-bezier(.2, .8, .2, 1); } +.rt-accts li.idle { display: block; color: var(--muted); border-style: dashed; text-align: center; } +.rt-accts b { font-weight: 560; color: var(--fg); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.rt-accts b > span:not(.ic) { font-weight: 450; color: var(--muted); } +.rt-accts b > span.who { color: var(--fg); font-weight: 560; } +.rt-accts b .ic { display: inline-flex; width: 16px; height: 16px; margin-right: 7px; vertical-align: -3px; } +.rt-accts b .ic img, .rt-accts b .ic svg { width: 16px; height: 16px; } +.rt-accts b .fb { margin-left: 6px; font-size: 10.5px; font-weight: 560; padding: 0 6px; border-radius: 999px; border: 1px solid var(--line); color: var(--muted); } +.rt-accts em { font-style: normal; font-size: 12px; color: var(--muted); white-space: nowrap; font-variant-numeric: tabular-nums; } +.rt-accts .bar { grid-column: 2 / 4; height: 3px; border-radius: 2px; background: var(--card-2); overflow: hidden; } +.rt-accts .bar i { display: block; height: 100%; width: 0; border-radius: 2px; background: var(--muted); transition: width .4s; } +.rt-accts li.nobar .bar { display: none; } +.rt-accts .dot { width: 8px; height: 8px; border-radius: 50%; border: 1.5px solid var(--muted); } +.rt-accts li.on { border-color: var(--fg); } +.rt-accts li.on em { color: var(--fg); } +.rt-accts li.on .bar i { background: var(--fg); } +.rt-accts li.on .dot { background: var(--fg); border-color: var(--fg); animation: rtlive 1.8s infinite; } +@keyframes rtlive { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--fg) 40%, transparent); } 70%, 100% { box-shadow: 0 0 0 6px transparent; } } +.rt-accts li.low em { color: var(--fg-2); } +.rt-accts li.rest { border-style: dashed; } +.rt-accts li.rest > :not(.tag) { opacity: .5; } +.rt-accts li.rest em { color: var(--red); opacity: .85; } +.rt-accts li.left { border-style: dotted; } +.rt-accts li.left > :not(.tag) { opacity: .45; } +.rt-accts li.hit { animation: rthit .45s; } +@keyframes rthit { 20% { translate: -5px; } 40% { translate: 4px; } 60% { translate: -2px; } 80% { translate: 1px; } } +.rt-accts .tag { position: absolute; right: 10px; top: -10px; padding: 1px 7px; border-radius: 6px; background: var(--red); color: #fff; font: 600 10.5px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; opacity: 0; transform: translateY(4px) scale(.9); transition: opacity .25s, transform .25s; pointer-events: none; } +.rt-accts li.tagged .tag { opacity: 1; transform: none; } +.rt-foot { display: flex; align-items: center; justify-content: space-between; gap: 10px 20px; flex-wrap: wrap; padding-top: 10px; border-top: 1px solid var(--line); } +.rt-cap { flex: 1 1 20em; margin: 0; min-height: 3em; display: flex; align-items: center; font-size: 13px; line-height: 1.45; color: var(--fg); } +.rt-cap.in { animation: rtin .4s ease-out; } +@keyframes rtin { from { opacity: 0; transform: translateY(4px); } } +.rt-stats { display: flex; gap: 18px; font-size: 11px; color: var(--muted); } +.rt-stats > span { display: flex; flex-direction: column; } +.rt-stats b { font-size: 19px; line-height: 1.2; font-weight: 650; letter-spacing: -.02em; color: var(--fg); font-variant-numeric: tabular-nums; } +.rt-hist { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; padding-top: 10px; margin-top: 10px; border-top: 1px solid var(--line); } +.rt-hist .label { font-size: 11px; color: var(--muted); margin-right: 4px; } +.rt-h { display: inline-flex; align-items: center; gap: 5px; font: inherit; font-size: 11px; font-variant-numeric: tabular-nums; color: var(--fg-2); background: none; border: 1px solid transparent; border-radius: 6px; padding: 2px 6px; cursor: pointer; } +.rt-h:hover { background: var(--card-2); } +.rt-h[aria-pressed="true"] { border-color: var(--line); background: var(--card-2); color: var(--fg); } +.rt-h i { width: 6px; height: 6px; border-radius: 50%; background: var(--green); } +.rt-h.moved i { background: var(--accent); } +.rt-h.bad i { background: var(--red); } +.rt-h.wait i { background: var(--muted); } +.rt-log { padding-top: 10px; margin-top: 10px; border-top: 1px solid var(--line); } +.rt-log-head { display: flex; align-items: center; font-size: 12px; font-weight: 600; color: var(--fg); } +.rt-log-head .grow { flex: 1; } +.rt-steps { list-style: none; margin: 6px 0 0; padding: 0; display: grid; gap: 5px; counter-reset: rt; } +.rt-steps li { position: relative; padding-left: 20px; font-size: 12.5px; line-height: 1.45; color: var(--fg-2); } +.rt-steps li::before { content: ""; position: absolute; left: 5px; top: .5em; width: 6px; height: 6px; border-radius: 50%; background: var(--muted); } +.rt-steps li.why { color: var(--fg); } +.rt-steps li.why::before { background: var(--fg); } +.rt-steps li.aside { color: var(--muted); } +.rt-steps li.aside::before { background: none; border: 1px solid var(--muted); width: 4px; height: 4px; } +.rt-steps li.ok::before { background: var(--green); } +.rt-steps li.bad::before { background: var(--red); } +.rt-steps li.wait::before { animation: rtlive 1.8s infinite; } +.rt-off { padding: 18px 4px; text-align: center; color: var(--muted); font-size: 13px; } +@media (prefers-reduced-motion: reduce) { + .rt-accts li.on .dot, .rt-wires path.live, .rt-accts li.hit, .rt-hub.tick, .rt-src.tick, .rt-cap.in, .rt-steps li.wait::before { animation: none; } + .rt-accts li { transition: none; } +} +/* a narrow list: what a row says goes under its name */ +@container (max-width: 460px) { + .rt-accts li { grid-template-columns: 10px minmax(0, 1fr); } + .rt-accts em { grid-column: 2; white-space: normal; } + .rt-accts .bar { grid-column: 2; } +} +/* narrow (the tray panel): magpie and the agent side by side, the + accounts under them, on a lane down their left */ +@container (max-width: 560px) { + .rt-stage { grid-template-columns: 1fr 1fr; column-gap: 28px; row-gap: 26px; padding: 16px 0; } + .rt-accts { grid-column: 1 / -1; padding-left: 22px; } + .rt-accts li { grid-template-columns: 10px minmax(0, 1fr); } + .rt-accts em { grid-column: 2; white-space: normal; } + .rt-accts .bar { grid-column: 2; } + .rt-stats { gap: 14px; } +} +.rt-livedot { width: 6px; height: 6px; margin-left: 7px; border-radius: 50%; background: var(--green); animation: rtlive 1.8s infinite; --fg: var(--green); } +@media (prefers-reduced-motion: reduce) { .rt-livedot { animation: none; } } diff --git a/internal/gui/assets/routing.js b/internal/gui/assets/routing.js new file mode 100644 index 000000000..061fde8ec --- /dev/null +++ b/internal/gui/assets/routing.js @@ -0,0 +1,603 @@ +// Routing, live: the gateway's own trace of each request, played as it +// happens. A request travels from the agent to magpie and on to the account +// routing put first; one that can't answer sends it back, and the next +// takes it. Every row, number and sentence comes from what the gateway +// recorded while deciding (see internal/gateway/trace.go) — the order it +// weighed the accounts in, what it weighed them by, what each answered, +// how long a failed one rests. Nothing here is worked out again or made up. +(() => { + const box = $("#rt"); + if (!box) return; + const NS = "http://www.w3.org/2000/svg"; + const still = () => matchMedia("(prefers-reduced-motion: reduce)").matches; + const shown = () => !$("#view-gateway").hidden && !document.hidden; + + // ---------- the stage ---------- + + const top = el("div", "rt-top"); + const what = el("div", "rt-what"); + const mode = el("p", "rt-mode"); + top.append(what, mode); + const stage = el("div", "rt-stage"); + const wires = document.createElementNS(NS, "svg"); + wires.setAttribute("class", "rt-wires"); + wires.setAttribute("aria-hidden", "true"); + const src = el("div", "rt-node rt-src"); + const srcIc = el("span", "rt-ic"), srcName = el("b"), srcSub = el("small"); + src.append(srcIc, srcName, srcSub); + const hub = el("div", "rt-node rt-hub"); + const bird = document.createElementNS(NS, "svg"); + bird.setAttribute("viewBox", "0 0 44 44"); + bird.setAttribute("class", "rt-bird"); + bird.innerHTML = ''; + const hubSub = el("small"), chip = el("i"); + hub.append(bird, el("b", "", "magpie"), hubSub, chip); + const list = el("ol", "rt-accts"); + stage.append(wires, src, hub, list); + const foot = el("div", "rt-foot"); + const cap = el("p", "rt-cap"); + cap.setAttribute("aria-live", "polite"); + const stats = el("div", "rt-stats"); + const statB = []; + for (const k of ["requests", "rerouted", "errors your agent saw"]) { + const s = el("span"), b = el("b", "", "0"); + s.append(b, el("span", "", k)); + s.dataset.label = k; + statB.push(b); + stats.append(s); + } + foot.append(cap, stats); + const log = el("div", "rt-log"); + const logHead = el("div", "rt-log-head"); + const steps = el("ol", "rt-steps"); + const hist = el("div", "rt-hist"); + log.append(logHead, steps); + const off = el("div", "none rt-off"); + box.append(top, stage, foot, hist, log, off); + + const path = () => { const p = document.createElementNS(NS, "path"); wires.appendChild(p); return p; }; + const wSrc = path(); + const tick = (e) => { e.classList.remove("tick"); void e.offsetWidth; e.classList.add("tick"); }; + + // ---------- words ---------- + + let skew = 0; // the gateway's clock less this page's + const now = () => Date.now() + skew; + const at = (s) => new Date(s).getTime(); + const known0 = (s) => s && !s.startsWith("0001-"); + function dur(ms) { + const s = Math.max(1, Math.round(ms / 1000)); + if (s < 60) return t("{n} s", { n: s }); + const m = Math.round(s / 60); + if (m < 60) return t("{n} min", { n: m }); + const h = Math.floor(m / 60), mm = m % 60; + if (h < 10 && mm) return t("{h} h {m} min", { h, m: mm }); + if (h < 48) return t("{n} h", { n: Math.round(m / 60) }); + return t("{n} d", { n: Math.round(m / 1440) }); + } + const took = (ms) => ms < 1000 ? t("{n} ms", { n: ms }) : t("{n} s", { n: (ms / 1000).toFixed(ms < 10e3 ? 1 : 0) }); + function clock(s) { + const d = new Date(s), n = new Date(); + const hm = d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); + return d.toDateString() === n.toDateString() ? hm : d.toLocaleDateString([], { weekday: "short" }) + " " + hm; + } + const tokens = (n) => n >= 1e6 ? (n / 1e6).toFixed(1) + "M" : n >= 1e3 ? (n / 1e3).toFixed(1) + "k" : String(Math.round(n)); + const pct = (n) => Math.round(n) + "%"; + const FAIL = { rate: "rate limited", credit: "out of credit", quota: "quota used up", other: "failed" }; + const failWord = (why) => t(FAIL[why] || "failed"); + const API = { anthropic: "Anthropic", chat: "OpenAI", responses: "OpenAI Responses", gemini: "Gemini" }; + const MODES = { + "": ["Smart", "Smart: of the accounts with quota to spare, the one whose allowance renews soonest goes first — what it has left would be lost at the reset. One at 90% or more waits until the others can't answer; one resting after a failure goes last."], + order: ["In order", "In order: the first answers everything until it can't; then the next."], + rotate: ["In turn", "In turn: each request starts one account further along."], + usage: ["Least used", "Least used first: the account with the most of its allowance left goes first; a key by the tokens magpie sent it lately."], + }; + const KEYS_SMART = "Smart: keys that suit the request go first — one made for the model's own API — then in their order. One resting after a failure goes last."; + + const agentOf = (id) => state.agents.find((a) => a.id === id); + const agentName = (id) => agentOf(id)?.name || (id && id !== "other" ? id : t("your agent")); + // who names an account or key in a sentence + const who = (w) => w.kind === "provider" ? w.name : w.who; + const group = (w) => w.used >= 98 ? "spent" : w.used >= 90 ? "low" : "fine"; + const renews = (w) => (w.renews || []).map((s) => known0(s) ? at(s) : 0); + + // cmpRenews orders two accounts' windows as the gateway does: the + // biggest first, to the hour, one not known after those known. It says + // which window decided, too. + function cmpRenews(a, b) { + const ra = renews(a), rb = renews(b), H = 3600e3; + for (let k = 0; k < ra.length || k < rb.length; k++) { + const x = ra[k] ? Math.floor(ra[k] / H) : 0, y = rb[k] ? Math.floor(rb[k] / H) : 0; + if (x === y) continue; + if (!x || !y) return { c: x ? -1 : 1, k }; + return { c: x < y ? -1 : 1, k }; + } + return { c: 0, k: -1 }; + } + + // how long a rest is from a moment: now for a row, the moment it was + // decided for the story of a request + function restWhen(rest, from = now()) { + const left = at(rest.until) - from; + return left < 3600e3 ? t("back in {d}", { d: dur(left) }) : t("back at {time}", { time: clock(rest.until) }); + } + // restHow says how long a failed account sits out, and what said so. + function restHow(rest, from) { + const d = dur(at(rest.until) - from), time = clock(rest.until); + switch (rest.by) { + case "retry-after": return t("It rests {d}, as the vendor's Retry-After says", { d }); + case "credit": return t("It sits out half an hour, until someone tops it up"); + case "window": return t("Its allowance is used up: it rests until that renews, at {time}", { time }); + case "resets": return t("It rests until {time}, when Claude Code says the limit resets", { time }); + case "quota": return t("It rests 15 minutes: out of quota, with no word of when it resets"); + case "backoff": return rest.failures > 1 + ? t("It has failed {n} times in a row: it rests {d}, longer each time", { n: rest.failures, d }) + : t("It rests {d}, longer if it fails again", { d }); + case "cooldown": return rest.why === "rate" + ? t("It cools down {d}: the vendor didn't say for how long", { d }) + : t("It rests {d}", { d }); + default: return t("It rests {d}", { d }); + } + } + + // why routing put the first where it did + function firstWhy(r) { + const f = r.order[0]; + if (!f) return t("Nothing could take {model}.", { model: r.model }); + const w = who(f); + if (r.order.length === 1) { + if (f.rest) return t("{who} is the only one, so it's tried though it is resting.", { who: w }); + return f.kind === "account" ? t("{who} is the only account on for {model} — nothing to choose between.", { who: w, model: r.model }) + : t("{name} has one key on — nothing to choose between.", { name: f.name }); + } + if (f.rest) return t("Every one is resting after a failure, so {who}, first in line, is tried all the same.", { who: w }); + if (f.fallback) { + const name = r.order.find((x) => !x.fallback)?.name || r.provider; + return t("{name} is resting, so its fallback {fb} goes first.", { name, fb: `${f.provider}/${f.model}` }); + } + const peers = r.order.filter((x) => x !== f && !x.fallback && !x.rest); + const rested = r.order.filter((x) => x !== f && !x.fallback && x.rest).map(who); + const restedTo = (s) => rested.length ? t("With {rested} resting after a failure, {who} goes first: ", { rested: rested.join(", "), who: w }) + s : null; + switch (f.routing) { + case "order": return rested.length + ? t("In order: with {rested} resting after a failure, {who} is the first that can answer.", { rested: rested.join(", "), who: w }) + : t("In order: {who} is first, and answers everything while it can.", { who: w }); + case "rotate": return t("In turn: it's {who}'s turn — each request starts one further along.", { who: w }); + case "usage": + if (f.kind === "account" && f.known) return t("Least used first: {who} has the most of its allowance left — {n} used.", { who: w, n: pct(f.used) }); + if (f.kind === "key") return t("Least used first: {who} served the fewest tokens lately — {n}.", { who: w, n: tokens(f.tokens || 0) }); + return t("Least used first: {who} goes first.", { who: w }); + } + if (f.kind === "key") { + if (!f.fit && peers.some((p) => p.fit > 0)) return t("{who} goes first: it's made for {api}, the API {model} is at home in, so nothing is translated.", { who: w, api: API[f.speaks] || f.speaks, model: f.model }); + return restedTo(t("the others go in their order.")) || t("{who} goes first: keys go in their order, those that suit the request first.", { who: w }); + } + if (f.kind !== "account") return t("{who} goes first.", { who: w }); + if (!f.known && !peers.some((p) => p.known)) return t("The vendor hasn't said yet what these accounts have left, so they go in their order: {who} first.", { who: w }); + if (group(f) !== "fine") return t("Every account is at 90% or more of its allowance, so the one with the most left goes first: {who}, at {n}.", { who: w, n: pct(f.used) }); + const next = peers.find((p) => p.known && group(p) === "fine"); + const soon = renews(f).find(Boolean); + if (!next) return t("{who} goes first: it has quota to spare, and the others are kept for last.", { who: w }); + const { c, k } = cmpRenews(f, next); + if (c < 0 && k === 0) return t("{who} goes first: of those with quota to spare, its allowance renews soonest — in {d} — and what it has left then is lost. {other} renews later and keeps its own.", { who: w, d: dur(renews(f)[0] - at(r.time)), other: who(next) }); + if (c < 0) return t("{who} goes first: its allowance renews in the same hour as {other}'s, and its shorter one sooner — in {d}.", { who: w, other: who(next), d: dur(renews(f)[k] - at(r.time)) }); + if (soon) return t("{who} and {other} renew within the same hour, so the order given stays — and the vendor's prompt cache stays warm.", { who: w, other: who(next) }); + return t("{who} goes first, in the order given: when its allowance renews isn't known.", { who: w }); + } + + // asides: the others' places, where they say something + function asides(r) { + const out = []; + const smart = (x) => !x.routing && x.kind === "account"; + const someKnown = r.order.some((x) => x.known); + for (const x of r.order.slice(1)) { + if (x.rest) out.push(t("{who} is resting — {why}, {when} — so it waits at the back.", { who: who(x), why: `${x.rest.status} · ${failWord(x.rest.why)}`, when: restWhen(x.rest, at(r.time)) })); + else if (smart(x) && x.known && group(x) === "spent") out.push(t("{who} is at {n} — all but used up, it answers only when nothing else can.", { who: who(x), n: pct(x.used) })); + else if (smart(x) && x.known && group(x) === "low") out.push(t("{who} is at {n} — kept for when the others can't.", { who: who(x), n: pct(x.used) })); + else if (smart(x) && !x.known && someKnown) out.push(t("{who}: what it has left isn't known yet, so it goes after those known.", { who: who(x) })); + } + for (const x of r.left || []) out.push(t("{who} is left out: its plan doesn't list {model}.", { who: who(x), model: x.model })); + return out; + } + + function tryWhy(r, i) { + const tr = r.tries[i], w = r.order.find((x) => x.id === tr.id), name = w ? who(w) : tr.id, agent = agentName(r.agent); + if (!tr.done) return t("{who} is answering…", { who: name }); + if (tr.status < 400) { + const tk = r.tokens ? " · " + t("{n} tokens", { n: tokens(r.tokens) }) : ""; + return i > 0 + ? t("{who} answered in {ms}{tk}. {agent} got one clean reply and never saw the {n} that failed first.", { who: name, ms: took(tr.ms), tk, agent, n: i }) + : t("{who} answered in {ms}{tk}.", { who: name, ms: took(tr.ms), tk }); + } + if (tr.rest) { + const next = r.tries[i + 1], nw = next && r.order.find((x) => x.id === next.id); + return t("{who} answered {status} · {fail}. {how}; the request goes on to {next} before any of the reply reaches {agent}.", + { who: name, status: tr.status, fail: failWord(tr.fail), how: restHow(tr.rest, at(tr.start) + (tr.ms || 0)), next: nw ? who(nw) : t("the next"), agent }); + } + const last = i === r.order.length - 1; + return last + ? t("{who} answered {status} and nobody is left to try, so {agent} gets the error.", { who: name, status: tr.status, agent }) + : t("{who} answered {status} — an error another account wouldn't fix, so {agent} gets it.", { who: name, status: tr.status, agent }); + } + + // ---------- state ---------- + + const routes = new Map(); // id → the latest of each route + let seq = 0, mine = true, loaded = false; + let cur = null; // the route the stage shows + let pinned = null; // a past route picked from the strip + let rows = new Map(); // id → { li, wire, st, bi, tg, w } + let key = ""; // the ids the stage has rows for + let gen = 0, trips = [], waiters = [], active = 0, queue = []; + let capQ = [], capAt = -1e9, capLo = false, flipUntil = 0; + + const travel = (dot, p, rev, ms) => new Promise((res) => trips.push({ dot, p, rev, t0: performance.now(), ms: still() || !shown() ? 0 : ms, res, g: gen })); + const until = (f) => f() ? Promise.resolve() : new Promise((res) => waiters.push({ f, res })); + const wake = () => { const w = waiters; waiters = []; for (const x of w) if (x.f()) x.res(); else waiters.push(x); }; + function say(s, lo) { + if (!s) return; + if (!shown()) { capQ = []; show({ s, lo }); return; } + if (lo && capQ.length) return; + if (!lo) capQ = capQ.filter((c) => !c.lo); + capQ.push({ s, lo }); + if (capQ.length > 3) capQ.shift(); + } + function show(c) { capLo = !!c.lo; cap.textContent = c.s; cap.classList.remove("in"); void cap.offsetWidth; cap.classList.add("in"); capAt = performance.now(); } + + function layout() { + const r = stage.getBoundingClientRect(); + if (!r.width) return; + const b = (e) => { const x = e.getBoundingClientRect(); return { l: x.left - r.left, r: x.right - r.left, t: x.top - r.top, b: x.bottom - r.top, cx: (x.left + x.right) / 2 - r.left, cy: (x.top + x.bottom) / 2 - r.top }; }; + wires.setAttribute("viewBox", `0 0 ${r.width} ${r.height}`); + const s = b(src), h = b(hub); + wSrc.setAttribute("d", h.l > s.r ? `M${s.r} ${s.cy} L${h.l} ${h.cy}` : `M${s.cx} ${s.b} L${h.cx} ${h.t}`); + for (const row of rows.values()) { + const a = b(row.li); + if (a.l > h.r) { + const mx = (h.r + a.l) / 2; + row.wire.setAttribute("d", `M${h.r} ${h.cy} C${mx} ${h.cy} ${mx} ${a.cy} ${a.l} ${a.cy}`); + } else { // the accounts sit under magpie: a lane down their left + const x = a.l - 12; + row.wire.setAttribute("d", `M${h.cx} ${h.b} C${h.cx} ${h.b + 22} ${x} ${h.b + 2} ${x} ${h.b + 24} L${x} ${a.cy - 10} Q${x} ${a.cy} ${a.l} ${a.cy}`); + } + } + } + + // stageFor puts a route's accounts on the stage: in the order it weighed + // them, those left out after. The same accounts in another order move + // to their places, so a new order shows. + function stageFor(r) { + const all = [...r.order, ...(r.left || [])]; + const k = all.map((w) => w.id).sort().join("\n"); + if (k !== key) { + key = k; + for (const row of rows.values()) row.wire.remove(); + rows = new Map(); + list.replaceChildren(); + for (const w of all) { + const li = el("li"), b = el("b"); + b.append(icon(w.icon || (w.preset ? w.preset : "generic"))); + const name = el("span", "who", who(w)); + // the provider's name heads the card; a row names what differs + const sub = el("span", "", w.fallback ? `${w.name} · ${w.provider}/${w.model}` : w.kind === "provider" ? w.model : w.plan || ""); + b.append(name, " ", sub); + if (w.fallback) b.append(el("small", "fb", t("fallback"))); + const st = el("em"), bar = el("div", "bar"), bi = el("i"), tg = el("span", "tag"); + bar.append(bi); + li.append(el("i", "dot"), b, st, bar, tg); + li.title = w.id; + list.append(li); + rows.set(w.id, { li, wire: path(), st, bi, tg, w }); + } + } else { + // FLIP: from where each was to its new place + const before = new Map([...rows].map(([id, row]) => [id, row.li.getBoundingClientRect().top])); + for (const w of all) list.append(rows.get(w.id).li); + let moved = false; + for (const [id, row] of rows) { + const dy = before.get(id) - row.li.getBoundingClientRect().top; + if (!dy || still()) continue; + moved = true; + row.li.style.transition = "none"; + row.li.style.transform = `translateY(${dy}px)`; + } + if (moved) { + void list.offsetWidth; + for (const row of rows.values()) { row.li.style.transition = ""; row.li.style.transform = ""; } + flipUntil = performance.now() + 520; + } + } + for (const w of all) rows.get(w.id).w = w; + cur = r; + const ag = agentOf(r.agent); + srcIc.replaceChildren(icon(ag?.icon || "generic")); + srcName.textContent = agentName(r.agent); + srcSub.textContent = r.model; + const f = r.order.find((x) => !x.fallback) || r.order[0]; + const m = MODES[f?.routing || ""] || MODES[""]; + chip.textContent = t(m[0]); + chip.hidden = false; + hubText(); + what.replaceChildren(el("b", "", f?.name || r.provider), el("span", "", " · " + t(r.order.filter((x) => !x.fallback).length + (r.left || []).length === 1 ? "one on" : "{n} on", { n: r.order.filter((x) => !x.fallback).length + (r.left || []).length }))); + mode.textContent = t(!f?.routing && f?.kind === "key" ? KEYS_SMART : m[1]); + layout(); + } + + // what a row says now: resting, answering, or what routing weighed it by + function render() { + if (!cur) return; + hubText(); + const r = pinned || cur, n = now(); + const trying = new Set(), answered = new Set(), rests = new Map(), gave = new Map(); + for (const w of r.order) if (w.rest) rests.set(w.id, w.rest); + for (const tr of r.tries) { + if (!tr.done) trying.add(tr.id); + else if (tr.status < 400) answered.add(tr.id); + else if (!tr.rest) gave.set(tr.id, tr); // the error the agent got + if (tr.rest) rests.set(tr.id, tr.rest); + } + const onWire = new Set(flying.values()); + for (const [id, row] of rows) { + const w = row.w, rest = rests.get(id), resting = rest && at(rest.until) > n; + let s; + if (w.unlisted) s = t("its plan doesn't list {model}", { model: w.model }); + else if (resting) s = `${failWord(rest.why)} · ${restWhen(rest)}`; + else if (trying.has(id)) s = t("answering…"); + else if (answered.has(id)) s = t("answered this request"); + else if (gave.has(id)) s = t("{status} · {fail} · passed to {agent}", { status: gave.get(id).status, fail: failWord(gave.get(id).fail), agent: agentName(r.agent) }); + else if (w.kind === "account" && w.known) { + const soon = renews(w)[0]; + s = !w.routing && w.used >= 98 ? t("{n} used · all but used up", { n: pct(w.used) }) + : !w.routing && w.used >= 90 ? t("{n} used · kept for last", { n: pct(w.used) }) + : soon ? t("{n} used · renews in {d}", { n: pct(w.used), d: dur(soon - n) }) : t("{n} used", { n: pct(w.used) }); + } else if (w.kind === "account") s = t("what's left not known yet"); + else if (w.routing === "usage") s = t("{n} tokens lately", { n: tokens(w.tokens || 0) }); + else if (w.speaks) s = t("{api} only", { api: API[w.speaks] || w.speaks }); + else s = w.kind === "key" ? t("API key") : t("one key"); + if (row.st.textContent !== s) row.st.textContent = s; + const bar = w.kind === "account" && w.known; + row.li.classList.toggle("nobar", !bar); + row.bi.style.width = bar ? Math.min(100, w.used) + "%" : "0"; + const on = !resting && (trying.has(id) || answered.has(id) || onWire.has(id)); + row.li.classList.toggle("on", on); + row.li.classList.toggle("low", !!(!w.routing && w.known && w.used >= 90)); + row.li.classList.toggle("rest", !!resting || gave.has(id)); + row.li.classList.toggle("left", !!w.unlisted); + row.wire.classList.toggle("live", on); + row.wire.classList.toggle("rest", !!resting || !!w.unlisted); + } + wSrc.classList.toggle("live", trying.size > 0 || flying.size > 0); + } + + // ---------- the log: how one request was routed ---------- + + function renderLog() { + const r = pinned || cur; + log.hidden = !r; + if (!r) return; + logHead.replaceChildren( + el("span", "", pinned ? t("How the request at {time} was routed", { time: clock(r.time) }) : t("How the last request was routed")), + el("span", "grow")); + if (pinned) { + const live = el("button", "text", t("Back to live")); + live.onclick = () => { pinned = null; stageFor(newest()); renderAll(); }; + logHead.append(live); + } + const items = []; + items.push([t("{agent} asked for {model}", { agent: agentName(r.agent), model: r.model }) + " → " + (r.order.find((x) => !x.fallback)?.name || r.provider), ""]); + items.push([firstWhy(r), "why"]); + for (const a of asides(r)) items.push([a, "aside"]); + r.tries.forEach((_, i) => items.push([tryWhy(r, i), r.tries[i].done ? (r.tries[i].status < 400 ? "ok" : "bad") : "wait"])); + if (r.done && !r.tries.length) items.push([t("Nothing was tried: {error}", { error: r.error || r.status }), "bad"]); + steps.replaceChildren(...items.map(([s, c]) => el("li", c, s))); + } + + // the strip of recent requests: pick one to see how it was routed + function renderHist() { + const rs = [...routes.values()].sort((a, b) => b.id - a.id).slice(0, 14); + hist.hidden = rs.length < 2; + hist.replaceChildren(el("span", "label", t("Recent"))); + for (const r of rs) { + const b = el("button", "rt-h" + (r.done ? r.status >= 400 ? " bad" : r.tries.length > 1 ? " moved" : "" : " wait")); + const sel = pinned ? pinned.id === r.id : cur?.id === r.id; + b.setAttribute("aria-pressed", String(sel)); + b.title = `${clock(r.time)} · ${r.model}` + (r.tries.length > 1 ? " · " + t("rerouted {n}×", { n: r.tries.length - 1 }) : "") + (r.done ? ` · ${r.status}` : ""); + b.append(el("i"), el("span", "", new Date(r.time).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" }))); + b.onclick = () => { + pinned = r.id === newest()?.id ? null : r; + gen++; trips = []; flying.clear(); for (const p of wires.querySelectorAll(".pkt")) p.remove(); + stageFor(r); renderAll(); + say(firstWhy(r)); + }; + hist.append(b); + } + } + + function renderAll() { render(); renderLog(); renderHist(); } + const newest = () => [...routes.values()].reduce((a, b) => (!a || b.id > a.id ? b : a), null); + + // ---------- playing a request ---------- + + const flying = new Map(); // packet → the id it is at + + async function play(id) { + let r = routes.get(id); + const k = [...r.order, ...(r.left || [])].map((w) => w.id).sort().join("\n"); + if (k !== key && active) { + // another set of accounts: wait for the stage to be free + queue.push(id); + if (queue.length > 2) { queue.shift(); } + return; + } + active++; + const g = gen; + stageFor(r); + say(firstWhy(r)); + const aside = asides(r).find((s) => s); + if (aside) say(aside, true); + renderAll(); + const dot = document.createElementNS(NS, "circle"); + dot.setAttribute("r", 4.5); + dot.setAttribute("class", "pkt"); + dot.setAttribute("cx", -20); + wires.appendChild(dot); + tick(src); + await travel(dot, wSrc, false, 380); + for (let i = 0; g === gen; ) { + r = routes.get(id); + if (i >= r.tries.length) { + if (r.done) break; + await until(() => g !== gen || routes.get(id).tries.length > i || routes.get(id).done); + continue; + } + const row = rows.get(r.tries[i].id); + if (!row) { i++; continue; } + tick(hub); + flying.set(dot, r.tries[i].id); + await travel(dot, row.wire, false, 420); + await until(() => g !== gen || routes.get(id).tries[i].done); + if (g !== gen) break; + r = routes.get(id); + const tr = r.tries[i]; + if (cur.id === id) cur = r; + if (tr.status < 400) { + // the reply's tokens are counted once the route is done + await until(() => g !== gen || routes.get(id).done); + r = routes.get(id); + say(tryWhy(r, i), true); + renderAll(); + dot.classList.add("back"); + dot.setAttribute("r", 4); + await travel(dot, row.wire, true, 360); + flying.delete(dot); + await travel(dot, wSrc, true, 320); + break; + } + row.li.classList.remove("hit"); void row.li.offsetWidth; row.li.classList.add("hit", "tagged"); + row.tg.textContent = `${tr.status} · ${failWord(tr.fail)}`; + setTimeout(() => row.li.classList.remove("tagged"), 1800); + say(tryWhy(r, i)); + renderAll(); + await travel(dot, row.wire, true, 300); + flying.delete(dot); + if (!tr.rest) { // that was the answer: the agent gets the error + dot.classList.add("err"); + await travel(dot, wSrc, true, 320); + break; + } + i++; + } + flying.delete(dot); + dot.remove(); + active--; + renderAll(); + if (!active && queue.length) play(queue.shift()); + } + + // ---------- the loop ---------- + + function frame(ts) { + if (shown()) { + const now_ = trips; trips = []; + for (const tr of now_) { + if (tr.g !== gen) { tr.res(); continue; } + const k = tr.ms ? Math.min(1, (ts - tr.t0) / tr.ms) : 1; + if (tr.dot && tr.p.getTotalLength) { + const e = k < .5 ? 2 * k * k : 1 - (-2 * k + 2) ** 2 / 2; + const len = tr.p.getTotalLength(), pt = tr.p.getPointAtLength((tr.rev ? 1 - e : e) * len); + tr.dot.setAttribute("cx", pt.x); + tr.dot.setAttribute("cy", pt.y); + } + if (k >= 1) tr.res(); else trips.push(tr); + } + if (ts < flipUntil) layout(); + if (capQ.length && ts - capAt > (capLo && !capQ[0].lo ? 500 : 1700)) show(capQ.shift()); + } else { + for (const tr of trips) tr.res(); + trips = []; + if (capQ.length) { show(capQ[capQ.length - 1]); capQ = []; } + } + requestAnimationFrame(frame); + } + // countdowns tick once a second + setInterval(() => { if (shown()) render(); }, 1000); + + function offline(msg) { + off.textContent = msg; + off.hidden = !msg; + for (const e of [top, stage, foot, hist, log]) e.hidden = !!msg; + } + + function empty() { + offline(""); + what.replaceChildren(el("b", "", t("Waiting for a request"))); + mode.textContent = t("Send one from any agent routed through magpie and it plays here as it happens: who routing put first and why, each try, and what each answered."); + srcIc.replaceChildren(icon("generic")); + srcName.textContent = t("your agent"); + srcSub.textContent = ""; + chip.hidden = true; + hubText(); + list.replaceChildren(el("li", "idle", t("No request yet"))); + say(t("Every request an agent sends to magpie shows up here, routed for real.")); + log.hidden = hist.hidden = true; + layout(); + } + + async function poll() { + for (;;) { + try { + const res = await fetch(`/api/gateway/trace?after=${seq}${loaded ? "&wait=1" : ""}`); + const d = await res.json(); + skew = at(d.now) - Date.now(); + mine = d.mine; + hubText(); + statB[0].textContent = d.totals.requests; + statB[1].textContent = d.totals.rerouted; + statB[2].textContent = d.totals.errors; + if (!mine) { + offline(t(providers?.gateway?.running ? "Another magpie serves the gateway; its routing plays live in that magpie's window." : "The gateway isn't running, so nothing is routed.")); + loaded = false; + await new Promise((r) => setTimeout(r, 5000)); + continue; + } + if (d.seq < seq) routes.clear(); // the gateway started over + seq = d.seq; + const first = !loaded; + const fresh = []; + for (const r of d.routes) { + if (!routes.has(r.id) && !first) fresh.push(r.id); + routes.set(r.id, r); + } + for (const id of [...routes.keys()].sort((a, b) => a - b).slice(0, -60)) routes.delete(id); + loaded = true; + if (first) { + offline(""); + const r = newest(); + if (r) { stageFor(r); say(firstWhy(r)); renderAll(); } else empty(); + } else { + if (cur && routes.has(cur.id) && !active) cur = routes.get(cur.id); + if (pinned && routes.has(pinned.id)) pinned = routes.get(pinned.id); + for (const id of fresh) if (!pinned) play(id); + wake(); + renderAll(); + } + } catch { + await new Promise((r) => setTimeout(r, 3000)); + } + } + } + + function hubText() { hubSub.textContent = (providers?.gateway?.url || "").replace(/^https?:\/\//, "") || t("gateway"); } + + // labels in the page's language, and again when it changes + function words() { + for (const s of stats.children) s.lastChild.textContent = t(s.dataset.label); + hubText(); + if (loaded) { if (cur) { stageFor(cur); renderAll(); } else empty(); } + } + new MutationObserver(words).observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] }); + new ResizeObserver(() => layout()).observe(stage); + words(); + requestAnimationFrame(frame); + poll(); +})(); diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 325ed5896..5830d2331 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -226,6 +226,7 @@ func ago(t time.Time) string { func providerRoutes(mux *http.ServeMux, w Windows, gw *gateway.Server) { importAppsRoutes(mux, gw) + traceRoutes(mux, gw) mux.HandleFunc("GET /api/providers", func(rw http.ResponseWriter, r *http.Request) { writeJSON(rw, providersState(gw)) }) diff --git a/internal/gui/trace.go b/internal/gui/trace.go new file mode 100644 index 000000000..ec9232cae --- /dev/null +++ b/internal/gui/trace.go @@ -0,0 +1,35 @@ +package gui + +import ( + "net/http" + "strconv" + "time" + + "github.com/yetone/magpie/internal/gateway" +) + +// 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 + Now time.Time `json:"now"` +} + +// 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, gw *gateway.Server) { + mux.HandleFunc("GET /api/gateway/trace", func(rw http.ResponseWriter, r *http.Request) { + out := traceJSON{TraceState: gateway.TraceState{Routes: []gateway.Route{}}, Mine: gw != nil} + 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) + } + out.Now = time.Now() + writeJSON(rw, out) + }) +}