codex: a reset about to expire can be used from 3 minutes before, or after any minutes typed (Custom…)

shangyuan0818 asked again, and the coordinator agreed: magpie runs the
whole time, a reset's expiry is known to the second, and a user who is
worried can pick a long lead. So the menu ends with Custom…, and the
floor is now what the gateway needs, not 15 or 5 minutes.

- settings: CodexResetLeadLeast 5 -> 3; the presets start at 3. The CLI
  (magpie quota reset-lead) and settings/codex-reset-lead check the same
  constant. Saved values stay valid: everything from 5 to 1440 still is.
- Why 3: since v0.1.3204 the loop wakes at the lead's start (timer, at
  most 1s late), a try is bounded by the pass's 2 minutes, and a failure
  in the last 15 minutes is tried again a minute after it began, at once
  when that has passed. At 3 minutes a try hung to its bound ends at
  T-0:57 and a retry starts at T-0:56. At 2 minutes a hung try leaves no
  retry before expiry.
- GUI (autoresetown.js): Custom…, the menu's last item, puts a field of
  minutes where the button was, at the button's size, so the row doesn't
  rewrap. Enter or leaving it saves. Escape keeps the lead. A number
  outside 3 to 1440 is shown as an error and not written. A redraw
  leaves the field alone while it is open. It uses the app menu and no
  native select. There is one new string, in all five languages.

Tests:
- TestShortLeadSpentInTime: at the least lead, for four phases, the
  reset is spent at T-3:00, and after a 2-minute hung try plus a 30s
  retry it is spent before expiry.
- TestQuotaResetLeadCmd: 3m is taken and 2m is refused.
- codex-reset-lead.test.cjs: 12 items, picking 3 min, and Custom… in
  every language at 1100 and 420. Typing 7 and pressing Enter posts 7.
  Typing 2 is said and not posted. Escape posts nothing, and leaving the
  field posts 12. Opening the field moves no page.

Run on mote at this tree:
- go test of the reset-lead, short-lead, reset-loop, expiring and
  quota-reset tests in provider, cli and settings: ok.
- go vet: darwin, linux -tags nogui and windows on provider, settings
  and cli, plus darwin on gui: ok.
- go test ./internal/gui: TestCoreScriptBudget ok with no raise (the
  field lives in the lazy autoresetown.js). TestMainWindowCorners is red,
  as in #3949.
- GUI codex-reset-lead, codex-auto-reset-settings and i18n-keys in
  Chromium and WebKit: 49/50. The red is i18n-keys "a plugin's words are
  its own", filed as #5327, #5332, #5426 and #5482. Before the last
  comment trims, codex-reset-lead, codex-auto-reset-settings and
  providers-reset-use passed 86/86.

Broken by hand, each red:
- Floor at 2: the least-lead hung case goes red (one try, no retry), and
  so does the CLI (2m taken).
- Floor at 5: the CLI refuses 3m.
- The GUI range check removed: "2 isn't posted".
- Escape saving: "Escape posts nothing".
- The field at its own size (76x27) instead of the button's: WebKit ja
  and de at 1100 move the page 1px.

Not tried: a real ChatGPT reset spent at 3 minutes, since none of my
accounts has a reset about to expire. The redraw guard has no test of
its own, because a click elsewhere blurs the field and saves first.

