codex: the ChatGPT app left on "hit a snag" after an app-server restart is reopened when idle (#4550)

ysm119 on Discord: each Restart of Codex in magpie left the ChatGPT
desktop app on "ChatGPT 遇到了问题 / 请重试" till it was quit and opened
again. magpie ends the app's own app-server cleanly (code 0); a
signed-in ChatGPT 26.1021 then fails "Hosted AppServerManager identity
is not ready" on the one it starts, logs fatal_error_broadcasted and
shows the page. That is the app's bug; magpie now follows it up.

- provider/codex_app_crash.go: for 60s after every end magpie makes
  (the watcher's step, RestartCodexApp, RestartSwitchedCodexApp) the
  app's logs are read for a whole fatal_error_broadcasted line stamped
  after the end. On one, with no request through magpie since or in
  flight and no Codex turn opened since, the app is quit and opened
  once. Otherwise it is left as it is and logged. Where it can't be
  reopened (Linux, an app that didn't quit) the Agents row says
  "The Codex app hit an error · quit it and open it again" (appSnag)
  until the app-servers seen then are gone or the app is closed.
  Unreadable logs reopen nothing.
- agent/codex_app_crash.go: the logs as the app's file logger writes
  them (macOS ~/Library/Logs/com.openai.codex, Windows
  %LOCALAPPDATA%\Codex\Logs and the Store package's LocalCache, Linux
  $XDG_STATE_HOME/codex/logs; YYYY/MM/DD folders, tail-read, half
  lines dropped). The relaunch is the Agents row's: on macOS
  ChatGPT.app found by its bundle id, quit as ⌘Q does and opened once
  it has ended, never forced; on Windows codexAppReopen.
- GUI line in en, zh, zh-TW, ja, de; docs/subsystems/agent-wiring.md.

Run on mote (macOS) at this head on origin/main 08982805e:
- go vet ./internal/agent ./internal/provider ./internal/gui (darwin
  and GOOS=windows), GOOS=linux go vet ./internal/agent
  ./internal/provider; go build ./...; gofmt -l clean.
- go test ./internal/provider ok; go test -run
  'TestCodexApp|Restart|Reopen' ./internal/agent ok.
- go test ./internal/gui: red only in TestMainWindowCorners (#3949) and
  TestPanelHiddenByWailsMarksPageOutOfSight (#5322), AppKit window tests
  red on mote's macOS 27 and filed before this change.
- win-run and wsl-run: go test -run TestCodexApp ./internal/agent
  ./internal/provider ok (the macOS relaunch test skips on Windows, as
  TestWorkBuddySidecarOutlivesQuitOnMac does, #4115).
- node --test codex-app-snag, codex-app-out, codex-app-back, i18n-keys,
  i18n-en-no-cjk: chromium and webkit, every language, 980 and 440px.
  i18n-keys' "a plugin's words are its own" stays red for "View routing"
  (#5327/#5332, red on main since 73c98ebc2); this change added a word
  there and took it out again.
- Core script budget: under it, not raised.

Broken by hand, each red then restored:
- codexAppCrashStep's call removed: 4 provider tests red.
- the watch not armed in RestartSwitchedCodexApp:
  TestCodexAppRestartsWatchForTheErrorPage red; in RestartCodexApp:
  TestCodexAppRowRestartWatchesForTheErrorPage red.
- the turn and request checks off: TestCodexAppInUseAfterItsErrorPageIsLeft red.
- the snag not set: TestCodexAppSnagSaidTillTheAppRestarts red.
- the stamp's >= since check dropped, or a half-written last line kept:
  TestCodexAppCrashedReadsItsOwnLogs red.
- a wrong Store package path: TestCodexAppCrashedReadsEachSystemsFolder red.

Not tried: a real signed-in ChatGPT app reaching the identity-not-ready
page, and a real quit and reopen of the user's ChatGPT.app (the relaunch
is tested with faked process listing, quit and open in a sandbox HOME).
The log line and folders are read from ChatGPT 26.1021's
file-based-logger and the reporters' logs; a later app that renames
them reopens nothing, as before this change.
This commit is contained in:
yetone
2026-11-05 17:24:53 +08:00
parent 08982805eb
commit 4f624241f7
12 changed files with 976 additions and 2 deletions
File diff suppressed because one or more lines are too long
+2
View File
@@ -59,6 +59,8 @@ func init() {
// reopened on Windows, where its stdout was held open
provider.CodexAppOpen = codexAppOpen
provider.CodexAppReopen = codexAppReopen
provider.CodexAppCrashed = codexAppCrashed
provider.CodexAppRelaunch = codexAppRelaunch
// and what the Codex app holds is read while Codex takes magpie's
// models beside its sign-in, Codex switched off in magpie or not
// Claude Code's own sign-in is left where the user put it while its
+198
View File
@@ -0,0 +1,198 @@
package agent
import (
"bytes"
"context"
"errors"
"io"
"os"
"path/filepath"
"slices"
"strings"
"time"
)
// The Codex app's own logs, read for the page it shows when it can't go on
// after magpie restarted its app-server (provider.CodexAppCrashed, see
// provider/codex_app_crash.go). The app writes them as its file logger
// does in 26.1021 (file-based-logger: macOS ~/Library/Logs/<bundle id>,
// Windows %LOCALAPPDATA%\Codex\Logs, Linux $XDG_STATE_HOME/codex/logs,
// each with a YYYY/MM/DD folder for the UTC day a file was opened), one
// line per entry: `<RFC 3339 UTC> <level> [<scope>] <event> <key=value…>`.
// The Store app on Windows writes the same folder under its package's
// LocalCache (seen on the Windows box).
// codexLogEnv reads the environment for the log folders; a var for tests.
var codexLogEnv = os.Getenv
// codexAppLogRoots are the folders the Codex app writes its logs in here.
func codexAppLogRoots() []string {
home := codexLogEnv("HOME")
if home == "" {
home, _ = os.UserHomeDir()
}
switch {
case restartOnMac:
return []string{filepath.Join(home, "Library", "Logs", desktopApps["codex"].id)}
case restartOnWindows:
local := codexLogEnv("LOCALAPPDATA")
if local == "" {
local = filepath.Join(home, "AppData", "Local")
}
return []string{
filepath.Join(local, "Codex", "Logs"),
filepath.Join(local, "Packages", "OpenAI.Codex_2p2nqsd0c76g0", "LocalCache", "Local", "Codex", "Logs"),
}
case restartOnLinux:
state := codexLogEnv("XDG_STATE_HOME")
if state == "" {
state = filepath.Join(home, ".local", "state")
}
return []string{filepath.Join(state, "codex", "logs")}
}
return nil
}
// codexLogDays is how many of a root's newest day folders are read: a file
// stays in the day it was opened in while the app writes on to it.
const codexLogDays = 7
// codexLogTail is how much of the end of a log file is read.
const codexLogTail = 512 << 10
// codexFatalLine is what the app's AppServerConnection logs as it shows the
// page (broadcastFatalError).
const codexFatalLine = " [AppServerConnection] fatal_error_broadcasted"
// codexAppCrashed is provider.CodexAppCrashed: the first page the app
// logged at or after since (less a second for the clock's grain), read in
// the files written to since then. known is false when no root can be
// read; a root that isn't there is the app never having run on it.
func codexAppCrashed(since time.Time) (at time.Time, crashed, known bool) {
from := since.Add(-time.Second)
for _, root := range codexAppLogRoots() {
files, ok := codexLogFiles(root, from)
known = known || ok
for _, f := range files {
if t, ok := codexFatalIn(f, from); ok && (!crashed || t.Before(at)) {
at, crashed = t, true
}
}
}
return at, crashed, known
}
// codexLogFiles are the .log files under root's newest day folders written
// to at or after from; ok is false when root can't be read.
func codexLogFiles(root string, from time.Time) (files []string, ok bool) {
if _, err := os.ReadDir(root); errors.Is(err, os.ErrNotExist) {
return nil, true
} else if err != nil {
return nil, false
}
var days []string
for _, y := range codexLogDirs(root) {
for _, m := range codexLogDirs(y) {
days = append(days, codexLogDirs(m)...)
}
}
slices.Sort(days)
if len(days) > codexLogDays {
days = days[len(days)-codexLogDays:]
}
for _, d := range days {
es, _ := os.ReadDir(d)
for _, e := range es {
if e.IsDir() || !strings.HasSuffix(e.Name(), ".log") {
continue
}
if info, err := e.Info(); err == nil && !info.ModTime().Before(from) {
files = append(files, filepath.Join(d, e.Name()))
}
}
}
return files, true
}
// codexLogDirs are dir's folders named by digits alone (a year, month or
// day), in full.
func codexLogDirs(dir string) []string {
es, _ := os.ReadDir(dir)
var out []string
for _, e := range es {
if e.IsDir() && e.Name() != "" && strings.Trim(e.Name(), "0123456789") == "" {
out = append(out, filepath.Join(dir, e.Name()))
}
}
return out
}
// codexFatalIn is the time of the first page logged in the file at path
// at or after from, read in its last codexLogTail bytes. A line the app
// is still writing (no newline yet) and the part line the tail cuts into
// are left out.
func codexFatalIn(path string, from time.Time) (time.Time, bool) {
f, err := os.Open(path)
if err != nil {
return time.Time{}, false
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return time.Time{}, false
}
off := max(info.Size()-codexLogTail, 0)
b, err := io.ReadAll(io.NewSectionReader(f, off, info.Size()-off))
if err != nil {
return time.Time{}, false
}
if off > 0 {
i := bytes.IndexByte(b, '\n')
if i < 0 {
return time.Time{}, false
}
b = b[i+1:]
}
if i := bytes.LastIndexByte(b, '\n'); i >= 0 {
b = b[:i+1]
} else {
return time.Time{}, false
}
for line := range bytes.Lines(b) {
if !bytes.Contains(line, []byte(codexFatalLine)) {
continue
}
stamp, _, _ := bytes.Cut(line, []byte(" "))
t, err := time.Parse(time.RFC3339Nano, string(stamp))
if err == nil && !t.Before(from) {
return t, true
}
}
return time.Time{}, false
}
// codexAppRelaunch is provider.CodexAppRelaunch: it quits the Codex app
// and opens it again, as the Agents row's Restart does for an app: on
// macOS ChatGPT.app (com.openai.codex) asked to quit as ⌘Q does and opened
// once every process of its bundle has ended, never forced (an app still
// open then is left, and the row says to quit it); on Windows the Store
// app's windows closed, its tree ended when it stays in the tray, and
// opened again (codexAppReopen). Nothing is done for an app not running:
// it was quit meanwhile. Linux isn't reopened.
func codexAppRelaunch(ctx context.Context) error {
switch {
case restartOnWindows:
return codexAppReopen(ctx)
case restartOnMac:
c, ok := findRestartable(restartable{mac: desktopApps["codex"]})
if !ok {
return nil
}
a, err := Find("codex")
if err != nil {
a = &Agent{ID: "codex", Name: "Codex"}
}
return reopenBundle(ctx, a, c.bundle, c.exe)
}
return errors.New("magpie reopens the Codex app on macOS and Windows only")
}
+225
View File
@@ -0,0 +1,225 @@
package agent
import (
"context"
"os"
"path/filepath"
"regexp"
"runtime"
"slices"
"testing"
"time"
)
// codexLog writes a log file of the Codex app's under root's day folder
// for day, as the app's file logger names it, modified at mod.
func codexLog(t *testing.T, root string, day time.Time, text string, mod time.Time) string {
t.Helper()
dir := filepath.Join(root, day.UTC().Format("2006"), day.UTC().Format("01"), day.UTC().Format("02"))
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
p := filepath.Join(dir, "codex-desktop-581d5b6a-a43b-4ec2-8343-17b4d18217bb-390-t0-i1-000015-0.log")
if err := os.WriteFile(p, []byte(text), 0o644); err != nil {
t.Fatal(err)
}
if err := os.Chtimes(p, mod, mod); err != nil {
t.Fatal(err)
}
return p
}
// the lines as ChatGPT.app 26.1021 writes them (the owner's logs and the
// app's broadcastFatalError)
func exitedLine(at time.Time) string {
return at.UTC().Format("2006-01-02T15:04:05.000Z") + " error [AppServerConnection] Codex CLI process exited classifiedAsExpected=true code=0 connectionId=93 signal=null transport=stdio\n"
}
func fatalLine(at time.Time) string {
return at.UTC().Format("2006-01-02T15:04:05.000Z") + " error [AppServerConnection] fatal_error_broadcasted initialized=true listenerCount=2 pendingRequestCount=0 transportKind=stdio\n"
}
// The page the Codex app shows when it can't go on after magpie restarted
// its app-server (ysm119 on Discord) is read from the app's own logs: a
// complete fatal_error_broadcasted line at or after the end, in a file
// written to since, in the newest day folders (a file opened the day
// before is written on to past midnight UTC). The clean exit it logs
// first, a page from before, a line still being written and another
// app's folder are none of it.
func TestCodexAppCrashedReadsItsOwnLogs(t *testing.T) {
home := restartSandbox(t)
restartOnMac = true
root := filepath.Join(home, "Library", "Logs", "com.openai.codex")
since := time.Date(2026, 11, 5, 23, 59, 58, 0, time.UTC)
if _, crashed, known := codexAppCrashed(since); crashed || !known {
t.Fatalf("no logs at all: crashed %v, known %v (the app never ran)", crashed, known)
}
// the end's clean exit and a page from an hour before
p := codexLog(t, root, since.Add(-2*time.Hour), fatalLine(since.Add(-time.Hour))+exitedLine(since.Add(time.Second)), since.Add(time.Second))
if _, crashed, _ := codexAppCrashed(since); crashed {
t.Fatal("the clean exit or an old page read as the page")
}
// the page, half-written
half := fatalLine(since.Add(3 * time.Second))
os.WriteFile(p, []byte(fatalLine(since.Add(-time.Hour))+exitedLine(since.Add(time.Second))+half[:len(half)-1]), 0o644)
os.Chtimes(p, since.Add(3*time.Second), since.Add(3*time.Second))
if _, crashed, _ := codexAppCrashed(since); crashed {
t.Fatal("a line still being written read as the page")
}
// whole, in the file opened the day before
os.WriteFile(p, []byte(fatalLine(since.Add(-time.Hour))+exitedLine(since.Add(time.Second))+half), 0o644)
os.Chtimes(p, since.Add(3*time.Second), since.Add(3*time.Second))
at, crashed, known := codexAppCrashed(since)
if !crashed || !known || !at.Equal(since.Add(3*time.Second)) {
t.Fatalf("the page: at %v, crashed %v, known %v", at, crashed, known)
}
// a file not written to since the end isn't read
os.Chtimes(p, since.Add(-time.Minute), since.Add(-time.Minute))
if _, crashed, _ := codexAppCrashed(since); crashed {
t.Fatal("a file untouched since the end read")
}
// the next day's folder
codexLog(t, root, since.Add(time.Hour), exitedLine(since.Add(time.Second))+fatalLine(since.Add(4*time.Second)), since.Add(5*time.Second))
if at, crashed, _ := codexAppCrashed(since); !crashed || !at.Equal(since.Add(4*time.Second)) {
t.Fatalf("the next day's folder: at %v, crashed %v", at, crashed)
}
// another app's logs (the beta's bundle id) are not the Codex app's
home = restartSandbox(t)
restartOnMac = true
codexLog(t, filepath.Join(home, "Library", "Logs", "com.openai.codex.beta"), since, fatalLine(since.Add(time.Second)), since.Add(time.Second))
if _, crashed, _ := codexAppCrashed(since); crashed {
t.Fatal("another app's page read as the Codex app's")
}
// a log folder that can't be read is unknown
if runtime.GOOS != "windows" {
root := filepath.Join(home, "Library", "Logs", "com.openai.codex")
os.MkdirAll(root, 0o755)
os.Chmod(root, 0)
t.Cleanup(func() { os.Chmod(root, 0o755) })
if _, err := os.ReadDir(root); err == nil {
t.Skip("running as a user who reads any folder")
}
if _, crashed, known := codexAppCrashed(since); crashed || known {
t.Fatalf("an unreadable folder: crashed %v, known %v", crashed, known)
}
}
}
// Windows and Linux keep the logs where the app's file logger puts them
// there: %LOCALAPPDATA%\Codex\Logs, which the Store app writes under its
// package's LocalCache, and $XDG_STATE_HOME/codex/logs (~/.local/state
// without it).
func TestCodexAppCrashedReadsEachSystemsFolder(t *testing.T) {
since := time.Date(2026, 11, 5, 8, 0, 0, 0, time.UTC)
page := exitedLine(since.Add(time.Second)) + fatalLine(since.Add(2*time.Second))
for _, tc := range []struct {
name string
set func(home string)
root func(home string) string
}{
{"windows", func(home string) {
restartOnWindows = true
t.Setenv("LOCALAPPDATA", filepath.Join(home, "AppData", "Local"))
}, func(home string) string { return filepath.Join(home, "AppData", "Local", "Codex", "Logs") }},
{"windows store", func(home string) {
restartOnWindows = true
t.Setenv("LOCALAPPDATA", filepath.Join(home, "AppData", "Local"))
}, func(home string) string {
return filepath.Join(home, "AppData", "Local", "Packages", "OpenAI.Codex_2p2nqsd0c76g0", "LocalCache", "Local", "Codex", "Logs")
}},
{"linux", func(home string) {
restartOnLinux = true
t.Setenv("XDG_STATE_HOME", filepath.Join(home, "state"))
}, func(home string) string { return filepath.Join(home, "state", "codex", "logs") }},
{"linux default", func(home string) {
restartOnLinux = true
t.Setenv("XDG_STATE_HOME", "")
}, func(home string) string { return filepath.Join(home, ".local", "state", "codex", "logs") }},
} {
t.Run(tc.name, func(t *testing.T) {
home := restartSandbox(t)
tc.set(home)
if _, crashed, _ := codexAppCrashed(since); crashed {
t.Fatal("a page with no logs")
}
codexLog(t, tc.root(home), since, page, since.Add(3*time.Second))
if at, crashed, known := codexAppCrashed(since); !crashed || !known || !at.Equal(since.Add(2*time.Second)) {
t.Fatalf("at %v, crashed %v, known %v", at, crashed, known)
}
})
}
}
// The app is reopened as the Agents row's Restart reopens an app on a Mac:
// ChatGPT.app, known by its bundle id, quit as ⌘Q does and opened once it
// has ended, never another bundle (a Codex.app of another id), and never
// forced (one still open is said). An app not open: nothing. Linux: not done.
func TestCodexAppRelaunchOnlyTheCodexApp(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("the bundle paths are built with filepath, so a Windows run spells them with \\ (#4115)")
}
home := restartSandbox(t)
apps := filepath.Join(home, "Applications")
chatgpt := macApp(t, apps, "ChatGPT.app", "com.openai.codex", "ChatGPT")
other := macApp(t, apps, "Codex.app", "com.openai.codex.beta", "Codex")
restartOnMac = true
appFolders = func() []string { return []string{apps} }
appQuitWait = 100 * time.Millisecond
alive := map[string]bool{chatgpt: true, other: true}
stays := false
running = func(pat string) []runningProc {
var out []runningProc
exe := map[string]string{chatgpt: "ChatGPT", other: "Codex"}
for b, on := range alive {
for _, cmd := range []string{
b + "/Contents/MacOS/" + exe[b],
b + "/Contents/Resources/codex app-server --analytics-default-enabled",
} {
if on && regexp.MustCompile(pat).MatchString(cmd) {
out = append(out, runningProc{time.Hour, cmd})
}
}
}
return out
}
var quit, opened []string
appQuit = func(_ context.Context, b string) error {
quit = append(quit, b)
if !stays {
alive[b] = false
}
return nil
}
appOpen = func(_ context.Context, b string) error {
opened = append(opened, b)
alive[b] = true
return nil
}
if err := codexAppRelaunch(context.Background()); err != nil {
t.Fatal(err)
}
if !slices.Equal(quit, []string{chatgpt}) || !slices.Equal(opened, []string{chatgpt}) || !alive[other] {
t.Fatalf("quit %q, opened %q, the other app running %v", quit, opened, alive[other])
}
// one that doesn't quit: said, not opened again
quit, opened, stays = nil, nil, true
if err := codexAppRelaunch(context.Background()); err == nil || len(opened) > 0 {
t.Fatalf("an app that stayed: %v, opened %q", err, opened)
}
// not running: nothing
quit, alive[chatgpt] = nil, false
if err := codexAppRelaunch(context.Background()); err != nil || len(quit) > 0 {
t.Fatalf("not running: %v, quit %q", err, quit)
}
restartOnMac, restartOnLinux = false, true
alive[chatgpt] = true
if err := codexAppRelaunch(context.Background()); err == nil || len(quit) > 0 {
t.Fatalf("linux: %v, quit %q", err, quit)
}
}
+6
View File
@@ -244,6 +244,9 @@ type agentJSON struct {
// was its provider, which shows no account or usage till it restarts
// (provider.CodexAppBack), for the row's Restart
AppBack bool `json:"appBack,omitempty"`
// AppSnag: the Codex app showed its error page after magpie restarted
// its app-server and magpie couldn't reopen it (provider.CodexAppSnagged)
AppSnag bool `json:"appSnag,omitempty"`
// Failover: not connected, yet its requests go through magpie for
// account failover alone (agent.Agent.FailingOver, #1385)
Failover bool `json:"failover,omitempty"`
@@ -2772,6 +2775,9 @@ func state() stateJSON {
aj.Source = a.Source()
aj.Failover = a.FailingOver != nil && a.FailingOver()
}
if a.ID == "codex" && a.WSL == "" {
aj.AppSnag = provider.CodexAppSnagged()
}
aj.AppRestart = a.AppBehind()
if a.Import != nil {
aj.Import = a.Import()
+1
View File
@@ -1389,6 +1389,7 @@ function connectLine(a, kind) {
return line;
}
if (kind === "empty" && !switchable(a)) { say(t("Add a key or a subscription first; then there are models to connect")); return line; }
if (a.appSnag) { say(t("The {agent} app hit an error · quit it and open it again", { agent: a.name }), "wait"); return line; }
if (!a.wired && a.native && a.native.provider !== "disconnected") {
say(t(a.native.detail), "bad");
if (a.native.provider === "invalid") line.append(driftFix(a, "Reconnect"));
+4
View File
@@ -2149,6 +2149,7 @@ const I18N = {
"{user}'s ChatGPT allowance is used up, so magpie serves {agent}'s turns until it resets.": "{user} 的 ChatGPT 额度已用完,重置前由 magpie 接管 {agent} 的对话。",
"{agent}'s ChatGPT allowance is used up, so magpie serves its turns until it resets.": "{agent} 的 ChatGPT 额度已用完,重置前由 magpie 接管它的对话。",
"Till then the {agent} app's ChatGPT side is off: its ChatGPT chats and projects, browser use (its Chrome control), cloud tasks, its account, its usage meter and Log out. They come back after the reset, once the app's app-server restarts: this row offers the restart then.": "在此之前,{agent} 应用的 ChatGPT 功能暂时关闭:ChatGPT 聊天和项目、浏览器操作(Chrome 控制)、云端任务、账号、用量显示和退出登录。额度重置后,等应用的 app-server 重启就会恢复;届时这一行会提供重启按钮。",
"The {agent} app hit an error · quit it and open it again": "{agent} 应用出错了 · 请退出后重新打开",
"Back on ChatGPT · restart the {agent} app to see its account": "已回到 ChatGPT · 重启 {agent} 应用才能看到账号",
"magpie gave {agent} back its ChatGPT account after the reset. The {agent} app still runs on the app-server it started while magpie served it, so it shows no account, no usage and none of its ChatGPT side until that restarts. Restart does it now; its window stays.": "额度重置后,magpie 已把 ChatGPT 账号还给 {agent}。但 {agent} 应用仍在用 magpie 接管期间启动的 app-server,所以在它重启前看不到账号、用量和其他 ChatGPT 功能。点“重启”即可立即重启;窗口保持不变。",
"Only its app-server restarts, for its ChatGPT account; its window stays. A running turn stops.": "只重启它的 app-server,以读取 ChatGPT 账号;窗口保持不变。正在运行的回合会停止。",
@@ -6766,6 +6767,7 @@ const I18N = {
"{user}'s ChatGPT allowance is used up, so magpie serves {agent}'s turns until it resets.": "{user} 的 ChatGPT 額度已用完,重設前由 magpie 接管 {agent} 的對話。",
"{agent}'s ChatGPT allowance is used up, so magpie serves its turns until it resets.": "{agent} 的 ChatGPT 額度已用完,重設前由 magpie 接管它的對話。",
"Till then the {agent} app's ChatGPT side is off: its ChatGPT chats and projects, browser use (its Chrome control), cloud tasks, its account, its usage meter and Log out. They come back after the reset, once the app's app-server restarts: this row offers the restart then.": "在此之前,{agent} 應用的 ChatGPT 功能暫時關閉:ChatGPT 聊天和專案、瀏覽器操作(Chrome 控制)、雲端任務、帳號、用量顯示和登出。額度重設後,等應用的 app-server 重新啟動就會恢復;屆時這一行會提供重新啟動按鈕。",
"The {agent} app hit an error · quit it and open it again": "{agent} 應用程式出錯了 · 請結束後重新開啟",
"Back on ChatGPT · restart the {agent} app to see its account": "已回到 ChatGPT · 重新啟動 {agent} 應用才能看到帳號",
"magpie gave {agent} back its ChatGPT account after the reset. The {agent} app still runs on the app-server it started while magpie served it, so it shows no account, no usage and none of its ChatGPT side until that restarts. Restart does it now; its window stays.": "額度重設後,magpie 已把 ChatGPT 帳號還給 {agent}。但 {agent} 應用仍在使用 magpie 接管期間啟動的 app-server,所以在它重新啟動前看不到帳號、用量和其他 ChatGPT 功能。點「重啟」即可立即重新啟動;視窗保持不變。",
"Only its app-server restarts, for its ChatGPT account; its window stays. A running turn stops.": "只重新啟動它的 app-server,以讀取 ChatGPT 帳號;視窗保持不變。正在執行的回合會停止。",
@@ -11359,6 +11361,7 @@ const I18N = {
"{user}'s ChatGPT allowance is used up, so magpie serves {agent}'s turns until it resets.": "{user} の ChatGPT の利用枠を使い切ったため、リセットまで magpie が {agent} のターンを処理します。",
"{agent}'s ChatGPT allowance is used up, so magpie serves its turns until it resets.": "{agent} の ChatGPT の利用枠を使い切ったため、リセットまで magpie がそのターンを処理します。",
"Till then the {agent} app's ChatGPT side is off: its ChatGPT chats and projects, browser use (its Chrome control), cloud tasks, its account, its usage meter and Log out. They come back after the reset, once the app's app-server restarts: this row offers the restart then.": "それまで {agent} アプリの ChatGPT 機能(ChatGPT のチャットとプロジェクト、ブラウザ操作(Chrome の操作)、クラウドタスク、アカウント、使用量の表示、ログアウト)はオフになります。リセット後、アプリの app-server が再起動すると戻ります。そのときこの行に再起動ボタンが出ます。",
"The {agent} app hit an error · quit it and open it again": "{agent} アプリでエラーが発生しました · 終了してもう一度開いてください",
"Back on ChatGPT · restart the {agent} app to see its account": "ChatGPT に戻りました · アカウントを表示するには {agent} アプリを再起動",
"magpie gave {agent} back its ChatGPT account after the reset. The {agent} app still runs on the app-server it started while magpie served it, so it shows no account, no usage and none of its ChatGPT side until that restarts. Restart does it now; its window stays.": "リセット後、magpie は {agent} に ChatGPT アカウントを戻しました。ただし {agent} アプリは magpie が代わりに応答していた間に起動した app-server のままなので、再起動するまでアカウント、使用量、その他の ChatGPT 機能は表示されません。「再起動」ですぐに再起動します。ウィンドウはそのままです。",
"Only its app-server restarts, for its ChatGPT account; its window stays. A running turn stops.": "app-server だけを再起動して ChatGPT アカウントを読み込ませます。ウィンドウはそのままです。実行中のターンは止まります。",
@@ -15983,6 +15986,7 @@ const I18N = {
"{user}'s ChatGPT allowance is used up, so magpie serves {agent}'s turns until it resets.": "Das ChatGPT-Kontingent von {user} ist aufgebraucht, daher bedient magpie die Anfragen von {agent}, bis es zurückgesetzt wird.",
"{agent}'s ChatGPT allowance is used up, so magpie serves its turns until it resets.": "Das ChatGPT-Kontingent von {agent} ist aufgebraucht, daher bedient magpie seine Anfragen, bis es zurückgesetzt wird.",
"Till then the {agent} app's ChatGPT side is off: its ChatGPT chats and projects, browser use (its Chrome control), cloud tasks, its account, its usage meter and Log out. They come back after the reset, once the app's app-server restarts: this row offers the restart then.": "Bis dahin ist die ChatGPT-Seite der {agent}-App aus: ihre ChatGPT-Chats und -Projekte, Browser-Nutzung (ihre Chrome-Steuerung), Cloud-Aufgaben, ihr Konto, ihre Nutzungsanzeige und Abmelden. Nach dem Zurücksetzen kommt sie wieder, sobald der App-Server der App neu startet: Diese Zeile bietet dann den Neustart an.",
"The {agent} app hit an error · quit it and open it again": "Die {agent}-App hat einen Fehler · beende sie und öffne sie erneut",
"Back on ChatGPT · restart the {agent} app to see its account": "Wieder bei ChatGPT · {agent}-App neu starten, um das Konto zu sehen",
"magpie gave {agent} back its ChatGPT account after the reset. The {agent} app still runs on the app-server it started while magpie served it, so it shows no account, no usage and none of its ChatGPT side until that restarts. Restart does it now; its window stays.": "magpie hat {agent} nach dem Zurücksetzen sein ChatGPT-Konto zurückgegeben. Die {agent}-App läuft noch auf dem App-Server, den sie startete, während magpie sie bediente, und zeigt darum kein Konto, keine Nutzung und nichts von ihrer ChatGPT-Seite, bis dieser neu startet. „Neu starten“ erledigt das jetzt; das Fenster bleibt offen.",
"Only its app-server restarts, for its ChatGPT account; its window stays. A running turn stops.": "Nur sein App-Server startet neu, um sein ChatGPT-Konto zu lesen; das Fenster bleibt offen. Ein laufender Turn wird angehalten.",
@@ -0,0 +1,84 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// ysm119 on Discord (#4550): after magpie restarted the Codex app's
// app-server, a signed-in ChatGPT app showed "ChatGPT hit a snag" till it
// was quit and opened again. magpie reopens it itself when nothing runs;
// where it couldn't (Linux, an app that didn't quit), the Agents row says
// to (appSnag), over what it would say of its provider. Every language,
// both engines, wide and narrow. No backend, the API is faked.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const codex = (appSnag) => ({
id: "codex", name: "Codex", path: "/fixture/config.toml", wired: true,
fields: [{ key: "model", label: "model", value: "gpt-6.1-sol", options: [{ value: "gpt-6.1-sol", label: "gpt-6.1-sol", ref: "gpt-6.1-sol" }] }],
appSnag,
});
const words = {
en: "The Codex app hit an error · quit it and open it again",
zh: "Codex 应用出错了 · 请退出后重新打开",
"zh-TW": "Codex 應用程式出錯了 · 請結束後重新開啟",
ja: "Codex アプリでエラーが発生しました · 終了してもう一度開いてください",
de: "Die Codex-App hat einen Fehler · beende sie und öffne sie erneut",
};
function serve(lang, snag) {
const state = { agents: [codex(snag)], profiles: [], settings: { lang, theme: "light" } };
return async (route) => {
const url = new URL(route.request().url());
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return route.fulfill({ json: state });
if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });
if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });
if (url.pathname === "/api/agents/cli") return route.fulfill({ json: { agents: {}, pending: false } });
if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], presets: [], excluded: [], gateway: { running: true, window: true } } });
if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} });
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const row = '.row.agent[data-id="codex"]';
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(words)) {
for (const width of [980, 440]) {
test(`${engine} ${lang} ${width}px: the Codex row says to quit and reopen the app after its error page`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await browser.newPage({ viewport: { width, height: 800 } });
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, true));
await page.goto("http://magpie.test/?view=agents");
const st = page.locator(`${row} .ag-st-t`);
await st.waitFor();
assert.equal((await st.textContent()).trim(), words[lang]);
assert.ok(await page.locator(`${row} .ag-st.wait, ${row} .wait .ag-st-t, ${row} .wait`).count() > 0, "said as a wait");
const box = await st.boundingBox();
assert.ok(box && box.x >= 0 && box.x + box.width <= width + 0.5, "the line is on the page: " + JSON.stringify(box));
const side = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
assert.ok(side <= 1, "scrolls sideways: " + side);
assert.deepEqual(errors, []);
});
}
}
test(`${engine}: without appSnag the row says nothing of it`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await browser.newPage({ viewport: { width: 980, height: 800 } });
await page.route("**/*", serve("en", undefined));
await page.goto("http://magpie.test/?view=agents");
await page.locator(`${row} .ag-st-t`).waitFor();
assert.doesNotMatch(await page.locator(`${row} .ag-st-t`).textContent(), /hit an error/);
});
}
+153
View File
@@ -0,0 +1,153 @@
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). Where that
// 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
if 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")
+279
View File
@@ -0,0 +1,279 @@
package provider
import (
"context"
"errors"
"slices"
"testing"
"time"
"github.com/yetone/magpie/internal/proc"
)
// crashStub has the Codex app's logs say it showed its error page at at,
// from the end on, and counts the relaunches.
type crashStub struct {
page bool
at time.Time
sinces []time.Time
relaunch int
err error
unknown bool
}
func stubCodexCrash(t *testing.T) *crashStub {
t.Helper()
c := &crashStub{}
CodexAppCrashed = func(since time.Time) (time.Time, bool, bool) {
c.sinces = append(c.sinces, since)
if c.unknown {
return time.Time{}, false, false
}
if c.page && !c.at.Before(since) {
return c.at, true, true
}
return time.Time{}, false, true
}
CodexAppRelaunch = func(context.Context) error {
c.relaunch++
return c.err
}
return c
}
// ysm119 on Discord: each restart magpie made of the Codex app's
// app-server left a signed-in ChatGPT app on its "ChatGPT hit a snag"
// page, which only quitting and opening it again ends (#4550). magpie
// reads the app's logs after its end and reopens the app once, when no
// turn has started since; it does nothing when the app logged no page.
func TestCodexAppReopenedWhenItShowsItsErrorPage(t *testing.T) {
signIn(t)
s := stubCodexApp(t)
c := stubCodexCrash(t)
now := time.Now()
idle := func() (int, time.Time) { return 0, now.Add(-time.Minute) }
step := func() []int { return codexAppStep(context.Background(), now, idle) }
s.running = []int{60}
step()
if len(c.sinces) > 0 {
t.Fatalf("the logs read with nothing ended: %v", c.sinces)
}
s.on = true
if got := step(); !slices.Equal(got, []int{60}) {
t.Fatalf("ended %v, want [60]", got)
}
ended := now
// no page: nothing done, and the watch ends with its window
now = now.Add(3 * time.Second)
step()
if c.relaunch != 0 || len(c.sinces) != 1 || !c.sinces[0].Equal(ended) {
t.Fatalf("no page: relaunched %d, logs read since %v", c.relaunch, c.sinces)
}
now = ended.Add(codexAppCrashWait)
step()
n := len(c.sinces)
now = now.Add(3 * time.Second)
step()
if len(c.sinces) != n {
t.Fatal("the logs still read after the watch's window")
}
// the page, logged two seconds after the end: reopened once
s.on = false
ended = now
if got := step(); !slices.Equal(got, []int{100}) {
t.Fatalf("ended %v, want [100]", got)
}
c.page, c.at = true, ended.Add(2*time.Second)
now = now.Add(3 * time.Second)
step()
if c.relaunch != 1 || CodexAppSnagged() {
t.Fatalf("the error page: relaunched %d, snag %v", c.relaunch, CodexAppSnagged())
}
now = now.Add(3 * time.Second)
step()
if c.relaunch != 1 {
t.Fatalf("relaunched %d times for one page", c.relaunch)
}
}
// A page logged before magpie's end is none of magpie's: the app showed
// it for its own reasons, and the user has it in front of them.
func TestCodexAppErrorPageBeforeTheEndIsLeft(t *testing.T) {
signIn(t)
s := stubCodexApp(t)
c := stubCodexCrash(t)
now := time.Now()
idle := func() (int, time.Time) { return 0, now.Add(-time.Minute) }
s.running, s.on = []int{60}, true
c.page, c.at = true, now.Add(-time.Minute)
codexAppStep(context.Background(), now, idle)
now = now.Add(3 * time.Second)
codexAppStep(context.Background(), now, idle)
if c.relaunch != 0 {
t.Fatalf("relaunched %d for a page before the end", c.relaunch)
}
}
// The app that came back by itself (its Try again) or is in use is never
// quit: a Codex turn open since the page, or a request through magpie
// since or in flight, leaves it running.
func TestCodexAppInUseAfterItsErrorPageIsLeft(t *testing.T) {
for _, tc := range []struct {
name string
turn bool
busy func(at time.Time) (int, time.Time)
}{
{name: "turn open", turn: true},
{name: "request in flight", busy: func(at time.Time) (int, time.Time) { return 1, at.Add(-time.Minute) }},
{name: "request since", busy: func(at time.Time) (int, time.Time) { return 0, at.Add(time.Second) }},
} {
t.Run(tc.name, func(t *testing.T) {
signIn(t)
s := stubCodexApp(t)
c := stubCodexCrash(t)
now := time.Now()
idle := func() (int, time.Time) { return 0, now.Add(-time.Minute) }
s.running, s.on = []int{60}, true
codexAppStep(context.Background(), now, idle)
c.page, c.at = true, now.Add(time.Second)
var since []time.Time
codexTurnRunning = func(_ string, _, from time.Time) bool {
since = append(since, from)
return tc.turn
}
busy := idle
if tc.busy != nil {
busy = func() (int, time.Time) { return tc.busy(c.at) }
}
now = now.Add(3 * time.Second)
codexAppStep(context.Background(), now, busy)
if c.relaunch != 0 {
t.Fatalf("relaunched an app in use")
}
if tc.turn && (len(since) == 0 || !since[0].Equal(c.at)) {
t.Fatalf("turns read since %v, want the page's time %v", since, c.at)
}
})
}
}
// Where the app can't be reopened (Linux, a quit it didn't take) the
// Agents row says to quit it and open it again, until the app-servers
// that ran at the page are gone or the app is closed.
func TestCodexAppSnagSaidTillTheAppRestarts(t *testing.T) {
signIn(t)
s := stubCodexApp(t)
c := stubCodexCrash(t)
c.err = errors.New("still open")
now := time.Now()
idle := func() (int, time.Time) { return 0, now.Add(-time.Minute) }
step := func() { codexAppStep(context.Background(), now, idle) }
s.running, s.on = []int{60}, true
step()
c.page, c.at = true, now.Add(time.Second)
now = now.Add(3 * time.Second)
step()
if c.relaunch != 1 || !CodexAppSnagged() {
t.Fatalf("relaunched %d, snag %v", c.relaunch, CodexAppSnagged())
}
// a listing that fails is unknown: still said
s.listErr = errors.New("ps")
now = now.Add(3 * time.Second)
step()
if !CodexAppSnagged() {
t.Fatal("a failed listing cleared the snag")
}
s.listErr = nil
step()
if !CodexAppSnagged() || c.relaunch != 1 {
t.Fatalf("the same app-server running: snag %v, relaunched %d", CodexAppSnagged(), c.relaunch)
}
s.running = []int{200} // quit and opened by the user
now = now.Add(3 * time.Second)
step()
if CodexAppSnagged() {
t.Fatal("still said after the app started again")
}
// closed: no longer said
codexApp.Lock()
codexApp.snag, codexApp.snagPids = true, []int{200}
codexApp.Unlock()
CodexAppOpen = func(context.Context) (bool, bool) { return false, true }
step()
if CodexAppSnagged() {
t.Fatal("still said with the app closed")
}
}
// The Agents row's Restart and the switch notice's Restart end the
// app-server themselves: the logs are read after them too.
func TestCodexAppRestartsWatchForTheErrorPage(t *testing.T) {
signIn(t)
s := stubCodexApp(t)
c := stubCodexCrash(t)
oldWait, oldGone := codexAppBackWait, codexAppGoneWait
t.Cleanup(func() { codexAppBackWait, codexAppGoneWait = oldWait, oldGone })
codexAppBackWait, codexAppGoneWait = time.Second, time.Second
s.running = []int{60}
before := time.Now()
if err := RestartSwitchedCodexApp(context.Background()); err != nil {
t.Fatal(err)
}
c.page, c.at = true, time.Now()
now := time.Now().Add(3 * time.Second)
codexAppStep(context.Background(), now, func() (int, time.Time) { return 0, before.Add(-time.Minute) })
if c.relaunch != 1 {
t.Fatalf("the switch notice's Restart: relaunched %d", c.relaunch)
}
if len(c.sinces) == 0 || c.sinces[0].Before(before) {
t.Fatalf("logs read since %v, want from the end on", c.sinces)
}
}
// A watch whose logs can't be read is kept to its window and never
// reopens the app.
func TestCodexAppUnreadLogsReopenNothing(t *testing.T) {
signIn(t)
s := stubCodexApp(t)
c := stubCodexCrash(t)
c.unknown = true
now := time.Now()
idle := func() (int, time.Time) { return 0, now.Add(-time.Minute) }
s.running, s.on = []int{60}, true
codexAppStep(context.Background(), now, idle)
for range 3 {
now = now.Add(codexAppCrashWait)
codexAppStep(context.Background(), now, idle)
}
if c.relaunch != 0 || CodexAppSnagged() {
t.Fatalf("unread logs: relaunched %d, snag %v", c.relaunch, CodexAppSnagged())
}
}
// ysm119's case: the Agents row's Restart (RestartCodexApp) ends the app's
// own app-server, and the page the app shows after it is read and the app
// reopened.
func TestCodexAppRowRestartWatchesForTheErrorPage(t *testing.T) {
signIn(t)
stubCodexApp(t)
c := stubCodexCrash(t)
const bundle = "/Applications/ChatGPT.app"
ps := []proc.Process{{PID: 2, Args: bundle + "/Contents/Resources/codex app-server --analytics-default-enabled"}}
oldList, oldEnd, oldPoll := listProcesses, endCodexAppServer, codexAppPoll
t.Cleanup(func() { listProcesses, endCodexAppServer, codexAppPoll = oldList, oldEnd, oldPoll })
codexAppPoll = time.Millisecond
listProcesses = func(context.Context) ([]proc.Process, error) { return slices.Clone(ps), nil }
endCodexAppServer = func(pid int) error { ps[0].PID = 102; return nil }
before := time.Now()
if err := RestartCodexApp(context.Background(), bundle); err != nil {
t.Fatal(err)
}
c.page, c.at = true, time.Now()
codexAppStep(context.Background(), time.Now().Add(3*time.Second), func() (int, time.Time) { return 0, before.Add(-time.Minute) })
if c.relaunch != 1 {
t.Fatalf("the Agents row's Restart: relaunched %d", c.relaunch)
}
}
+14 -1
View File
@@ -47,7 +47,8 @@ import (
// a new list at its next launch, or on the Agents row's Restart.
//
// The app-server is ended as a clean exit (proc.End): the app reads any
// other exit as a crash and shows it.
// other exit as a crash and shows it. A signed-in ChatGPT app can show its
// error page all the same; codex_app_crash.go reopens it then.
// CodexAppRoute is set by the agent package: what in Codex's config the
// app-server reads as it starts and magpie writes (its provider and base
@@ -288,6 +289,14 @@ var codexApp struct {
// were last listed
back map[int]bool
backAt time.Time
// crashSince, crashBy: magpie last ended the app's app-server at
// crashSince, and until crashBy its logs are read for the page the
// app shows when it can't take another (codexAppCrashStep); snag:
// the app showed that page and magpie couldn't reopen it, while the
// app-servers in snagPids (those running then) run
crashSince, crashBy time.Time
snag bool
snagPids []int
}
// codexAppBackEvery is how often the app-servers left on the takeover
@@ -406,6 +415,7 @@ func KeepCodexAppOnItsProvider(ctx context.Context, busy func() (int, time.Time)
// have opened before: its app-servers are ended too. It says which pids it
// ended.
func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Time)) []int {
codexAppCrashStep(ctx, now, busy)
if CodexAppRoute == nil {
return nil
}
@@ -614,6 +624,7 @@ func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Tim
}
if len(ended) > 0 {
log.Printf("codex: ended the Codex app's app-server %v for the app to start another: %s", ended, c.why)
watchCodexAppCrashLocked(now)
}
return ended
}
@@ -757,6 +768,7 @@ func RestartCodexApp(ctx context.Context, bundle string) error {
return err
}
ended = append(ended, p.PID)
watchCodexAppCrash(time.Now())
}
if len(ended) == 0 {
return errors.New("the Codex app's app-server isn't running")
@@ -905,6 +917,7 @@ func RestartSwitchedCodexApp(ctx context.Context) error {
log.Printf("codex: restarting the Codex app's app-server %d for the account switched to: %v", p, err)
return ErrCodexAppNoEnd
}
watchCodexAppCrash(time.Now())
}
// waitFor lists the app-servers until ok holds of them, for at most limit
waitFor := func(limit time.Duration, ok func([]int) bool) (bool, error) {
@@ -48,13 +48,22 @@ func stubCodexApp(t *testing.T) *codexAppStub {
codexApp.seen, codexApp.route, codexApp.stale, codexApp.stuck, codexApp.switched, codexApp.auto = false, "", nil, false, false, false
codexApp.ended, codexApp.backBy, codexApp.spent, codexApp.why = nil, time.Time{}, false, ""
codexApp.back, codexApp.backAt = nil, time.Time{}
codexApp.crashSince, codexApp.crashBy, codexApp.snag, codexApp.snagPids = time.Time{}, time.Time{}, false, nil
codexApp.Unlock()
}
oldCrashed, oldRelaunch := CodexAppCrashed, CodexAppRelaunch
t.Cleanup(func() {
CodexAppRoute, codexAppServersOn, endCodexAppServer, codexTurnRunning = oldOn, oldList, oldEnd, oldTurn
CodexAppOpen, CodexAppReopen, codexSessionsQuiet, codexRestartsApp = oldOpen, oldReopen, oldQuiet, oldRestarts
CodexAppCrashed, CodexAppRelaunch = oldCrashed, oldRelaunch
reset()
})
// the app's logs as tests find them: no error page, and never reopened
CodexAppCrashed = func(time.Time) (time.Time, bool, bool) { return time.Time{}, false, true }
CodexAppRelaunch = func(context.Context) error {
t.Error("the Codex app relaunched")
return errors.New("not in this test")
}
reset()
// the user asked magpie to restart the app for its own changes too
// (RestartApp); TestCodexAppLeftRunningForMagpiesOwnChanges is without