codex: every account shares one list of the Codex app's projects, removals remembered (Michael25651150 on X)

The reporter wants the Codex app's projects kept however magpie switches
ChatGPT accounts. v0.1.3559 (15acba534) copied the longest list only to
an identity with no list yet, so an account with a list of its own (an
empty one too) never got the others' projects, and a project added on
one account never reached an account that had any.

Now, while the app is closed (the same moments as before: the 3s loop
once the state file or logins changed, and between a reopen's quit and
open), shareCodexProjects gives every identity the file has and every
saved Codex login one list: each identity's local-projects together,
the signed-in identity's copy first, with the ties the other
codexProjectKeys have to them (thread-project-assignments,
project-order, pins, appearances, the app-server id maps one level
down). A folder is one project: the app gives a new project a random id
per account (randomUUID in 26.1103's bundle), so a project of a folder
an identity already has maps onto that one, its threads renamed to it.

Removals: codex-projects.json (beside logins.json) keeps each
identity's project ids and folders as the last look left them. A
project a look saw on an identity that the next doesn't have was
removed there; it goes from every identity with every tie, as do other
projects of its folders, unless the user added that project or folder
again since. No record yet removes nothing. A record that can't be
read or parsed means what was removed is unknown: nothing is written.
The record is written after the state file, and not when the app's
start overtook the write, so that look is taken again. The state file
is still written through temp + rename, only when it is byte-for-byte
what was read, with the first-write backup beside it.

Checked against ChatGPT.app 26.1103.60933's own bundle (downloaded from
its appcast into a scratch dir, unpacked there): the renderer state
schema {owner, inactive:{<hash>:{atoms, globals}}}, selectRendererOwner
parking/loading Object.values of the global-state key table (the
account-scoped keys, codexProjectKeys among them), the local project
schema (id, name, rootPaths, backings, createdAt, updatedAt) and
randomUUID ids for new projects. The live ~/.codex was not touched.

Run (mote refused ssh all session, kex reset; so on xiaomi-gpu):
- wsl-run go vet -tags nogui, GOOS=darwin CGO_ENABLED=0 go vet and
  GOOS=windows go vet of ./internal/provider: ok
- wsl-run go test -tags nogui ./internal/provider: ok (281s)
- wsl-run go test -run 'TestCodexProjects|TestCodexRendererOwner|
  TestCodexApp' ./internal/provider ./internal/agent: ok
- win-run go test -run 'TestCodexProjects|TestCodexRendererOwner'
  ./internal/provider: ok
- gofmt -l: clean.

Red on the old code (origin/main's codex_projects.go with a 3-arg
shim): TestCodexProjectsShared (shared with 1, want 2),
TestCodexProjectsRemovalRemembered (0, want 3),
TestCodexProjectsRecordUnreadable (written).
Broken by hand: removals never gone -> RemovalRemembered red; no
folder dedupe -> Shared red; no graft of ties -> FollowASwitch and
Shared red; a tie not renamed to the folder's project -> Shared red;
no MkdirAll for the record -> StepWaitsForTheAppToClose red.

