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.
This commit is contained in:
yetone
2026-11-03 20:49:32 +08:00
parent 6cfe786351
commit 78667e9b77
5 changed files with 168 additions and 17 deletions
+10 -12
View File
@@ -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)
+5
View File
@@ -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
+129
View File
@@ -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)
}
})
}
+16 -1
View File
@@ -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)
}
})
}
+8 -4
View File
@@ -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"`