Reported-by: shangyuan0818 (Discord)
This commit is contained in:
yetone
2026-11-07 06:39:39 +08:00
parent 5f01b9d052
commit da548b4548
7 changed files with 148 additions and 36 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}, {"5m", 5}, {"10m", 10}, {"24h", 1440}, {"90", 90}, {"1h30m", 90}} {
}{{"2h", 120}, {"15m", 15}, {"3m", 3}, {"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{"4m", "1m", "25h", "-1h", "30s", "90s", "soon", "--help"} {
for _, bad := range []string{"2m", "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 = [5, 10, 15, 30, 60, 120, 180, 360, 720, 1440];
const RESET_LEADS = [3, 5, 10, 15, 30, 60, 120, 180, 360, 720, 1440];
function resetLeadMinutes(s = state?.settings) {
const m = s?.codexResetLead;
return Number.isInteger(m) && m >= 5 && m <= 1440 ? m : 30;
return Number.isInteger(m) && m >= 3 && m <= 1440 ? m : 30;
}
function resetLeadWords(m) {
return m < 60 || m % 60 ? t("{n} min", { n: m }) : t("{n} h", { n: m / 60 });
+50 -16
View File
@@ -6,9 +6,8 @@
// renderAutoResetOwn lists each ChatGPT account under Settings › Usage's
// "Codex: auto-use resets", with its switch, the same say as on the
// account's card (settings' codexAutoReset, the CLI's quota auto-reset).
// Avalon on Discord, after foobra12 asked where it was: it was only on the
// accounts' cards, and they found it from the menu bar's panel alone,
// nothing for it in the window's Settings. The row shows while a Codex
// Avalon on Discord: it was only on the accounts' cards, not in the
// window's Settings. The row shows while a Codex
// account is signed in, or one is still on.
window.autoResetOwnPaint = function (s) {
const head = $("#codexAutoResetRow");
@@ -76,11 +75,14 @@ window.autoResetOwnPaint = function (s) {
// renderResetLead: how long before a reset about to run out unused it is
// used, under the accounts' switches, one for them all; a pick from the
// app's menu (settings/codex-reset-lead). A value set outside the choices
// (the CLI takes any minutes in range) is shown and kept.
// (Custom…, or the CLI) is shown and kept (shangyuan0818 on Discord).
function renderResetLead(s, hidden) {
const row = $("#codexResetLeadRow");
if (!row) return;
row.hidden = hidden;
// a redraw leaves Custom…'s field being typed in
const own = $("#codexResetLeadPick .reset-lead-own");
if (own && !own.dataset.done) return;
const cur = resetLeadMinutes(s);
const leads = RESET_LEADS.includes(cur) ? RESET_LEADS : [...RESET_LEADS, cur].sort((a, b) => a - b);
const name = (m) => t("{lead} before", { lead: resetLeadWords(m) });
@@ -100,18 +102,50 @@ function renderResetLead(s, hidden) {
b.onclick = (e) => {
e.stopPropagation();
if (b.classList.contains("open")) return closeProtoMenu();
openProtoMenu(b, leads.map((m) => ({ v: String(m), name: name(m), note: m === 30 ? "Default" : "", literalName: true })), String(cur), async (v) => {
if (Number(v) === cur) return;
try {
prefs = await writingPrefs(api("settings/codex-reset-lead", { minutes: Number(v) }));
if (state) state.settings = prefs;
renderSettings();
if (quotas) renderQuotas(); // the cards' titles say it too
} catch (err) {
statusTErr(err);
renderSettings();
}
}, "Used before it expires", "sess-menu", "right");
const opts = leads.map((m) => ({ v: String(m), name: name(m), note: m === 30 ? "Default" : "", literalName: true }));
openProtoMenu(b, [...opts, { v: "\x01", name: "Custom…" }], String(cur), (v) => v === "\x01" ? resetLeadOwn(b, cur, set) : set(Number(v)), "Used before it expires", "sess-menu", "right");
};
const set = async (m) => {
if (m === cur) return renderSettings();
try {
prefs = await writingPrefs(api("settings/codex-reset-lead", { minutes: m }));
if (state) state.settings = prefs;
renderSettings();
if (quotas) renderQuotas(); // the cards' titles say it too
} catch (err) {
statusTErr(err);
renderSettings();
}
};
$("#codexResetLeadPick").replaceChildren(b);
}
// resetLeadOwn: Custom…'s field of minutes in the button's place; Enter or
// leaving saves, Escape doesn't, one out of range is said, not written.
function resetLeadOwn(b, cur, set) {
const least = RESET_LEADS[0], most = RESET_LEADS.at(-1);
const i = input(String(cur), least + "–" + most);
i.className = "words compact-num reset-lead-own";
i.inputMode = "numeric";
i.setAttribute("aria-label", t("Minutes"));
let done = false;
const finish = (save) => {
if (done) return;
done = true;
i.dataset.done = "1";
const v = i.value.trim(), m = /^\d+$/.test(v) ? Number(v) : NaN;
if (!save || !v) return renderSettings();
if (!(m >= least && m <= most)) {
status(t("Minutes is a whole number from 3 to 1440"), "err");
return renderSettings();
}
set(m);
};
i.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") finish(true); else if (e.key === "Escape") finish(false); };
i.onblur = () => finish(true);
// in the button's box: the row doesn't rewrap and move the page
i.style.width = b.offsetWidth + "px";
i.style.height = b.offsetHeight + "px";
b.replaceWith(i);
i.focus(NO_SCROLL);
}
+4
View File
@@ -503,6 +503,7 @@ const I18N = {
"Hours": "小时数",
"Hours in a cycle": "每个周期的小时数",
"Hours is a whole number from 1 to 8760": "小时数应为 1 到 8760 的整数",
"Minutes is a whole number from 3 to 1440": "分钟数应为 3 到 1440 的整数",
"The tokens and cost {name} has used go back to 0 together, and a new {n}-hour cycle starts now.": "{name} 已用的 Token 和费用一起清零,并从现在开始新的 {n} 小时周期。",
"Days": "天数",
"Days in a cycle": "每个周期的天数",
@@ -5178,6 +5179,7 @@ const I18N = {
"Hours": "小時數",
"Hours in a cycle": "每個週期的小時數",
"Hours is a whole number from 1 to 8760": "小時數應為 1 到 8760 的整數",
"Minutes is a whole number from 3 to 1440": "分鐘數應為 3 到 1440 的整數",
"The tokens and cost {name} has used go back to 0 together, and a new {n}-hour cycle starts now.": "{name} 已用的 Token 和費用一起歸零,並從現在開始新的 {n} 小時週期。",
"Days": "天數",
"Days in a cycle": "每個週期的天數",
@@ -9814,6 +9816,7 @@ const I18N = {
"Hours": "時間数",
"Hours in a cycle": "1 周期の時間数",
"Hours is a whole number from 1 to 8760": "時間数は 1〜8760 の整数です",
"Minutes is a whole number from 3 to 1440": "分数は 3〜1440 の整数です",
"The tokens and cost {name} has used go back to 0 together, and a new {n}-hour cycle starts now.": "{name} が使ったトークンと費用を一緒に 0 に戻し、今から新しい {n} 時間の周期を始めます。",
"Days": "日数",
"Days in a cycle": "1 周期の日数",
@@ -14468,6 +14471,7 @@ const I18N = {
"Hours": "Stunden",
"Hours in a cycle": "Stunden je Zyklus",
"Hours is a whole number from 1 to 8760": "Stunden sind eine ganze Zahl von 1 bis 8760",
"Minutes is a whole number from 3 to 1440": "Minuten sind eine ganze Zahl von 3 bis 1440",
"The tokens and cost {name} has used go back to 0 together, and a new {n}-hour cycle starts now.": "Die von {name} verbrauchten Token und Kosten gehen zusammen auf 0 zurück, und ab jetzt beginnt ein neuer {n}-Stunden-Zyklus.",
"Days": "Tage",
"Days in a cycle": "Tage je Zyklus",
+57 -8
View File
@@ -6,7 +6,10 @@
// posts settings/codex-reset-lead with its minutes and the row, and the
// "before one expires" titles, say the new lead. A value set outside the
// choices (the CLI's 45m) is shown and kept; one out of range (written by
// hand) reads as the half hour, as the gateway reads it. Five languages,
// hand) reads as the half hour, as the gateway reads it. Custom… after the
// choices opens a field of minutes in the row (shangyuan0818 on Discord):
// Enter or leaving it posts the number, Escape posts nothing, and one out
// of range is said and not posted. Five languages,
// 1100 and 420 wide, both engines; the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
@@ -132,7 +135,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(), 10, "5 min to 24 h");
assert.equal(await items.count(), 12, "3 min to 24 h, then Custom…");
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,12 +145,58 @@ 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)
// the shortest, three 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"
await page.locator(`.proto-menu .pm-item .pm-name:text-is(${JSON.stringify(await say(page, lang, 3))})`).click(); // not "3 h 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.deepEqual(posts, [{ minutes: 180 }, { minutes: 3 }]);
await page.waitForFunction((want) => document.querySelector("#codexResetLeadRow button.reset-lead .rl-say > .on")?.textContent.trim() === want, await say(page, lang, 3));
assert.equal(await page.locator("#view-settings").evaluate((v) => v.scrollTop), top, "no click moved the page");
// Custom…: the last item, a field of minutes in the row, focused
const custom = await page.evaluate((lang) => I18N[lang]?.["Custom…"] || "Custom…", lang);
const own = page.locator("#codexResetLeadRow input.reset-lead-own");
const ownField = async () => {
await page.locator("#codexResetLeadRow button.reset-lead").click();
const last = page.locator(".proto-menu .pm-item").last();
assert.equal((await last.locator(".pm-name").textContent()).trim(), custom);
await last.click();
await own.waitFor();
assert.equal(await own.evaluate((i) => i === document.activeElement), true, "the field has the keys");
};
await ownField();
assert.equal(await own.inputValue(), "3", "it starts at the lead");
assert.equal(await own.getAttribute("inputmode"), "numeric");
const r = await own.boundingBox(), v = await page.locator("#view-settings").boundingBox();
assert(r.x >= v.x && r.x + r.width <= v.x + v.width + 1, "the field fits");
assert.equal(await page.locator("#view-settings").evaluate((v) => v.scrollTop), top, "opening the field moved nothing");
await own.fill("7");
await own.press("Enter");
for (let i = 0; i < 100 && posts.length < 3; i++) await page.waitForTimeout(20);
assert.deepEqual(posts.at(-1), { minutes: 7 });
await page.waitForFunction((want) => document.querySelector("#codexResetLeadRow button.reset-lead .rl-say > .on")?.textContent.trim() === want, await say(page, lang, 7));
// under the least: said, nothing posted, the lead kept
await ownField();
await own.fill("2");
await own.press("Enter");
await page.locator("#codexResetLeadRow button.reset-lead").waitFor();
assert.equal(posts.length, 3, "2 isn't posted");
assert.equal(await page.locator("#status.err").textContent(), await page.evaluate((lang) => I18N[lang]?.["Minutes is a whole number from 3 to 1440"] || "Minutes is a whole number from 3 to 1440", lang));
assert.equal((await page.locator("#codexResetLeadRow .rl-say > .on").textContent()).trim(), await say(page, lang, 7));
assert(await page.evaluate(() => RESET_LEADS[0] === 3 && RESET_LEADS.at(-1) === 1440), "the words say the range RESET_LEADS has");
// Escape: nothing posted
await ownField();
await own.fill("9");
await own.press("Escape");
await page.locator("#codexResetLeadRow button.reset-lead").waitFor();
assert.equal(posts.length, 3, "Escape posts nothing");
// leaving the field saves it
await ownField();
await own.fill("12");
await page.locator("#codexResetLeadRow .name").click();
for (let i = 0; i < 100 && posts.length < 4; i++) await page.waitForTimeout(20);
assert.deepEqual(posts.at(-1), { minutes: 12 });
await page.waitForFunction((want) => document.querySelector("#codexResetLeadRow button.reset-lead .rl-say > .on")?.textContent.trim() === want, await say(page, lang, 12));
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
@@ -172,12 +221,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(), 11);
assert.equal(await page.locator(".proto-menu .pm-item").count(), 13);
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, 4, []);
const bad = await open(t, engine, "en", 900, 2, []);
assert.equal((await bad.page.locator("#codexResetLeadRow button.reset-lead .rl-say > .on").textContent()).trim(), "30 min before");
assert.deepEqual(bad.errors, []);
});
+23 -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, 4, 24*60 + 1, 1 << 30} {
for _, m := range []int{-5, 1, 2, 24*60 + 1, 1 << 30} {
setResetLead(t, m)
if got := resetLead(); got != 30*time.Minute {
t.Errorf("%d minutes: lead %v", m, got)
@@ -230,6 +230,28 @@ func TestShortLeadSpentInTime(t *testing.T) {
t.Errorf("7m lead, phase %v: spent %v before it runs out", phase, until.Sub(spent))
}
}
// the least lead (3m): spent at its start, and a try hung to the pass's
// two-minute bound still leaves a retry that is spent before it runs out
setResetLead(t, settings.CodexResetLeadLeast)
least := time.Duration(settings.CodexResetLeadLeast) * 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)
spent, tries := runLoop(t, start, until, func(int, time.Time) (ResetOutcome, error, time.Duration) {
return ResetOutcome{Code: "reset"}, nil, time.Second
})
if want := until.Add(-least); spent.Before(want) || spent.After(want.Add(5*time.Second)) || len(tries) != 1 {
t.Errorf("least lead, phase %v: spent %v before it runs out; tries at %v", phase, until.Sub(spent), tries)
}
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, 30 * time.Second
})
if spent.IsZero() || !spent.Before(until) || len(tries) != 2 {
t.Errorf("least lead, phase %v, a hung try: spent %v before it runs out; tries at %v", phase, until.Sub(spent), tries)
}
}
// 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)
+10 -7
View File
@@ -1178,18 +1178,21 @@ 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. 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.
// CodexResetLeads the choices the app's menu offers, besides its Custom…
// (any minutes in range, as the CLI takes). Three minutes is the least
// (shangyuan0818 on Discord asked for less than 15): the loop wakes at the
// lead's start, a try is bounded at two minutes (the pass's), and a
// failed one is tried again a minute after it began, or at once when that
// is past, so a try hung to its bound still leaves a retry with ~56s before
// the reset runs out; at two a hung try leaves none. app.js's RESET_LEADS
// and resetLeadMinutes, and Custom…'s words, say it too.
const (
CodexResetLeadDefault = 30
CodexResetLeadLeast = 5
CodexResetLeadLeast = 3
CodexResetLeadMost = 24 * 60
)
var CodexResetLeads = []int{5, 10, 15, 30, 60, 120, 180, 360, 720, 1440}
var CodexResetLeads = []int{3, 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