Not tried: the real Codex app switching real accounts (it would share
Electron's userData with the user's running app); the switch is played
by the tests' Go port of 26.1103's selectRendererOwner. No macOS run
(mote down). The first look after this release has no record, so a
project the user removed on one account before it comes back there.
This commit is contained in:
yetone
2026-11-10 21:04:11 +08:00
parent c2c2c82ca8
commit 10bef5fe09
3 changed files with 618 additions and 147 deletions
File diff suppressed because one or more lines are too long
+480 -124
View File
@@ -7,6 +7,7 @@ import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log"
"maps"
"os"
@@ -16,6 +17,7 @@ import (
"sync"
"time"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/steady"
)
@@ -34,11 +36,15 @@ import (
//
// The app reads the file only as it starts and holds it in memory, so a
// write while it runs is lost (it writes its own over it). So while the
// app is closed magpie gives each identity of its saved Codex logins that
// has no projects of its own the projects of the one that has the most
// (carryCodexProjects); the app then loads them on its next switch to
// that account. An identity that has projects, an emptied list included,
// is left alone. With no account at all (magpie's takeover, when Codex's
// app is closed magpie gives every identity, those of its saved Codex
// logins and those the file has, one list (shareCodexProjects): each
// identity's projects together, a folder once, less what the user
// removed. A project a look saw on an identity and the next look doesn't
// was removed there, and goes from every identity rather than coming
// back from another (codex-projects.json keeps what was seen). The app
// then loads the list on its next switch to any account. Projects added
// or removed while the app runs reach the other accounts once it is
// closed. With no account at all (magpie's takeover, when Codex's
// provider takes no ChatGPT account) the app shows no projects, by its
// own rule; they come back with the account.
@@ -130,12 +136,89 @@ func codexGlobalStatePath(home string) string {
// nothing is written to it.
var errCodexStateUnknown = errors.New("the Codex app's state file isn't the shape magpie knows")
// carryCodexProjects gives every identity in auths (auth.json bytes) that
// has no projects in the Codex app's state file at home the projects of
// the identity that has the most, and says how many it gave them to. The
// app must be closed: it writes its own over the file. A file that can't
// be read or parsed, or has no per-identity state, is left as it is.
func carryCodexProjects(home string, auths [][]byte) (int, error) {
// codexProjectsRecordPath is what shareCodexProjects last saw of each
// identity's projects, so a project the user removed is told apart from
// one an account never had.
func codexProjectsRecordPath() string {
return appdir.Join(filepath.Dir(Path()), "codex-projects.json")
}
// codexProjectsRecord is that file: per identity hash, each of its local
// projects' id and the folders it is (codexRootKey).
type codexProjectsRecord struct {
Identities map[string]map[string]string `json:"identities"`
}
// readCodexProjectsRecord is the record at p; none yet is an empty one,
// and one that can't be read or parsed is an error: what was removed is
// unknown then, so nothing is written.
func readCodexProjectsRecord(p string) (map[string]map[string]string, []byte, error) {
b, err := os.ReadFile(p)
if errors.Is(err, os.ErrNotExist) {
return map[string]map[string]string{}, nil, nil
}
if err != nil {
return nil, nil, err
}
var r codexProjectsRecord
if err := json.Unmarshal(b, &r); err != nil {
return nil, nil, fmt.Errorf("%s: %w", p, err)
}
if r.Identities == nil {
r.Identities = map[string]map[string]string{}
}
return r.Identities, b, nil
}
// codexRootKey is the folders a local project is, "" for none: two
// projects of one folder are one project to the user, whatever their ids
// (the app gives a new project a random id on each account).
func codexRootKey(p json.RawMessage) string {
var v struct {
RootPaths []string `json:"rootPaths"`
}
if json.Unmarshal(p, &v) != nil || len(v.RootPaths) == 0 {
return ""
}
rs := slices.Clone(v.RootPaths)
for i, r := range rs {
rs[i] = filepath.Clean(r)
}
slices.Sort(rs)
return strings.Join(rs, "\x00")
}
// codexLocalProjects is the local projects of globals g by id, the
// ChatGPT projects' mirrors left out; has is whether g has a list at all.
func codexLocalProjects(g map[string]json.RawMessage) (lp map[string]json.RawMessage, has bool, err error) {
v, ok := g["local-projects"]
if !ok {
return nil, false, nil
}
var all map[string]json.RawMessage
if json.Unmarshal(v, &all) != nil {
return nil, true, errCodexStateUnknown
}
lp = map[string]json.RawMessage{}
for id, p := range all {
if !strings.HasPrefix(id, codexChatGPTProject) {
lp[id] = p
}
}
return lp, true, nil
}
// shareCodexProjects gives every Codex identity in the Codex app's state
// file at home, and every one of auths (auth.json bytes), one list of
// projects: every identity's, less those the user removed. A project the
// record (at recordPath) saw on an identity that no longer has it was
// removed there, and goes from every identity, as do other projects of
// its folders, unless the user added it again on some identity since. It
// says how many identities it changed. The app must be closed: it writes
// its own over the file. A file that can't be read or parsed, or has no
// per-identity state, is left as it is, as is everything when the record
// can't be read.
func shareCodexProjects(home string, auths [][]byte, recordPath string) (int, error) {
path := codexGlobalStatePath(home)
raw, err := os.ReadFile(path)
if err != nil {
@@ -163,6 +246,10 @@ func carryCodexProjects(home string, auths [][]byte) (int, error) {
if json.Unmarshal(rs, &keep) != nil {
return 0, errCodexStateUnknown
}
prev, prevRaw, err := readCodexProjectsRecord(recordPath)
if err != nil {
return 0, err
}
owner := ""
if r.Owner != nil {
owner = *r.Owner
@@ -171,7 +258,7 @@ func carryCodexProjects(home string, auths [][]byte) (int, error) {
parked := map[string]map[string]json.RawMessage{}
for h, v := range r.Inactive {
var s map[string]json.RawMessage
if json.Unmarshal(v, &s) != nil {
if json.Unmarshal(v, &s) != nil || s == nil {
return 0, errCodexStateUnknown
}
var g map[string]json.RawMessage
@@ -183,82 +270,158 @@ func carryCodexProjects(home string, auths [][]byte) (int, error) {
if owner != "" {
snaps[owner] = top // the owner's globals are the file's own
}
// the source: the identity with the most projects, the owner first
src, most := "", 0
count := func(g map[string]json.RawMessage) int {
var lp map[string]json.RawMessage
if json.Unmarshal(g["local-projects"], &lp) != nil {
return 0
}
n := 0
for id := range lp {
if !strings.HasPrefix(id, codexChatGPTProject) {
n++
}
}
return n
}
// every identity, the one signed in first: its copy of a project wins
ident := map[string]codexIdentity{}
var order []string
if owner != "" {
src, most = owner, count(top)
order = append(order, owner)
}
hashes := slices.Sorted(maps.Keys(parked))
for _, h := range hashes {
if n := count(snaps[h]); n > most {
src, most = h, n
for _, h := range slices.Sorted(maps.Keys(parked)) {
if h != owner {
order = append(order, h)
}
}
if most == 0 {
return 0, nil
}
given := 0
seen := map[string]bool{}
for _, auth := range auths {
h := codexRendererOwner(auth)
if h == "" || seen[h] || h == src {
for _, a := range auths {
h := codexRendererOwner(a)
if h == "" {
continue
}
if _, ok := ident[h]; !ok {
ident[h] = codexIdentityOf(a)
}
if !slices.Contains(order, h) {
order = append(order, h)
}
}
// what the user removed since the record, and added
cur := map[string]map[string]json.RawMessage{}
for _, h := range order {
lp, has, err := codexLocalProjects(snaps[h])
if err != nil {
return 0, err
}
if has {
cur[h] = lp
}
}
removedIDs, removedRoots := map[string]bool{}, map[string]bool{}
addedIDs, addedRoots := map[string]bool{}, map[string]bool{}
for h, lp := range cur {
was, ok := prev[h]
if !ok {
continue // never seen: nothing it has was added or removed
}
for id, root := range was {
if _, still := lp[id]; !still {
removedIDs[id] = true
if root != "" {
removedRoots[root] = true
}
}
}
for id, p := range lp {
if _, had := was[id]; !had {
addedIDs[id] = true
if k := codexRootKey(p); k != "" {
addedRoots[k] = true
}
}
}
}
gone := func(id string, p json.RawMessage) bool {
if addedIDs[id] {
return false // added again since: the user's latest word
}
k := codexRootKey(p)
if k != "" && addedRoots[k] {
return false
}
return removedIDs[id] || (k != "" && removedRoots[k])
}
// the shared list, in the order the identities show them
union := map[string]json.RawMessage{}
var seq []string
for _, h := range order {
lp := cur[h]
var po []string
_ = json.Unmarshal(snaps[h]["project-order"], &po)
ids := slices.Clone(po)
ids = append(ids, slices.Sorted(maps.Keys(lp))...)
for _, id := range ids {
p, ok := lp[id]
if !ok || gone(id, p) {
continue
}
if _, ok := union[id]; !ok {
union[id] = p
seq = append(seq, id)
}
}
}
changed := 0
after := map[string]map[string]string{} // the record to keep
for _, h := range order {
if h == "" {
continue
}
seen[h] = true
g := snaps[h]
if _, has := g["local-projects"]; has {
continue // its own list, an emptied one too
ng, did, err := sharedGlobals(g, h, ident[h], union, seq, gone, order, snaps)
if err != nil {
return 0, err
}
carried := carriedProjects(snaps[src], codexIdentityOf(auth))
if len(carried) == 0 {
if lp, has, _ := codexLocalProjects(ng); has {
rec := map[string]string{}
for id, p := range lp {
rec[id] = codexRootKey(p)
}
after[h] = rec
}
if !did {
continue
}
changed++
if h == owner {
for k, v := range carried {
top[k] = v
maps.Copy(top, ng)
for k := range top {
if _, ok := ng[k]; !ok && slices.Contains(codexProjectKeys, k) {
delete(top, k)
}
}
} else {
s := parked[h]
if s == nil {
s = map[string]json.RawMessage{"atoms": json.RawMessage("{}")}
}
if g == nil {
g = map[string]json.RawMessage{}
}
for k, v := range carried {
g[k] = v
}
gb, err := json.Marshal(g)
if err != nil {
return 0, err
}
s["globals"] = gb
sb, err := json.Marshal(s)
if err != nil {
return 0, err
}
if r.Inactive == nil {
r.Inactive = map[string]json.RawMessage{}
}
r.Inactive[h] = sb
continue
}
given++
s := parked[h]
if s == nil {
s = map[string]json.RawMessage{"atoms": json.RawMessage("{}")}
}
gb, err := json.Marshal(ng)
if err != nil {
return 0, err
}
s["globals"] = gb
sb, err := json.Marshal(s)
if err != nil {
return 0, err
}
if r.Inactive == nil {
r.Inactive = map[string]json.RawMessage{}
}
r.Inactive[h] = sb
}
if given == 0 {
return 0, nil
saveRecord := func() error {
b, err := json.Marshal(codexProjectsRecord{Identities: after})
if err != nil || bytes.Equal(b, prevRaw) {
return err
}
if err := os.MkdirAll(filepath.Dir(recordPath), 0o700); err != nil {
return err
}
return steady.WriteFile(recordPath, b, 0o600)
}
if changed == 0 {
return 0, saveRecord()
}
ib, err := json.Marshal(r.Inactive)
if err != nil {
@@ -289,79 +452,272 @@ func carryCodexProjects(home string, auths [][]byte) (int, error) {
return 0, err
}
}
// the app opened meanwhile: its own state wins
// the app opened meanwhile: its own state wins, and the record waits
// for the next look
if now, err := os.ReadFile(target); err != nil || !bytes.Equal(now, raw) {
return 0, nil
}
if err := steady.WriteFile(target, out, mode); err != nil {
return 0, err
}
return given, nil
return changed, saveRecord()
}
// carriedProjects is the project keys of globals g as an identity id gets
// them: a ChatGPT project's mirror and every tie to one left out, and a
// project's ties to another ChatGPT account's own project dropped.
func carriedProjects(g map[string]json.RawMessage, id codexIdentity) map[string]json.RawMessage {
out := map[string]json.RawMessage{}
for _, k := range codexProjectKeys {
v, ok := g[k]
if !ok {
// sharedGlobals is globals g of identity h (who: its ChatGPT identity,
// zero when magpie has no login for it) with the shared list: its own
// projects that are gone dropped with every tie to them, and each project
// of union it hasn't got added with the ties the other identities have
// to it. A project of a folder it has already is that one. did is whether
// anything changed; g itself is not.
func sharedGlobals(g map[string]json.RawMessage, h string, who codexIdentity, union map[string]json.RawMessage, seq []string, gone func(string, json.RawMessage) bool, order []string, snaps map[string]map[string]json.RawMessage) (map[string]json.RawMessage, bool, error) {
var all map[string]json.RawMessage // its own, ChatGPT mirrors too
if v, ok := g["local-projects"]; ok && json.Unmarshal(v, &all) != nil {
return nil, false, errCodexStateUnknown
}
if all == nil {
all = map[string]json.RawMessage{}
}
removed := map[string]bool{}
roots := map[string]string{} // folders → its project
for id, p := range all {
if strings.HasPrefix(id, codexChatGPTProject) {
continue
}
if gone(id, p) {
removed[id] = true
delete(all, id)
continue
}
if k := codexRootKey(p); k != "" {
roots[k] = id
}
}
as := map[string]string{} // another identity's project id → its own here
for _, id := range seq {
if _, ok := all[id]; ok {
continue
}
p := union[id]
if k := codexRootKey(p); k != "" {
if mine, ok := roots[k]; ok {
as[id] = mine
continue
}
roots[k] = id
}
all[id] = projectFor(p, who)
as[id] = id
}
added := 0
for id, to := range as {
if id == to {
added++
}
}
if len(removed) == 0 && added == 0 {
return g, false, nil
}
out := maps.Clone(g)
if out == nil {
out = map[string]json.RawMessage{}
}
lb, err := json.Marshal(all)
if err != nil {
return nil, false, err
}
out["local-projects"] = lb
for _, k := range codexProjectKeys {
if k == "local-projects" {
v = ownLocalProjects(v, id)
} else {
v = withoutChatGPTProjects(v)
continue
}
if v != nil {
out[k] = v
var v any
if raw, ok := g[k]; ok && json.Unmarshal(raw, &v) != nil {
continue // a value this doesn't read stays as it is
}
had := v != nil
v = codexPrune(v, removed, 0)
for _, s := range order {
if s == h {
continue
}
raw, ok := snaps[s][k]
if !ok {
continue
}
var sv any
if json.Unmarshal(withoutChatGPTProjects(raw), &sv) != nil {
continue
}
v = codexGraft(v, sv, as, 0)
}
switch {
case v == nil && had:
delete(out, k)
case v != nil:
b, err := json.Marshal(v)
if err != nil {
return nil, false, err
}
out[k] = b
}
}
if _, ok := out["local-projects"]; !ok {
return nil
}
return out
return out, true, nil
}
// codexBackings are a local project's ties to a ChatGPT account's project.
var codexBackings = []string{"chatGptBacking", "retiredChatGptBacking", "chatGptBackingCreation"}
func ownLocalProjects(v json.RawMessage, id codexIdentity) json.RawMessage {
var lp map[string]map[string]json.RawMessage
if json.Unmarshal(v, &lp) != nil {
return nil
// projectFor is project p as identity id gets it: a tie to another
// ChatGPT account's own project dropped (the app refuses one: "belongs to
// a different ChatGPT account").
func projectFor(p json.RawMessage, id codexIdentity) json.RawMessage {
var m map[string]json.RawMessage
if json.Unmarshal(p, &m) != nil {
return p
}
for pid, p := range lp {
if strings.HasPrefix(pid, codexChatGPTProject) {
delete(lp, pid)
continue
dropped := false
for _, b := range codexBackings {
var who struct {
AccountID string `json:"accountId"`
UserID string `json:"userId"`
}
dropped := false
for _, b := range codexBackings {
var who struct {
AccountID string `json:"accountId"`
UserID string `json:"userId"`
}
if bv, ok := p[b]; ok && (json.Unmarshal(bv, &who) != nil || who.AccountID != id.account || who.UserID != id.user) {
delete(p, b)
dropped = true
}
}
if dropped {
delete(p, "chatGptBackingRecoveryPending")
if bv, ok := m[b]; ok && (json.Unmarshal(bv, &who) != nil || who.AccountID == "" || who.AccountID != id.account || who.UserID != id.user) {
delete(m, b)
dropped = true
}
}
if len(lp) == 0 {
return nil
if !dropped {
return p
}
b, err := json.Marshal(lp)
delete(m, "chatGptBackingRecoveryPending")
b, err := json.Marshal(m)
if err != nil {
return nil
return p
}
return b
}
// codexPrune drops every mention of a removed project from v: an id in a
// list, an entry keyed by one or naming one, one level down too, and v
// itself when it names one.
func codexPrune(v any, removed map[string]bool, depth int) any {
if len(removed) == 0 {
return v
}
switch t := v.(type) {
case string:
if removed[t] {
return nil
}
case []any:
out := []any{}
for _, e := range t {
if s, ok := e.(string); ok && removed[s] {
continue
}
out = append(out, e)
}
return out
case map[string]any:
out := map[string]any{}
for k, e := range t {
if s, ok := e.(string); removed[k] || (ok && removed[s]) {
continue
}
if depth == 0 {
if m, ok := e.(map[string]any); ok {
e = codexPrune(m, removed, 1)
}
}
out[k] = e
}
return out
}
return v
}
// codexGraft adds to v what src says of the projects in as (another
// identity's id → this one's): an id in a list, an entry keyed by one or
// naming one, one level down too. What v says already stays.
func codexGraft(v, src any, as map[string]string, depth int) any {
switch s := src.(type) {
case []any:
d, ok := v.([]any)
if v != nil && !ok {
return v
}
for _, e := range s {
id, ok := e.(string)
to, mapped := as[id]
if !ok || !mapped || slices.Contains(d, any(to)) {
continue
}
d = append(d, to)
}
if d == nil {
return v
}
return d
case map[string]any:
d, ok := v.(map[string]any)
if v != nil && !ok {
return v
}
out := maps.Clone(d)
if out == nil {
out = map[string]any{}
}
for k, e := range s {
if to, ok := as[k]; ok {
if _, has := out[to]; !has {
out[to] = codexRename(e, as)
}
continue
}
if id, ok := e.(string); ok {
if to, ok := as[id]; ok {
if _, has := out[k]; !has {
out[k] = to
}
}
continue
}
if m, ok := e.(map[string]any); ok && depth == 0 {
sub, _ := out[k].(map[string]any)
if _, has := out[k]; has && sub == nil {
continue
}
if g, _ := codexGraft(sub, m, as, 1).(map[string]any); len(g) > 0 {
out[k] = g
}
}
}
if v == nil && len(out) == 0 {
return nil
}
return out
}
return v
}
// codexRename is e with a project id in as, or a list of them, named as
// this identity names it.
func codexRename(e any, as map[string]string) any {
switch t := e.(type) {
case string:
if to, ok := as[t]; ok {
return to
}
case []any:
out := make([]any, len(t))
for i, x := range t {
out[i] = codexRename(x, as)
}
return out
}
return e
}
// withoutChatGPTProjects drops a ChatGPT project's id from a list, and an
// entry keyed by one or naming one from a record, one level down.
func withoutChatGPTProjects(v json.RawMessage) json.RawMessage {
@@ -411,16 +767,16 @@ func codexProjectAuths() [][]byte {
return out
}
// CodexAppClosed carries the user's projects to each of Codex's accounts
// that has none in the Codex app (carryCodexProjects); the caller knows
// the app is closed: the agent package between its quit and its open.
// CodexAppClosed gives all of Codex's accounts one list of projects in
// the Codex app (shareCodexProjects); the caller knows the app is closed:
// the agent package between its quit and its open.
func CodexAppClosed() {
n, err := carryCodexProjects(codexHome(), codexProjectAuths())
n, err := shareCodexProjects(codexHome(), codexProjectAuths(), codexProjectsRecordPath())
switch {
case err != nil:
log.Printf("codex: carrying the Codex app's projects to its other accounts: %v", err)
log.Printf("codex: sharing the Codex app's projects between its accounts: %v", err)
case n > 0:
log.Printf("codex: gave %d of Codex's accounts the Codex app's projects", n)
log.Printf("codex: shared the Codex app's projects with %d of Codex's accounts", n)
}
codexProjects.Lock()
codexProjects.last = codexProjectsMark()
+137 -22
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"os"
"path/filepath"
"slices"
"testing"
"time"
@@ -158,10 +159,11 @@ func codexStateFixture(t *testing.T, home string, a []byte, b []byte) string {
// switched as magpie switches it, shows them on every account.
func TestCodexProjectsFollowASwitch(t *testing.T) {
home := t.TempDir()
rec := filepath.Join(t.TempDir(), "codex-projects.json")
a, b, c := codexTestAuth("user-a", "acct-a"), codexTestAuth("user-b", "acct-b"), codexTestAuth("user-c", "acct-c")
path := codexStateFixture(t, home, a, b)
n, err := carryCodexProjects(home, [][]byte{a, b, c})
n, err := shareCodexProjects(home, [][]byte{a, b, c}, rec)
if err != nil || n != 2 {
t.Fatalf("carried to %d (%v), want b and c", n, err)
}
@@ -206,39 +208,148 @@ func TestCodexProjectsFollowASwitch(t *testing.T) {
t.Fatalf("no backup: %v", err)
}
// once more: nothing to do
if n, err := carryCodexProjects(home, [][]byte{a, b, c}); n != 0 || err != nil {
if n, err := shareCodexProjects(home, [][]byte{a, b, c}, rec); n != 0 || err != nil {
t.Fatalf("carried again to %d (%v)", n, err)
}
}
// A project the user added or removed on an account is that account's:
// an identity with a list of its own, an emptied one too, is left alone,
// and the source can be a parked identity when the owner has none.
func TestCodexProjectsOwnListKept(t *testing.T) {
// add is the user adding a folder as a project in the app's sidebar.
func (s *codexAppSim) add(id, root string) {
lp, _ := s.state["local-projects"].(map[string]any)
if lp == nil {
lp = map[string]any{}
}
lp[id] = map[string]any{"id": id, "name": filepath.Base(root), "rootPaths": []any{root}, "createdAt": 3, "updatedAt": 3}
s.state["local-projects"] = lp
po, _ := s.state["project-order"].([]any)
s.state["project-order"] = append(po, id)
}
// remove is the user removing a project from the sidebar.
func (s *codexAppSim) remove(id string) {
lp, _ := s.state["local-projects"].(map[string]any)
delete(lp, id)
var po []any
for _, e := range anyStrings(s.state["project-order"]) {
if e != id {
po = append(po, e)
}
}
s.state["project-order"] = po
}
func shareOnce(t *testing.T, home, rec string, want int, auths ...[]byte) {
t.Helper()
if n, err := shareCodexProjects(home, auths, rec); n != want || err != nil {
t.Fatalf("shared with %d (%v), want %d", n, err, want)
}
}
func shows(t *testing.T, path string, who []byte, want ...string) *codexAppSim {
t.Helper()
app := codexAppLaunch(t, path)
app.signIn(who)
if got := app.projects(); !slices.Equal(got, want) {
t.Fatalf("%s's account shows %v, want %v", codexIdentityOf(who).user, got, want)
}
return app
}
// Michael25651150 on X: projects are kept however accounts are switched.
// Every account shows every account's projects, even one that has a list
// of its own, and a folder added on two accounts is one project, its
// threads with it.
func TestCodexProjectsShared(t *testing.T) {
home := t.TempDir()
a, b := codexTestAuth("user-a", "acct-a"), codexTestAuth("user-b", "acct-b")
rec := filepath.Join(t.TempDir(), "codex-projects.json")
a, b, c := codexTestAuth("user-a", "acct-a"), codexTestAuth("user-b", "acct-b"), codexTestAuth("user-c", "acct-c")
path := codexStateFixture(t, home, a, b)
app := codexAppLaunch(t, path)
app.signIn(a)
app.signIn(b)
app.state["local-projects"] = map[string]any{} // b removed them all
app.save(t, path)
app.signIn(b) // a switch with the app open: b's own list
app.add("p-b", "/Users/me/b")
app.add("p-dup", "/Users/me/site/") // a's p-site, added again on b
app.state["thread-project-assignments"] = map[string]any{"t5": "p-b"}
app.save(t, path) // the app quit
shareOnce(t, home, rec, 2, a, b, c) // a and c; b has them all
app = shows(t, path, a, "g-p-1", "p-b", "p-site")
if got := app.state["thread-project-assignments"].(map[string]any); got["t5"] != "p-b" || got["t1"] != "p-site" {
t.Fatalf("a's thread-project-assignments %v", got)
}
shows(t, path, b, "p-b", "p-dup")
app = shows(t, path, c, "p-b", "p-dup")
if got := app.state["thread-project-assignments"].(map[string]any); got["t1"] != "p-dup" || got["t5"] != "p-b" || len(got) != 2 {
t.Fatalf("c's thread-project-assignments %v: a's thread in site, under c's id for it", got)
}
// once more: nothing to do, nothing written
before, _ := os.ReadFile(path)
if n, err := carryCodexProjects(home, [][]byte{a, b}); n != 0 || err != nil {
t.Fatalf("carried to %d (%v)", n, err)
}
shareOnce(t, home, rec, 0, a, b, c)
if after, _ := os.ReadFile(path); string(after) != string(before) {
t.Fatal("the file was written with nothing to carry")
t.Fatal("the file was written with nothing to share")
}
// c, new, gets a's parked projects
c := codexTestAuth("user-c", "acct-c")
if n, err := carryCodexProjects(home, [][]byte{a, b, c}); n != 1 || err != nil {
t.Fatalf("carried to %d (%v), want c", n, err)
}
// A project the user removes on one account is removed from every
// account, not given back from another, and comes back only when the
// user adds it again.
func TestCodexProjectsRemovalRemembered(t *testing.T) {
home := t.TempDir()
rec := filepath.Join(t.TempDir(), "codex-projects.json")
a, b, c := codexTestAuth("user-a", "acct-a"), codexTestAuth("user-b", "acct-b"), codexTestAuth("user-c", "acct-c")
path := codexStateFixture(t, home, a, b)
shareOnce(t, home, rec, 2, a, b, c)
app := codexAppLaunch(t, path)
app.signIn(a)
app.add("p-new", "/Users/me/new") // added on a
app.signIn(b)
if got := app.projects(); !slices.Equal(got, []string{"p-site"}) {
t.Fatalf("b shows %v", got)
}
app.remove("p-site") // removed on b
app.save(t, path)
shareOnce(t, home, rec, 3, a, b, c)
for range 2 {
app = shows(t, path, a, "g-p-1", "p-new")
if got := anyStrings(app.state["project-order"]); slices.Contains(got, "p-site") {
t.Fatalf("a's project-order %v", got)
}
if got := app.state["thread-project-assignments"].(map[string]any); got["t1"] != nil {
t.Fatalf("a's thread-project-assignments %v", got)
}
shows(t, path, b, "p-new")
shows(t, path, c, "p-new")
shareOnce(t, home, rec, 0, a, b, c) // and it stays gone
}
// added again on c, under a new id: back on every account
app = codexAppLaunch(t, path)
app.signIn(c)
if got := app.projects(); !slices.Equal(got, []string{"p-site"}) {
t.Fatalf("c shows %v", got)
app.add("p-site2", "/Users/me/site")
app.save(t, path)
shareOnce(t, home, rec, 2, a, b, c)
shows(t, path, a, "g-p-1", "p-new", "p-site2")
shows(t, path, b, "p-new", "p-site2")
}
// What was removed is unknown when magpie's record can't be read: the
// file isn't written then.
func TestCodexProjectsRecordUnreadable(t *testing.T) {
home := t.TempDir()
rec := filepath.Join(t.TempDir(), "codex-projects.json")
if err := os.WriteFile(rec, []byte(`{"identities":`), 0o600); err != nil {
t.Fatal(err)
}
a, b := codexTestAuth("user-a", "acct-a"), codexTestAuth("user-b", "acct-b")
path := codexStateFixture(t, home, a, b)
before, _ := os.ReadFile(path)
if n, err := shareCodexProjects(home, [][]byte{a, b}, rec); n != 0 || err == nil {
t.Fatalf("shared with %d (%v)", n, err)
}
if after, _ := os.ReadFile(path); string(after) != string(before) {
t.Fatal("written without knowing what was removed")
}
}
@@ -252,11 +363,12 @@ func TestCodexProjectsUnknownFileLeft(t *testing.T) {
"odd shape": `{"electron-account-renderer-state-v1":{"owner":1,"inactive":[]}}`,
} {
home := t.TempDir()
rec := filepath.Join(t.TempDir(), "codex-projects.json")
path := codexGlobalStatePath(home)
if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
t.Fatal(err)
}
n, _ := carryCodexProjects(home, [][]byte{a, b})
n, _ := shareCodexProjects(home, [][]byte{a, b}, rec)
if got, _ := os.ReadFile(path); n != 0 || string(got) != body {
t.Fatalf("%s: carried to %d, file %s", name, n, got)
}
@@ -264,7 +376,7 @@ func TestCodexProjectsUnknownFileLeft(t *testing.T) {
t.Fatalf("%s: a backup written", name)
}
}
if n, err := carryCodexProjects(t.TempDir(), [][]byte{a}); n != 0 || err != nil {
if n, err := shareCodexProjects(t.TempDir(), [][]byte{a}, filepath.Join(t.TempDir(), "rec.json")); n != 0 || err != nil {
t.Fatalf("no file: %d %v", n, err)
}
}
@@ -314,6 +426,9 @@ func TestCodexProjectsStepWaitsForTheAppToClose(t *testing.T) {
if got := app.projects(); !slices.Equal(got, []string{"p-site"}) {
t.Fatalf("b, signed in now, shows %v once the app closed", got)
}
if _, err := os.Stat(codexProjectsRecordPath()); err != nil {
t.Fatalf("no record of what each account has: %v", err)
}
}
func anyStrings(v any) []string {