Files
magpie/internal/gateway/codex_follow_test.go
T
yetone 81a73c1c01 gateway: a Codex title that comes before its conversation's first turn follows the model just switched to
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.
2026-10-26 22:55:29 +08:00

280 lines
11 KiB
Go

package gateway
import (
"net/http/httptest"
"strings"
"testing"
"time"
)
// codexFollowSetup is Codex signed in to ChatGPT, its conversation put on
// a relay's model (third/gpt-6-astra) through magpie, and Codex's config
// naming no model for its subagents or memories unless set says so.
func codexFollowSetup(t *testing.T, set bool) (*chatgptSeen, *relayOfChatGPT, *Server) {
t.Helper()
up := codexSubagentSetup(t)
relay := relayOn(t, "third")
was := CodexSideSet
CodexSideSet = func(string) bool { return set }
t.Cleanup(func() { CodexSideSet = was })
s := New()
if rec := codexSubTurn(s, "third/gpt-6-astra", "lead-1", "", leadAsk); rec.Code != 200 {
t.Fatalf("lead: %d %s", rec.Code, rec.Body.String())
}
return up, relay, s
}
// codexSide is one of Codex's side calls of kind on one of its own models.
func codexSide(t *testing.T, s *Server, kind, input string) {
t.Helper()
if rec := codexAsks(s, "gpt-5.5", kind, input); rec.Code != 200 {
t.Fatalf("%s: %d %s", kind, rec.Code, rec.Body.String())
}
}
// cybercaius on Discord: with Codex on a model routed through magpie, a
// subagent its lead put on one of Codex's own models, with no model set
// for subagents, went to the ChatGPT account. It follows the session now,
// and the trace says what it asked for.
func TestCodexSubagentFollowsTheSession(t *testing.T) {
up, relay, s := codexFollowSetup(t, false)
codexSide(t, s, "collab_spawn", plainTask)
if got := up.asked(); len(got) != 0 {
t.Fatalf("ChatGPT was asked for %v", got)
}
reqs := relay.requests()
if len(reqs) != 2 || modelOf([]byte(reqs[1])) != "gpt-6-astra" {
t.Fatalf("the relay got %d requests: %v", len(reqs), reqs)
}
r := lastRoute(s)
if r.Subagent == nil || *r.Subagent != (SubagentPick{Asked: "gpt-5.5", To: "third/gpt-6-astra"}) {
t.Fatalf("trace: model %q subagent %+v", r.Model, r.Subagent)
}
}
// Codex's memories, written on gpt-5.6-luna and -terra whatever the
// conversation is on, follow it too.
func TestCodexMemoriesFollowTheSession(t *testing.T) {
up, relay, s := codexFollowSetup(t, false)
codexSide(t, s, "memgen", leadAsk)
if got := up.asked(); len(got) != 0 {
t.Fatalf("ChatGPT was asked for %v", got)
}
if reqs := relay.requests(); len(reqs) != 2 {
t.Fatalf("the relay got %d requests", len(reqs))
}
}
// A model Codex's config names for them is the user's own pick: the side
// calls go as Codex sent them.
func TestCodexSideCallsKeepTheConfigsModel(t *testing.T) {
up, relay, s := codexFollowSetup(t, true)
codexSide(t, s, "collab_spawn", plainTask)
codexSide(t, s, "memgen", leadAsk)
if got := up.asked(); len(got) != 2 || got[0] != "gpt-5.5" || got[1] != "gpt-5.5" {
t.Fatalf("ChatGPT was asked for %v", got)
}
if reqs := relay.requests(); len(reqs) != 1 {
t.Fatalf("the relay got %d requests", len(reqs))
}
}
// A conversation on Codex's own model, and a task the ChatGPT backend
// sealed (which opens on a ChatGPT account alone), stay on ChatGPT.
func TestCodexSideCallsStayOnChatGPT(t *testing.T) {
up := codexSubagentSetup(t)
relay := relayOn(t, "third")
was := CodexSideSet
CodexSideSet = func(string) bool { return false }
t.Cleanup(func() { CodexSideSet = was })
s := New()
codexSide(t, s, "", leadAsk)
codexSide(t, s, "collab_spawn", plainTask)
if got := up.asked(); len(got) != 2 {
t.Fatalf("ChatGPT was asked for %v", got)
}
if rec := codexSubTurn(s, "third/gpt-6-astra", "lead-1", "", leadAsk); rec.Code != 200 {
t.Fatalf("lead: %d", rec.Code)
}
codexSide(t, s, "collab_spawn", sealedTaskFernet)
if got := up.asked(); len(got) != 3 || got[2] != "gpt-5.5" {
t.Fatalf("ChatGPT was asked for %v", got)
}
if reqs := relay.requests(); len(reqs) != 1 {
t.Fatalf("the relay got %d requests", len(reqs))
}
}
// codexAppSide is one of the Codex app's hidden side turns of a thread
// (source: thread_title, thread_description, composer_predictions), asked
// on one of Codex's own models as the app asks for them.
func codexAppSide(t *testing.T, s *Server, source, session string) {
t.Helper()
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", session)
req.Header.Set("x-codex-turn-metadata", `{"thread_source":"`+source+`"}`)
s.Handler().ServeHTTP(httptest.NewRecorder(), req)
}
// cybercaius on Discord: with the conversation put on one of magpie's
// models in the Codex app, and nothing in Codex's config, the app's thread
// titles, descriptions and composer predictions still went to ChatGPT on
// its own models. They follow the session now, as the subagents do.
func TestCodexAppSideTurnsFollowTheSession(t *testing.T) {
up, relay, s := codexFollowSetup(t, false)
was := CodexSideModel
CodexSideModel = func() string { return "" }
t.Cleanup(func() { CodexSideModel = was })
for _, src := range []string{"composer_predictions", "thread_title", "thread_description"} {
codexAppSide(t, s, src, "lead-1")
if got := up.asked(); len(got) != 0 {
t.Fatalf("%s: ChatGPT was asked for %v", src, got)
}
reqs := relay.requests()
if m := modelOf([]byte(reqs[len(reqs)-1])); len(reqs) < 2 || m != "gpt-6-astra" {
t.Fatalf("%s: the relay got %d requests, the last on %q", src, len(reqs), m)
}
}
if reqs := relay.requests(); len(reqs) != 4 {
t.Fatalf("the relay got %d requests", len(reqs))
}
}
// 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.
func TestCodexAppSideTurnsStayWithAnOwnModelSession(t *testing.T) {
up := codexSubagentSetup(t)
relay := relayOn(t, "third")
was := CodexSideModel
CodexSideModel = func() string { return "third/gpt-6-astra" }
t.Cleanup(func() { CodexSideModel = was })
s := New()
codexSide(t, s, "", leadAsk)
codexAppSide(t, s, "thread_title", "worker-1")
if got := up.asked(); len(got) != 2 || got[1] != "gpt-6-luna" {
t.Fatalf("ChatGPT was asked for %v", got)
}
if reqs := relay.requests(); len(reqs) != 0 {
t.Fatalf("the relay got %d requests", len(reqs))
}
}
// Codex consolidates its memories as it starts, before any turn of its
// has come through magpie: with one of magpie's models in its config,
// they go on that model, not to ChatGPT.
func TestCodexMemoriesBeforeAnyTurnFollowTheConfig(t *testing.T) {
up := codexSubagentSetup(t)
relay := relayOn(t, "third")
wasSet, wasModel := CodexSideSet, CodexSideModel
CodexSideSet = func(string) bool { return false }
CodexSideModel = func() string { return "third/gpt-6-astra" }
t.Cleanup(func() { CodexSideSet, CodexSideModel = wasSet, wasModel })
s := New()
codexSide(t, s, "memgen", leadAsk)
if got := up.asked(); len(got) != 0 {
t.Fatalf("ChatGPT was asked for %v", got)
}
if reqs := relay.requests(); len(reqs) != 1 || modelOf([]byte(reqs[0])) != "gpt-6-astra" {
t.Fatalf("the relay got %v", reqs)
}
}