sessions: a deleted Codex session leaves the Codex app's list too
zhuddan (Discord, Codex app 26.1023): a Codex conversation deleted in magpie went on showing in the Codex app. The app lists threads from its own catalog, <CODEX_HOME>/sqlite/codex.db (codex-dev.db for a non-prod build), table local_thread_catalog, and drops a row only on the app-server's thread/deleted or thread/archived. After its first full sweep it takes in only threads newer than its watermark, so a row of a thread whose rollout magpie moved to its trash stayed. Delete now does what the app does on thread/deleted: the local host's rows of threads whose rollout is gone from that Codex folder's sessions and archived_sessions (as Codex's state database names them; neither the file nor its packed twin there, and a file that can't be looked at counts as there) are deleted and catalog_revision raised, in one BEGIN IMMEDIATE transaction that waits for the app's own. The rows go into the trash note (codex_catalog) and Restore puts them back, since the app wouldn't take in a thread that old by itself. /api/sessions/manage does the same once a run (TidyCodexCatalog) for threads deleted before this release. Run (Windows, win-run, go1.26.8): - go test -count=1 -v -timeout 25m ./internal/sessions/: 339 PASS, including TestDeleteForgetsCodexAppCatalog, TestTidyCodexCatalogForgetsEarlierDeletes and TestTidyCodexCatalogKeepsWhatItCantJudge. Red: TestAgySessions, TestAgyRowOnly (#4115), TestOneListing and TestShareListing hanging the package (#4114). The same four are red at origin/mainbc247a8ccon the same box, run alone. A second run also had TestPurgeOne, TestPurgeAll, TestUnchangedPackedNotReadAgain red and TestReadNotHeldByAnotherRead hanging, and internal/gui TestGatewaySessionHistoryAndCalendar red; all the same atbc247a8cc(#4177). After the rebase onto origin/main (mote, go test -count=1 ./internal/sessions/ ./internal/gui/): sessions ok; gui red only in ten AppKit window tests killed at 30s (TestPanelCloseHidesIt, TestMainWindowCorners and others), mote's pboard being down (#4125). Broken by hand: forgetCodexCatalog returning nothing turns TestDeleteForgetsCodexAppCatalog and TestTidyCodexCatalogForgetsEarlierDeletes red. Not tried: the real Codex app (its catalog is in the owner's live ~/.codex, which sessions never touch); the schemas in testdata are Codex 26.1023's.
This commit is contained in:
@@ -154,6 +154,24 @@ list the session), and `HasGatewayConversations` counts it.
|
||||
Implementation: [`internal/sessions/gateway_delete.go`](../../internal/sessions/gateway_delete.go),
|
||||
`Restore` in [`internal/sessions/manage.go`](../../internal/sessions/manage.go), and
|
||||
[`internal/gui/sessions_manage.go`](../../internal/gui/sessions_manage.go).
|
||||
A deleted Codex session also leaves the Codex app's list (zhuddan on Discord).
|
||||
The app (ChatGPT.app's Codex, 26.x) lists threads from its own catalog,
|
||||
`<CODEX_HOME>/sqlite/codex.db` (`codex-dev.db` for a non-prod build), table
|
||||
`local_thread_catalog`, and drops a row only on the app-server's
|
||||
`thread/deleted` or `thread/archived`; after its first full sweep it takes in
|
||||
only threads newer than its watermark. Delete removes the local host's rows of
|
||||
threads whose rollout is gone from that Codex folder's `sessions` and
|
||||
`archived_sessions` (named by Codex's state database, neither the file nor its
|
||||
packed twin there; a file that can't be looked at counts as there) and raises
|
||||
`catalog_revision`, in one `BEGIN IMMEDIATE` transaction that waits for the
|
||||
app's own. The removed rows go into the trash note (`codex_catalog`), and
|
||||
Restore puts them back. `/api/sessions/manage` does the same once a run
|
||||
(`TidyCodexCatalog`) for threads deleted before this. Implementation:
|
||||
[`internal/sessions/codex_catalog.go`](../../internal/sessions/codex_catalog.go);
|
||||
verification: `TestDeleteForgetsCodexAppCatalog`,
|
||||
`TestTidyCodexCatalogForgetsEarlierDeletes`,
|
||||
`TestTidyCodexCatalogKeepsWhatItCantJudge`, with schemas from Codex 26.1023 in
|
||||
`internal/sessions/testdata/codex-app/`.
|
||||
All-time statistics include gateway history older than native files. Calendar
|
||||
activity and output totals use each session's actual request dates, including
|
||||
intermediate dates; extending the range rebases existing native calendar indices.
|
||||
|
||||
@@ -116,6 +116,9 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) {
|
||||
// manage is the agents with sessions, and every session of ?agent=
|
||||
// (the one with the most when none is named), and the trash.
|
||||
mux.HandleFunc("GET /api/sessions/manage", func(rw http.ResponseWriter, r *http.Request) {
|
||||
// the Codex app's list forgets the threads deleted before it
|
||||
// was told of each delete, once a run
|
||||
sessions.TidyCodexCatalog()
|
||||
defer sessions.OneListing()()
|
||||
looks := agentLooks()
|
||||
out := struct {
|
||||
|
||||
@@ -0,0 +1,419 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The Codex app (ChatGPT.app's Codex, 26.x) lists conversations from a
|
||||
// catalog of its own, not from the rollouts: <CODEX_HOME>/sqlite/codex.db
|
||||
// (codex-dev.db for a build whose BUILD_FLAVOR isn't "prod"), table
|
||||
// local_thread_catalog, a row per host and thread. It fills the catalog
|
||||
// from its app-server's thread/list, but once its first full sweep is done
|
||||
// (local_thread_catalog_sync_state.last_full_reconciled_at) it only takes
|
||||
// in threads updated since its watermark. A row leaves the catalog only on
|
||||
// the app-server's thread/deleted or thread/archived notification
|
||||
// (removeThreadFromCatalog), which Codex's own delete sends. A rollout
|
||||
// magpie moved to its trash was no longer listed by the app-server
|
||||
// (thread/list skips a thread whose rollout is gone), but its catalog row
|
||||
// stayed, so the app went on listing it (zhuddan on Discord, Codex
|
||||
// 26.1023).
|
||||
//
|
||||
// forgetCodexCatalog does what the app does on thread/deleted: the local
|
||||
// host's row of a thread whose rollout is gone is deleted and
|
||||
// catalog_revision raised, in one write transaction that waits for the
|
||||
// app's own. Only threads Codex's state database names with a rollout
|
||||
// under that Codex folder's sessions or archived_sessions, and neither it
|
||||
// nor its packed twin there, are forgotten; a rollout that can't be
|
||||
// looked at counts as there. The rows of a thread in magpie's trash are
|
||||
// kept in its note, and Restore puts them back, since the app wouldn't
|
||||
// take in a thread that old again.
|
||||
|
||||
// codexCatalogNames are the Codex app's database names, by build flavor.
|
||||
var codexCatalogNames = []string{"codex.db", "codex-dev.db"}
|
||||
|
||||
// codexCatalogRow is a catalog row taken out, to be put back on Restore.
|
||||
type codexCatalogRow struct {
|
||||
DB string `json:"db"`
|
||||
Cols []string `json:"cols"`
|
||||
Vals []sqlValue `json:"vals"`
|
||||
}
|
||||
|
||||
// sqlValue is a column's value with its SQLite type: none set is NULL.
|
||||
type sqlValue struct {
|
||||
I *int64 `json:"i,omitempty"`
|
||||
R *float64 `json:"r,omitempty"`
|
||||
S *string `json:"s,omitempty"`
|
||||
B []byte `json:"b,omitempty"`
|
||||
}
|
||||
|
||||
func toSQLValue(v any) sqlValue {
|
||||
switch x := v.(type) {
|
||||
case int64:
|
||||
return sqlValue{I: &x}
|
||||
case float64:
|
||||
return sqlValue{R: &x}
|
||||
case string:
|
||||
return sqlValue{S: &x}
|
||||
case []byte:
|
||||
return sqlValue{B: append([]byte{}, x...)}
|
||||
case bool:
|
||||
n := int64(0)
|
||||
if x {
|
||||
n = 1
|
||||
}
|
||||
return sqlValue{I: &n}
|
||||
case time.Time:
|
||||
s := x.Format(time.RFC3339Nano)
|
||||
return sqlValue{S: &s}
|
||||
}
|
||||
return sqlValue{}
|
||||
}
|
||||
|
||||
func (v sqlValue) value() any {
|
||||
switch {
|
||||
case v.I != nil:
|
||||
return *v.I
|
||||
case v.R != nil:
|
||||
return *v.R
|
||||
case v.S != nil:
|
||||
return *v.S
|
||||
case v.B != nil:
|
||||
return v.B
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// codexCatalogDBs are the Codex app's catalog databases of a Codex folder.
|
||||
func codexCatalogDBs(home string) []string {
|
||||
var out []string
|
||||
for _, n := range codexCatalogNames {
|
||||
p := filepath.Join(home, "sqlite", n)
|
||||
if fi, err := os.Stat(p); err == nil && fi.Mode().IsRegular() {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// sqliteURL is a database's file: URL with query q.
|
||||
func sqliteURL(path, q string) string {
|
||||
u := url.URL{Scheme: "file", Path: filepath.ToSlash(path), RawQuery: q}
|
||||
if len(u.Path) >= 2 && u.Path[1] == ':' {
|
||||
u.Path = "/" + u.Path
|
||||
}
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// codexGoneThreads are the threads a Codex folder's state databases name
|
||||
// whose rollout is gone from its sessions or archived_sessions.
|
||||
func codexGoneThreads(home string) map[string]bool {
|
||||
gone := map[string]bool{}
|
||||
// Codex may write the path through the folder's real name (/private/var
|
||||
// for /var on macOS), so both spellings count
|
||||
var roots []string
|
||||
for _, h := range []string{filepath.Clean(home), sameDirKey(home)} {
|
||||
roots = append(roots, filepath.Join(h, "sessions"), filepath.Join(h, "archived_sessions"))
|
||||
}
|
||||
for _, p := range codexStateDBs(home) {
|
||||
db, err := sql.Open("sqlite", sqliteURL(p, "mode=ro&_pragma=busy_timeout(2000)"))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
rs, err := db.Query(`SELECT id, rollout_path FROM threads`)
|
||||
if err != nil {
|
||||
db.Close()
|
||||
continue
|
||||
}
|
||||
for rs.Next() {
|
||||
var id, path string
|
||||
if rs.Scan(&id, &path) != nil || !safeID.MatchString(id) || !filepath.IsAbs(path) {
|
||||
continue
|
||||
}
|
||||
path = filepath.Clean(path)
|
||||
if !inside(path, roots) || !strings.Contains(filepath.Base(path), id) {
|
||||
continue
|
||||
}
|
||||
if missing(path) && missing(rolloutTwin(path)) {
|
||||
gone[id] = true
|
||||
}
|
||||
}
|
||||
rs.Close()
|
||||
db.Close()
|
||||
}
|
||||
return gone
|
||||
}
|
||||
|
||||
// missing says whether p is known not to be there: an error other than
|
||||
// "not there" is not knowing.
|
||||
func missing(p string) bool {
|
||||
_, err := os.Lstat(p)
|
||||
return errors.Is(err, fs.ErrNotExist)
|
||||
}
|
||||
|
||||
// forgetCodexCatalog takes the local host's catalog rows of the Codex
|
||||
// folder's threads whose rollout is gone out of the Codex app's catalog,
|
||||
// and says the rows it took out, by thread.
|
||||
func forgetCodexCatalog(home string) (map[string][]codexCatalogRow, error) {
|
||||
dbs := codexCatalogDBs(home)
|
||||
if len(dbs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
gone := codexGoneThreads(home)
|
||||
if len(gone) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
out := map[string][]codexCatalogRow{}
|
||||
var first error
|
||||
for _, p := range dbs {
|
||||
if err := forgetIn(p, gone, out); err != nil && first == nil {
|
||||
first = err
|
||||
}
|
||||
}
|
||||
return out, first
|
||||
}
|
||||
|
||||
func forgetIn(path string, gone map[string]bool, out map[string][]codexCatalogRow) error {
|
||||
db, err := sql.Open("sqlite", sqliteURL(path, "_pragma=busy_timeout(5000)"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
ctx := context.Background()
|
||||
conn, err := db.Conn(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
var n int
|
||||
// another version of the app: nothing to do
|
||||
if err := conn.QueryRowContext(ctx, `SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name IN ('local_thread_catalog', 'local_thread_catalog_hosts')`).Scan(&n); err != nil || n != 2 {
|
||||
return nil
|
||||
}
|
||||
ids, _ := json.Marshal(keys(gone))
|
||||
// the write lock first, so the rows read are the rows deleted
|
||||
if _, err := conn.ExecContext(ctx, `BEGIN IMMEDIATE`); err != nil {
|
||||
return err
|
||||
}
|
||||
done := false
|
||||
defer func() {
|
||||
if !done {
|
||||
conn.ExecContext(ctx, `ROLLBACK`)
|
||||
}
|
||||
}()
|
||||
rs, err := conn.QueryContext(ctx, `SELECT * FROM local_thread_catalog
|
||||
WHERE thread_id IN (SELECT value FROM json_each(?))
|
||||
AND host_id IN (SELECT host_id FROM local_thread_catalog_hosts WHERE host_kind = 'local')`, string(ids))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cols, _ := rs.Columns()
|
||||
type taken struct {
|
||||
host, thread string
|
||||
row codexCatalogRow
|
||||
}
|
||||
var rows []taken
|
||||
for rs.Next() {
|
||||
vals := make([]any, len(cols))
|
||||
ptrs := make([]any, len(cols))
|
||||
for i := range vals {
|
||||
ptrs[i] = &vals[i]
|
||||
}
|
||||
if err := rs.Scan(ptrs...); err != nil {
|
||||
rs.Close()
|
||||
return err
|
||||
}
|
||||
t := taken{row: codexCatalogRow{DB: path, Cols: cols}}
|
||||
for i, c := range cols {
|
||||
v := toSQLValue(vals[i])
|
||||
t.row.Vals = append(t.row.Vals, v)
|
||||
if v.S != nil && c == "host_id" {
|
||||
t.host = *v.S
|
||||
}
|
||||
if v.S != nil && c == "thread_id" {
|
||||
t.thread = *v.S
|
||||
}
|
||||
}
|
||||
rows = append(rows, t)
|
||||
}
|
||||
rs.Close()
|
||||
if err := rs.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
for _, t := range rows {
|
||||
if _, err := conn.ExecContext(ctx, `DELETE FROM local_thread_catalog WHERE host_id = ? AND thread_id = ?`, t.host, t.thread); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
bumpCatalogRevision(ctx, conn)
|
||||
if _, err := conn.ExecContext(ctx, `COMMIT`); err != nil {
|
||||
return err
|
||||
}
|
||||
done = true
|
||||
for _, t := range rows {
|
||||
out[t.thread] = append(out[t.thread], t.row)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// bumpCatalogRevision raises the catalog's revision, as the app does on
|
||||
// each change it makes, where the database has one.
|
||||
func bumpCatalogRevision(ctx context.Context, conn *sql.Conn) {
|
||||
conn.ExecContext(ctx, `UPDATE local_thread_catalog_metadata SET catalog_revision = catalog_revision + 1 WHERE id = 1`)
|
||||
}
|
||||
|
||||
func keys(m map[string]bool) []string {
|
||||
out := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
out = append(out, k)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// restoreCodexCatalog puts a restored thread's catalog rows back, with the
|
||||
// columns the table has now; a row the app has again is left as it is.
|
||||
func restoreCodexCatalog(rows []codexCatalogRow) error {
|
||||
by := map[string][]codexCatalogRow{}
|
||||
for _, r := range rows {
|
||||
if len(r.Cols) == 0 || len(r.Cols) != len(r.Vals) || !filepath.IsAbs(r.DB) || !contains(codexCatalogNames, filepath.Base(r.DB)) {
|
||||
continue
|
||||
}
|
||||
by[r.DB] = append(by[r.DB], r)
|
||||
}
|
||||
var first error
|
||||
for p, rs := range by {
|
||||
if err := restoreIn(p, rs); err != nil && first == nil {
|
||||
first = err
|
||||
}
|
||||
}
|
||||
return first
|
||||
}
|
||||
|
||||
func restoreIn(path string, rows []codexCatalogRow) error {
|
||||
if fi, err := os.Stat(path); err != nil || !fi.Mode().IsRegular() {
|
||||
return nil
|
||||
}
|
||||
db, err := sql.Open("sqlite", sqliteURL(path, "_pragma=busy_timeout(5000)"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
ctx := context.Background()
|
||||
conn, err := db.Conn(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
have := map[string]bool{}
|
||||
rs, err := conn.QueryContext(ctx, `SELECT name FROM pragma_table_info('local_thread_catalog')`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for rs.Next() {
|
||||
var n string
|
||||
if rs.Scan(&n) == nil {
|
||||
have[n] = true
|
||||
}
|
||||
}
|
||||
rs.Close()
|
||||
if !have["host_id"] || !have["thread_id"] {
|
||||
return nil
|
||||
}
|
||||
if _, err := conn.ExecContext(ctx, `BEGIN IMMEDIATE`); err != nil {
|
||||
return err
|
||||
}
|
||||
added := int64(0)
|
||||
for _, r := range rows {
|
||||
var cols, marks []string
|
||||
var args []any
|
||||
for i, c := range r.Cols {
|
||||
if have[c] {
|
||||
cols = append(cols, `"`+strings.ReplaceAll(c, `"`, `""`)+`"`)
|
||||
marks = append(marks, "?")
|
||||
args = append(args, r.Vals[i].value())
|
||||
}
|
||||
}
|
||||
res, err := conn.ExecContext(ctx, `INSERT OR IGNORE INTO local_thread_catalog (`+strings.Join(cols, ", ")+`) VALUES (`+strings.Join(marks, ", ")+`)`, args...)
|
||||
if err != nil {
|
||||
conn.ExecContext(ctx, `ROLLBACK`)
|
||||
return err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
added += n
|
||||
}
|
||||
if added > 0 {
|
||||
bumpCatalogRevision(ctx, conn)
|
||||
}
|
||||
_, err = conn.ExecContext(ctx, `COMMIT`)
|
||||
return err
|
||||
}
|
||||
|
||||
// tidyCodexCatalog forgets, in each Codex folder, the catalog rows of the
|
||||
// threads whose rollout is gone, and keeps the rows of those in magpie's
|
||||
// trash in their notes. The caller holds mu.
|
||||
func tidyCodexCatalog(homes []string) error {
|
||||
var first error
|
||||
took := map[string][]codexCatalogRow{}
|
||||
seen := map[string]bool{}
|
||||
for _, h := range homes {
|
||||
if h == "" || seen[sameDirKey(h)] {
|
||||
continue
|
||||
}
|
||||
seen[sameDirKey(h)] = true
|
||||
rows, err := forgetCodexCatalog(h)
|
||||
if err != nil && first == nil {
|
||||
first = err
|
||||
}
|
||||
for id, rs := range rows {
|
||||
took[id] = append(took[id], rs...)
|
||||
}
|
||||
}
|
||||
if len(took) == 0 {
|
||||
return first
|
||||
}
|
||||
notes, _ := filepath.Glob(filepath.Join(TrashDir(), "codex", "*", manifest))
|
||||
for _, p := range notes {
|
||||
var t Trashed
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil || json.Unmarshal(b, &t) != nil || len(took[t.ID]) == 0 {
|
||||
continue
|
||||
}
|
||||
t.CodexCatalog = append(t.CodexCatalog, took[t.ID]...)
|
||||
if err := writeManifest(filepath.Dir(p), t); err != nil && first == nil {
|
||||
first = err
|
||||
}
|
||||
}
|
||||
return first
|
||||
}
|
||||
|
||||
func sameDirKey(p string) string {
|
||||
if r, err := filepath.EvalSymlinks(p); err == nil {
|
||||
p = r
|
||||
}
|
||||
return filepath.Clean(p)
|
||||
}
|
||||
|
||||
var tidyOnce sync.Once
|
||||
|
||||
// TidyCodexCatalog takes the Codex app's catalog rows of the threads whose
|
||||
// rollout is gone out of it, once a run of magpie: those magpie deleted
|
||||
// before it did so itself.
|
||||
func TidyCodexCatalog() {
|
||||
tidyOnce.Do(func() {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
tidyCodexCatalog(CodexDirs())
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// cxOther is a thread whose rollout is still there: its catalog row stays.
|
||||
const cxOther = "01a183bb-6c1e-7a52-9f0e-2b7d5c3e8a41"
|
||||
|
||||
// cxExecFile runs a schema file the real app or Codex made.
|
||||
func cxExecFile(t *testing.T, db *sql.DB, name string) {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile(filepath.Join("testdata", "codex-app", name))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Exec(string(b)); err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
func cxOpenDB(t *testing.T, path string) *sql.DB {
|
||||
t.Helper()
|
||||
os.MkdirAll(filepath.Dir(path), 0o755)
|
||||
db, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { db.Close() })
|
||||
return db
|
||||
}
|
||||
|
||||
// cxMakeState makes Codex's state_5.sqlite with the real threads table: a
|
||||
// row for mgCX at its first rollout, and one for cxOther at a rollout
|
||||
// that is there.
|
||||
func cxMakeState(t *testing.T, codex string) {
|
||||
t.Helper()
|
||||
db := cxOpenDB(t, filepath.Join(codex, "state_5.sqlite"))
|
||||
cxExecFile(t, db, "state_5.sql")
|
||||
first := filepath.Join(codex, "sessions", "2026", "09", "20", "rollout-2026-09-20T15-48-28-"+mgCX+".jsonl")
|
||||
other := filepath.Join(codex, "sessions", "2026", "09", "21", "rollout-2026-09-21T10-00-00-"+cxOther+".jsonl")
|
||||
os.MkdirAll(filepath.Dir(other), 0o755)
|
||||
if err := os.WriteFile(other, []byte(`{"timestamp":"2026-09-21T10:00:00.000Z","type":"session_meta","payload":{"id":"`+cxOther+`","cwd":"/work/other"}}`+"\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, r := range []struct{ id, path string }{{mgCX, first}, {cxOther, other}} {
|
||||
if _, err := db.Exec(`INSERT INTO threads (id, rollout_path, created_at, updated_at, source, model_provider, cwd, title, sandbox_policy, approval_mode, cli_version, first_user_message, preview) VALUES (?, ?, 1790524108, 1790524300, 'vscode', 'openai', '/work/app', 'Fix the parser', '{"type":"workspace-write"}', 'on-request', '0.165.0-alpha.1.2', 'Fix the parser', 'Fix the parser')`, r.id, r.path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// cxMakeCatalog makes the Codex app's catalog under <codex>/sqlite/name
|
||||
// with the app's own tables: mgCX on the local host and on a ChatGPT host,
|
||||
// cxOther on the local host, catalog_revision 7. The rows are the shape
|
||||
// of a real one (Codex app 26.1021).
|
||||
func cxMakeCatalog(t *testing.T, codex, name string) *sql.DB {
|
||||
t.Helper()
|
||||
db := cxOpenDB(t, filepath.Join(codex, "sqlite", name))
|
||||
cxExecFile(t, db, "catalog.sql")
|
||||
for _, q := range []string{
|
||||
`INSERT INTO local_thread_catalog_hosts VALUES ('local', 'local'), ('chatgpt:acct', 'chatgpt')`,
|
||||
`INSERT INTO local_thread_catalog_metadata VALUES (1, 7)`,
|
||||
`INSERT INTO local_thread_catalog_sync_state (host_id, watermark_updated_at, initial_build_complete, observation_sequence, last_full_reconciled_at) VALUES ('local', 1793211692.0, 1, 368, 1788780881932)`,
|
||||
} {
|
||||
if _, err := db.Exec(q); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, r := range []struct{ host, id string }{{"local", mgCX}, {"chatgpt:acct", mgCX}, {"local", cxOther}} {
|
||||
if _, err := db.Exec(`INSERT INTO local_thread_catalog (host_id, thread_id, display_title, source_created_at, source_updated_at, cwd, source_kind, source_detail, model_provider, git_branch, observation_sequence, missing_candidate, thread_source, source_recency_at, pending_observed_title, project_id, conversation_origin, trial_conversation_type, chatgpt_async_status) VALUES (?, ?, '造型试穿自动任务', 1793211496.0, 1793211692.0, '/work/app', 'vscode', NULL, 'openai', NULL, 368, 0, NULL, 1793211496.0, 0, NULL, NULL, NULL, NULL)`, r.host, r.id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func cxRow(t *testing.T, db *sql.DB, host, id string) (title string, created float64, ok bool) {
|
||||
t.Helper()
|
||||
err := db.QueryRow(`SELECT display_title, source_created_at FROM local_thread_catalog WHERE host_id = ? AND thread_id = ?`, host, id).Scan(&title, &created)
|
||||
if err == sql.ErrNoRows {
|
||||
return "", 0, false
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return title, created, true
|
||||
}
|
||||
|
||||
func cxRevision(t *testing.T, db *sql.DB) int64 {
|
||||
t.Helper()
|
||||
var n int64
|
||||
if err := db.QueryRow(`SELECT catalog_revision FROM local_thread_catalog_metadata WHERE id = 1`).Scan(&n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// Deleting a Codex session takes it out of the Codex app's list too: the
|
||||
// app lists from its catalog and drops a row only when told the thread is
|
||||
// gone (zhuddan on Discord, Codex 26.1023). Restore puts the row back.
|
||||
func TestDeleteForgetsCodexAppCatalog(t *testing.T) {
|
||||
_, codex := manageSetup(t)
|
||||
cxMakeState(t, codex)
|
||||
db := cxMakeCatalog(t, codex, "codex.db")
|
||||
tr, err := Delete("codex", mgCX)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, ok := cxRow(t, db, "local", mgCX); ok {
|
||||
t.Fatal("the Codex app still lists the deleted conversation")
|
||||
}
|
||||
if _, _, ok := cxRow(t, db, "chatgpt:acct", mgCX); !ok {
|
||||
t.Fatal("another host's row was taken out")
|
||||
}
|
||||
if _, _, ok := cxRow(t, db, "local", cxOther); !ok {
|
||||
t.Fatal("a conversation whose rollout is there was taken out")
|
||||
}
|
||||
if n := cxRevision(t, db); n != 8 {
|
||||
t.Fatalf("catalog_revision %d, want 8", n)
|
||||
}
|
||||
var threads int
|
||||
db2 := cxOpenDB(t, filepath.Join(codex, "state_5.sqlite"))
|
||||
db2.QueryRow(`SELECT count(*) FROM threads`).Scan(&threads)
|
||||
if threads != 2 {
|
||||
t.Fatalf("Codex's state database changed: %d threads", threads)
|
||||
}
|
||||
if _, err := Restore(tr.Key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
title, created, ok := cxRow(t, db, "local", mgCX)
|
||||
if !ok || title != "造型试穿自动任务" || created != 1793211496.0 {
|
||||
t.Fatalf("restored row %q %v %v", title, created, ok)
|
||||
}
|
||||
if n := cxRevision(t, db); n != 9 {
|
||||
t.Fatalf("catalog_revision %d after restore, want 9", n)
|
||||
}
|
||||
}
|
||||
|
||||
// A conversation deleted before magpie forgot catalog rows is taken out
|
||||
// of the app's list when the Sessions page is next read, and Restore
|
||||
// still brings it back. The app's non-prod build's codex-dev.db counts.
|
||||
func TestTidyCodexCatalogForgetsEarlierDeletes(t *testing.T) {
|
||||
_, codex := manageSetup(t)
|
||||
cxMakeState(t, codex)
|
||||
tr, err := Delete("codex", mgCX) // no catalog yet: as an older magpie did
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db := cxMakeCatalog(t, codex, "codex-dev.db")
|
||||
tidyOnce = sync.Once{}
|
||||
t.Cleanup(func() { tidyOnce = sync.Once{} })
|
||||
TidyCodexCatalog()
|
||||
if _, _, ok := cxRow(t, db, "local", mgCX); ok {
|
||||
t.Fatal("the earlier delete is still in the Codex app's list")
|
||||
}
|
||||
if _, _, ok := cxRow(t, db, "local", cxOther); !ok {
|
||||
t.Fatal("a conversation whose rollout is there was taken out")
|
||||
}
|
||||
if _, err := Restore(tr.Key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, ok := cxRow(t, db, "local", mgCX); !ok {
|
||||
t.Fatal("Restore didn't put the row the tidy took back")
|
||||
}
|
||||
}
|
||||
|
||||
// A rollout that can't be looked at counts as there, and one the state
|
||||
// database names outside the Codex folder is never judged.
|
||||
func TestTidyCodexCatalogKeepsWhatItCantJudge(t *testing.T) {
|
||||
_, codex := manageSetup(t)
|
||||
cxMakeState(t, codex)
|
||||
db := cxMakeCatalog(t, codex, "codex.db")
|
||||
st := cxOpenDB(t, filepath.Join(codex, "state_5.sqlite"))
|
||||
if _, err := st.Exec(`UPDATE threads SET rollout_path = ? WHERE id = ?`, filepath.Join(t.TempDir(), "rollout-"+cxOther+".jsonl"), cxOther); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tidyCodexCatalog([]string{codex}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, ok := cxRow(t, db, "local", cxOther); !ok {
|
||||
t.Fatal("a row whose rollout is outside the Codex folder was taken out")
|
||||
}
|
||||
if _, _, ok := cxRow(t, db, "local", mgCX); !ok {
|
||||
t.Fatal("a row whose rollout is there was taken out")
|
||||
}
|
||||
if n := cxRevision(t, db); n != 7 {
|
||||
t.Fatalf("catalog_revision %d, want 7", n)
|
||||
}
|
||||
}
|
||||
@@ -314,6 +314,9 @@ type Trashed struct {
|
||||
// Gateway: a session seen only through magpie's gateway, whose items
|
||||
// are the conversation text magpie recorded of it (gateway_delete.go)
|
||||
Gateway bool `json:"gateway,omitempty"`
|
||||
// CodexCatalog: a Codex thread's rows in the Codex app's catalog,
|
||||
// taken out with it and put back on Restore (codex_catalog.go)
|
||||
CodexCatalog []codexCatalogRow `json:"codex_catalog,omitempty"`
|
||||
}
|
||||
|
||||
// moved is one file or folder of a session moved to the trash: where it
|
||||
@@ -427,6 +430,18 @@ func Delete(agent, id string) (Trashed, error) {
|
||||
}
|
||||
saveCache()
|
||||
wslForget(fs)
|
||||
if agent == "codex" {
|
||||
// the Codex app's list of it, which it keeps apart from the files
|
||||
var homes []string
|
||||
for _, p := range paths {
|
||||
homes = append(homes, codexHomeOf(p))
|
||||
}
|
||||
tidyCodexCatalog(homes)
|
||||
if b, err := os.ReadFile(filepath.Join(dir, manifest)); err == nil {
|
||||
json.Unmarshal(b, &t)
|
||||
}
|
||||
t.Key = agent + "/" + name
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
@@ -736,6 +751,11 @@ func Restore(key string) (Trashed, error) {
|
||||
return Trashed{}, err
|
||||
}
|
||||
}
|
||||
// the Codex app lists it again: it wouldn't take in a thread that old
|
||||
// by itself
|
||||
if t.Agent == "codex" && len(t.CodexCatalog) > 0 {
|
||||
restoreCodexCatalog(t.CodexCatalog)
|
||||
}
|
||||
os.RemoveAll(dir)
|
||||
wslRelistNow(t.Items)
|
||||
return t, nil
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
-- The Codex app's catalog tables in <CODEX_HOME>/sqlite/codex.db, as its migrations made them (codex_schema_migrations up to legacy_0034, app 26.901 to 26.1023): sqlite3 .schema
|
||||
CREATE TABLE IF NOT EXISTS "local_thread_catalog" (
|
||||
host_id TEXT NOT NULL,
|
||||
thread_id TEXT NOT NULL,
|
||||
display_title TEXT NOT NULL,
|
||||
source_created_at REAL NOT NULL,
|
||||
source_updated_at REAL NOT NULL,
|
||||
cwd TEXT,
|
||||
source_kind TEXT NOT NULL,
|
||||
source_detail TEXT,
|
||||
model_provider TEXT,
|
||||
git_branch TEXT,
|
||||
observation_sequence INTEGER NOT NULL,
|
||||
missing_candidate INTEGER NOT NULL DEFAULT 0
|
||||
CHECK (missing_candidate IN (0, 1)),
|
||||
thread_source TEXT,
|
||||
source_recency_at REAL NOT NULL DEFAULT 0,
|
||||
pending_observed_title INTEGER NOT NULL DEFAULT 0,
|
||||
project_id TEXT,
|
||||
conversation_origin TEXT, trial_conversation_type TEXT, chatgpt_async_status INTEGER,
|
||||
PRIMARY KEY (host_id, thread_id)
|
||||
);
|
||||
CREATE INDEX local_thread_catalog_updated_idx
|
||||
ON local_thread_catalog (
|
||||
host_id, source_recency_at DESC, source_created_at DESC, thread_id
|
||||
) WHERE missing_candidate = 0;
|
||||
CREATE INDEX local_thread_catalog_created_idx
|
||||
ON local_thread_catalog (
|
||||
host_id, source_created_at DESC, source_updated_at DESC, thread_id
|
||||
) WHERE missing_candidate = 0;
|
||||
CREATE INDEX local_thread_catalog_cwd_updated_idx
|
||||
ON local_thread_catalog (
|
||||
host_id, cwd, source_recency_at DESC, source_created_at DESC,
|
||||
thread_id
|
||||
) WHERE missing_candidate = 0;
|
||||
CREATE INDEX local_thread_catalog_cwd_created_idx
|
||||
ON local_thread_catalog (
|
||||
host_id, cwd, source_created_at DESC, source_updated_at DESC,
|
||||
thread_id
|
||||
) WHERE missing_candidate = 0;
|
||||
CREATE INDEX local_thread_catalog_thread_lookup_idx
|
||||
ON local_thread_catalog (
|
||||
thread_id, source_recency_at DESC, source_created_at DESC, host_id
|
||||
) WHERE missing_candidate = 0;
|
||||
CREATE INDEX local_thread_catalog_project_updated_idx
|
||||
ON local_thread_catalog (
|
||||
host_id, project_id, source_recency_at DESC,
|
||||
source_created_at DESC, thread_id
|
||||
) WHERE missing_candidate = 0;
|
||||
CREATE INDEX local_thread_catalog_origin_updated_idx
|
||||
ON local_thread_catalog (
|
||||
host_id, conversation_origin, source_recency_at DESC,
|
||||
source_created_at DESC, thread_id
|
||||
) WHERE missing_candidate = 0;
|
||||
CREATE TABLE IF NOT EXISTS "local_thread_catalog_hosts" (
|
||||
host_id TEXT PRIMARY KEY,
|
||||
host_kind TEXT NOT NULL CHECK (
|
||||
host_kind IN ('local', 'ssh', 'wsl', 'remote-control', 'chatgpt')
|
||||
)
|
||||
);
|
||||
CREATE TABLE local_thread_catalog_metadata (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
catalog_revision INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE local_thread_catalog_sync_state (
|
||||
host_id TEXT PRIMARY KEY,
|
||||
watermark_updated_at REAL,
|
||||
initial_build_complete INTEGER NOT NULL DEFAULT 0,
|
||||
observation_sequence INTEGER NOT NULL DEFAULT 0
|
||||
, last_full_reconciled_at INTEGER);
|
||||
CREATE TABLE local_thread_catalog_scan_entries (
|
||||
host_id TEXT NOT NULL,
|
||||
thread_id TEXT NOT NULL,
|
||||
removed INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (host_id, thread_id)
|
||||
) WITHOUT ROWID;
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
-- Codex 0.165.0-alpha.1.2's state_5.sqlite (bundled with the Codex app 26.1023.51421), as its app-server made it: sqlite3 .schema of threads and the tables that point at it
|
||||
CREATE TABLE threads (
|
||||
id TEXT PRIMARY KEY,
|
||||
rollout_path TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
source TEXT NOT NULL,
|
||||
model_provider TEXT NOT NULL,
|
||||
cwd TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
sandbox_policy TEXT NOT NULL,
|
||||
approval_mode TEXT NOT NULL,
|
||||
tokens_used INTEGER NOT NULL DEFAULT 0,
|
||||
has_user_event INTEGER NOT NULL DEFAULT 0,
|
||||
archived INTEGER NOT NULL DEFAULT 0,
|
||||
archived_at INTEGER,
|
||||
git_sha TEXT,
|
||||
git_branch TEXT,
|
||||
git_origin_url TEXT
|
||||
, cli_version TEXT NOT NULL DEFAULT '', first_user_message TEXT NOT NULL DEFAULT '', agent_nickname TEXT, agent_role TEXT, memory_mode TEXT NOT NULL DEFAULT 'enabled', model TEXT, reasoning_effort TEXT, agent_path TEXT, created_at_ms INTEGER, updated_at_ms INTEGER, thread_source TEXT, preview TEXT NOT NULL DEFAULT '', recency_at INTEGER NOT NULL DEFAULT 0, recency_at_ms INTEGER NOT NULL DEFAULT 0, history_mode TEXT NOT NULL DEFAULT 'legacy', name TEXT, is_pinned INTEGER NOT NULL DEFAULT 0, thread_section_id TEXT
|
||||
REFERENCES thread_sections(id) ON DELETE SET NULL, section_position INTEGER, section_entered_at_ms INTEGER, project_id TEXT
|
||||
REFERENCES projects(id) ON DELETE SET NULL, originator TEXT, daybreak_enabled BOOLEAN, creator_user_id TEXT, creator_account_id TEXT, attached_thread_parent_id TEXT);
|
||||
CREATE INDEX idx_threads_created_at ON threads(created_at DESC, id DESC);
|
||||
CREATE INDEX idx_threads_updated_at ON threads(updated_at DESC, id DESC);
|
||||
CREATE INDEX idx_threads_archived ON threads(archived);
|
||||
CREATE INDEX idx_threads_source ON threads(source);
|
||||
CREATE INDEX idx_threads_provider ON threads(model_provider);
|
||||
CREATE TRIGGER threads_created_at_ms_after_insert
|
||||
AFTER INSERT ON threads
|
||||
WHEN NEW.created_at_ms IS NULL
|
||||
BEGIN
|
||||
UPDATE threads
|
||||
SET created_at_ms = NEW.created_at * 1000
|
||||
WHERE id = NEW.id;
|
||||
END;
|
||||
CREATE TRIGGER threads_updated_at_ms_after_insert
|
||||
AFTER INSERT ON threads
|
||||
WHEN NEW.updated_at_ms IS NULL
|
||||
BEGIN
|
||||
UPDATE threads
|
||||
SET updated_at_ms = NEW.updated_at * 1000
|
||||
WHERE id = NEW.id;
|
||||
END;
|
||||
CREATE TRIGGER threads_created_at_ms_after_update
|
||||
AFTER UPDATE OF created_at ON threads
|
||||
WHEN NEW.created_at != OLD.created_at
|
||||
AND NEW.created_at_ms IS OLD.created_at_ms
|
||||
BEGIN
|
||||
UPDATE threads
|
||||
SET created_at_ms = NEW.created_at * 1000
|
||||
WHERE id = NEW.id;
|
||||
END;
|
||||
CREATE TRIGGER threads_updated_at_ms_after_update
|
||||
AFTER UPDATE OF updated_at ON threads
|
||||
WHEN NEW.updated_at != OLD.updated_at
|
||||
AND NEW.updated_at_ms IS OLD.updated_at_ms
|
||||
BEGIN
|
||||
UPDATE threads
|
||||
SET updated_at_ms = NEW.updated_at * 1000
|
||||
WHERE id = NEW.id;
|
||||
END;
|
||||
CREATE INDEX idx_threads_created_at_ms ON threads(created_at_ms DESC, id DESC);
|
||||
CREATE INDEX idx_threads_updated_at_ms ON threads(updated_at_ms DESC, id DESC);
|
||||
CREATE INDEX idx_threads_archived_cwd_created_at_ms ON threads(archived, cwd, created_at_ms DESC, id DESC);
|
||||
CREATE INDEX idx_threads_archived_cwd_updated_at_ms ON threads(archived, cwd, updated_at_ms DESC, id DESC);
|
||||
CREATE INDEX idx_threads_visible_created_at_ms
|
||||
ON threads(archived, created_at_ms DESC)
|
||||
WHERE preview <> '';
|
||||
CREATE INDEX idx_threads_visible_updated_at_ms
|
||||
ON threads(archived, updated_at_ms DESC)
|
||||
WHERE preview <> '';
|
||||
CREATE TRIGGER threads_recency_at_after_insert
|
||||
AFTER INSERT ON threads
|
||||
WHEN NEW.recency_at_ms = 0
|
||||
BEGIN
|
||||
UPDATE threads
|
||||
SET recency_at = NEW.updated_at,
|
||||
recency_at_ms = COALESCE(NEW.updated_at_ms, NEW.updated_at * 1000)
|
||||
WHERE id = NEW.id;
|
||||
END;
|
||||
CREATE INDEX idx_threads_recency_at_ms
|
||||
ON threads(recency_at_ms DESC, id DESC);
|
||||
CREATE INDEX idx_threads_archived_cwd_recency_at_ms
|
||||
ON threads(archived, cwd, recency_at_ms DESC, id DESC);
|
||||
CREATE INDEX idx_threads_visible_recency_at_ms
|
||||
ON threads(archived, recency_at_ms DESC, id DESC)
|
||||
WHERE preview <> '';
|
||||
CREATE INDEX idx_threads_pinned_recency_at_ms
|
||||
ON threads(archived, recency_at_ms DESC, id DESC)
|
||||
WHERE is_pinned = 1 AND preview <> '';
|
||||
CREATE INDEX idx_threads_project_id
|
||||
ON threads(project_id, archived, created_at_ms DESC, id DESC)
|
||||
WHERE project_id IS NOT NULL;
|
||||
CREATE INDEX idx_threads_section_recency_at_ms
|
||||
ON threads(archived, thread_section_id, recency_at_ms DESC, id DESC)
|
||||
WHERE thread_section_id IS NOT NULL;
|
||||
CREATE INDEX idx_threads_section_position
|
||||
ON threads(archived, thread_section_id, section_position ASC, id ASC)
|
||||
WHERE thread_section_id IS NOT NULL;
|
||||
CREATE INDEX idx_threads_project_recency
|
||||
ON threads(project_id, recency_at_ms DESC)
|
||||
WHERE archived = 0 AND project_id IS NOT NULL;
|
||||
CREATE INDEX idx_threads_archive_created_at_ms
|
||||
ON threads(archived, created_at_ms DESC, id DESC)
|
||||
WHERE archived = 1;
|
||||
CREATE INDEX idx_threads_archive_updated_at_ms
|
||||
ON threads(archived, updated_at_ms DESC, id DESC)
|
||||
WHERE archived = 1;
|
||||
CREATE INDEX idx_threads_archive_recency_at_ms
|
||||
ON threads(archived, recency_at_ms DESC, id DESC)
|
||||
WHERE archived = 1;
|
||||
CREATE INDEX idx_threads_attached_parent ON threads(attached_thread_parent_id)
|
||||
WHERE attached_thread_parent_id IS NOT NULL;
|
||||
CREATE TABLE thread_dynamic_tools (
|
||||
thread_id TEXT NOT NULL,
|
||||
position INTEGER NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT NOT NULL,
|
||||
input_schema TEXT NOT NULL, defer_loading INTEGER NOT NULL DEFAULT 0, namespace TEXT,
|
||||
PRIMARY KEY(thread_id, position),
|
||||
FOREIGN KEY(thread_id) REFERENCES threads(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX idx_thread_dynamic_tools_thread ON thread_dynamic_tools(thread_id);
|
||||
CREATE TABLE thread_spawn_edges (
|
||||
parent_thread_id TEXT NOT NULL,
|
||||
child_thread_id TEXT NOT NULL PRIMARY KEY,
|
||||
status TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX idx_thread_spawn_edges_parent_status
|
||||
ON thread_spawn_edges(parent_thread_id, status);
|
||||
Reference in New Issue
Block a user