diff --git a/internal/agent/codex.go b/internal/agent/codex.go index 66dde2443..6c5d1d21d 100644 --- a/internal/agent/codex.go +++ b/internal/agent/codex.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "io/fs" + "log" "net/url" "os" "path/filepath" @@ -520,6 +521,34 @@ func codexIn(at place) *Agent { dropList() return nil } + // bringBack moves the threads started while magpie was Codex's + // provider (model_provider "magpie") onto the provider Codex is on now, + // once it is off magpie: Codex lists only the threads of its current + // provider (app-server thread/list, the TUI's resume picker), so after + // a Disconnect, a hand edit, or magpie stepping back beside the + // ChatGPT sign-in, every thread started on magpie was gone from Codex + // (kaizaoji on X). Only magpie's own threads move, never those of a + // provider of the user's (CC Switch's, #887); none while a profile + // still names magpie, whose threads they are; and a copy of each is + // kept in magpie's trash (MoveCodexProvider). A thread Codex wrote to + // in the last minute waits for the next Sync. This machine's Codex + // only: a distro's state database isn't magpie's to open. + bringBack := func() { + if at.spell != nil || namesMagpie() { + return + } + to := sessions.CodexProviderIn(dir) + if to == magpieID { + return + } + moved, err := sessions.MoveCodexThreads(dir, magpieID, to) + if len(moved) > 0 { + log.Printf("codex: %d thread(s) started on magpie moved to %s, where Codex lists them", len(moved), to) + } + if err != nil { + log.Println("codex: moving magpie's threads:", err) + } + } // mirrorsTaken are the mirrors takeMirrors pointed at magpie (#1796) mirrorsTaken := func() []string { var ids []string @@ -1162,6 +1191,8 @@ func codexIn(at place) *Agent { if at.spell == nil { portCodexHome(dir, codexPortUnwire) } + // and are listed where Codex now is + bringBack() return settle() }, // signed in with ChatGPT, Codex reaches magpie by the base URL with @@ -1223,6 +1254,9 @@ func codexIn(at place) *Agent { }, OwnVia: codexOwnViaMagpie, Sync: func() error { + // after the sync, which may have put Codex back beside its + // sign-in, and whatever it failed at + defer bringBack() // model_catalog_json naming magpie's list with the list gone, // as an older magpie's Disconnect could leave it (zwaydot on // X): Codex loads no config at all then. Connected or not, the diff --git a/internal/agent/codex_threads_back_test.go b/internal/agent/codex_threads_back_test.go new file mode 100644 index 000000000..8c4fe3dbe --- /dev/null +++ b/internal/agent/codex_threads_back_test.go @@ -0,0 +1,136 @@ +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) + } + } + }) +} diff --git a/internal/sessions/codex_provider.go b/internal/sessions/codex_provider.go index 9c276d94a..db951ee7d 100644 --- a/internal/sessions/codex_provider.go +++ b/internal/sessions/codex_provider.go @@ -13,6 +13,7 @@ import ( "path/filepath" "regexp" "strconv" + "strings" "time" "github.com/klauspost/compress/zstd" @@ -230,7 +231,12 @@ func MoveCodexProvider(id, to string) (CodexMove, error) { if len(paths) == 0 { return CodexMove{}, errors.New("no such session") } - now := time.Now() + return moveCodexPaths(id, to, paths, time.Now()) +} + +// moveCodexPaths moves one Codex thread, whose files are paths, to the +// provider to, as MoveCodexProvider says; storeMu and mu are held. +func moveCodexPaths(id, to string, paths []string, now time.Time) (CodexMove, error) { for _, p := range paths { if recent(p, now) { return CodexMove{}, ErrActive @@ -288,8 +294,8 @@ func MoveCodexProvider(id, to string) (CodexMove, error) { mv.Files = append(mv.Files, p) } } - for _, f := range fs { - delete(cache, f.path) + for _, p := range paths { + delete(cache, p) } saveCache() homes := map[string]bool{} @@ -340,6 +346,95 @@ func CodexThreadProviders(home string) []string { return out } +// codexThreadsOn are the ids of the threads a Codex folder's state +// databases keep on the provider p. A database without the threads table, +// or one that can't be read, says nothing. +func codexThreadsOn(home, p string) []string { + var out []string + for _, path := range codexStateDBs(home) { + u := url.URL{Scheme: "file", Path: filepath.ToSlash(path), RawQuery: "mode=ro&_pragma=busy_timeout(2000)"} + if len(u.Path) >= 2 && u.Path[1] == ':' { + u.Path = "/" + u.Path + } + db, err := sql.Open("sqlite", u.String()) + if err != nil { + continue + } + rows, err := db.Query(`SELECT id FROM threads WHERE model_provider = ?`, p) + if err == nil { + for rows.Next() { + var id string + if rows.Scan(&id) == nil && safeID.MatchString(id) && !contains(out, id) { + out = append(out, id) + } + } + rows.Close() + } + db.Close() + } + return out +} + +// MoveCodexThreads moves every thread of a Codex folder its state database +// keeps on the provider from to the provider to, each as MoveCodexProvider +// moves one: its files' session_meta and its row, a copy of the files kept +// in magpie's trash first. Codex lists only the threads of the provider it +// is on (app-server thread/list, the TUI's resume picker), so the threads +// started while magpie was Codex's provider were gone from Codex's lists +// once Codex was off magpie (kaizaoji on X: "the context doesn't exist"). +// A thread written to in the last minute is left for the next call, and +// so is one whose files can't be found; it says what it moved and the +// first error it met, having gone on past it. +func MoveCodexThreads(home, from, to string) ([]CodexMove, error) { + if !codexProviderRe.MatchString(from) || !codexProviderRe.MatchString(to) || from == to { + return nil, fmt.Errorf("can't move Codex's threads from %q to %q", from, to) + } + ids := codexThreadsOn(home, from) + if len(ids) == 0 { + return nil, nil + } + storeMu.Lock() + defer storeMu.Unlock() + mu.Lock() + defer mu.Unlock() + loadCache() + // each thread's files: its rollout, its segments (_) and + // their compressed twins, in sessions/ or archived_sessions/ + files := map[string][]string{} + for _, sub := range []string{"sessions", "archived_sessions"} { + filepath.WalkDir(filepath.Join(home, sub), func(p string, d os.DirEntry, err error) error { + if err != nil || !d.Type().IsRegular() || !strings.HasPrefix(d.Name(), "rollout-") { + return nil + } + for _, id := range ids { + if strings.Contains(d.Name(), id) { + files[id] = append(files[id], p) + break + } + } + return nil + }) + } + var moved []CodexMove + var first error + now := time.Now() + for _, id := range ids { + if len(files[id]) == 0 { + continue + } + mv, err := moveCodexPaths(id, to, files[id], now) + if err != nil { + if !errors.Is(err, ErrActive) && first == nil { + first = fmt.Errorf("thread %s: %w", id, err) + } + continue + } + mv.From = from + moved = append(moved, mv) + } + return moved, first +} + func contains(list []string, s string) bool { for _, x := range list { if x == s { diff --git a/internal/sessions/codex_threads_move_test.go b/internal/sessions/codex_threads_move_test.go new file mode 100644 index 000000000..86f2af741 --- /dev/null +++ b/internal/sessions/codex_threads_move_test.go @@ -0,0 +1,131 @@ +package sessions + +import ( + "database/sql" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// cxRollout writes a Codex rollout of the thread id on the provider p, as +// Codex 0.162 starts one, with the time at. +func cxRollout(t *testing.T, home, sub, id, p string, at time.Time) string { + t.Helper() + dir := filepath.Join(home, sub, "2026", "10", "21") + if sub == "archived_sessions" { + dir = filepath.Join(home, sub) + } + os.MkdirAll(dir, 0o755) + path := filepath.Join(dir, "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" + + `{"timestamp":"2026-10-21T10:00:01.000Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"remember: the build uses make"}]}}` + "\n" + if err := os.WriteFile(path, []byte(b), 0o644); err != nil { + t.Fatal(err) + } + os.Chtimes(path, at, at) + return path +} + +func cxThreadRows(t *testing.T, home string, rows map[string]string) string { + t.Helper() + p := filepath.Join(home, "state_5.sqlite") + db, err := sql.Open("sqlite", p) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if _, err := db.Exec(`CREATE TABLE threads (id TEXT PRIMARY KEY, rollout_path TEXT NOT NULL, model_provider TEXT NOT NULL, title TEXT NOT NULL, archived INTEGER NOT NULL DEFAULT 0)`); err != nil { + t.Fatal(err) + } + for id, prov := range rows { + if _, err := db.Exec(`INSERT INTO threads VALUES (?, 'x', ?, 't', 0)`, id, prov); err != nil { + t.Fatal(err) + } + } + return p +} + +// Codex lists only the threads of the provider it is on now, so the threads +// started while magpie was its provider ("magpie") were gone from Codex +// once it was off magpie (kaizaoji on X). MoveCodexThreads moves every +// thread on one provider to another, in its files and its row, a copy of +// each kept: an archived one too; one Codex wrote to in the last minute +// waits; a thread of another provider (CC Switch's "custom") stays. +func TestMoveCodexThreads(t *testing.T) { + _, home := manageSetup(t) + const ( + old = "019a0000-0000-7000-8000-00000000000a" + archived = "019a0000-0000-7000-8000-00000000000b" + hot = "019a0000-0000-7000-8000-00000000000c" + theirs = "019a0000-0000-7000-8000-00000000000d" + ) + day := time.Now().Add(-24 * time.Hour).Truncate(time.Second) + oldPath := cxRollout(t, home, "sessions", old, "magpie", day) + arPath := cxRollout(t, home, "archived_sessions", archived, "magpie", day) + hotPath := cxRollout(t, home, "sessions", hot, "magpie", time.Now()) + theirPath := cxRollout(t, home, "sessions", theirs, "custom", day) + db := cxThreadRows(t, home, map[string]string{old: "magpie", archived: "magpie", hot: "magpie", theirs: "custom"}) + + moved, err := MoveCodexThreads(home, "magpie", "openai") + if err != nil { + t.Fatal(err) + } + if len(moved) != 2 { + t.Fatalf("moved %+v, want the two not written to lately", moved) + } + for _, mv := range moved { + if mv.From != "magpie" || mv.To != "openai" || len(mv.DB) != 1 || mv.Backup == "" { + t.Fatalf("moved %+v", mv) + } + if _, err := os.Stat(filepath.Join(mv.Backup, "move.json")); err != nil { + t.Fatalf("no copy kept: %v", err) + } + } + want := map[string]string{oldPath: "openai", arPath: "openai", hotPath: "magpie", theirPath: "custom"} + for p, prov := range want { + if got := codexMetaProvider(p); got != prov { + t.Errorf("%s: file on %q, want %q", filepath.Base(p), got, prov) + } + if fi, _ := os.Stat(p); p != hotPath && !fi.ModTime().Equal(day) { + t.Errorf("%s: time %v, want %v kept", filepath.Base(p), fi.ModTime(), day) + } + } + for id, prov := range map[string]string{old: "openai", archived: "openai", hot: "magpie", theirs: "custom"} { + if got, _, _ := threadProvider(t, db, id); got != prov { + t.Errorf("row %s on %q, want %q", id, got, prov) + } + } + b, _ := os.ReadFile(oldPath) + if !strings.Contains(string(b), "remember: the build uses make") { + t.Fatalf("the thread's messages went:\n%s", b) + } + + // the one written to lately goes once Codex is done with it + hour := time.Now().Add(-time.Hour) + os.Chtimes(hotPath, hour, hour) + if moved, err = MoveCodexThreads(home, "magpie", "openai"); err != nil || len(moved) != 1 || moved[0].ID != hot { + t.Fatalf("again: %+v %v", moved, err) + } + if moved, err = MoveCodexThreads(home, "magpie", "openai"); err != nil || len(moved) != 0 { + t.Fatalf("a third time: %+v %v", moved, err) + } +} + +// A Codex folder with no state database, or none of its threads on the +// provider, is left as it is, with nothing kept in the trash. +func TestMoveCodexThreadsNone(t *testing.T) { + _, home := manageSetup(t) + day := time.Now().Add(-24 * time.Hour) + p := cxRollout(t, home, "sessions", "019a0000-0000-7000-8000-00000000000e", "magpie", day) + if moved, err := MoveCodexThreads(home, "magpie", "openai"); err != nil || len(moved) != 0 { + t.Fatalf("no database: %+v %v", moved, err) + } + if got := codexMetaProvider(p); got != "magpie" { + t.Fatalf("file on %q", got) + } + if _, err := MoveCodexThreads(home, "magpie", "magpie"); err == nil { + t.Fatal("a move to the same provider went") + } +}