warm-up: All accounts warms every account in use at one press (CoderMaurice on X)

CoderMaurice on X: with several Claude accounts, Warm up now had to be
pressed once per account. With two or more accounts, the Warm up… menu on
the Warm up now row (a Claude Code or Codex provider's editor, the warm-up
section) now starts with All accounts. It sends POST /api/warm-all, and
provider.WarmAll sends Warm up now to every account that is in use (the
one the agent is on, or one turned on beside it) and whose windows aren't
all running already, going by the cached readings the Usage page shares.
It runs three at a time. An account that is turned off or paused, or
already in its windows, is sent nothing. An account whose sign-in lapsed
is sent nothing and is listed as failed, as Warm up now treats it. The
row's line lists the accounts warmed, the ones already in a window, and
each refusal with its reason (in red).
Accounts that are turned off aren't listed. A gateway rest is not read
(the provider package can't see it). An account rested for a used-up
window is still inside that window, so it is skipped as running.

"All accounts" moves from the usage plugin's i18n.js into core i18n.js,
since the core uses it now. It and two new strings are in zh, zh-TW, ja
and de. app.js stays inside its budget: the single-account and
all-accounts results now go through one formatter.

Run at a1968a0b5 (rebased on origin/main aecf27efb), on mica:
- go test -run 'WarmAll|WarmNow|CoreScriptBudget|Budget' ./internal/provider
  ./internal/gui: ok. New: TestWarmAllWarmsEachIdleAccountInUse,
  TestWarmAllOnlyCodexAndClaude, warm-all cases in TestWarmNowAPISaysWhy.
- Broken by hand: with the "running" skip removed from warmAll,
  TestWarmAllWarmsEachIdleAccountInUse FAILs (busy@ and spent@ warmed).
  With the All accounts item removed from the menu, warm-now.test.cjs
  FAILs ("Warm up all warms every account at one press" and the menu
  list assertion).
- GUI, Chromium and WebKit, en/zh/zh-TW/ja/de, 900px and 440px:
  warm-now, i18n-keys, i18n-en-no-cjk, usage-accounts: 54/54 pass. Before
  the rebase, plan-name-fits, provider-prefs-layout and quota-warm also
  passed (54/54 with usage-accounts).
- gofmt -l: clean. go vet, GOOS=linux go vet -tags nogui and
  GOOS=windows go vet of internal/provider and internal/gui: ok.
  go build, GOOS=linux go build -tags nogui, GOOS=windows go build: ok.

Not run: the full go test ./... and the full GUI suite. Both mote and
mica had other sessions' GUI suites running throughout, and this ships
now per the owner's ship-immediately rule. Both will run when a machine
is free. Not tried: a real Warm up all against several real Claude
accounts (the send per account is the unchanged WarmNow).
This commit is contained in:
yetone
2026-11-15 11:00:37 +08:00
parent aecf27efbc
commit 5bd41301b9
9 changed files with 286 additions and 24 deletions
+1
View File
@@ -413,6 +413,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
- A switched-off provider (`Off`, #163) stays saved. The gateway says it is off instead of saying the model is unknown.
- A subscription switched off (`Off`) or whose account was removed from magpie (`Hidden`) is left alone in the background (`leftAlone` in [`left_alone.go`](../../internal/provider/left_alone.go); Riko on Discord, whose Claude switched off still ran `claude auth status --json` every minute). No CLI is asked who is signed in (`claudeIdentity`, `cliIdentity.get` for Cursor and Devin): what it said last, in memory or `cli-identity.json`, is served, so the account stays listed to switch on again. Nor is its allowance read (`fetchSubscriptionUsage`, `loginUsageAt`), a saved ChatGPT sign-in renewed (`RenewLogins`), the agent's account switched (`NextLogin`), a window warmed (`keepWarm`), its model list fetched (`newDue`), a daily check-in made by the loop (`checkinNow` with `soon` false; a press still checks in), a plugin's idle sign-in renewed (`KeepPluginsSignedIn`, #5080), or a Codex reset about to run out read and spent (`SpendExpiringCodexResets`, #2226; `TestExpiringResetLeftAlone`). A Cursor switched off that was never asked who is signed in isn't listed until it is switched on. `TestLeftAloneRunsNoCLI` runs those paths with fake `claude`, `cursor-agent` and `devin` CLIs on PATH and checks none ran. Plugins' model lists (`KeepPluginsListed`, and every listing after a sign-in or a plugin changes) are asked of the plugin host all at once, and a plugin provider switched off in magpie is named in the call (`plugin.ListingOff`, `pluginsOff` in [`plugins.go`](../../internal/provider/plugins.go)): `host.js` runs no models hook for it, nor the sign-in renewal before one, and tells its list as fallen back, so the list told last is kept (ChangQiu on Discord: `TestOffPluginProviderAskedNoModels`, `TestPluginsOffNamesThePluginsOwnIDs`). Refreshing every list (the window's Refresh, `POST /api/sync`, and `magpie sync`) goes through `RefreshLists`, which asks no provider switched off, and a key added to one isn't given its own list (`PrefillNewKeys`), nor is a provider switched off asked for its list when it is saved or a key is switched on in its editor (`TestRefreshListsAsksNoProviderSwitchedOff`, `TestPrefillAsksNoProviderSwitchedOff`).
- *Warm up now*, the last row of Settings › Usage's Codex and Claude Code warm-up tabs (`renderWarmNow` in `app.js`, `POST /api/warm-now`), sends one account the request the scheduled warm-up sends, whatever the warm-up settings say ([`warm_now.go`](../../internal/provider/warm_now.go)): `warmCodexLogin` for a ChatGPT account, then `StaleAllowance`; for a Claude account Claude Code's own run, `warmClaudeLogin` over the gateway's `warmClaude` (`WarmClaudeVia`), in the saved account's directory, then `claudeWarmedNow`, which has the account read again on its next look while its last reading keeps its own time, so the old windows never show as just read (`TestClaudeWarmedReadAgain`). With several accounts the press opens the app's menu of them. An account whose sign-in lapsed is sent nothing and says so, and the vendor's refusal comes back as the row's line, in red. The scheduled warm-up's file (`codex-warmup.json`) isn't written: its next look reads the window as started. `TestWarmNowSendsTheScheduledWarmUp` checks the body and headers equal the scheduled warm-up's; `warm-now.test.cjs` covers the GUI.
- *All accounts*, the first item of Warm up now's menu with several accounts (CoderMaurice on X, `POST /api/warm-all`, `WarmAll` in [`warm_now.go`](../../internal/provider/warm_now.go)), sends Warm up now to every account in use (the one the agent is on, or one turned on beside it) whose windows aren't all running, as the cached readings tell them (`windowsRunning`: one never read is warmed), three at a time. An account turned off or paused, and one already in its windows, is sent nothing; one whose sign-in lapsed is sent nothing and failed. The row's line says each account's result: the ones warmed, the ones already in a window, and each refusal with its reason, in red; one turned off goes unsaid. A gateway rest isn't read here (the provider package can't see it): an account rested for a used-up window is in that window, so it is left alone as running. `TestWarmAllWarmsEachIdleAccountInUse`; `warm-now.test.cjs` covers the GUI.
- The scheduled warm-up warms each window a Claude account is expected to have (`withExpected`), the 5-hour and the week, also one its reading left out: Anthropic leaves a window out until the request that starts it. A window left out while a shorter one is running is one the account doesn't have, since any use starts every window it has (a Claude Enterprise account with only the 5-hour, koohoko5924 on Discord, whose week was warmed over and over and its state read Idle): the warmer marks it `Absent` in `codex-warmup.json` and sends it nothing, and `usageRead` doesn't count it as due (`windowAbsent`, `shorterRunning` in [`codex_warmup.go`](../../internal/provider/codex_warmup.go)). A week once seen running, or left out of a reading that is only part of the plan's, is still warmed; one never read before is not. `TestClaudeWarmLeavesAWeekTheAccountHasnt`, `TestClaudeWarmStartsAWeekThatReset`, `TestUsageReadLeavesAWeekTheAccountHasnt`.
- A Copilot subscription offers the union of its On accounts' models too (`copilotPoolModels` in [`copilot_pool.go`](../../internal/provider/copilot_pool.go), merged by `poolModels` as Codex's ChatGPT accounts are): each GitHub account's plan lists its own (`/models`), kept under `accountModels` for `Account.Lists`. The first account's list is fetched as before (`FetchNew`, `KeepAccountsListed`, Refresh); each fetch of it also asks the other accounts on: one with no list at once, of the rest the one asked longest ago once its list is a day old (`copilotFetchSaved`). A model Copilot refused an account (`copilotRefuses`) goes to the others that list it, and stays in the provider's list while another account on lists it (`copilotOthersList`). Only a failed ask is remembered (`copilotSavedAsked`), so a list gone is asked for again at once. applemacssma on X; `TestCopilotAccountsWithOtherModels`, `TestCopilotRefusedModelGoesToTheAccountServedIt`.
- An Antigravity subscription offers the union of its On accounts' models (`antigravityPoolModels` in [`antigravity_pool.go`](../../internal/provider/antigravity_pool.go)), each account's own list kept beside it (`accountModels`, read by `Account.Lists` for routing). The lists are fetched at the first listing, a probe, a sync or a Refetch, and also at each account's quota reading, which asks `fetchAvailableModels` anyway: a reading whose models differ from the account's saved list saves it and merges the pooled list again from every On account's own (`noteAntigravityList`), so a model Google gives one account of several later (01huadalang on Discord: Gemini 4) is offered, routed to and given its bar without that account made preferred or probed. A switched-off account's reading changes nothing. `TestAntigravityQuotaReadingListsNewModels`. Each `fetchAvailableModels` names the account's paid and current tier first (`entitlement.userTier`, `askTiers`), then none; a tier Google answers 400 (a Google AI Pro account's g1-pro-tier, #1553) is left out of that account's lists and quota readings for `tierRefusedFor` (a day), and the refused request is no row of the request log.
+15
View File
@@ -2343,6 +2343,21 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
}
writeJSON(rw, map[string]bool{"ok": true})
})
// Warm up all: each of a Codex or Claude agent's accounts in use and not
// in a window already warmed at once, and what each came to
mux.HandleFunc("POST /api/warm-all", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ Agent string }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
rs, err := provider.WarmAll(r.Context(), in.Agent)
if err != nil {
fail(rw, err)
return
}
writeJSON(rw, map[string]any{"results": rs})
})
// whether a Codex account spends one of its resets by itself once its
// week is used up, the Usage card's toggle, set on its own
// a Codex account's own daily warm-up time: "06:00", "off", or "" to
+13 -11
View File
@@ -21203,22 +21203,24 @@ function renderWarmNow(agent, users, rowId) {
if (users.length > 1) b.setAttribute("aria-haspopup", "menu");
const send = async (user) => {
const say = (o) => { warmNowSaid[agent] = o; if ($(rowId).isConnected) renderWarmNow(agent, users, rowId); };
say({ busy: true, text: t("Warming up {who}…", { who: user }) });
try {
await api("warm-now", { agent, user });
say({ text: t("Warmed up {who} {when}", { who: user, when: syncWhen(new Date().toISOString()) }) });
status(t("Warmed up {who}", { who: user }), "ok");
loadQuotas(); // the window it started
} catch (e) {
say({ bad: true, text: t("Couldn't warm up {who}: {why}", { who: user, why: e.message }) });
status(t("Couldn't warm up {who}: {why}", { who: user, why: e.message }), "err");
}
// "" is All accounts (CoderMaurice on X): each in use and not in a
// window already, what each came to on the one line
const who = user || t("All accounts");
say({ busy: true, text: t("Warming up {who}…", { who }) });
let rs;
try { rs = user ? (await api("warm-now", { agent, user }), [{ user }]) : (await api("warm-all", { agent })).results; } catch (e) { rs = [{ user: who, error: e.message }]; }
const by = (f) => rs.filter(f).map((r) => r.user).join(", "), ok = by((r) => !r.skip && !r.error), on = by((r) => r.skip == "running"), bad = rs.filter((r) => r.error);
const text = [ok && t("Warmed up {who} {when}", { who: ok, when: syncWhen(new Date().toISOString()) }), on && t("Already in a window: {who}", { who: on }),
...bad.map((r) => t("Couldn't warm up {who}: {why}", { who: r.user, why: r.error }))].filter(Boolean).join(" · ") || t("No account in use to warm up");
say({ bad: !!bad.length, text });
status(text, bad.length ? "err" : "ok");
if (ok) loadQuotas(); // the windows it started
};
b.onclick = (e) => {
e.stopPropagation();
if (users.length === 1) return send(users[0]);
if (b.classList.contains("open")) return closeProtoMenu();
openProtoMenu(b, users.map((u) => ({ v: u, name: u, note: "", literalName: true })), null, send, "Warm up which account", "sess-menu", "right");
openProtoMenu(b, [{ v: "", name: "All accounts", note: "" }, ...users.map((u) => ({ v: u, name: u, note: "", literalName: true }))], null, send, "Warm up which account", "sess-menu", "right");
};
box.replaceChildren(b);
}
+12
View File
@@ -1573,6 +1573,9 @@ const I18N = {
"Warmed up {who} {when}": "已预热 {who},{when}",
"Warmed up {who}": "已预热 {who}",
"Couldn't warm up {who}: {why}": "{who} 预热失败:{why}",
"All accounts": "全部账号",
"Already in a window: {who}": "窗口已在计时:{who}",
"No account in use to warm up": "没有可预热的在用账号",
"One tiny request through Claude Code (Haiku) starts the next window at once": "通过 Claude Code(Haiku)发一条极小的请求,让下一个窗口立即开始计时",
"Starts each account's 5-hour window at this time every day": "每天到这个时间开启各账号的 5 小时窗口",
"Starts each account's 5-hour window at each of these times every day": "每天到其中每个时间开启各账号的 5 小时窗口",
@@ -6888,6 +6891,9 @@ const I18N = {
"Warmed up {who} {when}": "已預熱 {who},{when}",
"Warmed up {who}": "已預熱 {who}",
"Couldn't warm up {who}: {why}": "{who} 預熱失敗:{why}",
"All accounts": "全部帳號",
"Already in a window: {who}": "時段已在計時:{who}",
"No account in use to warm up": "沒有可預熱的使用中帳號",
"One tiny request through Claude Code (Haiku) starts the next window at once": "透過 Claude Code(Haiku)發一條極小的請求,讓下一個時段立即開始計時",
"Starts each account's 5-hour window at this time every day": "每天到這個時間開啟各帳號的 5 小時時段",
"Starts each account's 5-hour window at each of these times every day": "每天到其中每個時間開啟各帳號的 5 小時時段",
@@ -12171,6 +12177,9 @@ const I18N = {
"Warmed up {who} {when}": "{who} をウォームアップしました({when})",
"Warmed up {who}": "{who} をウォームアップしました",
"Couldn't warm up {who}: {why}": "{who} をウォームアップできませんでした: {why}",
"All accounts": "すべてのアカウント",
"Already in a window: {who}": "期間はすでに開始済み: {who}",
"No account in use to warm up": "ウォームアップできる使用中のアカウントがありません",
"One tiny request through Claude Code (Haiku) starts the next window at once": "Claude Code(Haiku)経由でごく小さなリクエストを 1 件送り、次の期間をすぐに開始します",
"Starts each account's 5-hour window at this time every day": "毎日この時刻に各アカウントの 5 時間枠を開始します",
"Starts each account's 5-hour window at each of these times every day": "毎日これらの各時刻に各アカウントの 5 時間枠を開始します",
@@ -17485,6 +17494,9 @@ const I18N = {
"Warmed up {who} {when}": "{who} vorgewärmt, {when}",
"Warmed up {who}": "{who} vorgewärmt",
"Couldn't warm up {who}: {why}": "{who} konnte nicht vorgewärmt werden: {why}",
"All accounts": "Alle Konten",
"Already in a window: {who}": "Zeitfenster läuft bereits: {who}",
"No account in use to warm up": "Kein genutztes Konto zum Vorwärmen",
"One tiny request through Claude Code (Haiku) starts the next window at once": "Eine winzige Anfrage über Claude Code (Haiku) startet sofort das nächste Zeitfenster",
"Starts each account's 5-hour window at this time every day": "Startet das 5-Stunden-Zeitfenster jedes Kontos täglich zu dieser Uhrzeit",
"Starts each account's 5-hour window at each of these times every day": "Startet das 5-Stunden-Zeitfenster jedes Kontos täglich zu jeder dieser Uhrzeiten",
@@ -104,7 +104,6 @@ magpie.strings({
"Pick the first day, then the last": "先选第一天,再选最后一天",
"No calls on the days picked.": "所选日期内没有调用。",
"All gateway keys": "全部网关密钥",
"All accounts": "全部账号",
"{agent} · on {computer}": "{agent} · 在 {computer}",
"What was said stays on {computer}: sync shares the usage alone.": "对话内容留在 {computer} 上:同步只共享用量。",
"Model · provider": "模型 · 供应商",
@@ -396,7 +395,6 @@ magpie.strings({
"Pick the first day, then the last": "先選第一天,再選最後一天",
"No calls on the days picked.": "所選日期內沒有呼叫。",
"All gateway keys": "全部閘道金鑰",
"All accounts": "全部帳號",
"{agent} · on {computer}": "{agent} · 在 {computer}",
"What was said stays on {computer}: sync shares the usage alone.": "對話內容留在 {computer} 上:同步只共享用量。",
"Model · provider": "模型 · 供應商",
@@ -688,7 +686,6 @@ magpie.strings({
"Pick the first day, then the last": "最初の日、次に最終日を選択",
"No calls on the days picked.": "選んだ日付の呼び出しはありません。",
"All gateway keys": "すべてのゲートウェイキー",
"All accounts": "すべてのアカウント",
"{agent} · on {computer}": "{agent} · {computer} 上",
"What was said stays on {computer}: sync shares the usage alone.": "会話内容は {computer} に残ります。同期で共有されるのは使用量だけです。",
"Model · provider": "モデル · プロバイダ",
@@ -980,7 +977,6 @@ magpie.strings({
"Pick the first day, then the last": "Erst den ersten Tag, dann den letzten wählen",
"No calls on the days picked.": "An den gewählten Tagen keine Aufrufe.",
"All gateway keys": "Alle Zugangsschlüssel",
"All accounts": "Alle Konten",
"{agent} · on {computer}": "{agent} · auf {computer}",
"What was said stays on {computer}: sync shares the usage alone.": "Die Inhalte bleiben auf {computer}: Die Synchronisierung teilt nur die Nutzung.",
"Model · provider": "Modell · Anbieter",
+62 -8
View File
@@ -32,6 +32,10 @@ function serve(lang, asked, codexUsers, claudeUsers) {
asked.push([b.agent, b.user]);
return b.user === "a@example.com" ? json({ error: WHY }, 400) : json({ ok: true });
}
if (url.pathname === "/api/warm-all") {
asked.push([route.request().postDataJSON().agent, "all"]);
return json({ results: ALL });
}
if (url.pathname === "/api/providers") return json(provPrefsProviders(["codex", "claude"], { codex: "Codex", claude: "Claude Code" }));
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
@@ -42,12 +46,17 @@ function serve(lang, asked, codexUsers, claudeUsers) {
};
}
// what POST /api/warm-all says of each account: two warmed, one in its
// windows already, one turned off (unsaid), one refused
const ALL = [{ user: "one@example.com" }, { user: "busy@example.com", skip: "running" }, { user: "off@example.com", skip: "off" },
{ user: "two@example.com" }, { user: "a@example.com", error: WHY }];
const W = {
en: { name: "Warm up now", go: "Warm up", pick: "Warm up…", head: "Warm up which account", done: "Warmed up B@Example.com at ", failed: "Couldn't warm up a@example.com: ", own: "Warmed up own@example.com at " },
zh: { name: "现在预热", go: "预热", pick: "预热…", head: "预热哪个账号", done: "已预热 B@Example.com,", failed: "a@example.com 预热失败:", own: "已预热 own@example.com," },
"zh-TW": { name: "現在預熱", go: "預熱", pick: "預熱…", head: "預熱哪個帳號", done: "已預熱 B@Example.com,", failed: "a@example.com 預熱失敗:", own: "已預熱 own@example.com," },
ja: { name: "今すぐウォームアップ", go: "ウォームアップ", pick: "ウォームアップ…", head: "ウォームアップするアカウント", done: "B@Example.com をウォームアップしました(", failed: "a@example.com をウォームアップできませんでした: ", own: "own@example.com をウォームアップしました(" },
de: { name: "Jetzt vorwärmen", go: "Vorwärmen", pick: "Vorwärmen…", head: "Welches Konto vorwärmen", done: "B@Example.com vorgewärmt, ", failed: "a@example.com konnte nicht vorgewärmt werden: ", own: "own@example.com vorgewärmt, " },
en: { name: "Warm up now", go: "Warm up", pick: "Warm up…", head: "Warm up which account", done: "Warmed up B@Example.com at ", failed: "Couldn't warm up a@example.com: ", own: "Warmed up own@example.com at ", all: "All accounts", running: "Already in a window: " },
zh: { name: "现在预热", go: "预热", pick: "预热…", head: "预热哪个账号", done: "已预热 B@Example.com,", failed: "a@example.com 预热失败:", own: "已预热 own@example.com,", all: "全部账号", running: "窗口已在计时:" },
"zh-TW": { name: "現在預熱", go: "預熱", pick: "預熱…", head: "預熱哪個帳號", done: "已預熱 B@Example.com,", failed: "a@example.com 預熱失敗:", own: "已預熱 own@example.com,", all: "全部帳號", running: "時段已在計時:" },
ja: { name: "今すぐウォームアップ", go: "ウォームアップ", pick: "ウォームアップ…", head: "ウォームアップするアカウント", done: "B@Example.com をウォームアップしました(", failed: "a@example.com をウォームアップできませんでした: ", own: "own@example.com をウォームアップしました(", all: "すべてのアカウント", running: "期間はすでに開始済み: " },
de: { name: "Jetzt vorwärmen", go: "Vorwärmen", pick: "Vorwärmen…", head: "Welches Konto vorwärmen", done: "B@Example.com vorgewärmt, ", failed: "a@example.com konnte nicht vorgewärmt werden: ", own: "own@example.com vorgewärmt, ", all: "Alle Konten", running: "Zeitfenster läuft bereits: " },
};
// where the button the reader pressed is on the screen: it stays there while
@@ -102,9 +111,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const menu = page.locator(".proto-menu");
await menu.waitFor();
assert.equal((await menu.locator(".pm-head").innerText()).trim(), w.head);
assert.deepEqual((await menu.locator(".pm-name").allInnerTexts()).map((s) => s.trim()), ["a@example.com", "B@Example.com"]);
assert.deepEqual((await menu.locator(".pm-name").allInnerTexts()).map((s) => s.trim()), [w.all, "a@example.com", "B@Example.com"]);
assert.deepEqual(asked, [], "the menu opening sent nothing");
await menu.locator(".pm-item").nth(1).click();
await menu.locator(".pm-item").nth(2).click();
await page.waitForFunction((s) => document.querySelector("#warmNowSub")?.textContent.startsWith(s), w.done);
assert.deepEqual(asked, [["codex", "B@Example.com"]], "that account alone, by its name as it is");
assert.equal(await page.locator("#warmNowSub.err").count(), 0);
@@ -112,7 +121,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// refused: the vendor's reason, in red, on the line and in the status
await go.click();
await menu.locator(".pm-item").nth(0).click();
await menu.locator(".pm-item").nth(1).click();
await page.waitForFunction(() => document.querySelector("#warmNowSub.err"));
assert.equal((await page.locator("#warmNowSub").innerText()).trim(), w.failed + WHY);
assert.ok((await page.locator("#status").textContent()).includes("usage limit reached"));
@@ -144,6 +153,51 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
}
}
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
const w = W[lang];
for (const width of [900, 440]) {
// Warm up all (CoderMaurice on X): the menu's first item warms every
// Claude account in one press (POST /api/warm-all {agent}), and the
// row's line says what each came to: the ones warmed, the ones in a
// window already, each refusal with its reason, in red; one turned
// off goes unsaid
test(`${engine} ${lang} ${width}px: Warm up all warms every account at one press`, async (t) => {
const browser = await launch(engine);
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], asked = [];
page.on("pageerror", (e) => { if (engine === "webkit" && /due to access control checks/.test(e.message)) return; errors.push(e.message); }); // a goto in WebKit can cut off a fetch (#1350)
await page.route("**/*", serve(lang, asked, undefined, ALL.map((r) => r.user)));
await openProvPrefs(page, "claude");
const row = page.locator(".editor .prov-prefs #claudeWarmNowRow"), go = row.locator("button");
await go.waitFor();
await inEditor(page, go);
assert.equal((await go.innerText()).trim(), w.pick);
await go.click();
const menu = page.locator(".proto-menu");
await menu.waitFor();
assert.deepEqual((await menu.locator(".pm-name").allInnerTexts()).map((s) => s.trim()), [w.all, ...ALL.map((r) => r.user)]);
await menu.locator(".pm-item").first().click();
await page.waitForFunction(() => document.querySelector("#claudeWarmNowSub.err"));
assert.deepEqual(asked, [["claude", "all"]], "one request for them all, none one by one");
const said = (await page.locator("#claudeWarmNowSub").innerText()).trim();
const parts = said.split(" · ");
assert.equal(parts.length, 3, said);
assert.ok(parts[0].startsWith(w.done.replace("B@Example.com", "one@example.com, two@example.com")), said);
assert.equal(parts[1], w.running + "busy@example.com");
assert.equal(parts[2], w.failed + WHY);
assert.ok(!said.includes("off@example.com"), "an account turned off goes unsaid");
assert.equal(await go.isDisabled(), false, "pressable again");
assert.deepEqual(await sideways(page), []);
if (process.env.ARTIFACT_DIR) await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `warm-all-${engine}-${lang}-${width}.png`) });
assert.equal(await page.locator("select").count(), 0);
assert.deepEqual(errors, []);
});
}
}
test(`${engine}: no account, no Warm up now`, async (t) => {
const browser = await launch(engine);
t.after(() => browser.close());
+9 -1
View File
@@ -26,9 +26,17 @@ func TestWarmNowAPISaysWhy(t *testing.T) {
{`{"agent":"claude","user":"nobody@example.com"}`, `no Claude account "nobody@example.com"`},
{`{"agent":"copilot","user":"octocat"}`, `"copilot" has no warm-up`},
{`{"agent":"codex"}`, `no ChatGPT account ""`},
// Warm up all: no account, or no warm-up
{`{"agent":"claude","all":true}`, `no Claude account to warm up`},
{`{"agent":"codex","all":true}`, `no ChatGPT account to warm up`},
{`{"agent":"copilot","all":true}`, `"copilot" has no warm-up`},
} {
route := "/api/warm-now"
if strings.Contains(c.body, `"all"`) {
route = "/api/warm-all"
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("POST", "/api/warm-now", strings.NewReader(c.body)))
h.ServeHTTP(rec, httptest.NewRequest("POST", route, strings.NewReader(c.body)))
var out struct{ Error string }
json.Unmarshal(rec.Body.Bytes(), &out)
if rec.Code != 400 || !strings.Contains(out.Error, c.want) {
+84
View File
@@ -0,0 +1,84 @@
package provider
import (
"context"
"errors"
"slices"
"sync"
"testing"
"time"
)
// Warm up all (CoderMaurice on X) sends the warm-up to each account in use
// whose windows aren't all running, and leaves alone, saying why, one
// turned off or paused and one already in its windows; one whose sign-in
// lapsed is sent nothing and failed, and one account's failure is its own.
func TestWarmAllWarmsEachIdleAccountInUse(t *testing.T) {
now := time.Date(2026, 11, 15, 12, 0, 0, 0, time.UTC)
at := func(d time.Duration) *time.Time { x := now.Add(d); return &x }
five := func(used float64, resets *time.Time) QuotaWindow {
return QuotaWindow{Name: "5 hours", Span: 5 * time.Hour, Used: used, ResetsAt: resets}
}
week := func(used float64, resets *time.Time) QuotaWindow {
return QuotaWindow{Name: "7 days", Span: 7 * 24 * time.Hour, Used: used, ResetsAt: resets}
}
ls := []Login{
{User: "own@example.com", Active: true}, // idle: warmed
{User: "on@example.com", On: true}, // never read: warmed
{User: "ON@example.com", On: true}, // listed twice: once
{User: "week@example.com", On: true}, // week running, five hours idle: warmed
{User: "busy@example.com", On: true}, // both running: left
{User: "reset@example.com", On: true}, // read running, reset since: warmed
{User: "spent@example.com", On: true}, // used up, still running: left
{User: "off@example.com"}, // turned off: left
{User: "paused@example.com", Active: true, Paused: true}, // paused: left
{User: "lapsed@example.com", On: true, Lapsed: "OAuth token revoked"},
{User: "fails@example.com", On: true},
}
usage := map[string]SubscriptionQuota{
"own@example.com": {Windows: []QuotaWindow{five(0, nil), week(0, nil)}},
"week@example.com": {Windows: []QuotaWindow{five(0, nil), week(30, at(3*24*time.Hour))}},
"busy@example.com": {Windows: []QuotaWindow{five(4, at(2*time.Hour)), week(10, at(24*time.Hour))}},
"reset@example.com": {Windows: []QuotaWindow{five(40, at(-time.Minute)), week(10, at(24*time.Hour))}},
"spent@example.com": {Windows: []QuotaWindow{five(100, at(time.Hour)), week(100, at(time.Hour)),
{Name: "Extra usage", Text: true, Used: 100}}},
"fails@example.com": {Windows: []QuotaWindow{five(0, nil)}},
}
var mu sync.Mutex
var sent []string
rs := warmAll(context.Background(), ls, usage, now, func(_ context.Context, user string) error {
mu.Lock()
sent = append(sent, user)
mu.Unlock()
if user == "fails@example.com" {
return errors.New("Claude Code: You've hit your session limit")
}
return nil
})
want := []WarmAllResult{
{User: "own@example.com"},
{User: "on@example.com"},
{User: "week@example.com"},
{User: "busy@example.com", Skip: "running"},
{User: "reset@example.com"},
{User: "spent@example.com", Skip: "running"},
{User: "off@example.com", Skip: "off"},
{User: "paused@example.com", Skip: "off"},
{User: "lapsed@example.com", Err: "needs signing in again: OAuth token revoked"},
{User: "fails@example.com", Err: "Claude Code: You've hit your session limit"},
}
if !slices.Equal(rs, want) {
t.Fatalf("results\n%+v\nwant\n%+v", rs, want)
}
slices.Sort(sent)
if w := []string{"fails@example.com", "on@example.com", "own@example.com", "reset@example.com", "week@example.com"}; !slices.Equal(sent, w) {
t.Fatalf("sent to %q, want %q", sent, w)
}
}
// Warm up all is only for the agents with a warm-up.
func TestWarmAllOnlyCodexAndClaude(t *testing.T) {
if _, err := WarmAll(context.Background(), "copilot"); err == nil {
t.Fatal("warmed Copilot accounts")
}
}
+90
View File
@@ -14,6 +14,7 @@ import (
"fmt"
"slices"
"strings"
"sync"
"time"
)
@@ -69,3 +70,92 @@ func WarmNow(ctx context.Context, agent, user string) error {
claudeWarmedNow(ls[i].User)
return nil
}
// WarmAllResult is what Warm up all came to for one account: Skip says why
// it was left alone ("off" or "running"), Err why its warm-up failed or
// couldn't be sent; both empty, it was warmed.
type WarmAllResult struct {
User string `json:"user"`
Skip string `json:"skip,omitempty"`
Err string `json:"error,omitempty"`
}
// warmAllAtOnce is how many of Warm up all's requests run together: each
// Claude one is a Claude Code run.
const warmAllAtOnce = 3
// WarmAll is Warm up now for each of agent's accounts at once
// (CoderMaurice on X: one press for several Claude accounts). It sends the
// warm-up to every account in use (the one the agent is on, or one turned
// on beside it) whose windows aren't all running already, as the cached
// reads the Usage page shares tell them. An account turned off or paused,
// and one already in its windows, are left alone and listed with why; one
// whose sign-in lapsed is sent nothing and failed, as Warm up now has it.
func WarmAll(ctx context.Context, agent string) ([]WarmAllResult, error) {
name := map[string]string{"codex": "ChatGPT", "claude": "Claude"}[agent]
if name == "" {
return nil, fmt.Errorf("%q has no warm-up", agent)
}
ls := Logins(agent)
if len(ls) == 0 {
return nil, fmt.Errorf("no %s account to warm up", name)
}
usage := LoginUsage(ctx, agent)
return warmAll(ctx, ls, usage, time.Now(), func(ctx context.Context, user string) error { return WarmNow(ctx, agent, user) }), nil
}
// warmAll is WarmAll on ls read as usage at now, each warm-up sent by send.
func warmAll(ctx context.Context, ls []Login, usage map[string]SubscriptionQuota, now time.Time, send func(context.Context, string) error) []WarmAllResult {
var out []WarmAllResult
var due []int
for _, l := range ls {
if l.User == "" || slices.ContainsFunc(out, func(r WarmAllResult) bool { return strings.EqualFold(r.User, l.User) }) {
continue
}
r := WarmAllResult{User: l.User}
switch {
case l.Lapsed != "":
// as Warm up now says of it
r.Err = "needs signing in again: " + l.Lapsed
case !l.Active && !l.On || l.Paused:
r.Skip = "off"
case windowsRunning(usage[l.User], now):
r.Skip = "running"
default:
due = append(due, len(out))
}
out = append(out, r)
}
var wg sync.WaitGroup
slots := make(chan struct{}, warmAllAtOnce)
for _, i := range due {
wg.Add(1)
go func() {
defer wg.Done()
slots <- struct{}{}
defer func() { <-slots }()
if err := send(ctx, out[i].User); err != nil {
out[i].Err = err.Error()
}
}()
}
wg.Wait()
return out
}
// windowsRunning says whether every one of q's own windows with a span is
// running as of now, so a warm-up would start none: false when none is
// known, as for an account never read.
func windowsRunning(q SubscriptionQuota, now time.Time) bool {
n := 0
for _, w := range q.Windows {
if w.Span <= 0 || w.Aside || w.Text || w.Model != "" || w.Lane != "" {
continue
}
if idle(asOf(w, now), now) {
return false
}
n++
}
return n > 0
}