Skip to content

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

gateway: images, videos and embeddings are listed on Routing (zzzkl3994)

yetone5f6a46630a8a
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index 5f74fea42..a262990fc 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -39,7 +39,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md).
| Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). A routing group named for a drawing or a video (`drawingGroup`: `group/<id>`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). Pause rules and a gateway key's group hold apply as for a chat. A failed drawing rests no member and no key. An account out of quota for the image model (`failure` reads `failQuota`) rests that model on it alone (`restDrawer`, keyed by `restID`), until the reset its refusal names (`resetsAt`: Antigravity's "Your quota will reset after 3h19m30s.") or `quotaRest`, so the next drawing asks the accounts that still have it first (`restLast`), and the account's text models stay in. Antigravity also tells a model's quota used up as a 200 whose stream is the error; `drawCodeAssist` gives such an error the status its words stand for (`saidStatus`: quota or rate 429, credit 402, else 502), as the images API's 200 with no image does, so a spent account hands the drawing to the next one as its 429 does (01huadalang on Discord: a 502 ended the drawing on the spent account; `TestAntigravityDrawingOutOfQuotaInsideTheReplyGoesOn`, `TestAntigravityDrawingQuotaRestsTheImageModel`). `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. Such a group may be Settings → Images → Image generation's pick (7up6666 on X): the list offers each routing group with a member among its provider's `Drawers` (`GroupDraws`), so a request naming no model, the Magpie Image MCP's included, draws on the group; a picked group none of whose members draws any more is `DrawerMissing` (`drawerMissing`), the row says so and Automatic draws in its place. `TestImageGroupPickedInSettingsDraws`, `TestImageGenOffersDrawingGroups`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. A drawing is given Settings → Images → Image generation timeout (`imageTimeout`, 1 to 60 minutes, 5 when unset; neighbads on X: a slow image endpoint needed more) as its context's deadline (`drawTimeout`, `drawWithin`), and so is downloading an image answered as a link (`imageLongest`, never under `ImageLongest`). A drawing's request goes through a transport with no `ResponseHeaderTimeout` (`drawsApart`), since an images API sends its headers only once it has drawn, and every other request keeps `upstreamHeaderWait` (10 minutes). A video's submit, status and download calls keep 5 minutes each (`videoTimeout`). The `magpie mcp image` process, which may not read these settings (WSL), waits on a call up to `callLongest` (two hours and a minute), so it never cuts one the gateway still waits on. `TestLongImageTimeoutLetsASlowVendorFinish`, `TestImageTimeoutSettingReachesTheVendor`, `TestOnlyDrawingsWaitPastTheHeaderWait`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) |
| Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. A conversation is kept by its id (`conversationID`), and a Claude Code subagent's apart from its lead's by `x-claude-code-agent-id` (`stickKey`): Claude Code sends the session's id with its subagents' requests too, and a subagent's answer took the lead's stick over, so the lead's next turn was judged by the subagent's cache and moved to another account, where its whole conversation was written again (slkassinthehood on X, `TestClaudeConversationKeepsItsAccountsCache`). Behind a remote magpie, the key or account is the remote's key and the provider there that serves the model, its id's first part (`remoteUpstream`, `candidate.vendor`, `sameVendor`): the remote is one key here, but each of its providers keeps its own cache and seals, so a conversation is kept, held strictly, told its sealed reasoning was refused and given its native compaction's reader by that pair, as the same group on the remote does (fremontdango on Discord: a group of one model from two of the remote's providers kept a conversation on the second as the same account when the first was gone, and a strict one failed over to it; `TestRemoteMagpieStrictKeepsTheRemotesProvider`, `TestRemoteMagpieOtherProviderIsNotTheSameAccount`). A remote's group is one vendor by its whole id, its own routing deciding inside it; a model named without a provider is the key alone. Lanes and requests a minute still go by the key here, the limits the user set on it. | [`affinity.go`](../../internal/gateway/affinity.go) |
| One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A provider of the user's set not to check its certificate (`InsecureTLS`, #2383) has it skipped for its own base URLs' hosts alone, through `p.Via` ([Providers and accounts](providers-accounts.md)). Every request to one vendor's host shares one HTTP/2 connection (`upstreamTransport`); one with no frame for 20s is pinged, and dropped when no answer comes within 10s (`netproxy.HTTP2Health`, on `http.DefaultTransport` too), so a connection gone silent without closing (a proxy's way out died, a NAT forgot the flow) fails the requests on it, which move on as a 502 does, and the next request dials a new one. A live vendor answers a ping whatever its streams are doing, so a long wait for a first byte is not cut by it (#2843: a group's requests hung with no first byte until a restart; `TestGroupMovesOnFromSilentHTTP2Connection`). A large body (64KB or more, or of no stated length) is pinged too, as a silent connection takes a body that fits its send buffer, but its ping's answer is queued behind the body's own DATA, so on a slow uplink a working connection loses it (#3909: a ~680KB turn on a 2-10KB/s uplink failed every try). Such a body whose connection was dropped for a lost ping is sent once more, through `GetBody`, on a new connection that is not pinged and is given up on when a write moves no bytes for a minute (`uploadTransport`); for 30 minutes after, large bodies go there at once (`drawsApart.slow`; `TestUploadStillUnderwayIsNotCutByHealthPing`, `TestSlowUplinkSkipsTheLostTry`, `TestLargeBodyOnSilentConnectionIsSentAgain`). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. An account that only streams (`Account.Stream`: a plugin's, and most subscriptions magpie signs in to) has a request that asked for one body translated, which magpie always asks streamed, except a plugin's on Responses (`gathers`): that is relayed all the same, asked with `stream:true`, and the client given the `response` of the stream's `response.completed` (or `response.incomplete`) as one JSON body (`gathered` in [`gathered.go`](../../internal/gateway/gathered.go); its `output` filled from the stream's `response.output_item.done` items, or else its text, when that event's is empty). So the tools the vendor runs itself, and its response's `tools` and usage details, reach the client (plugins#112: a translation dropped Grok's `x_search`, and Grok answered without searching; `TestGrokPluginNonStreamKeepsHostedTools`). A stream that fails or ends before that event is a 502 (`TestGrokPluginNonStreamEndedShort`), never an empty 200. A Messages request is still translated, its stream having no event that holds the whole reply, and so is a subscription magpie signs in to itself (the ChatGPT backend's, Qoder's): its own code fits its requests. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`, `catalog.WrongEndpoint`: the English wordings and AgentRouter's Chinese one, #3766, read escaped too; a model's test reads them as well, see [Providers and accounts](providers-accounts.md)) is remembered in `unfit` until magpie restarts. A Chat API that refuses function tools with reasoning, with no other API to take them to, is asked once more with `reasoning_effort` `none` (#176), unless `none` is known refused (`turnedAway`); `none` refused naming the levels, the tools refusal is the answer, not a retry at the lowest level (#2670). When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. | [`gateway.go`](../../internal/gateway/gateway.go) |
-| Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. `Route.Folder` is the folder the agent says it works in (`workDir`), its last two levels only (`shortFolder`, e.g. `workspace/magpie`), never the full path; a request that says none (a title, a topic check) takes its session's as said last (`trace.sessionFolder`), one without a session id has none (#1068). It is kept in the routing history on disk for as long as the route is (`history.go`: 30 days, 200 MB). The GUI shows it in By session's headings, a request row's tooltip, the stage's agent working in more than one folder, and the tray panel's agent tooltip. | [`trace.go`](../../internal/gateway/trace.go) |
+| Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. `Route.Folder` is the folder the agent says it works in (`workDir`), its last two levels only (`shortFolder`, e.g. `workspace/magpie`), never the full path; a request that says none (a title, a topic check) takes its session's as said last (`trace.sessionFolder`), one without a session id has none (#1068). It is kept in the routing history on disk for as long as the route is (`history.go`: 30 days, 200 MB). The GUI shows it in By session's headings, a request row's tooltip, the stage's agent working in more than one folder, and the tray panel's agent tooltip. | [`trace.go`](../../internal/gateway/trace.go) A request outside the chat path gets a route of its own too ([`media_route.go`](../../internal/gateway/media_route.go), `sideRoute`): an image (`images`, each account `drawOnAccounts` asks a try), a video's start (`videosCreate`; its polls and download are the same video and add none) and an embedding, rerank or transcription (`retrieve`). Each try's key or account is put in `Order` so the page finds its seat, the route's `Kind` stays empty, and the one usage row names it in `RouteID` (zzzkl3994 on Discord: a video the magpie-image MCP made was in Usage's requests and not on Routing; `TestVideoIsOnRoutingOnce`, `TestImageIsOnRouting`, `TestEmbeddingAndRerankAreOnRouting`). |
| Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. `inspectPrompt` reads it from the body as the agent sent it, before translation; `calibrated` scales the estimate to the prompt the vendor counted and sets the window of the model that answered. The route keeps names and sizes only, never the text, so the routing history on disk holds none. For the card's text (masaka on Discord), the trace keeps the last `promptBodies` (10) request bodies in memory only (at most 32 MiB each, 64 MiB together), masked as the vendor got them; for a model let have it unmasked, the body is kept as it went and masked when `PromptText` first reads it, so the request itself never waits on masking (#3973). `PromptText` reads a part's items and their text from that body again (`prompt_text.go`), served to the GUI as `/api/context/text`; once a body is dropped, or magpie quits, its text is gone. It goes on the trace as `Route.Prompt`, with `Route.Conv` naming a conversation that has no session id. The GUI's `/api/context` scores each agent from it (`internal/gui/context.go`). A session's line and its compactions are its own turns': a call with a `Kind`, a Claude Code subagent's (`Route.Sub`, from `x-claude-code-agent-id`), and, in a session whose turns carry tool definitions, a request without any (auto mode's classifier, the title, the quota check) are left out, so a classifier's 40K after a 100K turn is no compaction (`toolSessions`, `TestContextSideCallsAreNoCompaction`). | [`prompt.go`](../../internal/gateway/prompt.go) |
| Vertex AI | A [Google Vertex AI provider](providers-accounts.md#responsibilities-and-sources-of-truth) speaks Gemini for its Gemini models, and chat completions for its partner models. A partner model (`provider.VertexPartner`: a `publisher/model` id such as `deepseek-ai/deepseek-v4.1-flash-maas`) goes to Google's OpenAI-compatible `<base>/endpoints/openapi/chat/completions` (`Base(Chat)`, `ListedAPIs`), signed with the same token, its full id in the body. It is relayed or translated there as any chat completions vendor is, and none of the Gemini rules below (`vertexEffort`, `vertexThinking`, signatures) touch it (`TestVertexPartnerModel`). A Gemini model's request goes to `<base>/publishers/google/models/<model>:streamGenerateContent?alt=sse` (`provider.VertexPath`, `upstreamPath`), the model named as the user's upstream name for it says (`UpstreamNameIn`, which the usage log's endpoint names too), with no `model` or `stream` field in its body (`passthrough`, `forwardOnce`, `geminiRequest`). A Gemini client's request is relayed as it came, its own `thinkingConfig`, `safetySettings` and the rest kept: streamed there, asked whole to `:generateContent` (`provider.VertexWholePath`), which answers one JSON body (Factory's rule of translating a whole request, as its route only streams, isn't Vertex AI's). Every other API's is translated (`buildFor`, `buildVertex`) and its stream read by `codeAssistDecoder`, which gives thought parts as reasoning, never as the answer's text. Effort: `vertexEffort` fits it to the model's levels, reasoning turned off going as `minimal` fitted the same way, and holds a model whose levels aren't known to `low`…`high`. `vertexThinking` sends Gemini 3 a `thinkingLevel` (`includeThoughts` false with reasoning off) and 2.5 a `thinkingBudget` in the model's range (`vertexBudgets`): turned off, the budget that stops its thinking, or Pro's least, as Pro can't stop. Thought signatures are every Gemini path's (#1445): a call's signature reaches the client in its id (`signedID`) and goes back on the call it came on, while a call with none in a step Vertex AI signed goes without; a step with nothing to give back has every call sent `skip_thought_signature_validator`. A 400 `Invalid thought signature.` is asked again with every call sent so (`withoutSignatures`), for that request only. A 400 refusing `minimal` (`geminiRefusedLevel`) is asked again at the model's lowest other level (`onEffort`), and `markUnfit(offRefused)` keeps that level until magpie restarts. Both retries are the translated path's. Vertex AI's own Google Search grounding isn't used: `searchHosts` names only `generativelanguage.googleapis.com` for Gemini, so magpie searches for it (`search.go`). | [`vertex.go`](../../internal/gateway/vertex.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codeassist.go`](../../internal/gateway/codeassist.go), [`gemini.go`](../../internal/gateway/gemini.go), [`gemini_signature.go`](../../internal/gateway/gemini_signature.go), [`search.go`](../../internal/gateway/search.go) |
| Bedrock Mantle | A request on chat completions or Responses to an [Amazon Bedrock Mantle provider](providers-accounts.md#responsibilities-and-sources-of-truth) goes to the prefix that serves its model (`mantleRoutes`, `provider.MantleBase` in `forwardOnce`): `/openai/v1` for OpenAI's closed GPTs and xAI's Grok, `/v1` for the rest. A model Mantle refuses there with "model `x` isn't supported on this route" (a maker the rule doesn't know yet) is asked once more at the other prefix, and when it is taken there that prefix is remembered for the model in `unfit` (`mantleRouteKey`) until the gateway restarts. A model refused at both gets the first refusal and nothing is remembered (`mantleReroute`). Messages go to `/anthropic` alone. | [`mantle.go`](../../internal/gateway/mantle.go), [`gateway.go`](../../internal/gateway/gateway.go) |
diff --git a/internal/gateway/draw.go b/internal/gateway/draw.go
index 24e4e38b5..0c74c502b 100644
--- a/internal/gateway/draw.go
+++ b/internal/gateway/draw.go
@@ -553,9 +553,16 @@ func (s *Server) images(edit bool) http.HandlerFunc {
fail(maskStatus(err), err.Error())
return
}
- noteMasked(r, "image", hits, d.Prompt, 0, p.ID, call.Model)
+ // the Routing page lists it as it does a chat, each account or
+ // member asked a try of its one route (sideRoute)
+ var grp *GroupRef
+ if isGroup {
+ grp = groupRef(g, ms)
+ }
+ side := s.beginSide(r, start, call.Model, p.ID, grp)
+ side.masked(noteMasked(r, "image", hits, d.Prompt, side.id(), p.ID, call.Model))
call.Provider, call.To = p.ID, provider.Chat
- ctx, cancel := drawWithin(r.Context(), drawTimeout())
+ ctx, cancel := drawWithin(withSide(r.Context(), side), drawTimeout())
defer cancel()
// the account that drew, or refused last, is the one recorded
var (
@@ -588,7 +595,8 @@ func (s *Server) images(edit bool) http.HandlerFunc {
if p.Account == nil && p.Key != "" {
providerKeyID, providerKeyName = provider.KeyID(p.Key), p.KeyName
}
- appendUsage(r, usage.Record{Operation: "generate_content", Time: start, Agent: call.Agent, Via: call.Via, Provider: p.ID, Host: p.Where(), Model: model, Requested: call.Model, ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: accountOf(p),
+ side.end(p, model, call.Status, err, Usage{Input: out.Input, Output: out.Output})
+ appendUsage(r, usage.Record{RouteID: side.id(), Operation: "generate_content", Time: start, Agent: call.Agent, Via: call.Via, Provider: p.ID, Host: p.Where(), Model: model, Requested: call.Model, ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: accountOf(p),
Input: out.Input, Output: out.Output, Millis: call.Millis, Status: call.Status, Session: sessionOf(r.Header)})
if err != nil {
call.Error = err.Error()
@@ -918,7 +926,9 @@ func viaFor(p provider.Provider, model string) drawVia {
func (s *Server) drawOnAccounts(ctx context.Context, r *http.Request, p provider.Provider, model string, d drawing) (provider.Provider, drawn, int, time.Time, error) {
if p.Account == nil && p.Key == "" {
// no key and no account (a local ollama): nothing to go over
+ tried := sideOf(ctx).try(candidateOf(p, model))
out, code, err := s.draw(ctx, p, model, d)
+ tried(code, err)
return p, out, code, time.Time{}, err
}
q := p
@@ -970,7 +980,9 @@ func (s *Server) drawOnAccounts(ctx context.Context, r *http.Request, p provider
var err error
for i, c := range cs {
p = c.p
+ tried := sideOf(ctx).try(c)
out, code, err = s.draw(ctx, p, model, d)
+ tried(code, err)
if err != nil && ctx.Err() == nil {
restDrawer(c, code, err.Error())
}
diff --git a/internal/gateway/embeddings.go b/internal/gateway/embeddings.go
index 71bb8b2ac..359d1220e 100644
--- a/internal/gateway/embeddings.go
+++ b/internal/gateway/embeddings.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
"net/http"
@@ -174,6 +175,13 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
tries = probeOne(tries) // of those resting, only the one back soonest (#1799)
var skipped []string
went := asked // the model the last try asked for
+ // the Routing page lists it as it does a chat, each account, key or
+ // member asked a try of its one route (sideRoute)
+ var grp *GroupRef
+ if isGroup {
+ grp = groupRef(g, ms)
+ }
+ side := s.beginSide(r, start, asked, tries[0].p.ID, grp)
// unless every try is on this machine or the local network, set
// to go unmasked (provider.SkipsRedaction)
if slices.ContainsFunc(tries, func(c candidate) bool { return !c.p.SkipsRedaction() }) {
@@ -185,6 +193,7 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
defer done()
if err != nil { // fails closed
call.Status, call.Error = maskStatus(err), err.Error()
+ side.end(tries[0].p, tries[0].model, call.Status, err, Usage{})
writeError(w, provider.Chat, call.Status, err.Error())
s.record(call)
return
@@ -195,27 +204,33 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
}
// the record names the try that had it last, not the first
// planned (noteMaskedUntil)
- _, noted := noteMaskedUntil(r, what, hits, sent, 0, tries[0].p.ID, asked)
+ masked, noted := noteMaskedUntil(r, what, hits, sent, side.id(), tries[0].p.ID, asked)
+ side.masked(masked)
defer func() { noted(call.Provider, went) }()
}
for i, c := range tries {
last := i == len(tries)-1
call.Provider, went = c.p.ID, c.model
base := strings.TrimRight(c.p.Base(provider.Chat), "/")
+ tried := side.try(c)
if base == "" {
msg := fmt.Sprintf("%s has no OpenAI-style API for %s", c.p.Name, path)
+ tried(400, errors.New(msg))
if !last {
skipped = append(skipped, c.label()+": "+msg)
continue
}
call.Status, call.Error, call.Millis = 400, msg, time.Since(start).Milliseconds()
call.Fallback = strings.Join(skipped, "; ")
+ side.end(c.p, c.model, 400, errors.New(msg), Usage{})
writeError(w, provider.Chat, 400, msg)
s.record(call)
return
}
out, ctype, err := req.forModel(c.model)
if err != nil {
+ tried(400, err)
+ side.end(c.p, c.model, 400, err, Usage{})
call.Status, call.Error, call.Millis = 400, err.Error(), time.Since(start).Milliseconds()
writeError(w, provider.Chat, 400, err.Error())
s.record(call)
@@ -224,6 +239,7 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
ctx, cancel := context.WithTimeout(r.Context(), retrieveTimeout)
b, got, code, err := s.retrieveAs(ctx, c.p, base+path, ctype, out)
cancel()
+ tried(code, err)
call.Millis = time.Since(start).Milliseconds()
if err != nil && !last && r.Context().Err() == nil {
skipped = append(skipped, c.label()+": "+err.Error())
@@ -237,7 +253,8 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
if c.p.Account == nil && c.p.Key != "" {
providerKeyID, providerKeyName = provider.KeyID(c.p.Key), c.p.KeyName
}
- appendUsage(r, usage.Record{Operation: operation, Time: start, Agent: call.Agent, Via: call.Via, Provider: c.p.ID, Host: c.p.Where(), Model: c.model, Requested: asked, ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: accountOf(c.p),
+ side.end(c.p, c.model, code, err, Usage{Input: in, Output: outTokens})
+ appendUsage(r, usage.Record{RouteID: side.id(), Operation: operation, Time: start, Agent: call.Agent, Via: call.Via, Provider: c.p.ID, Host: c.p.Where(), Model: c.model, Requested: asked, ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: accountOf(c.p),
Input: in, Output: outTokens, Millis: call.Millis, Status: code, Session: sessionOf(r.Header)})
if err != nil {
call.Error = err.Error()
diff --git a/internal/gateway/media_route.go b/internal/gateway/media_route.go
new file mode 100644
index 000000000..41929707e
--- /dev/null
+++ b/internal/gateway/media_route.go
@@ -0,0 +1,145 @@
+package gateway
+
+import (
+ "context"
+ "net/http"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// sideRoute is the Routing page's route of a request the chat path doesn't
+// carry: an image, a video's start, an embedding, a rerank or a
+// transcription. Each wrote its usage row but began no route, so Usage
+// listed it and Routing never did (zzzkl3994 on Discord: a video the
+// magpie-image MCP made). One route stands for one request, its tries the
+// accounts, keys or group members asked in turn; a video's polls and its
+// download are the same generation and add none, as they add no usage row.
+// A nil sideRoute does nothing, so a caller with none goes on as before.
+type sideRoute struct {
+ s *Server
+ tr *Route
+ start time.Time
+}
+
+// beginSide begins r's side route: asked is the model as the caller named
+// it, prov the provider it resolved to first, group the routing group it
+// named (nil for none).
+func (s *Server) beginSide(r *http.Request, start time.Time, asked, prov string, group *GroupRef) *sideRoute {
+ who := callerOf(r)
+ tr := s.trace.beginFor(r, Route{Time: start, Agent: who.agent, Session: sessionOf(r.Header), Model: asked, Provider: prov,
+ Group: group, Order: []Weighed{}})
+ return &sideRoute{s: s, tr: tr, start: start}
+}
+
+// id is the route's id, which its usage row names (RouteID); 0 for none.
+func (sr *sideRoute) id() int64 {
+ if sr == nil {
+ return 0
+ }
+ return sr.tr.ID
+}
+
+// masked puts what masking swapped in the request on the route.
+func (sr *sideRoute) masked(m *Masked) {
+ if sr == nil || m == nil {
+ return
+ }
+ sr.s.trace.update(sr.tr, func(t *Route) { t.Masked = m })
+}
+
+// try begins a try on c, put in the route's order too when it isn't yet,
+// as the page finds a try's seat there; the func it answers ends it.
+func (sr *sideRoute) try(c candidate) func(status int, err error) {
+ return sr.tryAt(c, time.Now())
+}
+
+// tryAt is try for one begun at at, told once it is known who had it
+// (a video's start picks its key inside startVideo).
+func (sr *sideRoute) tryAt(c candidate, at time.Time) func(status int, err error) {
+ if sr == nil {
+ return func(int, error) {}
+ }
+ if c.rest == "" {
+ c.rest = candidateOf(c.p, c.model).rest
+ }
+ sr.s.trace.update(sr.tr, func(t *Route) {
+ t.Provider = c.p.ID
+ if !slices.ContainsFunc(t.Order, func(w Weighed) bool { return w.ID == c.rest && w.Model == c.model }) {
+ t.Order = append(t.Order, weighed(c, c.p, weighing{}, false, provider.Chat))
+ }
+ t.Tries = append(t.Tries, Try{ID: c.rest, Model: c.model, Start: at})
+ })
+ i := -1
+ sr.s.trace.update(sr.tr, func(t *Route) { i = len(t.Tries) - 1 })
+ return func(status int, err error) {
+ ms := time.Since(at).Milliseconds()
+ sr.s.trace.update(sr.tr, func(t *Route) {
+ if i < 0 || i >= len(t.Tries) {
+ return
+ }
+ try := &t.Tries[i]
+ try.Done, try.Status, try.Millis = true, status, ms
+ if err != nil {
+ try.Error = err.Error()
+ }
+ })
+ }
+}
+
+// end ends the route as the request ended: p and model the ones that had
+// it last, u what they counted. A route ends once; a second end is a no-op.
+func (sr *sideRoute) end(p provider.Provider, model string, status int, err error, u Usage) {
+ if sr == nil {
+ return
+ }
+ ms := time.Since(sr.start).Milliseconds()
+ sr.s.trace.update(sr.tr, func(t *Route) {
+ if t.Done {
+ return
+ }
+ if p.ID != "" {
+ t.Provider = p.ID
+ }
+ t.Done, t.Status, t.Millis, t.Tokens, t.Output = true, status, ms, u.Input+u.Output, u.Output
+ if err != nil {
+ t.Error = err.Error()
+ }
+ t.Usage = routeUsage(t.Provider, model, u)
+ })
+}
+
+// candidateOf is the candidate p, the key or account a request went out
+// on, stands for, named as perKeyBarred names it in rest: the account
+// signed in to by the provider's id, another by its user after an "@",
+// one of several keys by its key after a "#", else the provider alone.
+func candidateOf(p provider.Provider, model string) candidate {
+ c := candidate{p: p, model: model, rest: p.ID}
+ switch {
+ case p.Account != nil:
+ if own, err := provider.Find(p.ID); err == nil && own.Account != nil && !strings.EqualFold(own.Account.User, p.Account.User) {
+ c.rest = p.ID + "@" + p.Account.User
+ }
+ case p.Key != "" && len(p.KeysOn()) > 1:
+ c.rest = p.ID + "#" + provider.KeyID(p.Key)
+ }
+ return c
+}
+
+type sideRouteKey struct{}
+
+// withSide carries sr to the code that asks each account (drawOnAccounts).
+func withSide(ctx context.Context, sr *sideRoute) context.Context {
+ if sr == nil {
+ return ctx
+ }
+ return context.WithValue(ctx, sideRouteKey{}, sr)
+}
+
+// sideOf is the side route ctx carries, nil for none.
+func sideOf(ctx context.Context) *sideRoute {
+ sr, _ := ctx.Value(sideRouteKey{}).(*sideRoute)
+ return sr
+}
diff --git a/internal/gateway/media_route_test.go b/internal/gateway/media_route_test.go
new file mode 100644
index 000000000..19a9c13b4
--- /dev/null
+++ b/internal/gateway/media_route_test.go
@@ -0,0 +1,167 @@
+package gateway
+
+import (
+ "context"
+ "encoding/json"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/usage"
+)
+
+// usageRows waits for n usage rows of op, and answers those there are.
+func usageRows(t *testing.T, op string, n int) []usage.Record {
+ t.Helper()
+ var got []usage.Record
+ for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) {
+ got = got[:0]
+ for _, r := range usage.Load(time.Time{}) {
+ if r.Operation == op {
+ got = append(got, r)
+ }
+ }
+ if len(got) >= n {
+ break
+ }
+ }
+ return got
+}
+
+// oneSideRoute is the one route s has, done, which the one usage row of op
+// names: what Routing lists of a request Usage lists.
+func oneSideRoute(t *testing.T, s *Server, op string) (Route, usage.Record) {
+ t.Helper()
+ rows := usageRows(t, op, 1)
+ if len(rows) != 1 {
+ t.Fatalf("%d usage rows of %s, want 1: %+v", len(rows), op, rows)
+ }
+ routes := s.Trace(context.Background(), 0, 0).Routes
+ if len(routes) != 1 {
+ t.Fatalf("Routing lists %d routes, want the request's one: %+v", len(routes), routes)
+ }
+ tr := routes[0]
+ if !tr.Done || tr.ID == 0 || tr.ID != rows[0].RouteID {
+ t.Fatalf("route %d (done %v) isn't the one the usage row names (%d)", tr.ID, tr.Done, rows[0].RouteID)
+ }
+ if tr.Kind != "" {
+ t.Fatalf("route kind %q: the page would call it an unrecognized purpose", tr.Kind)
+ }
+ if tr.Agent == "" || tr.Agent != rows[0].Agent || tr.Session != rows[0].Session || tr.Status != rows[0].Status {
+ t.Fatalf("route %+v doesn't say what its usage row does: %+v", tr, rows[0])
+ }
+ // each try has its seat in the order, as the page finds it
+ for _, try := range tr.Tries {
+ found := false
+ for _, w := range tr.Order {
+ found = found || w.ID == try.ID && w.Model == try.Model
+ }
+ if !found || !try.Done {
+ t.Fatalf("try %+v (seated %v) in order %+v", try, found, tr.Order)
+ }
+ }
+ return tr, rows[0]
+}
+
+// zzzkl3994 on Discord: a video the magpie-image MCP made was in Usage's
+// requests and not on Routing's. Every request magpie sends is listed on
+// Routing: an image, a video's start (once, however often it is polled
+// and fetched) and an embedding, as a chat is, with its one usage row.
+func TestImageIsOnRouting(t *testing.T) {
+ s, _ := easeled(t)
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest("POST", "/v1/images/generations", strings.NewReader(`{"model":"art/gpt-image-1","prompt":"a magpie"}`))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("User-Agent", "claude-code/2.1.0 "+DrawAgent)
+ req.Header.Set("X-Magpie-Session", "draw-session")
+ s.Handler().ServeHTTP(rec, req)
+ if rec.Code != 200 {
+ t.Fatalf("%d %s", rec.Code, rec.Body)
+ }
+ tr, row := oneSideRoute(t, s, "generate_content")
+ if tr.Provider != "art" || tr.Model != "art/gpt-image-1" || tr.Status != 200 || tr.Session != "draw-session" || tr.Error != "" {
+ t.Fatalf("route %+v", tr)
+ }
+ if len(tr.Tries) != 1 || tr.Tries[0].ID != "art" || tr.Tries[0].Model != "gpt-image-1" || tr.Tries[0].Status != 200 {
+ t.Fatalf("tries %+v", tr.Tries)
+ }
+ if tr.Tokens != row.Input+row.Output || len(tr.Usage) == 0 {
+ t.Fatalf("route tokens %d usage %+v, row %+v", tr.Tokens, tr.Usage, row)
+ }
+}
+
+func TestFailedImageIsOnRouting(t *testing.T) {
+ grokSignedIn(t)
+ newGrokMedia(t)
+ s := New()
+ code, _, raw := postImages(t, s, "/v1/images/generations", "application/json", `{"model":"grok/grok-imagine-image","prompt":"REFUSED"}`)
+ if code != 400 {
+ t.Fatalf("%d %s", code, raw)
+ }
+ tr, _ := oneSideRoute(t, s, "generate_content")
+ if tr.Provider != "grok" || tr.Status != 400 || !strings.Contains(tr.Error, "moderation") || len(tr.Tries) != 1 || tr.Tries[0].ID != "grok" || tr.Tries[0].Status != 400 {
+ t.Fatalf("route %+v", tr)
+ }
+}
+
+func TestVideoIsOnRoutingOnce(t *testing.T) {
+ grokSignedIn(t)
+ newGrokMedia(t)
+ s := New()
+ code, obj, raw, _ := request(t, s, "POST", "/v1/videos", "application/json", `{"model":"grok/grok-imagine-video","prompt":"a kite sways"}`)
+ if code != 200 {
+ t.Fatalf("%d %s", code, raw)
+ }
+ id, _ := obj["id"].(string)
+ // generate_video's polls and its download are the same video
+ for range 3 {
+ if code, _, raw, _ = request(t, s, "GET", "/v1/videos/"+id, "", ""); code != 200 {
+ t.Fatalf("poll %d %s", code, raw)
+ }
+ }
+ if code, _, raw, _ = request(t, s, "GET", "/v1/videos/"+id+"/content", "", ""); code != 200 {
+ t.Fatalf("content %d %s", code, raw)
+ }
+ tr, _ := oneSideRoute(t, s, "generate_content")
+ if tr.Provider != "grok" || tr.Model != "grok/grok-imagine-video" || tr.Status != 200 || len(tr.Tries) != 1 || tr.Tries[0].ID != "grok" || tr.Tries[0].Model != "grok-imagine-video" {
+ t.Fatalf("route %+v", tr)
+ }
+}
+
+func TestRefusedVideoIsOnRouting(t *testing.T) {
+ grokSignedIn(t)
+ newGrokMedia(t)
+ s := New()
+ code, _, raw, _ := request(t, s, "POST", "/v1/videos", "application/json", `{"model":"grok/grok-imagine-video","prompt":"TOOLONG"}`)
+ if code != 400 {
+ t.Fatalf("%d %s", code, raw)
+ }
+ tr, _ := oneSideRoute(t, s, "generate_content")
+ if tr.Status != 400 || !strings.Contains(tr.Error, "Duration") || len(tr.Tries) != 1 || tr.Tries[0].Status != 400 {
+ t.Fatalf("route %+v", tr)
+ }
+}
+
+func TestEmbeddingAndRerankAreOnRouting(t *testing.T) {
+ for _, tc := range []struct{ path, op, body, model string }{
+ {"/v1/embeddings", "embeddings", `{"model":"lib/embed-1","input":["hello"]}`, "embed-1"},
+ {"/v1/rerank", "rerank", `{"model":"lib/rerank-1","query":"q","documents":["a","b"]}`, "rerank-1"},
+ } {
+ t.Run(tc.op, func(t *testing.T) {
+ s, _ := shelved(t)
+ if code, raw := postRetrieval(t, s, tc.path, tc.body); code != 200 {
+ t.Fatalf("%d %s", code, raw)
+ }
+ tr, row := oneSideRoute(t, s, tc.op)
+ var asked struct{ Model string }
+ json.Unmarshal([]byte(tc.body), &asked)
+ if tr.Provider != "lib" || tr.Model != asked.Model || tr.Status != 200 || len(tr.Tries) != 1 || tr.Tries[0].ID != "lib" || tr.Tries[0].Model != tc.model {
+ t.Fatalf("route %+v", tr)
+ }
+ if tr.Tokens == 0 || tr.Tokens != row.Input+row.Output {
+ t.Fatalf("route tokens %d, row %+v", tr.Tokens, row)
+ }
+ })
+ }
+}
diff --git a/internal/gateway/video.go b/internal/gateway/video.go
index f0c7b941b..05a5f2bd6 100644
--- a/internal/gateway/video.go
+++ b/internal/gateway/video.go
@@ -802,7 +802,16 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) {
sent += " " + string(b)
}
// the record names the member that had it last (noteMaskedUntil)
- _, noted := noteMaskedUntil(r, "video", hits, sent, 0, cmp.Or(call.Provider, p.ID), call.Model)
+ // the Routing page lists it as it does a chat, each member asked a
+ // try of its one route (sideRoute); its polls and download are the
+ // same video, and add none
+ var grp *GroupRef
+ if isGroup {
+ grp = groupRef(g, ms)
+ }
+ side := s.beginSide(r, start, call.Model, p.ID, grp)
+ masked, noted := noteMaskedUntil(r, "video", hits, sent, side.id(), cmp.Or(call.Provider, p.ID), call.Model)
+ side.masked(masked)
defer func() { noted(call.Provider, model) }()
if n > 0 && f.Prompt == prompt { // the prompt's mask wraps w already
var done func()
@@ -818,8 +827,10 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) {
)
for i, m := range tries {
model = m.Model
+ at := time.Now()
v, code, err = s.startVideo(ctx, r, m.Provider, m.Model, f)
p, call.Provider = v.p, v.p.ID
+ side.tryAt(candidateOf(v.p, m.Model), at)(code, err)
// a group's next member is asked as a chat's would be: while this
// one can't make videos, its vendor fails, is out of quota or
// doesn't serve the model; a refusal of the request is the request's
@@ -835,6 +846,7 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) {
if len(skipped) > 0 {
msg += " (tried first: " + call.Fallback + ")"
}
+ side.end(p, model, code, errors.New(msg), Usage{})
fail(code, msg)
return
}
@@ -849,7 +861,8 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) {
call.Status = code
}
}
- appendUsage(r, usage.Record{Operation: "generate_content", Time: start, Agent: call.Agent, Via: call.Via, Provider: p.ID, Host: p.Where(), Model: model, Requested: call.Model, ProviderAccount: accountOf(p),
+ side.end(p, model, call.Status, err, Usage{})
+ appendUsage(r, usage.Record{RouteID: side.id(), Operation: "generate_content", Time: start, Agent: call.Agent, Via: call.Via, Provider: p.ID, Host: p.Where(), Model: model, Requested: call.Model, ProviderAccount: accountOf(p),
Millis: call.Millis, Status: call.Status, Session: sessionOf(r.Header)})
if err != nil {
call.Error = err.Error()