Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

codex: a turn left open by a gone app-server doesn't hold an account switch back (danzi002)

yetone51aa4c0ef32c
diff --git a/internal/proc/started.go b/internal/proc/started.go
new file mode 100644
index 000000000..36667a66c
--- /dev/null
+++ b/internal/proc/started.go
@@ -0,0 +1,14 @@
+package proc
+
+import (
+ "errors"
+ "time"
+)
+
+// ErrNoStart is a system that doesn't tell when a process started.
+var ErrNoStart = errors.New("this system doesn't tell when a process started")
+
+// Started is when process pid started, as the system recorded it. An
+// error says it couldn't be read (gone, another user's, ErrNoStart), not
+// that it started at any time.
+func Started(pid int) (time.Time, error) { return startTime(pid) }
diff --git a/internal/proc/started_darwin.go b/internal/proc/started_darwin.go
new file mode 100644
index 000000000..0b2d12dd7
--- /dev/null
+++ b/internal/proc/started_darwin.go
@@ -0,0 +1,20 @@
+package proc
+
+import (
+ "errors"
+ "time"
+
+ "golang.org/x/sys/unix"
+)
+
+func startTime(pid int) (time.Time, error) {
+ kp, err := unix.SysctlKinfoProc("kern.proc.pid", pid)
+ if err != nil {
+ return time.Time{}, err
+ }
+ if int(kp.Proc.P_pid) != pid {
+ return time.Time{}, errors.New("no such process")
+ }
+ tv := kp.Proc.P_starttime
+ return time.Unix(int64(tv.Sec), int64(tv.Usec)*1000), nil
+}
diff --git a/internal/proc/started_linux.go b/internal/proc/started_linux.go
new file mode 100644
index 000000000..a7f082a80
--- /dev/null
+++ b/internal/proc/started_linux.go
@@ -0,0 +1,64 @@
+package proc
+
+import (
+ "bytes"
+ "errors"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// clockTicks is USER_HZ, the unit of /proc/<pid>/stat's starttime: 100 on
+// every Linux the kernel's ABI keeps it fixed for.
+const clockTicks = 100
+
+func startTime(pid int) (time.Time, error) {
+ b, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/stat")
+ if err != nil {
+ return time.Time{}, err
+ }
+ ticks, err := statStartTicks(b)
+ if err != nil {
+ return time.Time{}, err
+ }
+ s, err := os.ReadFile("/proc/stat")
+ if err != nil {
+ return time.Time{}, err
+ }
+ boot, err := bootTime(s)
+ if err != nil {
+ return time.Time{}, err
+ }
+ return boot.Add(time.Duration(ticks) * time.Second / clockTicks), nil
+}
+
+// statStartTicks is field 22 of a /proc/<pid>/stat line, starttime: the
+// fields are counted after the command's closing parenthesis, since the
+// command itself may hold spaces and parentheses.
+func statStartTicks(b []byte) (uint64, error) {
+ i := bytes.LastIndexByte(b, ')')
+ if i < 0 {
+ return 0, errors.New("unreadable /proc stat")
+ }
+ f := strings.Fields(string(b[i+1:]))
+ // f[0] is field 3 (state), so field 22 is f[19]
+ if len(f) < 20 {
+ return 0, errors.New("unreadable /proc stat")
+ }
+ return strconv.ParseUint(f[19], 10, 64)
+}
+
+// bootTime is /proc/stat's btime.
+func bootTime(b []byte) (time.Time, error) {
+ for _, line := range strings.Split(string(b), "\n") {
+ if v, ok := strings.CutPrefix(line, "btime "); ok {
+ n, err := strconv.ParseInt(strings.TrimSpace(v), 10, 64)
+ if err != nil {
+ return time.Time{}, err
+ }
+ return time.Unix(n, 0), nil
+ }
+ }
+ return time.Time{}, errors.New("no btime in /proc/stat")
+}
diff --git a/internal/proc/started_other.go b/internal/proc/started_other.go
new file mode 100644
index 000000000..372819b9f
--- /dev/null
+++ b/internal/proc/started_other.go
@@ -0,0 +1,7 @@
+//go:build !darwin && !linux && !windows
+
+package proc
+
+import "time"
+
+func startTime(int) (time.Time, error) { return time.Time{}, ErrNoStart }
diff --git a/internal/proc/started_test.go b/internal/proc/started_test.go
new file mode 100644
index 000000000..4c9f5b686
--- /dev/null
+++ b/internal/proc/started_test.go
@@ -0,0 +1,37 @@
+package proc
+
+import (
+ "os"
+ "runtime"
+ "testing"
+ "time"
+)
+
+// initAt is read as the test binary initialises its packages, moments
+// after the system recorded its start.
+var initAt = time.Now()
+
+// Started reads this process's start as the system recorded it: before
+// its package init ran, and not long before (a loaded machine is slow to
+// start a binary). A pid that isn't running errs.
+func TestStarted(t *testing.T) {
+ got, err := Started(os.Getpid())
+ switch runtime.GOOS {
+ case "darwin", "linux", "windows":
+ default:
+ if err != ErrNoStart {
+ t.Fatalf("on %s: %v %v, want ErrNoStart", runtime.GOOS, got, err)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Linux's btime is whole seconds
+ if got.After(initAt.Add(time.Second)) || got.Before(initAt.Add(-time.Minute)) {
+ t.Fatalf("started %v, package init at %v", got, initAt)
+ }
+ if _, err := Started(1 << 30); err == nil {
+ t.Fatal("a pid that isn't running: no error")
+ }
+}
diff --git a/internal/proc/started_windows.go b/internal/proc/started_windows.go
new file mode 100644
index 000000000..b54bcda0f
--- /dev/null
+++ b/internal/proc/started_windows.go
@@ -0,0 +1,20 @@
+package proc
+
+import (
+ "time"
+
+ "golang.org/x/sys/windows"
+)
+
+func startTime(pid int) (time.Time, error) {
+ h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
+ if err != nil {
+ return time.Time{}, err
+ }
+ defer windows.CloseHandle(h)
+ var created, exited, kernel, user windows.Filetime
+ if err := windows.GetProcessTimes(h, &created, &exited, &kernel, &user); err != nil {
+ return time.Time{}, err
+ }
+ return time.Unix(0, created.Nanoseconds()), nil
+}
diff --git a/internal/provider/codex_app_server.go b/internal/provider/codex_app_server.go
index 8c1aadd53..3f0c85b55 100644
--- a/internal/provider/codex_app_server.go
+++ b/internal/provider/codex_app_server.go
@@ -3,6 +3,7 @@ package provider
import (
"bytes"
"context"
+ "encoding/json"
"errors"
"io"
"io/fs"
@@ -65,6 +66,11 @@ var (
// whose app-server died leaves one open for good.
const codexTurnWindow = 30 * time.Minute
+// codexTurnSlack is how much earlier than the app-servers' start a turn's
+// timestamp may be and still count as theirs: the two clocks are read by
+// different programs.
+const codexTurnSlack = 2 * time.Second
+
// codexAppListWait bounds one listing of the app-servers and their homes:
// at a load of 200 a 10s bound ran out on the owner's Mac (the change was
// taken up at the next look, 9s later).
@@ -87,9 +93,27 @@ var (
return out, nil
}
endCodexAppServer = proc.End
- codexTurnRunning = func(home string, now time.Time) bool { return codexTurnOpen(home, now) }
+ codexTurnRunning = func(home string, now, since time.Time) bool { return codexTurnOpen(home, now, since) }
+ codexServerStart = proc.Started
)
+// codexServersSince is when the oldest of the app-servers pids started: a
+// turn started before it can't be running in any of them. It is zero,
+// "unknown", when one's start can't be read, and every open turn counts.
+func codexServersSince(pids []int) time.Time {
+ var since time.Time
+ for _, p := range pids {
+ t, err := codexServerStart(p)
+ if err != nil || t.IsZero() {
+ return time.Time{}
+ }
+ if since.IsZero() || t.Before(since) {
+ since = t
+ }
+ }
+ return since
+}
+
// isCodexAppOwnServer is whether a command line is the Codex app's own
// app-server, which it talks to over stdio: one another program starts
// from the app's bundled codex names where it listens (`app-server
@@ -271,7 +295,13 @@ func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Tim
if inFlight, last := busy(); inFlight > 0 || now.Sub(last) < codexAppIdle {
return nil
}
- if codexTurnRunning(home, now) {
+ c.Lock()
+ stale := make([]int, 0, len(c.stale))
+ for p := range c.stale {
+ stale = append(stale, p)
+ }
+ c.Unlock()
+ if codexTurnRunning(home, now, codexServersSince(stale)) {
return nil
}
var ended []int
@@ -298,8 +328,15 @@ func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Tim
// codexTurnOpen is whether a Codex session under home has a turn started
// and not ended (task_started after its last task_complete or
// turn_aborted) in a file written to within codexTurnWindow of now: the
-// app-server running it would cut it short.
-func codexTurnOpen(home string, now time.Time) bool {
+// app-server running it would cut it short. A turn started before since,
+// when the app-servers about to be ended started, ran in an app-server
+// gone since (force quit, crashed): a SIGKILLed one writes no
+// turn_aborted, and opening that thread again in the app writes
+// thread_settings_applied, so the file stays in the window as long as
+// the user looks at it. Counting it kept a switched account from ever
+// reaching the app (蛋仔 on Discord, 10-29 and 10-30: "点了会话再切换账号
+// 就重启不了"). A zero since counts every open turn.
+func codexTurnOpen(home string, now, since time.Time) bool {
open := false
_ = filepath.WalkDir(filepath.Join(home, "sessions"), func(path string, d fs.DirEntry, err error) error {
if err != nil || open {
@@ -315,7 +352,7 @@ func codexTurnOpen(home string, now time.Time) bool {
if err != nil || now.Sub(info.ModTime()) > codexTurnWindow {
return nil
}
- open = sessionTurnOpen(path)
+ open = sessionTurnOpen(path, since)
return nil
})
return open
@@ -324,10 +361,11 @@ func codexTurnOpen(home string, now time.Time) bool {
// sessionTurnTail is how much of a session file's end sessionTurnOpen reads.
const sessionTurnTail = 512 << 10
-// sessionTurnOpen is whether the session file at path ends inside a turn.
-// A file that can't be read counts as open: a turn cut short costs more
-// than an app greyed a few seconds more.
-func sessionTurnOpen(path string) bool {
+// sessionTurnOpen is whether the session file at path ends inside a turn
+// started at since or later. A file that can't be read, or a turn whose
+// start can't be read, counts as open: a turn cut short costs more than
+// an app greyed a few seconds more.
+func sessionTurnOpen(path string, since time.Time) bool {
f, err := os.Open(path)
if err != nil {
return !errors.Is(err, fs.ErrNotExist)
@@ -344,7 +382,30 @@ func sessionTurnOpen(path string) bool {
}
started := bytes.LastIndex(b, []byte(`"type":"task_started"`))
ended := max(bytes.LastIndex(b, []byte(`"type":"task_complete"`)), bytes.LastIndex(b, []byte(`"type":"turn_aborted"`)))
- return started > ended
+ if started <= ended {
+ return false
+ }
+ if since.IsZero() {
+ return true
+ }
+ at, ok := sessionLineTime(b, started)
+ return !ok || !at.Before(since.Add(-codexTurnSlack))
+}
+
+// sessionLineTime is the "timestamp" of the session file line holding
+// offset i of b, which Codex writes on every rollout line.
+func sessionLineTime(b []byte, i int) (time.Time, bool) {
+ line := b[bytes.LastIndexByte(b[:i], '\n')+1:]
+ if j := bytes.IndexByte(line, '\n'); j >= 0 {
+ line = line[:j]
+ }
+ var l struct {
+ Timestamp time.Time `json:"timestamp"`
+ }
+ if json.Unmarshal(line, &l) != nil || l.Timestamp.IsZero() {
+ return time.Time{}, false
+ }
+ return l.Timestamp, true
}
// codexAppGoneWait is how long RestartCodexApp waits for the app-servers
@@ -410,7 +471,8 @@ func RestartCodexAppWhenIdle(ctx context.Context, wait time.Duration) (ended int
return 0, false, err
}
until := time.Now().Add(wait)
- for codexTurnRunning(home, time.Now()) {
+ since := codexServersSince(pids)
+ for codexTurnRunning(home, time.Now(), since) {
if time.Now().After(until) {
return 0, true, nil
}
diff --git a/internal/provider/codex_app_server_test.go b/internal/provider/codex_app_server_test.go
index 844b3fbce..3349dc6bb 100644
--- a/internal/provider/codex_app_server_test.go
+++ b/internal/provider/codex_app_server_test.go
@@ -8,6 +8,7 @@ import (
"path/filepath"
"runtime"
"slices"
+ "strconv"
"testing"
"time"
@@ -67,7 +68,7 @@ func stubCodexApp(t *testing.T) *codexAppStub {
}
return nil
}
- codexTurnRunning = func(string, time.Time) bool { return s.turnOpen }
+ codexTurnRunning = func(string, time.Time, time.Time) bool { return s.turnOpen }
return s
}
@@ -311,25 +312,118 @@ func TestCodexTurnOpen(t *testing.T) {
started := `{"type":"event_msg","payload":{"type":"task_started","turn_id":"1"}}` + "\n"
done := `{"type":"event_msg","payload":{"type":"task_complete","turn_id":"1"}}` + "\n"
aborted := `{"type":"event_msg","payload":{"type":"turn_aborted","turn_id":"1"}}` + "\n"
- if codexTurnOpen(home, now) {
+ if codexTurnOpen(home, now, time.Time{}) {
t.Fatal("no sessions: open")
}
write("rollout-a.jsonl", started+done, now)
- if codexTurnOpen(home, now) {
+ if codexTurnOpen(home, now, time.Time{}) {
t.Fatal("turn complete: open")
}
write("rollout-b.jsonl", started+aborted, now)
- if codexTurnOpen(home, now) {
+ if codexTurnOpen(home, now, time.Time{}) {
t.Fatal("turn aborted: open")
}
write("rollout-c.jsonl", started+done+started, now.Add(-codexTurnWindow-time.Minute))
- if codexTurnOpen(home, now) {
+ if codexTurnOpen(home, now, time.Time{}) {
t.Fatal("a turn left open long ago: open")
}
write("rollout-d.jsonl", started+done+started, now)
- if !codexTurnOpen(home, now) {
+ if !codexTurnOpen(home, now, time.Time{}) {
t.Fatal("a turn running: not open")
}
+ // since: a turn with no readable start still counts
+ if !codexTurnOpen(home, now, now.Add(-time.Hour)) {
+ t.Fatal("a turn running whose start can't be read: not open")
+ }
+ if err := os.Remove(filepath.Join(dir, "rollout-d.jsonl")); err != nil {
+ t.Fatal(err)
+ }
+ stamped := func(at time.Time) string {
+ return `{"timestamp":"` + at.UTC().Format(time.RFC3339Nano) + `","type":"event_msg","payload":{"type":"task_started","turn_id":"2"}}` + "\n"
+ }
+ since := now.Add(-time.Minute)
+ write("rollout-e.jsonl", started+done+stamped(since.Add(-time.Hour)), now)
+ if codexTurnOpen(home, now, since) {
+ t.Fatal("a turn started before the app-servers: open")
+ }
+ if !codexTurnOpen(home, now, time.Time{}) {
+ t.Fatal("a turn started an hour ago, since unknown: not open")
+ }
+ write("rollout-e.jsonl", started+done+stamped(since.Add(-time.Second)), now)
+ if !codexTurnOpen(home, now, since) {
+ t.Fatal("a turn started within the slack of the app-servers' start: not open")
+ }
+ write("rollout-e.jsonl", started+done+stamped(since.Add(time.Second)), now)
+ if !codexTurnOpen(home, now, since) {
+ t.Fatal("a turn started after the app-servers: not open")
+ }
+}
+
+// A turn left open by an app-server that is gone doesn't hold the switch
+// back. 蛋仔 (danzi002 on Discord, 10-29 and 10-30) switched the Codex
+// app's used-up account in magpie and the app stayed grey until it was
+// quit and opened: "点了会话再切换账号就重启不了". Codex 0.164's
+// app-server, killed mid-turn (force quit, crash), writes no turn_aborted,
+// and opening that thread in a new app-server writes
+// thread_settings_applied, so the session file read as a turn running for
+// as long as the user had it open. A turn started before the app-servers
+// to be ended can't be running in them; one started after still holds
+// them, and so does any open turn when their start can't be read. The
+// lines are the shape Codex 0.164.0-alpha.11.1 wrote for a SIGKILLed
+// app-server and a resume, payloads cut short.
+func TestCodexAppSwitchPastATurnItsServerNeverRan(t *testing.T) {
+ signIn(t)
+ home := t.TempDir()
+ t.Setenv("CODEX_HOME", home)
+ s := stubCodexApp(t)
+ codexTurnRunning = func(home string, now, since time.Time) bool { return codexTurnOpen(home, now, since) }
+ oldStart := codexServerStart
+ t.Cleanup(func() {
+ codexServerStart = oldStart
+ DismissCodexDaemon()
+ DismissCodexApp()
+ })
+ now := time.Now()
+ serverStart := now.Add(-5 * time.Minute)
+ startErr := error(nil)
+ codexServerStart = func(pid int) (time.Time, error) { return serverStart, startErr }
+ dir := filepath.Join(home, "sessions", "2026", "10", "30")
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ line := func(at time.Time, n int, typ, payload string) string {
+ return `{"timestamp":"` + at.UTC().Format("2006-01-02T15:04:05.000Z") + `","ordinal":` + strconv.Itoa(n) + `,"type":"` + typ + `","payload":` + payload + "}\n"
+ }
+ rollout := func(turnAt time.Time) {
+ body := line(turnAt, 0, "session_meta", `{"session_id":"01a188a5-f780-7dc3-92a8-919bf6116f56"}`) +
+ line(turnAt, 1, "event_msg", `{"type":"task_started","turn_attribution":{"turn_id":"01a188a5-f791-7341-aee6-b832a5a5ec87"}}`) +
+ line(turnAt, 7, "response_item", `{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}`) +
+ line(turnAt, 8, "event_msg", `{"type":"item_completed","thread_id":"01a188a5-f780-7dc3-92a8-919bf6116f56"}`) +
+ // the thread opened again in the app's next app-server
+ line(now.Add(-time.Second), 9, "event_msg", `{"type":"thread_settings_applied","thread_id":"01a188a5-f780-7dc3-92a8-919bf6116f56"}`)
+ if err := os.WriteFile(filepath.Join(dir, "rollout-2026-10-30T00-01-00-01a188a5.jsonl"), []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ 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()
+ rollout(serverStart.Add(time.Minute))
+ noteCodexSwitch("a@x", "b@x")
+ if got := step(); got != nil {
+ t.Fatalf("a turn started in the running app-server: ended %v", got)
+ }
+ rollout(serverStart.Add(-10 * time.Minute))
+ startErr = errors.New("gone")
+ if got := step(); got != nil {
+ t.Fatalf("an open turn with the app-server's start unknown: ended %v", got)
+ }
+ startErr = nil
+ if got := step(); !slices.Equal(got, []int{60}) {
+ t.Fatalf("a turn left open by an app-server gone since: ended %v, want [60]", got)
+ }
}
// While the account Codex is on is near out, or out, it is read every