codex: an old OpenAI thread follows Codex onto magpie by its row, and back at the Disconnect (Parry_Moody, Cyrus)
Parry_Moody and Cyrus on Discord: Codex on OpenAI through an API key
before magpie, and for two days the Codex app answered every older
conversation "继续聊天未成功: This chat uses openai, but your current
provider is magpie. Switch to openai to continue."
Cause, from Codex's source (rust-v0.167.0-alpha.3.1, same in 0.166.0):
every thread Codex 0.166 starts is paginated (history_mode 'paginated'
in its state-DB row), and for those thread-store read_thread takes the
provider from the row, never the rollout ("Paginated history may contain
only a suffix, so its display metadata lives in SQLite"). The app sends
thread/resume with modelProvider null (ChatGPT.app 26.1021, Kct in
app-shared), so the row alone decides, and load_for_resume refuses a row
other than the current provider. bringOver moved threads by rewriting
files: plain ones in place, packed ones only from the last 30 days and
128 MB a sync. An older or packed OpenAI thread kept an openai row.
Now sessions.RetagPagedCodexThreads moves every paginated thread on a
provider by its row alone: any age, packed or not, an id of any length,
no file read, written or copied. Each thread is held by its writer lock
(an open one stays: its writer would write the provider back), one
written to in the last minute waits, 200 rows a transaction. It runs
after the in-place relabel in bringOver, bringBack (so a Disconnect no
longer copies a whole paginated history to the trash), bringOfficial and
bringBeside, and giveBeside by ids (RetagPagedCodexThreadIDs). Legacy
threads keep the file path. The Sessions page lists a paginated thread
on its row's provider (codexPagedProviders, memoised on the DB and WAL
stamp), so it isn't offered a Move it had.
Run:
- real codex-cli 0.166.0 (npm latest) on mote in a sandbox CODEX_HOME,
a fake Responses server: a thread started with OpenAI (API key,
openai_base_url) is paginated, row openai; with model_provider magpie
`codex exec resume` failed with exactly "This chat uses openai, but
your current provider is magpie" (modelProviderMismatch). After
magpie's RetagPagedCodexThreads on that home (a throwaway test calling
it, not committed) it resumed and answered; the rollout still names
openai. Reversed (magpie -> openai) with config back on OpenAI, it
resumed again. The first retag try moved nothing: the rollout had been
written <1 minute before, the ActiveWindow skip, as intended.
- mote: gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
for ./internal/sessions ./internal/agent; go test ./internal/sessions
./internal/agent: ok (sessions 20.1s, agent 194.4s) on mote, plus go vet on darwin, linux -tags nogui and windows
Broken by hand:
- RetagPagedCodexThreads returning nil (the old behaviour):
TestCodexPagedThreadsFollowByRow red (250 packed 90-day-old threads
"on openai, want magpie"), TestRetagPagedCodexThreads red.
- the writer-lock hold skipped: TestCodexPagedThreadsFollowByRow red,
the open thread moved to magpie.
Not tried: the Codex app GUI itself (the app goes through the same
app-server thread/resume, whose modelProvider it sends null); Windows
and Linux runs (vet only). Codex rebuilds a row from its rollout when a
search listing reconciles it, which puts a retagged thread back on its
file's provider until the next sync; not seen, read from the source.
A legacy thread packed over 30 days still waits for Sessions' Move.
This commit is contained in:
File diff suppressed because one or more lines are too long
+47
-2
@@ -780,6 +780,16 @@ func codexIn(at place) *Agent {
|
||||
log.Println("codex: moving magpie's threads back:", err)
|
||||
}
|
||||
}
|
||||
// then a paginated thread by its row alone, packed or not (bringOver's, and those
|
||||
// started on magpie): Codex reads its provider there, so none of
|
||||
// a big history is copied to the trash or rewritten
|
||||
retagged, err := sessions.RetagPagedCodexThreads(dir, magpieID, to)
|
||||
if len(retagged) > 0 {
|
||||
log.Printf("codex: %d paginated thread(s) on magpie moved back to %s, where Codex resumes them", len(retagged), to)
|
||||
}
|
||||
if err != nil {
|
||||
log.Println("codex: moving magpie's paginated threads back:", err)
|
||||
}
|
||||
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)
|
||||
@@ -836,6 +846,15 @@ func codexIn(at place) *Agent {
|
||||
// packedBudget bytes a sync: the rest of a big history follows over
|
||||
// the next syncs, and older ones from Sessions (ResumeNow moves one
|
||||
// as it is reopened).
|
||||
//
|
||||
// A paginated thread (Codex 0.166 on) goes by its row in Codex's state
|
||||
// database, not its files: Codex lists and resumes it on the provider
|
||||
// the row names. Every one moves by that row alone, of any age, packed
|
||||
// or not, any id's length (RetagPagedCodexThreads): the 30 days and
|
||||
// the budget above left an API-key user's older OpenAI threads, and
|
||||
// the Codex app refused each one ("This chat uses openai, but your
|
||||
// current provider is magpie", Parry_Moody and Cyrus on Discord).
|
||||
// bringBack moves them back the same way.
|
||||
bringOver := func() {
|
||||
if at.spell != nil || !asProvider() || sessions.CodexProviderIn(dir) != magpieID {
|
||||
return
|
||||
@@ -863,6 +882,16 @@ func codexIn(at place) *Agent {
|
||||
log.Printf("codex: moving %s's threads to magpie: %v", from, err)
|
||||
}
|
||||
}
|
||||
// every paginated thread by its row, of any age: Codex resumes
|
||||
// one on the provider its row names (Parry_Moody and Cyrus on
|
||||
// Discord, whose old OpenAI threads the file moves below left)
|
||||
retagged, err := sessions.RetagPagedCodexThreads(dir, from, magpieID)
|
||||
if len(retagged) > 0 {
|
||||
log.Printf("codex: %d paginated thread(s) started on %s moved to magpie, where Codex resumes them now", len(retagged), from)
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("codex: moving %s's paginated threads to magpie: %v", from, err)
|
||||
}
|
||||
move := sessions.MovePackedCodexThreads
|
||||
if len(from) != len(magpieID) {
|
||||
move = sessions.MoveRecentCodexThreads
|
||||
@@ -919,6 +948,13 @@ func codexIn(at place) *Agent {
|
||||
if profileNamed(names)[ccSwitchOfficial] {
|
||||
return
|
||||
}
|
||||
retagged, err := sessions.RetagPagedCodexThreads(dir, ccSwitchOfficial, to)
|
||||
if len(retagged) > 0 {
|
||||
log.Printf("codex: %d paginated thread(s) of CC Switch's official route moved to %s, where Codex resumes them", len(retagged), to)
|
||||
}
|
||||
if err != nil {
|
||||
log.Println("codex: moving CC Switch's official paginated threads:", err)
|
||||
}
|
||||
moved, err := sessions.MoveCodexThreads(dir, ccSwitchOfficial, to)
|
||||
if len(moved) > 0 {
|
||||
log.Printf("codex: %d thread(s) of CC Switch's official route moved to %s, where Codex resumes them", len(moved), to)
|
||||
@@ -972,6 +1008,11 @@ func codexIn(at place) *Agent {
|
||||
log.Printf("codex: moving %s's threads to OpenAI: %v", from, err)
|
||||
}
|
||||
}
|
||||
retagged, err := sessions.RetagPagedCodexThreads(dir, from, "openai")
|
||||
ids = append(ids, retagged...)
|
||||
if err != nil {
|
||||
log.Printf("codex: moving %s's paginated threads to OpenAI: %v", from, err)
|
||||
}
|
||||
move := sessions.MovePackedCodexThreads
|
||||
if len(from) != len("openai") {
|
||||
move = sessions.MoveRecentCodexThreads
|
||||
@@ -1017,9 +1058,13 @@ func codexIn(at place) *Agent {
|
||||
return
|
||||
}
|
||||
}
|
||||
retagged, err := sessions.RetagPagedCodexThreadIDs(dir, "openai", to, b.IDs)
|
||||
if err != nil {
|
||||
log.Printf("codex: moving %s's paginated threads to %s: %v", b.From, to, err)
|
||||
}
|
||||
moved, err := sessions.MoveCodexThreadIDs(dir, "openai", to, b.IDs)
|
||||
if len(moved) > 0 {
|
||||
log.Printf("codex: %d thread(s) started on %s moved from OpenAI to %s", len(moved), b.From, to)
|
||||
if n := len(moved) + len(retagged); n > 0 {
|
||||
log.Printf("codex: %d thread(s) started on %s moved from OpenAI to %s", n, b.From, to)
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("codex: moving %s's threads to %s: %v", b.From, to, err)
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/filelock"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// Parry_Moody and Cyrus on Discord: Codex on OpenAI through an API key
|
||||
// before magpie, and for two days every older conversation in the Codex
|
||||
// app said "继续聊天未成功: This chat uses openai, but your current
|
||||
// provider is magpie. Switch to openai to continue". Codex 0.166 on keeps
|
||||
// a thread paginated (history_mode "paginated"), and reads its provider
|
||||
// from its row in the state database, not from its files (codex-rs
|
||||
// thread-store read_thread: "Paginated history may contain only a suffix,
|
||||
// so its display metadata lives in SQLite"); resume refuses a provider
|
||||
// other than the one Codex is on. The file moves left every packed thread
|
||||
// older than 30 days, and the rest of a big history past a sync's budget,
|
||||
// on OpenAI.
|
||||
//
|
||||
// Every paginated thread of OpenAI's now moves to magpie by its row
|
||||
// alone, of any age, its files neither rewritten nor copied, and back at
|
||||
// the Disconnect the same way. One a Codex has open stays, as its writer
|
||||
// would put its provider back, and so does a legacy thread past 30 days
|
||||
// (its provider is its file's, the Sessions page moves it).
|
||||
func TestCodexPagedThreadsFollowByRow(t *testing.T) {
|
||||
const (
|
||||
old = "019a0000-0000-7000-8000-0000000000d1"
|
||||
open = "019a0000-0000-7000-8000-0000000000d2"
|
||||
legacy = "019a0000-0000-7000-8000-0000000000d3"
|
||||
theirs = "019a0000-0000-7000-8000-0000000000d4"
|
||||
)
|
||||
home, _ := codexHome(t, "", "model = \"gpt-5.4\"\n")
|
||||
dir := filepath.Join(home, ".codex")
|
||||
db, err := sql.Open("sqlite", filepath.Join(dir, "state_5.sqlite"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
// as Codex 0.166's migration 0040 adds it
|
||||
if _, err := db.Exec(`CREATE TABLE threads (id TEXT PRIMARY KEY, rollout_path TEXT NOT NULL, model_provider TEXT NOT NULL, model TEXT, updated_at INTEGER NOT NULL DEFAULT 0, history_mode TEXT NOT NULL DEFAULT 'legacy')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// a history past a chunk, all packed and three months old
|
||||
var many []string
|
||||
for i := range 250 {
|
||||
many = append(many, fmt.Sprintf("019a0000-0000-7000-8000-%012x", 0xe00+i))
|
||||
}
|
||||
ago := time.Now().Add(-90 * 24 * time.Hour)
|
||||
stamp := map[string]time.Time{}
|
||||
for _, id := range append(append([]string{old, open, legacy}, many...), theirs) {
|
||||
p := "openai"
|
||||
if id == theirs {
|
||||
p = "custom"
|
||||
}
|
||||
path := codexThreadOn(t, dir, id, p)
|
||||
os.Chtimes(path, ago, ago)
|
||||
packThread(t, path)
|
||||
fi, _ := os.Stat(path + ".zst")
|
||||
stamp[id] = fi.ModTime()
|
||||
mode := "paginated"
|
||||
if id == legacy {
|
||||
mode = "legacy"
|
||||
}
|
||||
if _, err := db.Exec(`UPDATE threads SET history_mode = ?, updated_at = ? WHERE id = ?`, mode, ago.Unix(), id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// a Codex has open (codex-rs rollout writer_lock.rs)
|
||||
locks := filepath.Join(dir, "thread-writer-locks")
|
||||
os.MkdirAll(locks, 0o755)
|
||||
lf, err := os.OpenFile(filepath.Join(locks, open+".lock"), os.O_CREATE|os.O_RDWR, 0o600)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := filelock.TryLock(lf); !got {
|
||||
t.Fatal("lock:", err)
|
||||
}
|
||||
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 an API key", p)
|
||||
}
|
||||
want := map[string]string{old: "magpie", open: "openai", legacy: "openai", theirs: "custom"}
|
||||
for _, id := range many {
|
||||
want[id] = "magpie"
|
||||
}
|
||||
check := func(when string) {
|
||||
t.Helper()
|
||||
for id, w := range want {
|
||||
if p := codexRowOn(t, dir, id); p != w {
|
||||
t.Errorf("%s: thread %s on %q, want %q", when, id, p, w)
|
||||
}
|
||||
}
|
||||
for id, at := range stamp {
|
||||
z := filepath.Join(dir, "sessions", "2026", "10", "21", "rollout-2026-10-21T10-00-00-"+id+".jsonl.zst")
|
||||
fi, err := os.Stat(z)
|
||||
if err != nil || !fi.ModTime().Equal(at) {
|
||||
t.Fatalf("%s: thread %s's file written: %v", when, id, err)
|
||||
}
|
||||
on := "openai"
|
||||
if id == theirs {
|
||||
on = "custom"
|
||||
}
|
||||
if p := zstMetaProvider(t, z); p != on {
|
||||
t.Fatalf("%s: thread %s's file names %q", when, id, p)
|
||||
}
|
||||
}
|
||||
if l, _ := filepath.Glob(filepath.Join(settings.Dir(), "trash", "codex-provider", "*")); len(l) > 0 {
|
||||
t.Fatalf("%s: copied to the trash: %v", when, l)
|
||||
}
|
||||
}
|
||||
check("connected")
|
||||
// let go, the open one follows at the next sync
|
||||
filelock.Unlock(lf)
|
||||
lf.Close()
|
||||
if err := cx.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want[open] = "magpie"
|
||||
check("let go")
|
||||
if err := cx.Unwire(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for id, w := range want {
|
||||
if w == "magpie" {
|
||||
want[id] = "openai"
|
||||
}
|
||||
}
|
||||
check("disconnected")
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A paginated Codex thread (history_mode "paginated", Codex 0.166 on) is
|
||||
// on the provider its row names: Codex lists and resumes it there, never
|
||||
// reading its files' provider (codex-rs thread-store read_thread).
|
||||
// RetagPagedCodexThreads moves it by that row alone, of any age, packed
|
||||
// or not, and an id of any length (a paginated file can't be rewritten
|
||||
// with a longer one), its files not touched; a legacy thread, whose
|
||||
// provider is its file's, stays. The Sessions page lists it on the
|
||||
// provider its row names, so it isn't offered a Move it had.
|
||||
func TestRetagPagedCodexThreads(t *testing.T) {
|
||||
_, codex := manageSetup(t)
|
||||
main := filepath.Join(codex, "sessions", "2026", "09", "20", "rollout-2026-09-20T15-48-28-"+mgCX+".jsonl")
|
||||
b, err := os.ReadFile(main)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old := time.Now().Add(-90 * 24 * time.Hour).Truncate(time.Second)
|
||||
os.Chtimes(main, old, old)
|
||||
os.WriteFile(filepath.Join(codex, "config.toml"), []byte("model = \"gpt-6\"\nmodel_provider = \"magpie\"\n\n[model_providers.magpie]\nname = \"magpie\"\n"), 0o644)
|
||||
p := filepath.Join(codex, "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, history_mode TEXT NOT NULL DEFAULT 'legacy');
|
||||
INSERT INTO threads VALUES (?, ?, 'openai', 'paginated'), ('legacy-one', 'y', 'openai', 'legacy'), ('relayed', 'z', 'my-relay', 'paginated')`, mgCX, main); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
row := func(id string) string {
|
||||
var s string
|
||||
if err := db.QueryRow(`SELECT model_provider FROM threads WHERE id = ?`, id).Scan(&s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
if m, _ := findManaged(ListAgent("codex"), mgCX); m.Provider != "openai" || m.UsesProvider != "magpie" {
|
||||
t.Fatalf("listed %q, uses %q", m.Provider, m.UsesProvider)
|
||||
}
|
||||
moved, err := RetagPagedCodexThreads(codex, "openai", "magpie")
|
||||
if err != nil || len(moved) != 1 || moved[0] != mgCX {
|
||||
t.Fatalf("moved %v, %v", moved, err)
|
||||
}
|
||||
if row(mgCX) != "magpie" || row("legacy-one") != "openai" || row("relayed") != "my-relay" {
|
||||
t.Fatalf("rows: %s %s %s", row(mgCX), row("legacy-one"), row("relayed"))
|
||||
}
|
||||
if b2, _ := os.ReadFile(main); !bytes.Equal(b, b2) {
|
||||
t.Fatal("the file was written")
|
||||
}
|
||||
if fi, _ := os.Stat(main); !fi.ModTime().Equal(old) {
|
||||
t.Fatalf("the file's time: %v", fi.ModTime())
|
||||
}
|
||||
if m, _ := findManaged(ListAgent("codex"), mgCX); m.Provider != "magpie" {
|
||||
t.Fatalf("listed on %q after the move, want its row's magpie", m.Provider)
|
||||
}
|
||||
// an id of another length, and back
|
||||
if moved, err := RetagPagedCodexThreads(codex, "my-relay", "magpie"); err != nil || len(moved) != 1 {
|
||||
t.Fatalf("moved %v, %v", moved, err)
|
||||
}
|
||||
if moved, err := RetagPagedCodexThreadIDs(codex, "magpie", "my-relay", []string{"relayed"}); err != nil || len(moved) != 1 || row("relayed") != "my-relay" || row(mgCX) != "magpie" {
|
||||
t.Fatalf("moved %v, %v: %s %s", moved, err, row("relayed"), row(mgCX))
|
||||
}
|
||||
if moved, err := RetagPagedCodexThreads(codex, "magpie", "openai"); err != nil || len(moved) != 1 || row(mgCX) != "openai" {
|
||||
t.Fatalf("back: %v, %v, %s", moved, err, row(mgCX))
|
||||
}
|
||||
// a Codex from before history_mode: its threads go by their files
|
||||
if _, err := db.Exec(`ALTER TABLE threads DROP COLUMN history_mode`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if moved, err := RetagPagedCodexThreads(codex, "openai", "magpie"); err != nil || len(moved) != 0 {
|
||||
t.Fatalf("moved %v, %v with no history_mode", moved, err)
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/klauspost/compress/zstd"
|
||||
@@ -151,6 +152,7 @@ func codexStateDBs(home string) []string {
|
||||
// Codex uses now: read from the file once, then kept in the cache.
|
||||
func codexProviders(out []Managed, groups map[string][]file) {
|
||||
homes := map[string]string{}
|
||||
paged := map[string]map[string]string{}
|
||||
filled := false
|
||||
for i := range out {
|
||||
m := &out[i]
|
||||
@@ -180,6 +182,12 @@ func codexProviders(out []Managed, groups map[string][]file) {
|
||||
home := codexHomeOf(main.path)
|
||||
if _, ok := homes[home]; !ok {
|
||||
homes[home] = CodexProviderIn(home)
|
||||
paged[home] = codexPagedProviders(home)
|
||||
}
|
||||
// a paginated thread is on the provider its row names, which
|
||||
// RetagPagedCodexThreads moves without its files
|
||||
if p := paged[home][m.ID]; p != "" {
|
||||
m.Provider = p
|
||||
}
|
||||
m.UsesProvider = homes[home]
|
||||
}
|
||||
@@ -188,6 +196,80 @@ func codexProviders(out []Managed, groups map[string][]file) {
|
||||
}
|
||||
}
|
||||
|
||||
// pagedMemo keeps each state database's paginated threads' providers
|
||||
// while the database and its write-ahead log are as they were: Sessions
|
||||
// asks on every poll, and a history is thousands of rows.
|
||||
var pagedMemo = struct {
|
||||
sync.Mutex
|
||||
m map[string]pagedRead
|
||||
}{m: map[string]pagedRead{}}
|
||||
|
||||
type pagedRead struct {
|
||||
stamp string
|
||||
ids map[string]string
|
||||
}
|
||||
|
||||
// codexPagedProviders are the providers a Codex folder's state databases
|
||||
// keep for its paginated threads, by id. A database without history_mode
|
||||
// (an older Codex), or one that can't be read, says nothing.
|
||||
func codexPagedProviders(home string) map[string]string {
|
||||
out := map[string]string{}
|
||||
for _, p := range codexStateDBs(home) {
|
||||
stamp := ""
|
||||
for _, f := range []string{p, p + "-wal"} {
|
||||
if fi, err := os.Stat(f); err == nil {
|
||||
stamp += fmt.Sprintf("%d.%d;", fi.ModTime().UnixNano(), fi.Size())
|
||||
}
|
||||
}
|
||||
pagedMemo.Lock()
|
||||
r, ok := pagedMemo.m[p]
|
||||
pagedMemo.Unlock()
|
||||
if !ok || r.stamp != stamp {
|
||||
r = pagedRead{stamp: stamp, ids: readPagedProviders(p)}
|
||||
pagedMemo.Lock()
|
||||
pagedMemo.m[p] = r
|
||||
pagedMemo.Unlock()
|
||||
}
|
||||
for id, prov := range r.ids {
|
||||
out[id] = prov
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// forgetPaged drops what codexPagedProviders read: magpie wrote a row
|
||||
func forgetPaged() {
|
||||
pagedMemo.Lock()
|
||||
clear(pagedMemo.m)
|
||||
pagedMemo.Unlock()
|
||||
}
|
||||
|
||||
func readPagedProviders(path string) map[string]string {
|
||||
ids := map[string]string{}
|
||||
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 {
|
||||
return ids
|
||||
}
|
||||
defer db.Close()
|
||||
rows, err := db.Query(`SELECT id, model_provider FROM threads WHERE history_mode = 'paginated'`)
|
||||
if err != nil {
|
||||
return ids
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var id string
|
||||
var prov sql.NullString
|
||||
if rows.Scan(&id, &prov) == nil && codexProviderRe.MatchString(prov.String) {
|
||||
ids[id] = prov.String
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// MoveCodexProvider moves a Codex session to the provider to: the
|
||||
// model_provider of each session_meta in its files, and of its row in
|
||||
// Codex's state database. A session written to in the last minute is left
|
||||
@@ -813,6 +895,7 @@ func moveCodexThread(path, id, to string) (bool, error) {
|
||||
if err := db.QueryRow(`SELECT count(*) FROM pragma_table_info('threads') WHERE name IN ('id','model_provider')`).Scan(&n); err != nil || n != 2 {
|
||||
return false, nil
|
||||
}
|
||||
defer forgetPaged()
|
||||
res, err := db.Exec(`UPDATE threads SET model_provider = ? WHERE id = ?`, to, id)
|
||||
if err != nil {
|
||||
return false, err
|
||||
@@ -978,3 +1061,152 @@ func sameDir(a, b string) bool {
|
||||
fb, err := os.Stat(b)
|
||||
return err == nil && os.SameFile(fa, fb)
|
||||
}
|
||||
|
||||
// RetagPagedCodexThreads moves the paginated threads of a Codex folder
|
||||
// (history_mode "paginated", Codex 0.166 on) that its state databases keep
|
||||
// on the provider from to the provider to, by their rows alone. Codex
|
||||
// reads such a thread's provider from its row, never from its files: a
|
||||
// paginated rollout may hold only a suffix of the thread, so its listing
|
||||
// and its resume take the row's (codex-rs thread-store read_thread,
|
||||
// "Paginated history may contain only a suffix, so its display metadata
|
||||
// lives in SQLite"), and resume refuses a provider other than the one
|
||||
// Codex is on ("This chat uses openai, but your current provider is
|
||||
// magpie. Switch to openai to continue", Parry_Moody and Cyrus on
|
||||
// Discord). The file moves (RelabelCodexThreads, MovePackedCodexThreads)
|
||||
// left every packed one older than 30 days, and every one past a sync's
|
||||
// budget, on the provider it was started on; a row is a few bytes, so
|
||||
// every one moves at once, of any age and any id's length, no file read,
|
||||
// written or copied, and moving them back is the undo. A thread a Codex
|
||||
// has open, whose writer would put its provider back, and one written to
|
||||
// in the last minute stay for the next call, as do a database without
|
||||
// history_mode (an older Codex, whose threads go by their files) and a
|
||||
// legacy thread. It says the ids it moved and the first error it met,
|
||||
// having gone on past it.
|
||||
func RetagPagedCodexThreads(home, from, to string) ([]string, error) {
|
||||
return retagPagedCodexThreads(home, from, to, nil)
|
||||
}
|
||||
|
||||
// RetagPagedCodexThreadIDs is RetagPagedCodexThreads for those of the
|
||||
// threads ids still on from: to undo a move of those threads alone.
|
||||
func RetagPagedCodexThreadIDs(home, from, to string, ids []string) ([]string, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return retagPagedCodexThreads(home, from, to, ids)
|
||||
}
|
||||
|
||||
func retagPagedCodexThreads(home, from, to string, only []string) ([]string, 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)
|
||||
}
|
||||
var moved []string
|
||||
var first error
|
||||
fail := func(err error) {
|
||||
if first == nil {
|
||||
first = err
|
||||
}
|
||||
}
|
||||
for _, p := range codexStateDBs(home) {
|
||||
ids, err := retagPaged(home, p, from, to, only)
|
||||
moved = append(moved, ids...)
|
||||
if err != nil {
|
||||
fail(fmt.Errorf("Codex's %s: %w", filepath.Base(p), err))
|
||||
}
|
||||
}
|
||||
return moved, first
|
||||
}
|
||||
|
||||
// retagPaged is RetagPagedCodexThreads for one state database, a chunk of
|
||||
// threads held and written in one transaction at a time; with only, those
|
||||
// of its ids alone.
|
||||
func retagPaged(home, path, from, to string, only []string) ([]string, error) {
|
||||
u := url.URL{Scheme: "file", Path: filepath.ToSlash(path), RawQuery: "_pragma=busy_timeout(5000)"}
|
||||
if len(u.Path) >= 2 && u.Path[1] == ':' {
|
||||
u.Path = "/" + u.Path
|
||||
}
|
||||
db, err := sql.Open("sqlite", u.String())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer db.Close()
|
||||
var n int
|
||||
if err := db.QueryRow(`SELECT count(*) FROM pragma_table_info('threads') WHERE name IN ('id','model_provider','history_mode','rollout_path')`).Scan(&n); err != nil || n != 4 {
|
||||
return nil, nil
|
||||
}
|
||||
type row struct{ id, path string }
|
||||
var rows []row
|
||||
rs, err := db.Query(`SELECT id, rollout_path FROM threads WHERE model_provider = ? AND history_mode = 'paginated'`, from)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for rs.Next() {
|
||||
var r row
|
||||
if rs.Scan(&r.id, &r.path) == nil && safeID.MatchString(r.id) && (only == nil || contains(only, r.id)) {
|
||||
rows = append(rows, r)
|
||||
}
|
||||
}
|
||||
rs.Close()
|
||||
var moved []string
|
||||
var first error
|
||||
now := time.Now()
|
||||
const chunk = 200
|
||||
for len(rows) > 0 {
|
||||
part := rows[:min(chunk, len(rows))]
|
||||
rows = rows[len(part):]
|
||||
var held []string
|
||||
var letGos []func()
|
||||
for _, r := range part {
|
||||
if r.path != "" {
|
||||
if fi, err := os.Stat(filepath.Clean(r.path)); err == nil && now.Sub(fi.ModTime()) < ActiveWindow {
|
||||
continue
|
||||
}
|
||||
}
|
||||
letGo, err := holdCodexThread(home, r.id)
|
||||
if err != nil {
|
||||
if !errors.Is(err, ErrActive) && first == nil {
|
||||
first = fmt.Errorf("thread %s: %w", r.id, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
letGos = append(letGos, letGo)
|
||||
held = append(held, r.id)
|
||||
}
|
||||
done, err := retagRows(db, held, from, to)
|
||||
forgetPaged()
|
||||
for _, letGo := range letGos {
|
||||
letGo()
|
||||
}
|
||||
moved = append(moved, done...)
|
||||
if err != nil && first == nil {
|
||||
first = err
|
||||
}
|
||||
}
|
||||
return moved, first
|
||||
}
|
||||
|
||||
// retagRows sets the rows ids still on from, and paginated, to to, in one
|
||||
// transaction, and says which ones it set.
|
||||
func retagRows(db *sql.DB, ids []string, from, to string) ([]string, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var done []string
|
||||
for _, id := range ids {
|
||||
res, err := tx.Exec(`UPDATE threads SET model_provider = ? WHERE id = ? AND model_provider = ? AND history_mode = 'paginated'`, to, id, from)
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
return nil, err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n > 0 {
|
||||
done = append(done, id)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return done, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user