codex: the Codex app's projects follow an account switch, and the app isn't quit unasked (Michael25651150 on X)

"切换账号 codex 添加的项目丢了 发生过好几次了 另外额度用尽时会强制重启 codex 客户端"

Projects. The Codex app (ChatGPT.app 26.1103 and on) keeps its sidebar's
projects per ChatGPT identity in $CODEX_HOME/.codex-global-state.json,
under electron-account-renderer-state-v1 ({owner, inactive:{<sha256 of
JSON.stringify([chatgpt_user_id, chatgpt_account_id])>: {atoms, globals}}}).
On an account change it parks the old identity's account-scoped globals
and loads the new one's, so magpie's switch (auth.json, then the
app-server's restart) showed an account that never had the app open with
no projects (#5497, #5602, #5702, #5874). Read from the app's own bundle
(early-bootstrap-133 selectRendererOwner, -815's owner hash). The app reads
the file only at launch and writes its memory over it, so magpie writes
it only while the app is closed (codex_projects.go): from the 3s loop once
the file, auth.json or logins.json changed (process listing at most every
30s), and between the quit and the open of every reopen (appQuitDone in
reopenBundle and restartWin). Each identity of auth.json and the saved
Codex logins whose snapshot has no local-projects key gets the project
keys of the identity with the most; an own list (an emptied one too) is
left; g-p- ChatGPT project mirrors and their ties aren't carried, and a
backing naming another account is dropped (the app refuses those). A
file without the key or that doesn't parse is not written; the first
write keeps the file as it was beside it (.magpie-before-projects).

Restart. When quota runs out magpie restarts the app's app-server (the
takeover needs it: the app reads its account only as its app-server
starts, else Send stays grey). A ChatGPT app can then show "hit a snag",
and magpie quit and reopened the whole app (CodexAppRelaunch), and on
Windows reopened an app that started no app-server (codexAppGotNone).
Both now happen only with "Restart the Codex app when magpie switches its
account back" ticked (codexRestartsApp, off by default); otherwise the
Agents row says to quit and reopen, as it did where a relaunch failed.

Run (mote unreachable all session: ssh kex reset on every try; so on the
Linux box and Windows box instead):
- wsl-run: go vet -tags nogui, GOOS=darwin CGO_ENABLED=0 go vet and
  GOOS=windows go vet of internal/provider and internal/agent: ok.
- wsl-run go test -tags nogui ./internal/provider ./internal/agent:
  provider ok; agent red only on TestGrokInstalled (#3548, WSL binfmt).
- win-run go test -run 'TestCodexProjects|TestCodexRendererOwner|
  TestCodexApp|Restart' ./internal/provider ./internal/agent: provider ok;
  agent red on TestWorkBuddyRestartOnMac (#4115) and
  TestOpenMausBotRestartOnMac (added to #4115), neither touched.
- gofmt -l: clean.
- The owner hash checked against node's crypto (TestCodexRendererOwner).

Broken by hand: carryCodexProjects returning at once -> the four
TestCodexProjects* red; the snag gate removed -> TestCodexAppNotQuitUnasked
red (relaunched 1); the Windows gate removed -> red (reopened 1); the
backing strip removed -> TestCodexProjectsFollowASwitch red.

Not tried: the real Codex app. This Mac's ~/.codex state has no
per-identity key (read-only check), so the switch is reproduced against a
Go port of the app's selectRendererOwner on the issues' layout, not the
app itself. No macOS test run (mote down). The takeover (no account)
still shows no projects in the app, by the app's own rule; they come back
with the account. Projects added while the app runs reach other accounts
once it is closed.
This commit is contained in:
yetone
2026-11-10 17:10:32 +08:00
parent fbc1808f28
commit 15acba5347
7 changed files with 873 additions and 5 deletions
File diff suppressed because one or more lines are too long
+12
View File
@@ -451,6 +451,7 @@ func (a *Agent) restartWin(ctx context.Context, r restartable, c appRunning) err
return restartErr(noticeRestartStillThere, a)
}
}
appQuitDone(a.ID)
if err := winLaunch(c.main); err != nil {
return restartErr(noticeRestartNoOpen, a)
}
@@ -544,8 +545,19 @@ func reopenBundle(ctx context.Context, a *Agent, bundle, exe string) error {
case <-time.After(appPoll):
}
}
appQuitDone(a.ID)
if err := appOpen(ctx, bundle); err != nil {
return restartErr(noticeRestartNoOpen, a)
}
return nil
}
// appQuitDone runs once agent id's app has quit and before it opens
// again: the Codex app's projects are carried to its other accounts then,
// while it can't write over them (provider.CodexAppClosed). A var so
// tests don't touch the state file.
var appQuitDone = func(id string) {
if id == "codex" {
provider.CodexAppClosed()
}
}
+17 -4
View File
@@ -24,8 +24,11 @@ import (
// and no Codex turn has started since nor a request gone through magpie
// (the page has no composer: one that ran means it came back), magpie
// quits the app and opens it again, once (CodexAppRelaunch: ⌘Q's quit on
// macOS, never forced; the Agents row's Restart on Windows). Where that
// can't be done, or the app didn't quit, the Agents row says to (snag,
// macOS, never forced; the Agents row's Restart on Windows), but only
// with the user's "Restart the Codex app" on (RestartApp): unasked, a
// quit of the user's app read as magpie force-restarting it whenever
// quota ran out (Michael25651150 on X). Where that is off or can't be
// done, or the app didn't quit, the Agents row says to (snag,
// CodexAppSnagged) until the app-servers seen then are gone.
// CodexAppCrashed and CodexAppRelaunch are set by the agent package.
@@ -130,7 +133,14 @@ func codexAppCrashStep(ctx context.Context, now time.Time, busy func() (int, tim
pids, _ := codexAppServersOn(lctx, home)
cancel()
err := errNoRelaunch
if CodexAppRelaunch != nil {
switch {
case !codexRestartsApp():
// quitting the user's app and opening it again, unasked, takes
// their window with it (Michael25651150 on X: "额度用尽时会强制重启
// codex 客户端"); the Agents row says to, and its Try again or
// Restart is theirs
err = errRelaunchOff
case CodexAppRelaunch != nil:
err = CodexAppRelaunch(ctx)
}
if err == nil {
@@ -150,4 +160,7 @@ func codexAppUnsnag() {
c.Unlock()
}
var errNoRelaunch = errors.New("magpie doesn't reopen the Codex app here")
var (
errNoRelaunch = errors.New("magpie doesn't reopen the Codex app here")
errRelaunchOff = errors.New("left to the user: Restart the Codex app when magpie switches its account is off")
)
+32
View File
@@ -277,3 +277,35 @@ func TestCodexAppRowRestartWatchesForTheErrorPage(t *testing.T) {
t.Fatalf("the Agents row's Restart: relaunched %d", c.relaunch)
}
}
// Michael25651150 on X: "额度用尽时会强制重启 codex 客户端". With the
// user's "Restart the Codex app" off (as it ships), quota running out
// still restarts the app's app-server, which the takeover needs, but the
// app showing its error page after it is never quit and opened again
// unasked: the Agents row says to, and the app's Try again or the row's
// Restart is the user's. Nor is a Windows app that started no app-server.
func TestCodexAppNotQuitUnasked(t *testing.T) {
signIn(t)
s := stubCodexApp(t)
c := stubCodexCrash(t)
codexRestartsApp = func() bool { return false }
now := time.Now()
idle := func() (int, time.Time) { return 0, now.Add(-time.Minute) }
s.running = []int{60}
codexAppStep(context.Background(), now, idle)
s.on = true // the account used up: magpie serves it
if got := codexAppStep(context.Background(), now, idle); !slices.Equal(got, []int{60}) {
t.Fatalf("ended %v, want [60]: the takeover needs the app-server's restart", got)
}
c.page, c.at = true, now.Add(2*time.Second)
now = now.Add(3 * time.Second)
codexAppStep(context.Background(), now, idle)
if c.relaunch != 0 || !CodexAppSnagged() {
t.Fatalf("relaunched %d, snag %v: want left to the user, said on the row", c.relaunch, CodexAppSnagged())
}
reopened := 0
CodexAppReopen = func(context.Context) error { reopened++; return nil }
if stuck := codexAppGotNone(context.Background()); !stuck || reopened != 0 {
t.Fatalf("no app-server: reopened %d, stuck %v", reopened, stuck)
}
}
+7
View File
@@ -128,6 +128,12 @@ func codexAppGotNone(ctx context.Context) (stuck bool) {
if CodexAppReopen == nil {
return true
}
if !codexRestartsApp() {
// the user's app is never quit unasked (Michael25651150 on X):
// the Agents row says to, and its Restart does it
log.Printf("codex: the Codex app started no app-server in place of the one magpie ended; left for the user to reopen (Restart the Codex app is off)")
return true
}
if err := CodexAppReopen(ctx); err != nil {
log.Printf("codex: the Codex app started no app-server in place of the one magpie ended; reopening it: %v", err)
return true
@@ -429,6 +435,7 @@ func KeepCodexAppOnItsProvider(ctx context.Context, busy func() (int, time.Time)
// ended.
func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Time)) []int {
codexAppCrashStep(ctx, now, busy)
codexProjectsStep(ctx)
if CodexAppRoute == nil {
return nil
}
+475
View File
@@ -0,0 +1,475 @@
package provider
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"log"
"maps"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/steady"
)
// The Codex desktop app (26.1103 and on) keeps its sidebar's projects per
// signed-in ChatGPT identity, in $CODEX_HOME/.codex-global-state.json under
// electron-account-renderer-state-v1: {owner, inactive: {<hash>: {atoms,
// globals}}}. The owner's projects sit at the file's top level; each other
// identity's are parked under inactive, keyed by the sha256 hex of
// JSON.stringify([chatgpt_user_id, chatgpt_account_id]). When the app's
// account changes (magpie's switch: auth.json, then the app-server's
// restart) it parks the old identity's projects and loads the new one's,
// and an identity that never had the app open has none: the user's
// projects "disappear" on every switch to another account
// (Michael25651150 on X; #5497, #5602, #5702, #5874).
//
// 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
// provider takes no ChatGPT account) the app shows no projects, by its
// own rule; they come back with the account.
// codexRendererKey is the file's key for the per-identity state.
const codexRendererKey = "electron-account-renderer-state-v1"
// codexProjectKeys are the account-scoped globals that make up the
// projects the sidebar shows and what hangs off them, copied to an
// identity that has none. Accounts' own things (remote hosts, pins of
// ChatGPT projects, follow-ups) are not.
var codexProjectKeys = []string{
"local-projects",
"project-order",
"selected-project",
"project-appearances",
"project-writable-roots",
"project-files",
"pinned-project-ids",
"pinned-thread-ids",
"sidebar-project-thread-orders",
"sidebar-thread-metadata",
"thread-project-assignments",
"thread-project-membership-host-ids",
"thread-writable-roots",
"thread-workspace-root-hints",
"thread-projectless-output-directories",
"projectless-thread-ids",
"active-workspace-roots",
"electron-saved-workspace-roots",
"electron-workspace-root-labels",
"app-server-project-id-by-legacy-project-id-by-host",
"app-server-projects-migration-by-host",
"app-server-pending-project-deletions-by-host",
"app-server-migrated-pinned-thread-ids-by-host",
}
// codexChatGPTProject is the id prefix of a project the app mirrors from
// a ChatGPT account's own projects: that account's, never carried.
const codexChatGPTProject = "g-p-"
// codexRendererOwner is the app's key for the identity an auth.json is
// signed in to, "" when it has no ChatGPT identity.
func codexRendererOwner(auth []byte) string {
var a codexAuth
if json.Unmarshal(auth, &a) != nil || a.AuthMode == "apikey" {
return ""
}
claims := jwtClaims(a.Tokens.IDToken)
user := claimString(claims, "https://api.openai.com/auth", "chatgpt_user_id")
account := claimString(claims, "https://api.openai.com/auth", "chatgpt_account_id")
if account == "" {
account = a.Tokens.AccountID
}
if user == "" || account == "" {
return ""
}
var b bytes.Buffer
enc := json.NewEncoder(&b)
enc.SetEscapeHTML(false) // JSON.stringify's bytes
if enc.Encode([]string{user, account}) != nil {
return ""
}
sum := sha256.Sum256(bytes.TrimSuffix(b.Bytes(), []byte("\n")))
return hex.EncodeToString(sum[:])
}
// codexIdentity is what a backing in a project names.
type codexIdentity struct{ user, account string }
func codexIdentityOf(auth []byte) codexIdentity {
var a codexAuth
if json.Unmarshal(auth, &a) != nil {
return codexIdentity{}
}
claims := jwtClaims(a.Tokens.IDToken)
acc := claimString(claims, "https://api.openai.com/auth", "chatgpt_account_id")
if acc == "" {
acc = a.Tokens.AccountID
}
return codexIdentity{claimString(claims, "https://api.openai.com/auth", "chatgpt_user_id"), acc}
}
// codexGlobalStatePath is the Codex app's state file in home.
func codexGlobalStatePath(home string) string {
return filepath.Join(home, ".codex-global-state.json")
}
// errCodexStateUnknown is a state file that isn't the shape this reads:
// 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) {
path := codexGlobalStatePath(home)
raw, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return 0, nil
}
return 0, err
}
var top map[string]json.RawMessage
if json.Unmarshal(raw, &top) != nil || top == nil {
return 0, errCodexStateUnknown
}
rs, ok := top[codexRendererKey]
if !ok {
return 0, nil // an app before per-identity projects
}
var r struct {
Owner *string `json:"owner"`
Inactive map[string]json.RawMessage `json:"inactive"`
}
if json.Unmarshal(rs, &r) != nil {
return 0, errCodexStateUnknown
}
var keep map[string]json.RawMessage // the whole renderer object, unknown fields kept
if json.Unmarshal(rs, &keep) != nil {
return 0, errCodexStateUnknown
}
owner := ""
if r.Owner != nil {
owner = *r.Owner
}
snaps := map[string]map[string]json.RawMessage{} // hash → globals
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 {
return 0, errCodexStateUnknown
}
var g map[string]json.RawMessage
if gs, ok := s["globals"]; ok && json.Unmarshal(gs, &g) != nil {
return 0, errCodexStateUnknown
}
parked[h], snaps[h] = s, g
}
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
}
if owner != "" {
src, most = owner, count(top)
}
hashes := slices.Sorted(maps.Keys(parked))
for _, h := range hashes {
if n := count(snaps[h]); n > most {
src, most = h, n
}
}
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 {
continue
}
seen[h] = true
g := snaps[h]
if _, has := g["local-projects"]; has {
continue // its own list, an emptied one too
}
carried := carriedProjects(snaps[src], codexIdentityOf(auth))
if len(carried) == 0 {
continue
}
if h == owner {
for k, v := range carried {
top[k] = v
}
} 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
}
given++
}
if given == 0 {
return 0, nil
}
ib, err := json.Marshal(r.Inactive)
if err != nil {
return 0, err
}
keep["inactive"] = ib
kb, err := json.Marshal(keep)
if err != nil {
return 0, err
}
top[codexRendererKey] = kb
out, err := json.Marshal(top)
if err != nil {
return 0, err
}
target, err := edit.Target(path) // a symlink stays, its target written
if err != nil {
return 0, err
}
mode := os.FileMode(0o644)
if fi, err := os.Stat(target); err == nil {
mode = fi.Mode().Perm()
}
// the file as it was, once, beside it: magpie's write can be undone
backup := target + ".magpie-before-projects"
if _, err := os.Lstat(backup); errors.Is(err, os.ErrNotExist) {
if err := steady.WriteFile(backup, raw, mode); err != nil {
return 0, err
}
}
// the app opened meanwhile: its own state wins
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
}
// 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 {
continue
}
if k == "local-projects" {
v = ownLocalProjects(v, id)
} else {
v = withoutChatGPTProjects(v)
}
if v != nil {
out[k] = v
}
}
if _, ok := out["local-projects"]; !ok {
return nil
}
return out
}
// 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
}
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"`
}
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 len(lp) == 0 {
return nil
}
b, err := json.Marshal(lp)
if err != nil {
return nil
}
return b
}
// 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 {
isGP := func(r json.RawMessage) bool {
var s string
return json.Unmarshal(r, &s) == nil && strings.HasPrefix(s, codexChatGPTProject)
}
var list []json.RawMessage
if json.Unmarshal(v, &list) == nil {
out := list[:0]
for _, e := range list {
if !isGP(e) {
out = append(out, e)
}
}
b, _ := json.Marshal(out)
return b
}
var rec map[string]json.RawMessage
if json.Unmarshal(v, &rec) == nil && rec != nil {
for k, e := range rec {
if strings.HasPrefix(k, codexChatGPTProject) || isGP(e) {
delete(rec, k)
}
}
b, _ := json.Marshal(rec)
return b
}
if isGP(v) {
return nil
}
return v
}
// codexProjectAuths is the auth.json of every Codex identity magpie knows
// on this computer: the one signed in now and each saved login's.
func codexProjectAuths() [][]byte {
var out [][]byte
if b, err := readAccountFile(codexAuthPath()); err == nil {
out = append(out, b)
}
for _, l := range sharedLogins() {
if l.Agent == "codex" && len(l.Auth) > 0 {
out = append(out, l.Auth)
}
}
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.
func CodexAppClosed() {
n, err := carryCodexProjects(codexHome(), codexProjectAuths())
switch {
case err != nil:
log.Printf("codex: carrying the Codex app's projects to its other accounts: %v", err)
case n > 0:
log.Printf("codex: gave %d of Codex's accounts the Codex app's projects", n)
}
codexProjects.Lock()
codexProjects.last = codexProjectsMark()
codexProjects.Unlock()
}
// codexProjects is what codexProjectsStep last carried at: the state
// file's and the logins' change times and sizes, so an unchanged pair
// isn't read again nor the app's processes listed every look.
var codexProjects struct {
sync.Mutex
last string
tried time.Time
}
// codexProjectsEvery is how often a change is looked at while the app may
// be open: whether it is lists processes.
var codexProjectsEvery = 30 * time.Second
// codexProjectsMark names the state file and the logins as they are now.
func codexProjectsMark() string {
var b strings.Builder
for _, p := range []string{codexGlobalStatePath(codexHome()), codexAuthPath(), loginsPath()} {
if fi, err := os.Stat(p); err == nil {
b.WriteString(fi.ModTime().Format(time.RFC3339Nano))
b.WriteByte('/')
b.WriteString(fi.Name())
b.WriteByte(' ')
}
b.WriteByte(';')
}
return b.String()
}
// codexProjectsStep is codexAppStep's carry: once the state file or the
// logins changed, and only while the Codex app is closed.
func codexProjectsStep(ctx context.Context) {
codexProjects.Lock()
mark := codexProjectsMark()
skip := mark == codexProjects.last || time.Since(codexProjects.tried) < codexProjectsEvery
if !skip {
codexProjects.tried = time.Now()
}
codexProjects.Unlock()
if skip {
return
}
if open, known := codexAppOpenNow(ctx); !known || open {
return // carried once it is closed: what it has open it writes over
}
CodexAppClosed()
}
+327
View File
@@ -0,0 +1,327 @@
package provider
import (
"context"
"encoding/json"
"os"
"slices"
"testing"
"time"
)
// codexTestAuth is an auth.json signed in to ChatGPT user u in account a.
func codexTestAuth(u, a string) []byte {
b, _ := json.Marshal(map[string]any{
"auth_mode": "chatgpt",
"tokens": map[string]any{
"id_token": fakeJWT(map[string]any{
"email": u + "@example.com",
"https://api.openai.com/auth": map[string]any{"chatgpt_user_id": u, "chatgpt_account_id": a},
}),
"account_id": a,
},
})
return b
}
// codexAppSim is the Codex app's renderer state as its GlobalState keeps
// it (ChatGPT.app 26.1103, early-bootstrap-133's selectRendererOwner): the
// file read at launch, an owner switched in memory, the file written.
type codexAppSim struct{ state map[string]any }
// codexAccountScoped is the app's own list (nh0) of account-scoped
// globals that a switch parks and loads; the sidebar's are among them.
var codexAccountScoped = append(slices.Clone(codexProjectKeys), "remote-projects", "selected-remote-host-id", "queued-follow-ups")
func codexAppLaunch(t *testing.T, path string) *codexAppSim {
t.Helper()
b, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
s := &codexAppSim{}
if err := json.Unmarshal(b, &s.state); err != nil {
t.Fatal(err)
}
s.selectOwner(nil) // its constructor, before the account is known
return s
}
func (s *codexAppSim) selectOwner(r *string) {
rs, _ := s.state[codexRendererKey].(map[string]any)
if rs == nil {
return
}
cur, _ := rs["owner"].(string)
if r != nil && rs["owner"] != nil && cur == *r {
return
}
inactive := map[string]any{}
for k, v := range rs["inactive"].(map[string]any) {
inactive[k] = v
}
globals := map[string]any{}
for _, k := range codexAccountScoped {
if v, ok := s.state[k]; ok {
globals[k] = v
}
}
if rs["owner"] != nil {
inactive[cur] = map[string]any{"atoms": map[string]any{}, "globals": globals}
}
var o map[string]any
if r != nil {
o, _ = inactive[*r].(map[string]any)
delete(inactive, *r)
}
for _, k := range codexAccountScoped {
g, _ := o["globals"].(map[string]any)
if v, ok := g[k]; o != nil && ok {
s.state[k] = v
} else {
delete(s.state, k)
}
}
var owner any
if r != nil {
owner = *r
}
s.state[codexRendererKey] = map[string]any{"owner": owner, "inactive": inactive}
}
func (s *codexAppSim) signIn(auth []byte) {
h := codexRendererOwner(auth)
if h == "" {
s.selectOwner(nil)
return
}
s.selectOwner(&h)
}
func (s *codexAppSim) projects() []string {
lp, _ := s.state["local-projects"].(map[string]any)
return slices.Sorted(func(yield func(string) bool) {
for k := range lp {
if !yield(k) {
return
}
}
})
}
func (s *codexAppSim) save(t *testing.T, path string) {
t.Helper()
b, _ := json.Marshal(s.state)
if err := os.WriteFile(path, b, 0o644); err != nil {
t.Fatal(err)
}
}
// codexStateFixture is a state file as the app leaves it signed in to a,
// with a's projects at its top level: a folder of the user's own, and a
// mirror of a's ChatGPT project, and b parked with no projects (its
// snapshot from an earlier switch, as in #5702).
func codexStateFixture(t *testing.T, home string, a []byte, b []byte) string {
t.Helper()
ida := codexIdentityOf(a)
backing := map[string]any{"accountId": ida.account, "userId": ida.user, "projectId": "g-p-1"}
state := map[string]any{
"electron-main-window-bounds": map[string]any{"x": 10, "y": 20},
"local-projects": map[string]any{
"p-site": map[string]any{"id": "p-site", "name": "site", "rootPaths": []string{"/Users/me/site"},
"retiredChatGptBacking": backing, "createdAt": 1, "updatedAt": 2},
"g-p-1": map[string]any{"id": "g-p-1", "name": "a's ChatGPT project", "rootPaths": []string{},
"chatGptBacking": backing, "createdAt": 1, "updatedAt": 2},
},
"project-order": []string{"p-site", "g-p-1"},
"thread-project-assignments": map[string]any{"t1": "p-site", "t2": "g-p-1"},
"remote-projects": []any{map[string]any{"id": "r1"}},
codexRendererKey: map[string]any{
"owner": codexRendererOwner(a),
"inactive": map[string]any{
codexRendererOwner(b): map[string]any{"atoms": map[string]any{"x": 1}, "globals": map[string]any{"pinned-thread-ids": []string{"t9"}}},
},
},
}
path := codexGlobalStatePath(home)
bs, _ := json.Marshal(state)
if err := os.WriteFile(path, bs, 0o644); err != nil {
t.Fatal(err)
}
return path
}
// Michael25651150 on X: "切换账号 codex 添加的项目丢了 发生过好几次了". The
// Codex app keeps projects per ChatGPT identity, so magpie's switch to
// another account showed that account's empty list. With the app closed,
// magpie gives the accounts with none the projects: the app, launched and
// switched as magpie switches it, shows them on every account.
func TestCodexProjectsFollowASwitch(t *testing.T) {
home := t.TempDir()
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})
if err != nil || n != 2 {
t.Fatalf("carried to %d (%v), want b and c", n, err)
}
for _, to := range [][]byte{b, c} {
app := codexAppLaunch(t, path)
app.signIn(a)
if got := app.projects(); !slices.Equal(got, []string{"g-p-1", "p-site"}) {
t.Fatalf("a's own projects: %v", got)
}
app.signIn(to) // magpie's switch: auth.json, the app-server's restart
if got := app.projects(); !slices.Equal(got, []string{"p-site"}) {
t.Fatalf("after the switch the app shows %v, want the user's p-site", got)
}
if got := app.state["project-order"]; !slices.Equal(anyStrings(got), []string{"p-site"}) {
t.Fatalf("project-order %v: a's ChatGPT project went along", got)
}
if got := app.state["thread-project-assignments"].(map[string]any); len(got) != 1 || got["t1"] != "p-site" {
t.Fatalf("thread-project-assignments %v", got)
}
p := app.state["local-projects"].(map[string]any)["p-site"].(map[string]any)
if _, ok := p["retiredChatGptBacking"]; ok {
t.Fatal("a's backing went to another account: the app refuses it (\"belongs to a different ChatGPT account\")")
}
if _, ok := app.state["remote-projects"]; ok {
t.Fatal("a's remote projects went along")
}
}
// b's own things stay
app := codexAppLaunch(t, path)
app.signIn(b)
if got := anyStrings(app.state["pinned-thread-ids"]); !slices.Equal(got, []string{"t9"}) {
t.Fatalf("b's pins %v", got)
}
// what magpie doesn't know is kept, and the file as it was beside it
var top map[string]any
raw, _ := os.ReadFile(path)
_ = json.Unmarshal(raw, &top)
if top["electron-main-window-bounds"] == nil {
t.Fatal("an unrelated key was lost")
}
if _, err := os.Stat(path + ".magpie-before-projects"); err != nil {
t.Fatalf("no backup: %v", err)
}
// once more: nothing to do
if n, err := carryCodexProjects(home, [][]byte{a, b, c}); 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) {
home := t.TempDir()
a, b := codexTestAuth("user-a", "acct-a"), codexTestAuth("user-b", "acct-b")
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)
before, _ := os.ReadFile(path)
if n, err := carryCodexProjects(home, [][]byte{a, b}); n != 0 || err != nil {
t.Fatalf("carried to %d (%v)", n, err)
}
if after, _ := os.ReadFile(path); string(after) != string(before) {
t.Fatal("the file was written with nothing to carry")
}
// 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)
}
app = codexAppLaunch(t, path)
app.signIn(c)
if got := app.projects(); !slices.Equal(got, []string{"p-site"}) {
t.Fatalf("c shows %v", got)
}
}
// A file magpie can't read as the app's, or one from an app before
// per-identity projects, is never written.
func TestCodexProjectsUnknownFileLeft(t *testing.T) {
a, b := codexTestAuth("user-a", "acct-a"), codexTestAuth("user-b", "acct-b")
for name, body := range map[string]string{
"old app": `{"local-projects":{"p":{"id":"p","name":"p","rootPaths":[],"createdAt":1,"updatedAt":1}}}`,
"broken": `{"local-projects":`,
"odd shape": `{"electron-account-renderer-state-v1":{"owner":1,"inactive":[]}}`,
} {
home := t.TempDir()
path := codexGlobalStatePath(home)
if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
t.Fatal(err)
}
n, _ := carryCodexProjects(home, [][]byte{a, b})
if got, _ := os.ReadFile(path); n != 0 || string(got) != body {
t.Fatalf("%s: carried to %d, file %s", name, n, got)
}
if _, err := os.Stat(path + ".magpie-before-projects"); err == nil {
t.Fatalf("%s: a backup written", name)
}
}
if n, err := carryCodexProjects(t.TempDir(), [][]byte{a}); n != 0 || err != nil {
t.Fatalf("no file: %d %v", n, err)
}
}
// The owner's hash is the app's: sha256 of JSON.stringify([userId,
// accountId]) (early-bootstrap-815's eaD).
func TestCodexRendererOwner(t *testing.T) {
// node -e 'console.log(require("crypto").createHash("sha256").update(JSON.stringify(["user-a","acct-a"])).digest("hex"))'
const want = "3a83b2a14d3700e107eeba3a6b5fb3a80f6b16c3c8de079ee80f8cf8b4bd15ea"
if got := codexRendererOwner(codexTestAuth("user-a", "acct-a")); got != want {
t.Fatalf("owner %q, want %q", got, want)
}
if codexRendererOwner([]byte(`{"auth_mode":"apikey"}`)) != "" {
t.Fatal("an API key has an identity")
}
}
// The look every few seconds carries only while the app is closed: what
// the open app holds it writes over the file.
func TestCodexProjectsStepWaitsForTheAppToClose(t *testing.T) {
signIn(t)
a := codexTestAuth("user-a", "acct-a")
b := codexTestAuth("user-b", "acct-b")
if err := os.WriteFile(codexAuthPath(), b, 0o600); err != nil {
t.Fatal(err)
}
path := codexStateFixture(t, codexHome(), a, b)
oldOpen, oldEvery := CodexAppOpen, codexProjectsEvery
t.Cleanup(func() {
CodexAppOpen, codexProjectsEvery = oldOpen, oldEvery
codexProjects.Lock()
codexProjects.last, codexProjects.tried = "", time.Time{}
codexProjects.Unlock()
})
codexProjectsEvery = 0
open := true
CodexAppOpen = func(context.Context) (bool, bool) { return open, true }
before, _ := os.ReadFile(path)
codexProjectsStep(context.Background())
if after, _ := os.ReadFile(path); string(after) != string(before) {
t.Fatal("written while the app is open")
}
open = false
codexProjectsStep(context.Background())
app := codexAppLaunch(t, path)
app.signIn(b)
if got := app.projects(); !slices.Equal(got, []string{"p-site"}) {
t.Fatalf("b, signed in now, shows %v once the app closed", got)
}
}
func anyStrings(v any) []string {
var out []string
l, _ := v.([]any)
for _, e := range l {
s, _ := e.(string)
out = append(out, s)
}
return out
}