diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index bf2bb1c3c..e7d43118a 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -58,13 +58,23 @@ The Codex app asks for titles, descriptions and one-line thread summaries whatever the conversation is on, and composer predictions (`composer_predictions`) on the thread's model. An unset setting ("Same as the session" in the picker) sends these on the session's model when it is -one of magpie's (`codexSideTo` with `Server.codexSessionOf`): the model the -conversation's own turns last went on (`codexLeads`), else, before any turn +one of magpie's (`codexSideTo` with `Server.codexSideSession`): the model the +conversation's own turns last went on (`codexLeads`: its parent's, the +thread it was forked from for a prediction, its own), else the last turn by +the gateway key, else, before any turn has come through magpie, `agent.CodexSideModel` (Codex's config `model`, when it is magpie's and magpie is not Codex's provider). So a conversation on a third-party model spends none of the ChatGPT account's allowance (atom_Ray on X), whether the model was picked in Codex's config or in the app (cybercaius -on Discord, `TestCodexAppSideTurnsFollowTheSession`). A session on Codex's +on Discord, `TestCodexAppSideTurnsFollowTheSession`). Codex writes a new +conversation's title on a temporary thread with no link to it, started as +the first message is sent, so it can arrive before that conversation's +first turn, when the key's last turn is the previous conversation's, on the +model the user just switched from. A call tied to no seen thread whose +key's last turn is older than 3s (`codexSideFresh`) waits, up to 5s +(`codexSideWait`) or its cancellation, for the next turn and takes its +model (`codexLeads.sideOf`, `TestCodexTitleBeforeTheFirstTurnFollowsTheSwitch`); +a later rename suggestion with no turn beside it waits the 5s. A session on Codex's own model sends them to ChatGPT as Codex sent them, whatever the config says (`TestCodexAppSideTurnsStayWithAnOwnModelSession`); so does a session model magpie can't serve now (turned off, gone, held from the caller's key). Summaries use diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 91b948f6e..9b5353e17 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -109,7 +109,7 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) { // still on Codex's own model, through its sign-in, when it says // nothing of them if rest == "/responses" { - session := func() string { return s.codexSessionOf(r, body) } + session := func() string { return s.codexSideSession(r, body) } if to := codexTitlesTo(r.Header, body, false, session); to != "" { s.codexTitle(w, r, body, to) return diff --git a/internal/gateway/codex_follow.go b/internal/gateway/codex_follow.go index fddce35af..33f199553 100644 --- a/internal/gateway/codex_follow.go +++ b/internal/gateway/codex_follow.go @@ -41,7 +41,10 @@ const codexLeadsCap = 512 type codexLeads struct { mu sync.Mutex thread map[string]codexLead - last map[string]string + last map[string]codexLead + // next is closed, and replaced, when any conversation's own turn + // comes (codexSideSession waits on it) + next chan struct{} } type codexLead struct { @@ -59,9 +62,13 @@ func (l *codexLeads) saw(r *http.Request, kind, model string) { l.mu.Lock() defer l.mu.Unlock() if l.thread == nil { - l.thread, l.last = map[string]codexLead{}, map[string]string{} + l.thread, l.last = map[string]codexLead{}, map[string]codexLead{} + } + l.last[key] = codexLead{model: model, at: time.Now()} + if l.next != nil { + close(l.next) + l.next = nil } - l.last[key] = model if thread == "" { return } @@ -78,21 +85,72 @@ func (l *codexLeads) saw(r *http.Request, kind, model string) { } // of is the model the conversation a side call was made for is on: its -// parent thread's (a subagent's lead, a review's conversation), else its -// own thread's, else the one this key's Codex last had a turn on. +// parent thread's (a subagent's lead, a review's conversation), the +// thread it was forked from (a composer prediction), else its own +// thread's, else the one this key's Codex last had a turn on. func (l *codexLeads) of(r *http.Request, body []byte) string { - parent := requestSessionMetadata(r.Header, body).Parent + model, _, _ := l.lookup(r, body) + return model +} + +// lookup is of, with whether the call's conversation was one magpie has +// seen a turn of, and when this key's last turn came when it wasn't. +func (l *codexLeads) lookup(r *http.Request, body []byte) (model string, tied bool, at time.Time) { + meta := requestSessionMetadata(r.Header, body) + parent := meta.Parent if parent == "" { parent = strings.TrimSpace(r.Header.Get("x-codex-parent-thread-id")) } l.mu.Lock() defer l.mu.Unlock() - for _, id := range []string{parent, sessionOf(r.Header)} { + for _, id := range []string{parent, meta.Forked, sessionOf(r.Header)} { if v, ok := l.thread[id]; ok && id != "" { - return v.model + return v.model, true, v.at } } - return l.last[access.Caller(r.Context()).KeyID] + v := l.last[access.Caller(r.Context()).KeyID] + return v.model, false, v.at +} + +// codexSideFresh is how recent the key's last turn must be for a side +// call tied to no conversation magpie has seen to take its model at once; +// codexSideWait bounds how long such a call waits for the turn it was +// started beside. +var ( + codexSideFresh = 3 * time.Second + codexSideWait = 5 * time.Second +) + +// sideOf is of for the Codex app's own side turns: a title, description, +// summary or prediction. Codex writes a new conversation's title on a +// temporary thread of its own, with no link to the conversation, started +// as the user's first message is sent, so it often reaches magpie before +// that conversation's first turn. Read then, the key's last turn is the +// previous conversation's, on the model the user switched away from +// (cybercaius on Discord: the first title after a switch came from the +// old model). When this key's last turn is older than codexSideFresh, +// such a call waits, up to codexSideWait or until it is cancelled, for +// the next turn of any conversation, and takes that one's model. +func (l *codexLeads) sideOf(r *http.Request, body []byte) string { + model, tied, at := l.lookup(r, body) + if tied || model == "" || time.Since(at) < codexSideFresh { + return model + } + l.mu.Lock() + if l.next == nil { + l.next = make(chan struct{}) + } + next := l.next + l.mu.Unlock() + t := time.NewTimer(codexSideWait) + defer t.Stop() + select { + case <-next: + case <-t.C: + case <-r.Context().Done(): + } + model, _, _ = l.lookup(r, body) + return model } // codexFollowTo is the model a Codex side call that asked for one of @@ -142,7 +200,18 @@ func (s *Server) codexFollowTo(r *http.Request, agent, kind, asked string, body // conversation is on one of Codex's own models, or magpie can't serve its // model now (turned off, gone, or one the caller's key is held from). func (s *Server) codexSessionOf(r *http.Request, body []byte) string { - to := s.codexLeads.of(r, body) + return s.servedSession(r, s.codexLeads.of(r, body)) +} + +// codexSideSession is codexSessionOf for the Codex app's own side turns, +// read after the turn they were started beside (codexLeads.sideOf). +func (s *Server) codexSideSession(r *http.Request, body []byte) string { + return s.servedSession(r, s.codexLeads.sideOf(r, body)) +} + +// servedSession is to, else the model in Codex's config, when magpie can +// serve it to this caller now; "" otherwise. +func (s *Server) servedSession(r *http.Request, to string) string { if to == "" && CodexSideModel != nil { to = CodexSideModel() } diff --git a/internal/gateway/codex_follow_test.go b/internal/gateway/codex_follow_test.go index 3f99c568f..04fc02dd7 100644 --- a/internal/gateway/codex_follow_test.go +++ b/internal/gateway/codex_follow_test.go @@ -4,6 +4,7 @@ import ( "net/http/httptest" "strings" "testing" + "time" ) // codexFollowSetup is Codex signed in to ChatGPT, its conversation put on @@ -142,6 +143,101 @@ func TestCodexAppSideTurnsFollowTheSession(t *testing.T) { } } +// cybercaius on Discord: after switching Codex to another model, the first +// new conversation's title still came from the model before. Codex writes +// it on a temporary thread with no link to the conversation, started as +// the first message is sent, so it can reach magpie before that +// conversation's first turn, when the key's last turn is still the old +// conversation's. It waits for the turn now, and goes on its model. +func TestCodexTitleBeforeTheFirstTurnFollowsTheSwitch(t *testing.T) { + up, old, s := codexFollowSetup(t, false) + switched := relayOn(t, "fourth") + wasModel, wasFresh, wasWait := CodexSideModel, codexSideFresh, codexSideWait + CodexSideModel = func() string { return "" } + // the old conversation's turn is long past; the title waits on the + // new one's, not on the clock + codexSideFresh, codexSideWait = 0, time.Minute + t.Cleanup(func() { CodexSideModel, codexSideFresh, codexSideWait = wasModel, wasFresh, wasWait }) + done := make(chan struct{}) + go func() { + defer close(done) + codexAppSide(t, s, "thread_title", "title-thread") + }() + // the new conversation's first turn comes once the title is waiting + // (on the old code it never waits, and is answered first) + for waiting := false; !waiting; { + select { + case <-done: + waiting = true + default: + s.codexLeads.mu.Lock() + waiting = s.codexLeads.next != nil + s.codexLeads.mu.Unlock() + if !waiting { + time.Sleep(time.Millisecond) + } + } + } + if rec := codexSubTurn(s, "fourth/gpt-6-astra", "lead-2", "", leadAsk); rec.Code != 200 { + t.Fatalf("new conversation: %d %s", rec.Code, rec.Body.String()) + } + <-done + if got := up.asked(); len(got) != 0 { + t.Fatalf("ChatGPT was asked for %v", got) + } + if reqs := old.requests(); len(reqs) != 1 { + t.Fatalf("the model switched from got %d requests, the title among them", len(reqs)) + } + if reqs := switched.requests(); len(reqs) != 2 { + t.Fatalf("the model switched to got %d requests, want the turn and the title", len(reqs)) + } +} + +// A composer prediction runs on a fork of the conversation, a thread of +// its own: it follows the conversation it was forked from, not whichever +// one this key's Codex last had a turn in. +func TestCodexPredictionFollowsTheThreadItForks(t *testing.T) { + _, lead, s := codexFollowSetup(t, false) + other := relayOn(t, "fourth") + was := CodexSideModel + CodexSideModel = func() string { return "" } + t.Cleanup(func() { CodexSideModel = was }) + if rec := codexSubTurn(s, "fourth/gpt-6-astra", "lead-2", "", leadAsk); rec.Code != 200 { + t.Fatalf("other conversation: %d %s", rec.Code, rec.Body.String()) + } + body := `{"model":"gpt-6-luna","stream":true,"input":[` + leadAsk + `]}` + req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer chatgpt-token") + req.Header.Set("chatgpt-account-id", "acct-1") + req.Header.Set("session_id", "fork-of-lead-1") + req.Header.Set("x-codex-turn-metadata", `{"thread_source":"composer_predictions","forked_from_thread_id":"lead-1"}`) + s.Handler().ServeHTTP(httptest.NewRecorder(), req) + if reqs := lead.requests(); len(reqs) != 2 { + t.Fatalf("the forked conversation's model got %d requests", len(reqs)) + } + if reqs := other.requests(); len(reqs) != 1 { + t.Fatalf("the other conversation's model got %d requests", len(reqs)) + } +} + +// A title for a conversation magpie has seen a turn of goes on its model +// at once, however long ago that turn was, with no wait. +func TestCodexTitleOfAKnownThreadDoesNotWait(t *testing.T) { + _, relay, s := codexFollowSetup(t, false) + wasModel, wasFresh, wasWait := CodexSideModel, codexSideFresh, codexSideWait + CodexSideModel = func() string { return "" } + codexSideFresh, codexSideWait = 0, time.Minute + t.Cleanup(func() { CodexSideModel, codexSideFresh, codexSideWait = wasModel, wasFresh, wasWait }) + start := time.Now() + codexAppSide(t, s, "thread_title", "lead-1") + if d := time.Since(start); d > 30*time.Second { + t.Fatalf("the title waited %v", d) + } + if reqs := relay.requests(); len(reqs) != 2 { + t.Fatalf("the relay got %d requests", len(reqs)) + } +} + // A conversation on Codex's own model keeps its side turns on ChatGPT, // even with one of magpie's models in Codex's config: they follow the // session, not the config.