From 78667e9b770c9d669705322c9d61caa4471f462e Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 3 Nov 2026 20:33:48 +0800 Subject: [PATCH] gateway: a request in flight shows its model's context window packinggoods on Discord: Routing's context window card said "the model's window isn't known" for a request on remote-magpie/claude/claude-opus-5-5 that was still answering, though the remote magpie's list gives that model's window. The window was put on a route's prompt only when the request ended (calibrate at the route's end). A live request always showed it as unknown, on every provider. Now the window of the model a try goes to is read as the try goes out. That is windowOf(c.p, c.model), the same call the route's end makes. It is kept on the route (Route.window, unexported), and the prompt shows it while the request is under way (livePrompt). This holds whether the prompt is read before or after the try starts. A fallback to another model updates it. At the end the answering model's window still comes first, as before. Codex turns through magpie's Codex backend now work out Codex's own window (CodexWindow, else models.dev) when the turn begins, not when it ends, so they show it live too. Run at this head (rebased on fb1f4856a), on mote: - go test ./internal/gateway -run 'Window|Prompt|Context|Trace|Codex': ok - GOOS=linux and GOOS=windows go vet ./internal/gateway: ok; gofmt clean Run before the rebase (base 7d022bdb6; since then main changed only gateway-key code in internal/gateway): - go test -count=1 -timeout 45m ./internal/gateway: ok (724s) - go vet (darwin, linux, windows) ./internal/gateway: ok Broken by hand: TestLivePromptHasItsWindow, run on the old code, is red in both subtests ("in flight: prompt &{Window:0 ...}, want the window 1000000", and Codex's 272000). The done route was right on the old code too. Not tried: a real remote magpie on another computer. The test serves its /v1/models window through catalog.SaveLive, as the remote's list does. --- internal/gateway/codex_backend.go | 22 ++-- internal/gateway/gateway.go | 5 + internal/gateway/live_prompt_window_test.go | 129 ++++++++++++++++++++ internal/gateway/prompt.go | 17 ++- internal/gateway/trace.go | 12 +- 5 files changed, 168 insertions(+), 17 deletions(-) create mode 100644 internal/gateway/live_prompt_window_test.go diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 51a92f073..5de988e65 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -1047,7 +1047,16 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st captureTitle = link != nil && isTitleKind(kind) turn, scan := agentTurnOf(r, kind) tools = scan - tr = s.trace.beginFor(r, Route{turn: turn, 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), + // the window Codex holds the conversation to, not models.dev's + // for the id, which is OpenAI's API's (netube on Discord: 922K + // on Routing for a Codex Plus account's 272K), known as the turn + // goes out (livePrompt) + user := "" + if on != nil && on.Account != nil { + 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}}}) 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 }) @@ -1062,17 +1071,6 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st replyDigest = titleReplyDigest(titleReply.buf.Bytes(), nil) } prompt := promptRead() // outside the trace's lock, which reading it takes - // the window Codex holds the conversation to, not models.dev's - // for the id, which is OpenAI's API's (netube on Discord: 922K - // on Routing for a Codex Plus account's 272K) - window := 0 - if prompt != nil { - user := "" - if on != nil && on.Account != nil { - user = on.Account.User - } - window = cmp.Or(provider.CodexWindow(user, model), catalog.ContextOf(model)) - } s.trace.update(tr, func(t *Route) { // what masking took: magpie's own time isn't split here t.Masking = maskingMs(r.Context(), 0) diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index e1cbf2792..2b2e2d04c 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3443,9 +3443,14 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro attemptBody, updated = b, true } } + window := windowOf(c.p, c.model) // as the route's end reads it s.trace.update(tr, func(t *Route) { t.imageProvider = c.p.ID t.Tries = append(t.Tries, Try{ID: c.rest, Model: c.model, Effort: sent, Picked: picked, Fixed: fixed, RuleEffort: ruled, Fast: fast, Start: began}) + t.window = window + if t.Prompt != nil && !t.Done { + t.Prompt = livePrompt(t.Prompt, window) + } }) held := false // answered as its vendor did a moment ago, without asking var heldBack time.Time // when the first of those held out of their allowance is back diff --git a/internal/gateway/live_prompt_window_test.go b/internal/gateway/live_prompt_window_test.go new file mode 100644 index 000000000..2c26d9afd --- /dev/null +++ b/internal/gateway/live_prompt_window_test.go @@ -0,0 +1,129 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// packinggoods on Discord: a request still answering on a remote magpie's +// claude-opus-5-5 had Routing's context window card say the model's window +// isn't known, though its list gives it: the window was set on the route +// only once the request was done. A request in flight is in the window of +// the model its try went to, from the moment its prompt is read, on the +// gateway's routes and on a Codex turn through magpie's Codex backend +// alike; done, it keeps it. +func TestLivePromptHasItsWindow(t *testing.T) { + // held: an upstream that starts its reply and holds it until let go, + // so the request is in flight while the trace is read + held := func(t *testing.T, start string) (http.HandlerFunc, func()) { + release := make(chan struct{}) + var once sync.Once + let := func() { once.Do(func() { close(release) }) } + return func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, start) + w.(http.Flusher).Flush() + select { + case <-release: + case <-r.Context().Done(): + } + }, let + } + // inFlight sends req and returns the route's prompt once it has been + // read while the request is still answering, then the route as done + inFlight := func(t *testing.T, s *Server, req *http.Request, let func()) (live, done *Prompt) { + t.Helper() + rec := httptest.NewRecorder() + finished := make(chan struct{}) + go func() { + defer close(finished) + s.Handler().ServeHTTP(rec, req) + }() + t.Cleanup(func() { let(); <-finished }) + route := func() (Route, bool) { + for _, r := range s.Trace(t.Context(), 0, 0).Routes { + return r, true + } + return Route{}, false + } + // wait on the state: the prompt read, and the try gone out + for deadline := time.Now().Add(20 * time.Second); ; time.Sleep(5 * time.Millisecond) { + if r, ok := route(); ok && r.Prompt != nil && len(r.Tries) > 0 { + if r.Done { + t.Fatalf("done before it was let go: %+v", r) + } + if r.Prompt.Window > 0 || time.Now().After(deadline) { + live = r.Prompt + break + } + } + if time.Now().After(deadline) { + t.Fatal("the request never showed in flight with its prompt") + } + } + let() + <-finished + r, _ := route() + return live, r.Prompt + } + + t.Run("remote magpie", func(t *testing.T) { + fresh(t) + h, let := held(t, `data: {"id":"x","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":"o"}}]}`+"\n\n") + up := httptest.NewServer(h) + t.Cleanup(up.Close) + t.Cleanup(let) // before the server's Close, which waits on it + if err := provider.Save(provider.Provider{ID: "remote-magpie", Name: "Remote", Preset: provider.RemoteMagpiePreset, Key: "sk-magpie-x", Chat: up.URL}); err != nil { + t.Fatal(err) + } + // the other magpie's /v1/models, which says the window + if err := catalog.SaveLive("remote-magpie", up.URL+"/v1", []catalog.Model{{ID: "claude/claude-opus-5-5", Context: 1000000}}); err != nil { + t.Fatal(err) + } + req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"remote-magpie/claude/claude-opus-5-5","stream":true,"messages":[{"role":"user","content":"refactor the parser"}]}`)) + live, done := inFlight(t, New(), req, let) + if live == nil || live.Window != 1000000 { + t.Errorf("in flight: prompt %+v, want the window 1000000", live) + } + if done == nil || done.Window != 1000000 { + t.Errorf("done: prompt %+v, want the window 1000000", done) + } + }) + + t.Run("codex backend", func(t *testing.T) { + h, let := held(t, `data: {"type":"response.created","response":{"id":"r1"}}`+"\n\n") + chatgpt(t, h) + t.Cleanup(let) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + catalog.Reset() + t.Cleanup(catalog.Reset) + codexChatGPTAuth(t, "plus@example.com") + if err := os.WriteFile(filepath.Join(os.Getenv("CODEX_HOME"), "models_cache.json"), []byte(`{"etag":"\"e1\"","client_version":"0.159.0","models":[ + {"slug":"gpt-5.5","display_name":"GPT-5.5","priority":1,"visibility":"list","context_window":272000,"max_context_window":272000}]}`), 0o644); err != nil { + t.Fatal(err) + } + req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":[ + {"type":"message","role":"user","content":[{"type":"input_text","text":"refactor the parser"}]}]}`)) + req.Header.Set("Authorization", "Bearer chatgpt-token") + req.Header.Set("chatgpt-account-id", "acct-1") + live, done := inFlight(t, New(), req, let) + if live == nil || live.Window != 272000 { + t.Errorf("in flight: prompt %+v, want Codex's window 272000", live) + } + if done == nil || done.Window != 272000 { + t.Errorf("done: prompt %+v, want Codex's window 272000", done) + } + }) +} diff --git a/internal/gateway/prompt.go b/internal/gateway/prompt.go index 826bdb713..ee6eeee13 100644 --- a/internal/gateway/prompt.go +++ b/internal/gateway/prompt.go @@ -1229,6 +1229,21 @@ func windowFor(id, model string) int { return windowOf(*p, model) } +// livePrompt is p as a route still answering shows it: in the window of +// the model its try went to, read as the try went out (packinggoods on +// Discord: a request in flight on a remote magpie's claude-opus-5-5 said +// the model's window isn't known, its window set only once it was done). +// p itself is left as it is, for the route's end to scale and give the +// window of the model that answered. +func livePrompt(p *Prompt, window int) *Prompt { + if p == nil || window <= 0 || p.Window == window { + return p + } + c := *p + c.Window = window + return &c +} + // inspectPrompt reads the request's prompt beside it, putting the estimate // in the trace as soon as it is read; wait returns it, for the route's // end to scale to what was counted. masked is the body as the vendor would @@ -1242,7 +1257,7 @@ func (s *Server) inspectPrompt(tr *Route, from provider.Protocol, body, masked [ s.trace.keepBody(tr.ID, from, masked, plain) s.trace.update(tr, func(t *Route) { if t.Prompt == nil { - t.Prompt = p + t.Prompt = livePrompt(p, t.window) } }) } diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index 967acaa40..66e151223 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -58,10 +58,14 @@ type Route struct { // starts; tools, whether its reply called a tool; offFeed, it left // the trace unfinished (drop, trim) and the route-events feed was // told it went, so it hears no more of it - turn bool - offFeed bool - dirOf func() string - tools *toolScan + turn bool + offFeed bool + dirOf func() string + tools *toolScan + // window: the context window of the model the try under way went to, + // known as it goes out, so a request still answering shows how full + // its window is (livePrompt) and not only once it is done + window int Seq int64 `json:"seq"` // the trace's count when it last changed ID int64 `json:"id"` Time time.Time `json:"time"`