cybercaius on Discord: after switching Codex to another model, the first
new conversation's title was still written by the model before.
Cause: Codex writes a title on a temporary thread of its own
(tui/src/app/thread_title.rs, thread_source "thread_title"), with no
parent link to the conversation, started as the first message is sent and
so racing that conversation's first turn. codexLeads.of found neither a
parent nor its own thread and took the key's last turn, which, when the
title came first, was the previous conversation's, on the old model.
Composer predictions run on a fork and named it (forked_from_thread_id),
which of() never read, so they too took the key's last turn rather than
their conversation's.
Fix: of() reads the forked-from thread. The app's side turns (titles,
descriptions, summaries, predictions) read through codexLeads.sideOf: a
call tied to no thread magpie has seen, whose key's last turn is older
than 3s, waits for the next own turn (a channel saw() closes), up to 5s
or the request's cancellation, and takes that turn's model. Subagents and
memories keep codexSessionOf with no wait: they carry their lead's
thread. The auto-review follows the session only through codexcat's
per-entry override, and compaction goes on the conversation's own turn
model, so neither reads codexLeads.
Ran (at this head, rebased on origin/main):
- go test -count=1 -timeout 45m ./internal/gateway/... ./internal/agent/...: ok (gateway 521s, agent 316s), at the pushed tree (2ca0da8e5 before this body was written), base 51202cd43
- go test -race -count=5 on the new and neighbouring Codex side tests: ok
- TZ=UTC go test -run TestCodexTitle ./internal/gateway: ok
- gofmt -l internal/gateway: clean; GOOS=linux and GOOS=windows go vet
-tags nogui ./internal/gateway: clean
Broken by hand:
- the backend's session reader put back to codexSessionOf:
TestCodexTitleBeforeTheFirstTurnFollowsTheSwitch red ("the model
switched from got 2 requests, the title among them")
- meta.Forked taken out of lookup: TestCodexPredictionFollowsTheThreadItForks
red ("the forked conversation's model got 1 requests")
Not tried: a real Codex TUI or app switching models against a live
magpie (the race is reproduced in the test, ordering forced by waiting on
the state). A rename suggestion asked later, with no turn beside it, now
waits the 5s before going on the last turn's model.
233 lines
8.1 KiB
Go
233 lines
8.1 KiB
Go
package gateway
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/access"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
"github.com/yetone/magpie/internal/usage"
|
|
)
|
|
|
|
// Codex's side calls ask for one of Codex's own models by its bare name,
|
|
// whatever the conversation is on: a subagent goes on the model its lead
|
|
// names in spawn_agent (Codex lists its own first), its memories are
|
|
// written on gpt-5.6-luna and gpt-5.6-terra, its auto-review runs on
|
|
// codex-auto-review. With the conversation on one of magpie's models
|
|
// beside Codex's ChatGPT sign-in, each of those went to that ChatGPT
|
|
// account rather than where the user had routed Codex (cybercaius on
|
|
// Discord). With nothing set for them, a subagent and the memories follow
|
|
// the session: they go on the model the conversation's own turns go on,
|
|
// when that is one of magpie's (codexSessionOf), as the app's titles,
|
|
// descriptions, summaries and composer predictions do (codexSideTo). The auto-review follows it when set to
|
|
// (settings.CodexAutoReviewSession, which codexcat writes into each of
|
|
// magpie's entries); left to Codex it stays on codex-auto-review, which a
|
|
// ChatGPT sign-in runs free (#1593).
|
|
|
|
// CodexSideSet says whether Codex's own config names the model for a side
|
|
// call ("subagent": [agents] default_subagent_model; "memories": [memories]
|
|
// extract_model or consolidation_model), true when the config can't be
|
|
// read; nil leaves every such call as Codex sent it (agent.CodexSideSet).
|
|
var CodexSideSet func(which string) bool
|
|
|
|
// codexLeadsCap bounds how many conversations codexLeads keeps.
|
|
const codexLeadsCap = 512
|
|
|
|
// codexLeads is the model each Codex conversation's own turns last went
|
|
// on, by its thread id, and the one any of them last went on, by the
|
|
// gateway key it came with.
|
|
type codexLeads struct {
|
|
mu sync.Mutex
|
|
thread map[string]codexLead
|
|
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 {
|
|
model string
|
|
at time.Time
|
|
}
|
|
|
|
// saw notes a turn of a Codex conversation's own (no call kind) on model.
|
|
func (l *codexLeads) saw(r *http.Request, kind, model string) {
|
|
if kind != "" || model == "" {
|
|
return
|
|
}
|
|
key := access.Caller(r.Context()).KeyID
|
|
thread := sessionOf(r.Header)
|
|
l.mu.Lock()
|
|
defer l.mu.Unlock()
|
|
if l.thread == nil {
|
|
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
|
|
}
|
|
if thread == "" {
|
|
return
|
|
}
|
|
if _, ok := l.thread[thread]; !ok && len(l.thread) >= codexLeadsCap {
|
|
oldest, at := "", time.Time{}
|
|
for id, v := range l.thread {
|
|
if oldest == "" || v.at.Before(at) {
|
|
oldest, at = id, v.at
|
|
}
|
|
}
|
|
delete(l.thread, oldest)
|
|
}
|
|
l.thread[thread] = codexLead{model: model, at: time.Now()}
|
|
}
|
|
|
|
// 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), 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 {
|
|
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, meta.Forked, sessionOf(r.Header)} {
|
|
if v, ok := l.thread[id]; ok && id != "" {
|
|
return v.model, true, v.at
|
|
}
|
|
}
|
|
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
|
|
// Codex's own models goes on instead: the session's, when it is one of
|
|
// magpie's and nothing is set for that call. "" leaves the call as it
|
|
// came: another call, a model of magpie's asked for, a model set for it, a
|
|
// conversation on one of Codex's own models, or a session model magpie
|
|
// can't serve it on now.
|
|
func (s *Server) codexFollowTo(r *http.Request, agent, kind, asked string, body []byte) string {
|
|
if agent != "codex" && !fromCodex(r.Header) || asked == "" || strings.Contains(asked, "/") {
|
|
return ""
|
|
}
|
|
which := ""
|
|
switch {
|
|
case usage.PurposeOf(kind) == "kind:collab_spawn":
|
|
// a task the ChatGPT backend sealed opens only on a ChatGPT
|
|
// account (codexSubagentPick)
|
|
if provider.CodexSubagentModel() != "" || sealedTaskIn(body) {
|
|
return ""
|
|
}
|
|
which = "subagent"
|
|
case isMemoryKind(kind):
|
|
which = "memories"
|
|
default:
|
|
return ""
|
|
}
|
|
to := s.codexSessionOf(r, body)
|
|
if to == "" || to == asked {
|
|
return ""
|
|
}
|
|
// the user's own pick in Codex's config is kept; read last, as it
|
|
// reads the config
|
|
if CodexSideSet == nil || CodexSideSet(which) {
|
|
return ""
|
|
}
|
|
return to
|
|
}
|
|
|
|
// codexSessionOf is the model of magpie's a Codex side call with nothing
|
|
// set for it follows: the one its conversation's own turns go on
|
|
// (codexLeads), else, before any turn of Codex's has come through magpie
|
|
// (Codex consolidates its memories as it starts), the model Codex's config
|
|
// is set to when it is one of magpie's (CodexSideModel). cybercaius on
|
|
// Discord: with the model picked in the Codex app, not its config, the
|
|
// memories went to ChatGPT, and so did the titles, descriptions and
|
|
// composer predictions, which followed the config alone. "" when the
|
|
// 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 {
|
|
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()
|
|
}
|
|
if !strings.Contains(to, "/") {
|
|
return ""
|
|
}
|
|
if _, off := idOff(to); off {
|
|
return ""
|
|
}
|
|
p, model, ok := provider.Resolve(to)
|
|
if !ok {
|
|
return ""
|
|
}
|
|
if who, held := keyHolds(r); held && !modelAllowed(who, p, model) {
|
|
return ""
|
|
}
|
|
return to
|
|
}
|