Files
magpie/internal/provider/codex_app_crash.go
T
yetone 15acba5347 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.
2026-11-10 17:10:32 +08:00

167 lines
5.9 KiB
Go

package provider
import (
"context"
"errors"
"log"
"slices"
"time"
)
// A signed-in ChatGPT app (26.1021 and on) can't always take the
// app-server magpie ended: the one it starts in its place answers its
// handshake, and then the app's own Hosted AppServerManager finds the
// account it had cached cleared with the old connection ("Hosted
// AppServerManager identity is not ready"), logs fatal_error_broadcasted
// and shows "ChatGPT hit a snag / Please try again" over the whole window
// till it is quit and opened again (ysm119 on Discord, #4550: sljdxde,
// wang9262, Indekkusu545). That is in the app, out of magpie's reach; the
// app-server's own exit is clean (code 0, which it counts expected).
//
// So for codexAppCrashWait after magpie ends an app-server, its logs are
// read for that line (CodexAppCrashed, the agent package's: the app's own
// log folder, a line stamped after the end). When the app shows the page
// 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), 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.
// CodexAppCrashed says whether the Codex app logged the page it shows
// when it can't go on (fatal_error_broadcasted) at or after since, and
// when; known false when its logs can't be read. CodexAppRelaunch quits
// the app and opens it again, erring where it can't.
var (
CodexAppCrashed func(since time.Time) (at time.Time, crashed, known bool)
CodexAppRelaunch func(ctx context.Context) error
// codexAppCrashWait is how long after an end the logs are read: the
// app logs the page within seconds of the new app-server's start
codexAppCrashWait = 60 * time.Second
)
// watchCodexAppCrash starts reading the app's logs for the page, from
// now, or carries a watch already running on to now's window.
func watchCodexAppCrash(now time.Time) {
c := &codexApp
c.Lock()
defer c.Unlock()
watchCodexAppCrashLocked(now)
}
func watchCodexAppCrashLocked(now time.Time) {
c := &codexApp
if c.crashBy.IsZero() || c.crashSince.After(now) {
c.crashSince = now
}
c.crashBy = now.Add(codexAppCrashWait)
}
// CodexAppSnagged is whether the Codex app showed the page it shows when
// it can't go on after magpie restarted its app-server, and magpie
// couldn't reopen it: the user quits it and opens it again.
func CodexAppSnagged() bool {
c := &codexApp
c.Lock()
defer c.Unlock()
return c.snag
}
// codexAppCrashStep is codexAppStep's look at the app after an end: it
// reads the logs while a watch runs, reopens the app that shows the page,
// and forgets a snag once the app-servers running at it are gone.
func codexAppCrashStep(ctx context.Context, now time.Time, busy func() (int, time.Time)) {
c := &codexApp
c.Lock()
since, by, snag, snagPids := c.crashSince, c.crashBy, c.snag, slices.Clone(c.snagPids)
c.Unlock()
home := codexHome()
if snag {
if open, known := codexAppOpenNow(ctx); known && !open {
codexAppUnsnag()
return
}
lctx, cancel := context.WithTimeout(ctx, codexAppListWait)
pids, err := codexAppServersOn(lctx, home)
cancel()
// a listing that fails is unknown: the snag stays. With none
// running at it, one that starts is the app's new start
if err == nil && (len(snagPids) > 0 || len(pids) > 0) &&
!slices.ContainsFunc(pids, func(p int) bool { return slices.Contains(snagPids, p) }) {
codexAppUnsnag()
}
if by.IsZero() {
return
}
}
if by.IsZero() || CodexAppCrashed == nil {
return
}
at, crashed, _ := CodexAppCrashed(since)
if !crashed {
// a page not seen in the window, or logs that can't be read, end
// the watch: an unread log never reopens the app
if !now.Before(by) {
c.Lock()
if c.crashBy.Equal(by) {
c.crashSince, c.crashBy = time.Time{}, time.Time{}
}
c.Unlock()
}
return
}
c.Lock()
c.crashSince, c.crashBy = time.Time{}, time.Time{}
c.Unlock()
// the page has no composer: a request or a turn since means the app
// came back (its Try again) and is in use, never cut short
if busy != nil {
if n, last := busy(); n > 0 || last.After(at) {
log.Printf("codex: the Codex app showed its error page after magpie restarted its app-server, and has sent since; left as it is")
return
}
}
if codexTurnRunning(home, now, at) {
log.Printf("codex: the Codex app showed its error page after magpie restarted its app-server, and a Codex turn runs since; left as it is")
return
}
lctx, cancel := context.WithTimeout(ctx, codexAppListWait)
pids, _ := codexAppServersOn(lctx, home)
cancel()
err := errNoRelaunch
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 {
log.Printf("codex: the Codex app showed its error page after magpie restarted its app-server; quit it and opened it again")
return
}
log.Printf("codex: the Codex app showed its error page after magpie restarted its app-server; reopening it: %v", err)
c.Lock()
c.snag, c.snagPids = true, pids
c.Unlock()
}
func codexAppUnsnag() {
c := &codexApp
c.Lock()
c.snag, c.snagPids = false, nil
c.Unlock()
}
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")
)