diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 1476d4eee..82ae0621a 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -252,7 +252,7 @@ recorded as a prediction failure (`noPrediction`). - An error's own status beats the words (#4855). A provider that already sent its 200 can only say what went wrong in an in-stream error frame — a plugin's runtime watching a clock, aborting at 285s and emitting `{"error":{…,"code":"upstream_timeout","status":504}}` — and the frame is relayed to the client as it came. The status it names on a member of the error object (`namedStatusOf`, a number 400–599, `status` first, Gemini's relays' `code`; a string code is not one) is what the failure fails and rests as, before `streamStatus` guesses one from the message's words, wherever the frame is read: a held stream's error event (`errOf` in `streamEvent`), a whole 200 body that is only an error (`errorReply`), a carried error's words (`carriedStatus`), and a reply already streaming, whose turn rests at the status the sniffer noted on the try (`namedStatusHeader`, kept from the client; `failedNamed`/`restAfterMarked`) — so a terse frame naming 429 rests as a rate limit, not `other` at a word-guessed 502, and the rest says "Gateway Timeout", not "OK". With no such member, a status the words name as one, "(HTTP 503)" or "(HTTP 503)" (`textStatus`, `httpSaid`), counts too, for a 429 or a 5xx only, since a 4xx a message quotes may be someone else's ("the image link answered (HTTP 404)"): wps-lingxi's AuditFailed and AIError frames name theirs that way (mycf_711). A reply already streaming when its frame came is booked at that status as well, in Routing and Usage, though the client's 200 went out. Words magpie wrote itself (`magpieSaid`: the loop guard's `loopGuardSaid`, `emptyReply`, `reloopedError`) and words saying the request is too long name no status, whatever members they carry: a LAN peer's loop guard frame carries 502 in its Gemini shape, and is no failure of the provider, so it neither rests the route nor is booked as one (`lateRests`). An error naming no status reads exactly as before. `TestRelayStreamErrorFrameSaysItsStatus`, `TestRelayStreamErrorFrameWithoutStatusAsBefore`, `TestRelayStreamErrorFrameNamesItsStatusInWords`, `TestNamedStatusOf` in [`stream_frame_status_test.go`](../../internal/gateway/stream_frame_status_test.go). - A request is one usage record, counted once by how it ended (小一 on Discord: Codex on credits showed "5,482 · 1,094 failed" while rows said "2 tries/3 tries" and had been answered). The final record carries `tries` when the route took more than one (`rec.Tries`, from the trace's `Tries`). A try a vendor refused or turned away (`hw.refused`, `hw.turnedAway`) still writes its own record, for what it billed and why it failed, marked `handed_on`; so does any other try that failed, billed something and handed the request on, to another account or member or the same one again (`failedRow` in `serve`, written once the next try begins): a Claude subscription run that failed after Anthropic's `message_start` had written the conversation to that account's cache, and the next account wrote it again, while the Usage page counted the second alone (hhxk233 and Kayrainforest on X; `relay` keeps the reply start's usage on a failure, `TestClaudeSubscriptionFailedTryKeepsItsTokens`). A try that failed before anything was billed has no record; `usage.Totals.count` skips such a record for calls and failures. A request failed only when the agent got an error (`LostRequest`); one answered after a failed try is counted beside it as answered on a retry (`Totals.Retried`, `RetriedRequest`, the `retried` filter). Logs written before `handed_on` are read the same way: the log index marks a failed, non-rejected record followed by another of the same route id as handed on (`routeRows` in [`log_index.go`](../../internal/usage/log_index.go)). Counts by account or route (`vias`, window holds) still count every try. A turn relayed on Codex's own ChatGPT sign-in is recorded as that codex account (`codexServed` in [`codex_backend.go`](../../internal/gateway/codex_backend.go)), so the account card's window counts it; the Routing view still names the seat OpenAI, an API-key call stays `openai` with no account, as does one whose `chatgpt-account-id` isn't the account Codex's auth.json here is signed in to (a Codex in WSL or under another `CODEX_HOME`), and a row already written without an account is left as it is. Those relay rows are still not a lead's answerer (`loggedAnswers`, #1367); a row an account answered, its host `host as email`, still is. - A failed call is in `app.log` too, not only the Routing page and the usage ledger (wjh66 on Discord: Codex's "error decoding response body" after "reconnecting 5/5", and the log had nothing of the turn). `record` writes each call whose status is 400 or more, or that carries an error, as one line (`failedCallLine`: agent, model, provider, status, time, the error to 300 characters); the same failure again within a minute is counted into the next line, not written (`failedLogEvery`), so a client asking in a loop can't fill the log. A Codex reply relayed from the ChatGPT backend that ends before its last event also says which side ended it (`codexEndedEarly` in [`codex_backend.go`](../../internal/gateway/codex_backend.go)): the read of OpenAI's stream that failed, with its error, or a clean end; and the client gone, a write to it that failed, or the failure passed on as `response.failed`, with the bytes passed on. reqwest, Codex's HTTP client, says "error decoding response body" for any read of a body whose connection broke, so only this line tells the legs apart. A gateway that ends with requests still in flight logs that they were cut (`srv.Shutdown`'s error; on Windows there is no handover, so an update or quit cuts a stream after `shortDrain`) (`TestCodexReplyBrokenOffLogged`, `TestCodexClientGoneLogged`, `TestFailedCallLineOncePerMinute`). -- Each record keeps the service tier three ways (#1784): `tier_asked` is what the client's body asked (`bodyTier`; Claude's speed fast reads `fast`), `tier_sent` is what that try's last request went out with, noted in `forwardOnce` after every rewrite (fast picks, Ultrafast to priority on a plan without it) onto the per-attempt `wireAt`, and `tier_served` is only what the reply said it ran at (`upstreamTier`, read by the sniffer and the translated readers), empty when it says nothing; from the ChatGPT backend (CodexBase's host) its `auto` and `default` are empty too, since it says them whether priority ran or not (`servedTierAt`, applied in `attempt` and `codexUpstreamOn`). The route's tries carry `tier` and `tier_served` the same way. A bridge that doesn't go through `forwardOnce` (the Claude subscription, Cursor's built-in) leaves `tier_sent` empty. Code: [`tier_record.go`](../../internal/gateway/tier_record.go). +- Each record keeps the service tier three ways (#1784): `tier_asked` is what the client's body asked (`bodyTier`; Claude's speed fast reads `fast`), `tier_sent` is what that try's last request went out with, noted in `forwardOnce` after every rewrite (fast picks, Ultrafast to priority on a plan without it) onto the per-attempt `wireAt`, and `tier_served` is only what the reply said it ran at (`upstreamTier`, read by the sniffer and the translated readers), empty when it says nothing; from the ChatGPT backend (CodexBase's host) its `auto` and `default` are empty too, since it says them whether priority ran or not (`servedTierAt`, applied in `attempt` and `codexUpstreamOn`). The route's tries carry `tier` and `tier_served` the same way, on Codex's own sign-in (`codexUpstreamOn`) too, which before set only the route's `tier`, so a `/fast` turn there showed nothing (Anotiaww on X). The Routing page's request row shows a try's tier as a quiet tag beside the model (`fast` for `priority`, `Ultrafast`, `flex`; an in-flight row the route's asked tier), with the served tier in its title when the reply said another (`rowTier` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js), `routing-service-tier.test.cjs`). A bridge that doesn't go through `forwardOnce` (the Claude subscription, Cursor's built-in) leaves `tier_sent` empty. Code: [`tier_record.go`](../../internal/gateway/tier_record.go). - An agent's fast pick (`settings.FastPicks`, the bolt in its picker, #954) may also be in `settings.UltraPicks` (#1954), offered by the GUI only where one of Codex's accounts lists Ultrafast on the model (`provider.CanUltra`, `UltraModels`). `fastPick` marks its candidates `ultra`; a try of one goes with `service_tier: "ultrafast"` on Chat and Responses, and an agent on Messages carries it in the context (`withUltra`) to `forwardTranslated`, which sets `Request.Ultrafast` for the ChatGPT backend. Either way the same check as a client's own Ultrafast ask applies, now on Chat as well as Responses: an account whose list doesn't offer it is put after a mate that does (`tierMate`), or, with none left, sent `priority`. A Chat body's own `service_tier: "ultrafast"` is parsed as Ultrafast too (`chat.go`). `TestUltraPickSentUltrafast`. - A group's member may be Ultrafast as well as fast (`Group.Ultra`, a subset of `Fast`, `Group.SetMemberTier`; the member's button steps Standard speed, Fast, Ultrafast where `ultraOK`; `ultra=` in `magpie group`), and a model has its own speed (`settings.ModelTiers`, "/" to `priority` or `ultrafast`, `provider.SetModelTier`, Model settings and `magpie model tier`; kdajenks on X). The gateway sends it on a direct pick for an agent with no fast pick of its own (`provider.ModelTier`, the branch after `IsFastPick`), through the same `fastPick`, so an account without Ultrafast is sent `priority`. A group member goes as the group says. `TestModelTierSentToEveryAgent`, `TestGroupMemberUltrafast`, `model-speed.test.cjs`. - Codex's service tier (`settings.CodexServiceTier`, a row in Codex's settings, JackyFill on X) sets the `service_tier` of every request of Codex's, whatever Codex's own `/fast` asked: empty is as Codex asks (the default, nothing changed), `default` sends none (standard), `priority` is Codex's Fast and `ultrafast` its Ultra Fast (the request values in Codex's `ServiceTier`; Flex is not offered, since the ChatGPT backend's requests drop it in `codex_request.go`). `codexTiered` ([`codex_tier.go`](../../internal/gateway/codex_tier.go)) rewrites the body as it comes in, on both of Codex's ways in: `codexBackend` (Codex signed in, `/backend-api/codex`) and the main handler's Codex-on-Responses block, which a websocket turn reaches too. Everything after treats it as Codex's own ask: an account whose list lacks Ultrafast is put after a mate that offers it (`tierMate`) or sent `priority`, and a provider that refuses a tier drops it. A model with no provider (`gpt-…`, Codex's own sign-in, whose plan magpie doesn't know) is sent `ultrafast` only where one of magpie's Codex accounts lists it on the model (`UltraModels`), else `priority`. Another agent's request is never touched, and fast picks still apply after. `TestCodexServiceTierSet`, `codex-service-tier.test.cjs`. diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 8a2657e55..a94974948 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -1107,6 +1107,10 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st model := modelOf(body) kept.model = model // only a turn is kept alive (overload) effort = requestEffort(provider.Responses, body) + // the service tier the body goes out at, on the route and on each + // of its tries as the accounts loop's tries say it, so the Routing + // page's row tells a /fast turn (priority) apart (Anotiaww on X) + tier := bodyTier(provider.Responses, body) seat := Weighed{ID: "codex", Provider: "openai", Name: "OpenAI", Icon: "openai", Who: who, Kind: "account", Agent: "codex", Model: model} link := s.titlePrompts.observe(r, body, metadata, kind, start) captureTitle = link != nil && isTitleKind(kind) @@ -1121,8 +1125,8 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st user = on.Account.User } window := cmp.Or(provider.CodexWindow(user, model), catalog.ContextOf(model)) - tr = s.trace.beginFor(r, Route{turn: turn, window: window, dirOf: dirOf(provider.Responses, body), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, callerOf(r).agent), imageProvider: imageProvider, TitleLink: link, Time: start, Agent: callerOf(r).agent, Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, kind), Kind: kind, Model: model, Effort: effort, Tier: bodyTier(provider.Responses, body), Provider: "openai", Subagent: subagentPickOf(r), - Order: []Weighed{seat}, Tries: []Try{{ID: seat.ID, Model: model, Effort: effort, Start: start}}}) + tr = s.trace.beginFor(r, Route{turn: turn, window: window, dirOf: dirOf(provider.Responses, body), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, callerOf(r).agent), imageProvider: imageProvider, TitleLink: link, Time: start, Agent: callerOf(r).agent, Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, kind), Kind: kind, Model: model, Effort: effort, Tier: tier, Provider: "openai", Subagent: subagentPickOf(r), + Order: []Weighed{seat}, Tries: []Try{{ID: seat.ID, Model: model, Effort: effort, Tier: tier, Start: start}}}) if m := noteMasked(r, "chat", maskedHits, sentOf(maskedHits, body), tr.ID, "openai", model); m != nil { s.trace.update(tr, func(t *Route) { t.Masked = m }) } @@ -1171,6 +1175,9 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st if prompt != nil { t.Prompt = prompt.calibrated(promptCounted(t.Usage), window) } + // what the reply said it ran at; the ChatGPT backend's + // "auto"/"default" tell nothing (servedTierAt) + try.TierServed = servedTierAt(provider.HostOf(base), uu.Tier) try.Served, try.Swapped = served, swapped(model, served) t.Served, t.Swapped = try.Served, try.Swapped }) @@ -1206,7 +1213,8 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st rec := usage.Record{RouteID: tr.ID, Time: began, Agent: callerOf(r).agent, Provider: servedProvider, Host: provider.HostOf(base), ProviderAccount: servedAccount, Model: modelOf(body), Requested: modelOf(body), Effort: effort, Millis: time.Since(began).Milliseconds(), Status: status, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), - Kind: kind, Endpoint: r.URL.Path, HandedOn: true} + Kind: kind, Endpoint: r.URL.Path, HandedOn: true, + TierAsked: bodyTier(provider.Responses, body), TierSent: bodyTier(provider.Responses, body)} failedWith(&rec, status, msg, "") appendUsage(r, rec) tried = append(tried, fmt.Sprintf("openai: %d %s", status, msg)) @@ -1230,7 +1238,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st began, nt = time.Now(), &netTrace{} s.trace.update(tr, func(t *Route) { again := t.Tries[0] - t.Tries = append(t.Tries, Try{ID: again.ID, Model: again.Model, Effort: again.Effort, Start: began}) + t.Tries = append(t.Tries, Try{ID: again.ID, Model: again.Model, Effort: again.Effort, Tier: again.Tier, Start: began}) }) first, titleReply = firstToken{start: start, onFirst: s.trace.firstContent(tr)}, capturedBody{} return true diff --git a/internal/gateway/tier_chatgpt_test.go b/internal/gateway/tier_chatgpt_test.go index 5849cdf97..c0cedc6fa 100644 --- a/internal/gateway/tier_chatgpt_test.go +++ b/internal/gateway/tier_chatgpt_test.go @@ -134,3 +134,42 @@ func TestOpenAIAPITierKept(t *testing.T) { } } } + +// Anotiaww on X: a Codex /fast turn (service_tier "priority") on Codex's +// own sign-in showed nothing of it on the Routing page. The relayed +// route, and its try, says the tier the body went out at, the backend's +// "auto"/"default" left unknown; a turn without /fast says none. +func TestCodexRelayRouteSaysTier(t *testing.T) { + setup(t, provider.Chat, &fake{t: t}) + chatgpt(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `data: {"type":"response.created","response":{"id":"r1","service_tier":"auto"}}`, + `data: {"type":"response.completed","response":{"id":"r1","service_tier":"default","usage":{"input_tokens":9,"output_tokens":2}}}`)) + }) + s := New() + for i, tier := range []string{"priority", ""} { + body := `{"model":"gpt-5.5","stream":true,"input":"hi"}` + if tier != "" { + body = `{"model":"gpt-5.5","stream":true,"input":"hi","service_tier":"` + tier + `"}` + } + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer chatgpt-token") + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("%q: %d %s", tier, rec.Code, rec.Body) + } + st := s.Trace(t.Context(), 0, 0) + if len(st.Routes) != i+1 { + t.Fatalf("%q routes: %+v", tier, st.Routes) + } + r := st.Routes[len(st.Routes)-1] // in the order they came + if r.Order[0].Who != "Codex's own sign-in" || r.Tier != tier || len(r.Tries) != 1 || !r.Tries[0].Done || r.Tries[0].Tier != tier || r.Tries[0].TierServed != "" { + t.Errorf("%q route: tier %q order %+v tries %+v", tier, r.Tier, r.Order, r.Tries) + } + if sr := sessionRouteOf(r); sr.Tier != tier || sr.AskedTier != tier || sr.TierServed != "" { + t.Errorf("%q session route: %+v", tier, sr) + } + } +} diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 6e1b18308..2070122bb 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4284,6 +4284,7 @@ const I18N = { "as the group's effort says": "按分组的推理强度设置", "whatever the agent asks": "无论 Agent 要求什么", "fast": "快速", + "flex": "弹性", "Fast": "快速", "Standard speed": "标准速度", "Sent at this speed with every request for {id} from an agent with no fast pick of its own; where an account has no Ultrafast it goes fast": "{id} 的每个请求(没有自己快速选择的 Agent 发出的)都按这个速度发;账号没有极速时按快速发", @@ -9508,6 +9509,7 @@ const I18N = { "as the group's effort says": "按分組的推理強度設定", "whatever the agent asks": "無論 Agent 要求什麼", "fast": "快速", + "flex": "彈性", "Fast": "快速", "Standard speed": "標準速度", "Sent at this speed with every request for {id} from an agent with no fast pick of its own; where an account has no Ultrafast it goes fast": "{id} 的每個請求(沒有自己快速選擇的 Agent 發出的)都按這個速度發;帳號沒有極速時按快速發", @@ -14751,6 +14753,7 @@ const I18N = { "as the group's effort says": "グループの推論レベルに従う", "whatever the agent asks": "エージェントの指定にかかわらず", "fast": "高速", + "flex": "Flex", "Fast": "高速", "Standard speed": "通常速度", "Sent at this speed with every request for {id} from an agent with no fast pick of its own; where an account has no Ultrafast it goes fast": "{id} へのリクエストのうち、独自の高速指定を持たないエージェントのものは、すべてこの速度で送ります。アカウントに超高速がなければ高速で送ります", @@ -20002,6 +20005,7 @@ const I18N = { "as the group's effort says": "gemäß Effort der Gruppe", "whatever the agent asks": "egal was der Agent verlangt", "fast": "schnell", + "flex": "Flex", "Fast": "Schnell", "Standard speed": "Standardgeschwindigkeit", "Sent at this speed with every request for {id} from an agent with no fast pick of its own; where an account has no Ultrafast it goes fast": "Jede Anfrage an {id} von einem Agenten ohne eigene Schnell-Auswahl wird so gesendet; hat ein Konto kein Ultrafast, geht sie schnell", diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index 18fb5d924..ba9130964 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -4351,7 +4351,7 @@ function routingPage(part) { // all the row says, and its titles const title = reqTitle(r, how, tr); const sig = JSON.stringify([lang, said, how, title, r.time, r.agent, name, ag?.icon, r.model, r.provider, tagKind(r), r.effort, - tr?.effort, tr?.picked, tr?.fixed, tr?.fast, tr?.entry, tr?.entryWhy, tr?.swapped && tr.done && tryOk(tr) ? [tr.model, tr.served] : 0, tr?.routed && tr.done && tryOk(tr) ? tr.served : 0, tr?.done && tryOk(tr) ? tr.upstream : 0, meta, metrics, cost]); + tr?.effort, tr?.picked, tr?.fixed, tr?.fast, r.tier, tr?.tier, tr?.tierServed, tr?.done, tr?.entry, tr?.entryWhy, tr?.swapped && tr.done && tryOk(tr) ? [tr.model, tr.served] : 0, tr?.routed && tr.done && tryOk(tr) ? tr.served : 0, tr?.done && tryOk(tr) ? tr.upstream : 0, meta, metrics, cost]); s = { lang, shows, name, icon, cost, said, how, tr, ag, meta, metrics, title, sig }; rowSaid.set(r, s); return s; @@ -4650,6 +4650,23 @@ function routingPage(part) { kids.forEach((k, i) => { if (i < was.length) morphRow(was[i], k); else old.append(k); }); for (let i = kids.length; i < was.length; i++) was[i].remove(); } + // rowTier: the service tier a request's row says it went at, in the + // words its tag takes ("fast", "ultrafast", "flex"), "" for the usual + // one. The try's own tier once it has gone out (what was sent, a tier + // its provider drops included), the one asked for while it is on its way. + const TIER_TAG = { priority: "fast", fast: "fast", ultrafast: "ultrafast", flex: "flex" }; + function rowTier(r, tr) { + const v = tr?.tier || (tr?.done ? "" : r.tier) || ""; + return TIER_TAG[String(v).toLowerCase()] || ""; + } + function tierNote(r, tr, tier) { + const word = tr?.tier || r.tier; + const said = tr?.fast ? t("Sent in its vendor's fast mode, as the group says") + : tier === "flex" ? t("Sent at its vendor's flex tier (service tier {tier}): slower, at a lower price", { tier: word }) + : t("Sent in its vendor's fast mode (service tier {tier}): quicker, at a higher price", { tier: word }); + const served = tr?.tierServed && tr.tierServed !== tr.tier ? t("Its reply said it ran at {tier}.", { tier: tr.tierServed }) : ""; + return served ? `${said}\n${served}` : said; + } function reqRow(r, said, how, tr, ag, meta, metrics, title) { const b = el("button", "rt-req " + how); const when = el("span", "at", rowClock(r.time)); @@ -4687,10 +4704,13 @@ function routingPage(part) { ef.title = effortNote(r, tr); to.append(ef); } - if (tr?.fast) { - // sent in its vendor's fast mode, as the group's member is - const ft = el("span", "ef", t("fast")); - ft.title = t("Sent in its vendor's fast mode, as the group says"); + const tier = rowTier(r, tr); + if (tr?.fast || tier) { + // sent in its vendor's fast mode, as the group's member is, or at + // the service tier the request went out at: Codex's /fast asks + // for priority (Anotiaww on X), Claude's for speed "fast" + const ft = el("span", "ef tier", tier === "ultrafast" ? t("Ultrafast") : tier === "flex" ? t("flex") : t("fast")); + ft.title = tierNote(r, tr, tier); to.append(ft); } if (tr?.entry) { diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js index ead63316c..768b162f8 100644 --- a/internal/gui/assets/plugins/routing/i18n.js +++ b/internal/gui/assets/plugins/routing/i18n.js @@ -370,6 +370,9 @@ magpie.strings({ "Off: kept in its place, sent nothing. Click to switch it on": "已停用:保留位置,不会收到请求。点击启用", "On: requests may go to it. Click to switch it off and keep its place": "已启用:请求可能发给它。点击停用(保留位置)", "Sent in its vendor's fast mode, as the group says": "按分组设置,以服务商的快速模式发送", + "Sent in its vendor's fast mode (service tier {tier}): quicker, at a higher price": "以服务商的快速模式发送(service tier {tier}):更快,价格更高", + "Sent at its vendor's flex tier (service tier {tier}): slower, at a lower price": "以服务商的弹性档发送(service tier {tier}):更慢,价格更低", + "Its reply said it ran at {tier}.": "回复说它以 {tier} 运行。", "{level} reasoning: the model's nearest to the {asked} {agent} asked for": "{level} 推理强度:模型最接近 {agent} 要求的 {asked} 的档位", "{level} reasoning, as {agent} asked": "{level} 推理强度,按 {agent} 的要求", "Jev is asked once as each turn begins, with the message and what it said of the turn before. Its calls show in the usage as magpie’s own.": "每轮开始时问 Jev 一次,附上消息和它对上一轮的判断。其调用在用量中记为 magpie 自身的。", @@ -1117,6 +1120,9 @@ magpie.strings({ "Off: kept in its place, sent nothing. Click to switch it on": "已停用:保留位置,不會收到請求。點選啟用", "On: requests may go to it. Click to switch it off and keep its place": "已啟用:請求可能發給它。點選停用(保留位置)", "Sent in its vendor's fast mode, as the group says": "按分組設定,以服務商的快速模式傳送", + "Sent in its vendor's fast mode (service tier {tier}): quicker, at a higher price": "以服務商的快速模式傳送(service tier {tier}):更快,價格更高", + "Sent at its vendor's flex tier (service tier {tier}): slower, at a lower price": "以服務商的彈性檔傳送(service tier {tier}):更慢,價格更低", + "Its reply said it ran at {tier}.": "回覆說它以 {tier} 執行。", "{level} reasoning: the model's nearest to the {asked} {agent} asked for": "{level} 推理強度:模型最接近 {agent} 要求的 {asked} 的檔位", "{level} reasoning, as {agent} asked": "{level} 推理強度,按 {agent} 的要求", "Jev is asked once as each turn begins, with the message and what it said of the turn before. Its calls show in the usage as magpie’s own.": "每輪開始時問 Jev 一次,附上訊息和它對上一輪的判斷。其呼叫在用量中記為 magpie 自身的。", @@ -1862,6 +1868,9 @@ magpie.strings({ "Off: kept in its place, sent nothing. Click to switch it on": "オフ:位置は維持し、何も送りません。クリックでオン", "On: requests may go to it. Click to switch it off and keep its place": "オン:リクエストが送られることがあります。クリックで位置を維持したままオフ", "Sent in its vendor's fast mode, as the group says": "グループの設定どおり、ベンダーの高速モードで送ります", + "Sent in its vendor's fast mode (service tier {tier}): quicker, at a higher price": "ベンダーの高速モードで送りました(service tier {tier})。速くなりますが、料金は高くなります", + "Sent at its vendor's flex tier (service tier {tier}): slower, at a lower price": "ベンダーの Flex 階層で送りました(service tier {tier})。遅くなりますが、料金は安くなります", + "Its reply said it ran at {tier}.": "応答では {tier} で実行されたとのことです。", "{level} reasoning: the model's nearest to the {asked} {agent} asked for": "{level} の推論:{agent} が指定した {asked} に最も近いモデルのレベル", "{level} reasoning, as {agent} asked": "{level} の推論({agent} の指定どおり)", "Jev is asked once as each turn begins, with the message and what it said of the turn before. Its calls show in the usage as magpie’s own.": "Jev にはターンの開始時に 1 回、メッセージと前のターンについての判定を添えて尋ねます。その呼び出しは使用量に magpie 自身のものとして表示されます。", @@ -2609,6 +2618,9 @@ magpie.strings({ "Off: kept in its place, sent nothing. Click to switch it on": "Aus: behält seinen Platz, erhält nichts. Zum Einschalten klicken", "On: requests may go to it. Click to switch it off and keep its place": "An: Anfragen können dorthin gehen. Klicken, um es auszuschalten und den Platz zu behalten", "Sent in its vendor's fast mode, as the group says": "Im Schnellmodus des Anbieters gesendet, gemäß Gruppe", + "Sent in its vendor's fast mode (service tier {tier}): quicker, at a higher price": "Im Schnellmodus des Anbieters gesendet (Service-Tier {tier}): schneller, zu höherem Preis", + "Sent at its vendor's flex tier (service tier {tier}): slower, at a lower price": "In der Flex-Stufe des Anbieters gesendet (Service-Tier {tier}): langsamer, zu niedrigerem Preis", + "Its reply said it ran at {tier}.": "Laut Antwort lief sie mit {tier}.", "{level} reasoning: the model's nearest to the {asked} {agent} asked for": "{level} Reasoning: die Stufe des Modells, die dem von {agent} verlangten {asked} am nächsten liegt", "{level} reasoning, as {agent} asked": "{level} Reasoning, wie von {agent} verlangt", "Jev is asked once as each turn begins, with the message and what it said of the turn before. Its calls show in the usage as magpie’s own.": "Jev wird zu Beginn jeder Runde einmal gefragt, mit der Nachricht und seiner Einschätzung der vorigen Runde. Seine Aufrufe erscheinen in der Nutzung als eigene von magpie.", diff --git a/internal/gui/tests/routing-service-tier.test.cjs b/internal/gui/tests/routing-service-tier.test.cjs new file mode 100644 index 000000000..f7f26273a --- /dev/null +++ b/internal/gui/tests/routing-service-tier.test.cjs @@ -0,0 +1,116 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The Routing page's request row says the service tier a request went out +// at (Anotiaww on X: a Codex /fast turn, service_tier "priority", showed +// nothing of it): one quiet chip beside the model, "fast" for priority, +// "Ultrafast", "flex", its title naming the tier and, when the reply said +// another, what it said. A request in flight shows the tier it asked for; +// one that went out without it (a provider that drops the tier) and one +// that asked none show no chip. A group member sent fast keeps its one +// chip and its own title. Chromium and WebKit, 1000 and 480 wide, in +// every language, the API faked. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const now = new Date(); +const at = (i) => new Date(now.getTime() - (i + 1) * 9e3).toISOString(); +const seat = { id: "codex", provider: "openai", name: "OpenAI", who: "Codex's own sign-in", kind: "account", agent: "codex", model: "gpt-6.1-sol" }; +// newest first +const RUNS = [ + { tier: "priority", try: { tier: "priority" } }, // Codex /fast on its own sign-in + { tier: "priority", try: { tier: "priority", tierServed: "default" } }, // the reply said another + { tier: "ultrafast", try: { tier: "ultrafast" } }, + { tier: "flex", try: { tier: "flex" } }, + { tier: "priority", try: {} }, // went out without it + { try: {} }, // asked none + { try: { fast: true, tier: "priority" } }, // a group member sent fast + { tier: "priority", live: true, try: {} }, // on its way +]; +const routes = RUNS.map((run, i) => ({ + id: 100 - i, seq: 100 - i, time: at(i), agent: "codex", model: "gpt-6.1-sol", provider: "openai", ...(run.tier ? { tier: run.tier } : {}), + order: [seat], done: !run.live, status: run.live ? 0 : 200, ms: 5000, ttft: 900, tokens: 1000, + tries: [{ id: seat.id, model: "gpt-6.1-sol", start: at(i), done: !run.live, status: run.live ? 0 : 200, ms: 5000, ...run.try }], +})); + +const W = { + en: { fast: "fast", ultra: "Ultrafast", flex: "flex", + f: (t) => `Sent in its vendor's fast mode (service tier ${t}): quicker, at a higher price`, + x: (t) => `Sent at its vendor's flex tier (service tier ${t}): slower, at a lower price`, + r: (t) => `Its reply said it ran at ${t}.`, g: "Sent in its vendor's fast mode, as the group says" }, + zh: { fast: "快速", ultra: "极速", flex: "弹性", + f: (t) => `以服务商的快速模式发送(service tier ${t}):更快,价格更高`, + x: (t) => `以服务商的弹性档发送(service tier ${t}):更慢,价格更低`, + r: (t) => `回复说它以 ${t} 运行。`, g: "按分组设置,以服务商的快速模式发送" }, + "zh-TW": { fast: "快速", ultra: "極速", flex: "彈性", + f: (t) => `以服務商的快速模式傳送(service tier ${t}):更快,價格更高`, + x: (t) => `以服務商的彈性檔傳送(service tier ${t}):更慢,價格更低`, + r: (t) => `回覆說它以 ${t} 執行。`, g: "按分組設定,以服務商的快速模式傳送" }, + ja: { fast: "高速", ultra: "超高速", flex: "Flex", + f: (t) => `ベンダーの高速モードで送りました(service tier ${t})。速くなりますが、料金は高くなります`, + x: (t) => `ベンダーの Flex 階層で送りました(service tier ${t})。遅くなりますが、料金は安くなります`, + r: (t) => `応答では ${t} で実行されたとのことです。`, g: "グループの設定どおり、ベンダーの高速モードで送ります" }, + de: { fast: "schnell", ultra: "Ultrafast", flex: "Flex", + f: (t) => `Im Schnellmodus des Anbieters gesendet (Service-Tier ${t}): schneller, zu höherem Preis`, + x: (t) => `In der Flex-Stufe des Anbieters gesendet (Service-Tier ${t}): langsamer, zu niedrigerem Preis`, + r: (t) => `Laut Antwort lief sie mit ${t}.`, g: "Im Schnellmodus des Anbieters gesendet, gemäß Gruppe" }, +}; + +function serve(lang) { + const state = { agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3)); + return json({ mine: true, now: now.toISOString(), seq: 100, totals: { requests: routes.length, rerouted: 0, errors: 0 }, routes }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(W)) for (const width of [1000, 480]) { + test(`${engine} ${lang} ${width}px: a request row says the service tier it went at`, async (t) => { + const w = W[lang]; + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + await page.goto("http://magpie.test/?view=routing"); + await page.locator(".rt-req").nth(routes.length - 1).waitFor(); + const chips = await page.locator(".rt-req").evaluateAll((rows) => rows.map((r) => { + const cs = [...r.querySelectorAll(".ef.tier")]; + const c = cs[0], b = c?.getBoundingClientRect(), rb = r.getBoundingClientRect(); + return c ? { n: cs.length, text: c.textContent.trim(), title: c.title, inside: b.width > 0 && b.left >= rb.left - 1 && b.right <= rb.right + 1 } : null; + })); + assert.deepEqual(chips.map((c) => c && [c.n, c.text, c.title]), [ + [1, w.fast, w.f("priority")], + [1, w.fast, `${w.f("priority")}\n${w.r("default")}`], + [1, w.ultra, w.f("ultrafast")], + [1, w.flex, w.x("flex")], + null, + null, + [1, w.fast, w.g], + [1, w.fast, w.f("priority")], + ]); + assert(chips.every((c) => !c || c.inside), "each chip sits inside its row"); + assert.deepEqual(errors, []); + }); + } +}