Files
magpie/internal/agent/codex_threads_back_test.go
T
yetone 85534cd078 codex: threads started on magpie come back to the provider Codex is on
kaizaoji on X (10-22, zwaydot's Codex thread): after using magpie with
Codex and then disconnecting or editing the config, projects say their
context doesn't exist, and earlier threads can't be read.

Cause: Codex lists threads per provider. app-server thread/list filters
on the current model_provider when the caller names none
(thread_processor.rs), and the TUI resume picker does the same; no
setting turns that off. magpie sets model_provider = "magpie" with an
API-key sign-in, with no sign-in, with a ChatGPT account out of
allowance (codex.out), in the "magpie API" login mode and for a gateway
on another machine. Every thread started then is tagged "magpie" in its
rollout's session_meta and in state_5.sqlite. After Disconnect (or a
hand edit back to openai) Codex lists only "openai" threads, so those
threads are gone from resume and from the app.

Not done: routing through the built-in openai provider with
openai_base_url instead of switching model_provider. The built-in
requires OpenAI auth, so with no sign-in the TUI shows its login
screen; with an API key Codex skips /models (#322, why 953bce2cf
reverted c3931c91d's base-URL-only path); the Codex app blocks a
used-up ChatGPT account before any request (#540); "magpie API" is the
user's own choice of provider; a remote gateway needs its key (#2145).
In a sandbox, API key + openai_base_url does reach {base}/responses with
the key, but that covers only API-key users on this machine and reopens
#322.

Fix: magpie's own threads come back to whatever provider Codex is on.
sessions.MoveCodexThreads(home, from, to) takes the ids state_5.sqlite
has on "magpie", finds their rollout files (sessions/ and
archived_sessions/, segments too) and moves each with the same code as
MoveCodexProvider (now moveCodexPaths): a copy in magpie's trash first,
the rollout's session_meta and the DB row rewritten, a thread written
to in the last minute left for the next pass. The agent runs it after
Unwire and after every Sync (start, catalog change, the out() check),
only when the config doesn't name magpie, by model_provider or by any
profile, and not for a WSL distro's Codex. Only threads tagged "magpie"
move: a CC Switch or custom provider's threads (#887, #1372, #1796)
stay where they are, and a hand-set model_provider = "custom" gets
magpie's threads, since that is where Codex now lists.

Not moved the other way: while magpie is the provider, threads on
openai stay hidden, as before. Moving them onto magpie would strand
them if magpie goes away without a Disconnect (an uninstall, or the
reporter's hand edit), and the out() flip comes every allowance window,
which would rewrite and back up every thread each time.

Run:
- go test -run 'Codex|Thread|Provider' ./internal/agent
  ./internal/sessions on e6bed2f06: ok (27.2s,
  3.2s). The packages' full run waits behind another session's suite
  and runs after the push (owner: ship each verified fix at once).
  Rebased after onto 97902e938, which touches internal/provider only;
  go build ./... and go vet of both packages ran again there.
- gofmt -l clean; go vet ./... (darwin), GOOS=windows go vet ./...,
  GOOS=linux go vet -tags nogui ./... clean.
- Real codex 0.162.1 in a sandbox HOME/CODEX_HOME with a fake Responses
  server: two exec threads made on model_provider magpie, one on openai.
  Config back on openai: app-server thread/list (sourceKinds cli,
  vscode, exec) listed only the openai thread; with modelProviders []
  all three, two tagged magpie. MoveCodexThreads moved the two (backups
  in trash/codex-provider), and thread/list then listed all three on
  openai. `codex exec resume` of a moved thread went through and was
  appended to the same rollout, its first message still there.

Broken by hand, each red:
- bringBack off: TestCodexThreadsComeBackOffMagpie disconnect and
  by_hand fail ("on magpie, want openai").
- the namesMagpie guard removed: by_hand fails (moved while a profile
  is on magpie).
- the provider query widened (OR 1): TestMoveCodexThreads fails (the
  custom thread moved).

Not tried: a real OpenAI key or ChatGPT account (the sandbox used a
fake key and server); the TUI resume picker itself (it uses the same
provider filter as thread/list); a WSL distro's Codex (skipped on
purpose); a Codex old enough to have no state_5.sqlite (nothing moves
there).
2026-10-23 16:24:13 +08:00

137 lines
5.3 KiB
Go

package agent
import (
"database/sql"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/edit"
)
// codexThreadOn writes a thread of Codex's on the provider p, its rollout
// a day old and its row in the state database, as Codex 0.162 keeps them.
func codexThreadOn(t *testing.T, dir, id, p string) string {
t.Helper()
sub := filepath.Join(dir, "sessions", "2026", "10", "21")
os.MkdirAll(sub, 0o755)
path := filepath.Join(sub, "rollout-2026-10-21T10-00-00-"+id+".jsonl")
b := `{"timestamp":"2026-10-21T10:00:00.000Z","type":"session_meta","payload":{"id":"` + id + `","timestamp":"2026-10-21T10:00:00.000Z","cwd":"/work/proj","originator":"codex_cli_rs","cli_version":"0.162.1","source":"cli","model_provider":"` + p + `","base_instructions":{"text":"x"}}}` + "\n"
if err := os.WriteFile(path, []byte(b), 0o644); err != nil {
t.Fatal(err)
}
day := time.Now().Add(-24 * time.Hour)
os.Chtimes(path, day, day)
db, err := sql.Open("sqlite", filepath.Join(dir, "state_5.sqlite"))
if err != nil {
t.Fatal(err)
}
defer db.Close()
if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS threads (id TEXT PRIMARY KEY, rollout_path TEXT NOT NULL, model_provider TEXT NOT NULL, model TEXT)`); err != nil {
t.Fatal(err)
}
if _, err := db.Exec(`INSERT INTO threads VALUES (?, ?, ?, 'fake/m1')`, id, path, p); err != nil {
t.Fatal(err)
}
return path
}
func codexRowOn(t *testing.T, dir, id string) string {
t.Helper()
db, err := sql.Open("sqlite", filepath.Join(dir, "state_5.sqlite"))
if err != nil {
t.Fatal(err)
}
defer db.Close()
var p string
if err := db.QueryRow(`SELECT model_provider FROM threads WHERE id = ?`, id).Scan(&p); err != nil {
t.Fatal(err)
}
return p
}
// kaizaoji on X: after using magpie with Codex and disconnecting it, Codex
// said a project's earlier context didn't exist. Codex lists only the
// threads of the provider it is on (app-server thread/list, the resume
// picker), and with no ChatGPT sign-in (or an API key, or an account out
// of its allowance) magpie is Codex's provider, so every thread started
// then names "magpie" and was gone once Codex was back on OpenAI. They
// come back to the provider Codex is on: at the Disconnect, and at a sync
// after the provider was taken off by hand. A thread of a provider of the
// user's own (CC Switch's "custom") stays where it is, and none moves
// while Codex is on magpie, at its top or in a profile.
func TestCodexThreadsComeBackOffMagpie(t *testing.T) {
const (
mine = "019a0000-0000-7000-8000-0000000000a1"
theirs = "019a0000-0000-7000-8000-0000000000a2"
before = "019a0000-0000-7000-8000-0000000000a3"
)
t.Run("disconnect", func(t *testing.T) {
home, _ := codexHome(t, "", "model = \"gpt-5.4\"\n")
dir := filepath.Join(home, ".codex")
cx := codex(home)
if err := cx.Fields[0].Set("fake/m1"); err != nil {
t.Fatal(err)
}
if p, _ := edit.GetTOMLTop(filepath.Join(dir, "config.toml"), "model_provider"); p != "magpie" {
t.Fatalf("provider %q, want magpie as Codex's provider with no sign-in", p)
}
minePath := codexThreadOn(t, dir, mine, "magpie")
codexThreadOn(t, dir, theirs, "custom")
codexThreadOn(t, dir, before, "openai")
// connected, magpie's threads are where Codex lists them
if err := cx.Sync(); err != nil {
t.Fatal(err)
}
if p := codexRowOn(t, dir, mine); p != "magpie" {
t.Fatalf("moved off magpie while Codex is on it: %q", p)
}
if err := cx.Unwire(); err != nil {
t.Fatal(err)
}
for id, want := range map[string]string{mine: "openai", theirs: "custom", before: "openai"} {
if p := codexRowOn(t, dir, id); p != want {
t.Errorf("thread %s on %q, want %q", id, p, want)
}
}
if b, _ := os.ReadFile(minePath); !strings.Contains(string(b), `"model_provider":"openai"`) {
t.Fatalf("rollout:\n%s", b)
}
})
t.Run("by hand", func(t *testing.T) {
// magpie taken out of config.toml by hand, its table left for its
// threads, and a profile of the user's on magpie
table := "\n[model_providers.magpie]\nname = \"magpie\"\nbase_url = \"http://127.0.0.1:3425/v1\"\nwire_api = \"responses\"\n"
profile := "\n[profiles.mg]\nmodel_provider = \"magpie\"\n"
home, _ := codexHome(t, "", "model = \"gpt-5.4\"\n"+table+profile)
dir := filepath.Join(home, ".codex")
path := filepath.Join(dir, "config.toml")
codexThreadOn(t, dir, mine, "magpie")
codexThreadOn(t, dir, theirs, "custom")
cx := codex(home)
cx.Sync()
// its threads are where `codex -p mg` lists them
if p := codexRowOn(t, dir, mine); p != "magpie" {
t.Fatalf("moved while a profile is on magpie: %q", p)
}
os.WriteFile(path, []byte("model = \"gpt-5.4\"\n"+table), 0o644)
cx.Sync()
for id, want := range map[string]string{mine: "openai", theirs: "custom"} {
if p := codexRowOn(t, dir, id); p != want {
t.Errorf("thread %s on %q, want %q", id, p, want)
}
}
// CC Switch's provider set by hand: a thread left on magpie goes there
codexThreadOn(t, dir, before, "magpie")
os.WriteFile(path, []byte("model = \"gpt-5.4\"\nmodel_provider = \"custom\"\n"+table+"\n[model_providers.custom]\nname = \"custom\"\nbase_url = \"https://relay.example/v1\"\n"), 0o644)
cx.Sync()
for id, want := range map[string]string{mine: "openai", theirs: "custom", before: "custom"} {
if p := codexRowOn(t, dir, id); p != want {
t.Errorf("thread %s on %q, want %q", id, p, want)
}
}
})
}