codex: a reset about to expire can be used 5 or 10 minutes before it does

shangyuan0818 on Discord asked for leads under 15 minutes (1, 3, 5, 10, or
free seconds) for Codex's auto-use of the reset about to expire, to use
more of the windows first. The shortest was 15m because the gateway only
looked every 5 minutes after a pass ended (a pass is bounded at 2
minutes), so the gap between looks could reach ~7 minutes. With a 5-minute
lead, the reset could run out before any look landed inside it.

- provider: a look lands on the lead's start (nextResetLook takes the
  sooner of +5m and until-lead), and the loop sleeps until the soonest look
  due among the accounts its pass went over (expiringResets.wake: 5m at
  most, 1s at least; an account the pass skipped wakes nothing). A read or
  spend that fails inside the lead in the last 15 minutes is tried again
  in 1 minute (retryResetLook), not 5; a long lead failing earlier keeps
  the 5-minute cadence. A retry that came due while a hung pass ran is
  made at once.
- settings: CodexResetLeadLeast 15 -> 5; choices 5m, 10m, 15m, 30m (default),
  1h ... 24h. Saved values from 15 to 1440 stay valid; the default is
  unchanged.
- GUI (app.js RESET_LEADS, resetLeadMinutes) and CLI (magpie quota
  auto-reset lead) follow the same range. No new strings ("{n} min"
  already exists). Still the app menu, no seconds field.

Why 5 and not 3 or 1: in the worst case a try hangs to the pass's 2-minute
bound. At 5m: try at T-5:00, hung until T-2:57, retried at T-2:56, so two
tries before expiry (four when ChatGPT refuses at once). At 3m a hung try
leaves no retry. At 1m one try cannot even run to its own bound, and
local-vs-server clock skew eats the rest.

Run (mote, via mote-run, at base 49f207c78):
- go test -run 'Reset|Expir|Lead' ./internal/provider ./internal/settings
  ./internal/cli: ok. New: TestShortLeadSpentInTime (5m lead at four loop
  phases: spent at T-5 within 5s; a 2-minute hung try then a retry before
  T-1m; four quick failures, all before expiry; a 7m CLI lead lands on
  T-7; a 6h lead failing all along makes 70 to 90 tries, not ~360),
  TestResetLoopWakesForTheSoonestLook.
