diff --git a/internal/cli/quota_reset_lead_test.go b/internal/cli/quota_reset_lead_test.go index 22333faa0..1c9d06688 100644 --- a/internal/cli/quota_reset_lead_test.go +++ b/internal/cli/quota_reset_lead_test.go @@ -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) diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index cba44c638..d3c23d9bd 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -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 }); diff --git a/internal/gui/tests/codex-reset-lead.test.cjs b/internal/gui/tests/codex-reset-lead.test.cjs index 511460e7b..a9ce2117a 100644 --- a/internal/gui/tests/codex-reset-lead.test.cjs +++ b/internal/gui/tests/codex-reset-lead.test.cjs @@ -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, []); }); diff --git a/internal/provider/codex_expiring.go b/internal/provider/codex_expiring.go index 4aba4727e..d4a935117 100644 --- a/internal/provider/codex_expiring.go +++ b/internal/provider/codex_expiring.go @@ -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())) } } diff --git a/internal/provider/codex_reset_lead_test.go b/internal/provider/codex_reset_lead_test.go index 752c9cdf7..c5644830f 100644 --- a/internal/provider/codex_reset_lead_test.go +++ b/internal/provider/codex_reset_lead_test.go @@ -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) + } +} diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 74172df25..a131bab69 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -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