- go vet: darwin (provider, settings, cli, gui), GOOS=linux -tags nogui,
  GOOS=windows. go test ./internal/settings ./internal/settingsapi: ok.
  ./internal/gui: ok but TestMainWindowCorners/macOS_26_SDK (#3949) and
  TestPanelHiddenByWailsMarksPageOutOfSight (#5322), AppKit window tests
  red on mote's macOS 27, both filed; the size budgets pass.
- GUI: codex-reset-lead.test.cjs (now also picks 5 min and checks the
  10-item menu), codex-auto-reset-settings, i18n-keys; Chromium and
  WebKit, en/zh/zh-TW/ja/de, 1100 and 420 px: 49/50. The one red is
  i18n-keys "a plugin's words are its own", red on main and filed
  (#5327, #5332, #5426, #5482); nothing here touches those files.

Broken by hand, each went red:
- the look not landing on the lead's start: TestShortLeadSpentInTime's
  7m case (spent 4m59s before).
- wake fixed at 5m: TestShortLeadSpentInTime, TestResetLoopWakes...
- the 1-minute retry turned into nextResetLook: the hung-try case.
- CodexResetLeadLeast back at 15: TestShortLeadSpentInTime,
  TestQuotaResetLeadCmd.

Not tried: a real Codex account spending a card at a 5m lead; a Mac
asleep across the lead (no lead can help there, same as before); the
3-minute delay after start is unchanged, so a magpie started within the
lead spends at its first pass; Windows and Linux runs (vet only).

Reported-by: shangyuan0818 (Discord)
This commit is contained in:
yetone
2026-11-07 06:07:03 +08:00
parent 49f207c784
commit d4a221f79c
6 changed files with 217 additions and 19 deletions
+2 -2
View File
@@ -18,7 +18,7 @@ func TestQuotaResetLeadCmd(t *testing.T) {
for _, c := range []struct {
arg string
want int
}{{"2h", 120}, {"15m", 15}, {"24h", 1440}, {"90", 90}, {"1h30m", 90}} {
}{{"2h", 120}, {"15m", 15}, {"5m", 5}, {"10m", 10}, {"24h", 1440}, {"90", 90}, {"1h30m", 90}} {
arg, want := c.arg, c.want
if out, err := runOut(t, "quota", "auto-reset", "lead", arg); err != nil || settings.Load().CodexResetLead != want {
t.Fatalf("%s: %q %v, set %d", arg, out, err, settings.Load().CodexResetLead)
@@ -27,7 +27,7 @@ func TestQuotaResetLeadCmd(t *testing.T) {
if out, err := runOut(t, "quota", "auto-reset", "lead"); err != nil || !strings.Contains(out, "used 1h30m before it expires") || strings.Contains(out, "default") {
t.Fatalf("set: %q %v", out, err)
}
for _, bad := range []string{"10m", "25h", "-1h", "30s", "90s", "soon", "--help"} {
for _, bad := range []string{"4m", "1m", "25h", "-1h", "30s", "90s", "soon", "--help"} {
if bad == "--help" {
if out, err := runOut(t, "quota", "auto-reset", "lead", bad); err != nil || !strings.Contains(out, "usage:") {
t.Fatalf("--help: %q %v", out, err)
+2 -2
View File
@@ -17945,10 +17945,10 @@ function autoResetTitle(on) {
// How long before a reset runs out it is used (codexResetLead; the owner, 10-30):
// half an hour unless set or out of range, as the gateway reads it. RESET_LEADS in minutes.
const RESET_LEADS = [15, 30, 60, 120, 180, 360, 720, 1440];
const RESET_LEADS = [5, 10, 15, 30, 60, 120, 180, 360, 720, 1440];
function resetLeadMinutes(s = state?.settings) {
const m = s?.codexResetLead;
return Number.isInteger(m) && m >= 15 && m <= 1440 ? m : 30;
return Number.isInteger(m) && m >= 5 && m <= 1440 ? m : 30;
}
function resetLeadWords(m) {
return m < 60 || m % 60 ? t("{n} min", { n: m }) : t("{n} h", { n: m / 60 });
+10 -3
View File
@@ -132,7 +132,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const top = await page.locator("#view-settings").evaluate((v) => v.scrollTop);
await pick.click();
const items = page.locator(".proto-menu .pm-item");
assert.equal(await items.count(), 8, "15 min to 24 h");
assert.equal(await items.count(), 10, "5 min to 24 h");
assert.equal(await page.locator(".proto-menu .pm-item.on .pm-name").textContent(), await say(page, lang, 30));
await page.locator(".proto-menu .pm-item", { hasText: await say(page, lang, 180) }).click();
for (let i = 0; i < 100 && !posts.length; i++) await page.waitForTimeout(20);
@@ -142,6 +142,13 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const hours = await page.evaluate((lang) => (I18N[lang]?.["{n} h"] || "{n} h").replace("{n}", 3), lang);
assert(title.includes(hours), `the title says 3 h: ${title}`);
assert.equal(await page.locator("#view-settings").evaluate((v) => v.scrollTop), top, "no click moved the page");
// the shortest, five minutes (shangyuan0818 on Discord asked for less than 15)
await pick.click();
await page.locator(`.proto-menu .pm-item .pm-name:text-is(${JSON.stringify(await say(page, lang, 5))})`).click(); // not "15 min before"
for (let i = 0; i < 100 && posts.length < 2; i++) await page.waitForTimeout(20);
assert.deepEqual(posts, [{ minutes: 180 }, { minutes: 5 }]);
await page.waitForFunction((want) => document.querySelector("#codexResetLeadRow button.reset-lead .rl-say > .on")?.textContent.trim() === want, await say(page, lang, 5));
assert.equal(await page.locator("#view-settings").evaluate((v) => v.scrollTop), top, "no click moved the page");
// fits, no sideways scroll, no native select, no left border
const over = await page.evaluate(() => {
@@ -165,12 +172,12 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const pick = page.locator("#codexResetLeadRow button.reset-lead");
assert.equal((await pick.locator(".rl-say > .on").textContent()).trim(), "45 min before");
await pick.click();
assert.equal(await page.locator(".proto-menu .pm-item").count(), 9);
assert.equal(await page.locator(".proto-menu .pm-item").count(), 11);
assert.equal(await page.locator(".proto-menu .pm-item.on .pm-name").textContent(), "45 min before");
await page.keyboard.press("Escape");
assert.deepEqual(posts, [], "nothing written by looking");
assert.deepEqual(errors, []);
const bad = await open(t, engine, "en", 900, 5, []);
const bad = await open(t, engine, "en", 900, 4, []);
assert.equal((await bad.page.locator("#codexResetLeadRow button.reset-lead .rl-say > .on").textContent()).trim(), "30 min before");
assert.deepEqual(bad.errors, []);
});
+64 -8
View File
@@ -60,6 +60,14 @@ var (
// resetExpiryFar is the longest an account goes unread: a reset
// granted meanwhile is seen by then
resetExpiryFar = 6 * time.Hour
// resetExpiryRetry is how soon a read or spend that failed within the
// lead is tried again once the reset runs out within resetExpiryLast:
// a five-minute lead has room for several tries, not one
resetExpiryRetry = time.Minute
// resetExpiryLast is how close to running out a failure is tried again
// every resetExpiryRetry, not resetExpiryClose: a long lead failing all
// along isn't read every minute for hours
resetExpiryLast = 15 * time.Minute
)
// errResetsUntilUnread: the account holds resets, but when they run out
@@ -76,6 +84,9 @@ type expiringResets struct {
sync.Mutex
next map[string]time.Time // by account, when to read it again
until map[string]time.Time // by account, when its soonest reset runs out, as last read
// pass is the accounts check was asked about since the loop last
// woke (wake): the ones whose next look it waits for
pass map[string]bool
}
// check spends one of user's resets, if its windows have been used, when
@@ -92,6 +103,10 @@ func (e *expiringResets) check(user string, now time.Time, look func() ([]QuotaW
if e.until == nil {
e.until = map[string]time.Time{}
}
if e.pass == nil {
e.pass = map[string]bool{}
}
e.pass[key] = true
if now.Before(e.next[key]) {
return ResetOutcome{}, nil
}
@@ -106,7 +121,7 @@ func (e *expiringResets) check(user string, now time.Time, look func() ([]QuotaW
// tried again by the reset last read, soon when it is near
e.next[key] = now.Add(resetExpiryWatch)
if u, ok := e.until[key]; ok {
e.next[key] = nextResetLook(u, now)
e.next[key] = retryResetLook(u, now)
}
return ResetOutcome{}, err
}
@@ -132,7 +147,11 @@ func (e *expiringResets) check(user string, now time.Time, look func() ([]QuotaW
return ResetOutcome{}, nil
}
out, err := spend()
if err != nil || out.Code != "reset" {
if err != nil {
e.next[key] = retryResetLook(until, now)
return out, err
}
if out.Code != "reset" {
e.next[key] = nextResetLook(until, now)
return out, err
}
@@ -145,12 +164,48 @@ func (e *expiringResets) check(user string, now time.Time, look func() ([]QuotaW
// is looked at next: every resetExpiryClose within resetExpiryNear of
// that, every resetExpiryWatch before then but never past its start — so
// the reset is looked at several times within resetLead, a look missed
// or failed there still spends it in time.
// or failed there still spends it in time. Never past when the lead
// starts either: the look lands on it, not up to resetExpiryClose after,
// which a lead as short as five minutes couldn't spare.
func nextResetLook(until, now time.Time) time.Time {
if near := until.Add(-resetExpiryNear(resetLead())); near.After(now) {
lead := resetLead()
if near := until.Add(-resetExpiryNear(lead)); near.After(now) {
return minTime(now.Add(resetExpiryWatch), near)
}
return now.Add(resetExpiryClose)
next := now.Add(resetExpiryClose)
if at := until.Add(-lead); at.After(now) {
return minTime(next, at)
}
return next
}
// retryResetLook is when a read or spend that failed is tried again: every
// resetExpiryRetry once the reset runs out within resetExpiryLast and its
// lead has started, so a short lead gets several tries; nextResetLook
// otherwise.
func retryResetLook(until, now time.Time) time.Time {
if !until.Add(-resetLead()).After(now) && until.Sub(now) <= resetExpiryLast {
return now.Add(resetExpiryRetry)
}
return nextResetLook(until, now)
}
// wake is how long the loop (KeepResetsFromRunningOut) sleeps after a pass
// ending at now: until the soonest look due of the accounts the pass went
// over, resetExpiryClose at most, a second at least. A look due at a
// lead's start is made then, not at the next five-minute pass, and a retry
// due while the pass still ran (a try hung to its bound) is made at once.
// An account the pass skipped (auto-use turned off) waits for nothing.
func (e *expiringResets) wake(now time.Time) time.Duration {
now = now.Round(0)
e.Lock()
defer e.Unlock()
d := resetExpiryClose
for key := range e.pass {
d = min(d, e.next[key].Sub(now))
}
clear(e.pass)
return max(d, time.Second)
}
// expiringResetSpent is when a reset that runs out at until is spent by
@@ -267,8 +322,9 @@ func spendExpiringNow(windows []QuotaWindow, resets *ResetCredits, now time.Time
}
// KeepResetsFromRunningOut spends the Codex resets about to run out unused
// (SpendExpiringCodexResets), three minutes after it starts and every
// resetExpiryClose after that, until ctx ends.
// (SpendExpiringCodexResets), three minutes after it starts and then as
// soon as a look is due (wake: a lead's start, a retry), every
// resetExpiryClose at most, until ctx ends.
func KeepResetsFromRunningOut(ctx context.Context) {
t := time.NewTimer(3 * time.Minute)
defer t.Stop()
@@ -281,6 +337,6 @@ func KeepResetsFromRunningOut(ctx context.Context) {
c, cancel := context.WithTimeout(ctx, 2*time.Minute)
SpendExpiringCodexResets(c)
cancel()
t.Reset(resetExpiryClose)
t.Reset(expiring.wake(time.Now()))
}
}
+132 -1
View File
@@ -124,7 +124,7 @@ func TestResetLeadLooksInsideLongLead(t *testing.T) {
// only as it runs out.
func TestResetLeadUnreadIsDefault(t *testing.T) {
signIn(t)
for _, m := range []int{-5, 1, 14, 24*60 + 1, 1 << 30} {
for _, m := range []int{-5, 1, 4, 24*60 + 1, 1 << 30} {
setResetLead(t, m)
if got := resetLead(); got != 30*time.Minute {
t.Errorf("%d minutes: lead %v", m, got)
@@ -148,3 +148,134 @@ func TestResetLeadUnreadIsDefault(t *testing.T) {
t.Fatalf("not a number: lead %v", got)
}
}
// runLoop drives check as KeepResetsFromRunningOut does, from start until
// the reset runs out: a pass at now, which takes the time spend says (a
// pass hung on ChatGPT ends at its two-minute bound), then wake's sleep.
// It returns when the reset was spent (zero: never) and the tries.
func runLoop(t *testing.T, start, until time.Time, spend func(try int, now time.Time) (ResetOutcome, error, time.Duration)) (spent time.Time, tries []time.Time) {
t.Helper()
used := []QuotaWindow{{Span: 7 * 24 * time.Hour, Used: 40}}
e := expiringResets{next: map[string]time.Time{}}
for now := start; now.Before(until); {
took := 3 * time.Second
e.check("me@example.com", now, func() ([]QuotaWindow, *ResetCredits, error) {
if !spent.IsZero() {
return used, nil, nil
}
return used, &ResetCredits{Count: 1, Until: &until}, nil
}, func() (ResetOutcome, error) {
tries = append(tries, now)
out, err, d := spend(len(tries), now)
took += d
if err == nil && out.Code == "reset" {
spent = now.Add(d)
}
return out, err
})
now = now.Add(took)
now = now.Add(e.wake(now))
}
return spent, tries
}
// The shortest lead, five minutes (shangyuan0818 on Discord: less than 15,
// to use more of the windows first), is spent at its start, not at the
// next five-minute pass, whatever the loop's phase; a failed try is made
// again a minute on, so a try hung to the pass's two-minute bound still
// leaves another before the reset runs out.
func TestShortLeadSpentInTime(t *testing.T) {
signIn(t)
setResetLead(t, 5)
until := time.Date(2026, 11, 7, 18, 0, 0, 0, time.Local)
due := until.Add(-5 * time.Minute)
for _, phase := range []time.Duration{0, 17 * time.Second, 2*time.Minute + 41*time.Second, 4*time.Minute + 59*time.Second} {
start := until.Add(-3*time.Hour + phase)
// answers at once: spent at the lead's start
spent, tries := runLoop(t, start, until, func(int, time.Time) (ResetOutcome, error, time.Duration) {
return ResetOutcome{Code: "reset"}, nil, time.Second
})
if spent.Before(due) || spent.After(due.Add(5*time.Second)) || len(tries) != 1 {
t.Errorf("phase %v: spent %v before it runs out, want 5m; tries at %v", phase, until.Sub(spent), tries)
}
// the first try hangs two minutes and fails: tried again, in time
spent, tries = runLoop(t, start, until, func(n int, _ time.Time) (ResetOutcome, error, time.Duration) {
if n == 1 {
return ResetOutcome{}, http.ErrHandlerTimeout, 2 * time.Minute
}
return ResetOutcome{Code: "reset"}, nil, time.Second
})
if spent.IsZero() || !spent.Before(until.Add(-time.Minute)) || len(tries) != 2 {
t.Errorf("phase %v, a hung try: spent %v before it runs out; tries at %v", phase, until.Sub(spent), tries)
}
// ChatGPT refusing at once: a try every minute, four before it runs out
spent, tries = runLoop(t, start, until, func(n int, _ time.Time) (ResetOutcome, error, time.Duration) {
if n < 4 {
return ResetOutcome{}, http.ErrHandlerTimeout, time.Second
}
return ResetOutcome{Code: "reset"}, nil, time.Second
})
if spent.IsZero() || !spent.Before(until) || len(tries) != 4 {
t.Errorf("phase %v, failing tries: spent %v before it runs out; tries at %v", phase, until.Sub(spent), tries)
}
}
// a lead the CLI set off the five-minute marks (7m): the look lands on
// its start too, not at the pass after
setResetLead(t, 7)
for _, phase := range []time.Duration{0, 17 * time.Second, 4*time.Minute + 59*time.Second} {
spent, _ := runLoop(t, until.Add(-3*time.Hour+phase), until, func(int, time.Time) (ResetOutcome, error, time.Duration) {
return ResetOutcome{Code: "reset"}, nil, time.Second
})
if want := until.Add(-7 * time.Minute); spent.Before(want) || spent.After(want.Add(5*time.Second)) {
t.Errorf("7m lead, phase %v: spent %v before it runs out", phase, until.Sub(spent))
}
}
// a long lead failing all along is tried every five minutes until the
// last quarter hour, not every minute for hours
setResetLead(t, 6*60)
_, tries := runLoop(t, until.Add(-7*time.Hour), until, func(int, time.Time) (ResetOutcome, error, time.Duration) {
return ResetOutcome{}, http.ErrHandlerTimeout, time.Second
})
if n := len(tries); n < 70 || n > 90 {
t.Errorf("a six-hour lead failing: %d tries, want about 6h/5m + 15", n)
}
}
// The loop sleeps until the soonest look due of the accounts its pass went
// over, five minutes at most, a second at least: one due while the pass
// still ran is looked at once; an account the pass skipped (auto-use
// turned off) doesn't wake it.
func TestResetLoopWakesForTheSoonestLook(t *testing.T) {
now := time.Now().Round(0)
e := expiringResets{next: map[string]time.Time{}}
if got := e.wake(now); got != resetExpiryClose {
t.Fatalf("none due: %v", got)
}
passed := func(keys ...string) {
for _, k := range keys {
e.check(k, now.Add(-time.Hour), func() ([]QuotaWindow, *ResetCredits, error) { t.Fatal("looked"); return nil, nil, nil },
func() (ResetOutcome, error) { t.Fatal("spent"); return ResetOutcome{}, nil })
}
}
e.next["skipped"] = now.Add(-time.Hour)
e.next["far"] = now.Add(time.Hour)
passed("far")
if got := e.wake(now); got != resetExpiryClose {
t.Fatalf("skipped and far: %v", got)
}
e.next["soon"] = now.Add(97 * time.Second)
passed("far", "soon")
if got := e.wake(now); got != 97*time.Second {
t.Fatalf("one in 97s: %v", got)
}
// each pass names its own accounts: soon isn't waited for unless asked about again
passed("far")
if got := e.wake(now); got != resetExpiryClose {
t.Fatalf("soon not in the pass: %v", got)
}
e.next["overdue"] = now.Add(-30 * time.Second)
passed("far", "overdue")
if got := e.wake(now); got != time.Second {
t.Fatalf("one due while the pass ran: %v", got)
}
}
+7 -3
View File
@@ -1178,14 +1178,18 @@ func (s Settings) ImageWait() time.Duration {
// CodexResetLeadDefault is CodexResetLead's minutes when it is unset, and
// CodexResetLeadLeast and CodexResetLeadMost the range it can be set in;
// CodexResetLeads the choices the app and the CLI's words offer.
// CodexResetLeads the choices the app and the CLI's words offer. Five
// minutes is the least (shangyuan0818 on Discord asked for less than 15):
// the look lands on the lead's start, and a failure is tried again each
// minute, so a pass that hangs to its two-minute bound still leaves a
// second try before the reset runs out; at three a hung pass leaves none.
const (
CodexResetLeadDefault = 30
CodexResetLeadLeast = 15
CodexResetLeadLeast = 5
CodexResetLeadMost = 24 * 60
)
var CodexResetLeads = []int{15, 30, 60, 120, 180, 360, 720, 1440}
var CodexResetLeads = []int{5, 10, 15, 30, 60, 120, 180, 360, 720, 1440}
// ResetLead is how long before a Codex reset about to run out unused it
// is spent by itself: CodexResetLead's minutes, CodexResetLeadDefault's