Files
magpie/internal/provider/warm_now_test.go
T
yetone 1801c96bfb warm-up: Warm up now sends one account its warm-up at once (Codex and Claude)
A Windows user on Discord asked for a manual warm-up of a Codex account.
Settings > Warm-up and check-in now ends both the ChatGPT and the Claude
tab with a "Warm up now" row. Its text button sends the account's warm-up
right away. With one account it sends straight off. With several it opens
the app menu ("Warm up which account"), not a select. The row then says
"Warmed up {who} {when}", or "Couldn't warm up {who}: {why}" in red, and
the status line says the same.

What is sent: provider.WarmNow(agent, user) sends the scheduled warm-up's
own request to that one account and to no other. For Codex that is
warmCodexLogin; for Claude it is warmClaudeLogin over the gateway's
warmClaude (Claude Code's run in that account's config directory), set
through WarmClaudeVia. It works whether the warm-ups are on or off. An
account whose sign-in lapsed is refused with the reason. Afterwards the
allowance is read again (StaleAllowance / claudeWarmedNow), as after a
scheduled warm-up. The schedule's file is left to the schedule. The
Codex prompt, identity and base_instructions are unchanged: it is the
same body. The route is POST /api/warm-now, and /api/settings carries
claudeUsers beside codexUsers.

Claude gets the item too. It shares the warm-up engine and the same tab,
and the send is the same warmClaude the schedule uses.

No size budget was raised.

Run:
- WSL (wsl-run), Chromium and WebKit, with the GUI test
  warm-now.test.cjs in en/zh/zh-TW/ja/de at 900px and 440px: 22/22.
  The pressed button stays in place within 1px after two frames.
- WSL, the related files (warm-now, warm-at-own, warm-at-times,
  warm-reset-asleep, settings-groups, settings-search, i18n-keys):
  102/102.
- WSL, the other files that touch these lists (checkin-account,
  checkin-reason, checkin-reason-once, plugin-checkin, segs-press-redraw,
  settings-sections, usage-checkin): 169/170. The red is segs-press-redraw
  "webkit ja 440px: every Settings option..." with "could not bring the
  option into view" after 103s under load. It passed 3/3 alone and is
  filed as #4189.
- mote (macOS) at the final tree: go vet for internal/gui, provider and
  gateway; go test -run 'WarmNow|Budget|Warm' ./internal/gui
  ./internal/provider: ok. An earlier mote run, before the route move,
  ran go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./..., go build ./... and the budget tests: ok.
- Windows (win-run): go test -run 'TestWarmNow|TestCodexWarm|TestClaudeWarm'
  ./internal/provider/ ./internal/gui/: ok.
- WSL: go vet -tags nogui ./... is ok and gofmt -l is empty.
  go test -tags nogui -timeout 45m ./...: 75 packages ok, including
  internal/gui and internal/provider. internal/agent has 4 reds on the WSL
  box (TestInstalledVersion, TestGrokInstalled,
  TestCursorFolderFromTheEditorIsNotTheCLI, TestOmpDetectedWithPiDir). They
  are already filed as #4033 and #3548 (fake binaries hit WSL interop).
  internal/gateway has 1 red, TestUnroutedRequestShownThenAnswered: giveUp
  answers the 504 before it marks the route done. That is not this change,
  and it is filed as #4200.

At the head rebased on origin/main 9474eaf9c:
- mote: gofmt -l is empty. go vet passes for gui, provider and gateway,
  and GOOS=windows go vet passes for gui and provider. go test -run
  'WarmNow|Budget|Warm|I18n' ./internal/gui ./internal/provider: ok.
- WSL: warm-now, i18n-keys and warm-at-own GUI tests: 44/44.

Broken by hand (each was red, then restored and checked with cmp):
- WarmNow swallowing the Codex error: TestWarmNowSendsTheScheduledWarmUp
  went red on the refused request.
- Running Claude in ls[0]'s directory: TestWarmNowClaudeRunsClaudeCode
  went red.
- Dropping the lapsed check: TestWarmNowLapsedAccount went red.
- The menu always sending users[0]: warm-now.test.cjs went red (timed
  out) in both engines.

Not tried:
- A warm-up of a real account. The request-equality test compares
  against the scheduled warm-up's request through a fake vendor.
- Breaking the request-equality check by changing the body itself.
- The GUI suite on macOS, because mote's browsers hang (#4125).
2026-10-29 15:39:31 +08:00

160 lines
5.6 KiB
Go

package provider
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
)
// Warm up now sends a ChatGPT account the very request the scheduled
// warm-up sends, to that account alone and with the warm-ups off, and
// says why it failed.
func TestWarmNowSendsTheScheduledWarmUp(t *testing.T) {
signIn(t) // me@example.com, acct-1, lists gpt-5.5
rememberLogins(true)
var mu sync.Mutex
var bodies []map[string]any
var hdrs []http.Header
refuse := false
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()
switch r.URL.Path {
case "/backend-api/wham/usage":
// a week that hasn't started: nothing used, its reset a week off
json.NewEncoder(w).Encode(map[string]any{"plan_type": "plus", "rate_limit": map[string]any{
"primary_window": map[string]any{"used_percent": 0, "limit_window_seconds": 18000, "reset_after_seconds": 18000},
"secondary_window": map[string]any{"used_percent": 0, "limit_window_seconds": 604800, "reset_after_seconds": 604800}}})
case "/backend-api/codex/responses":
var m map[string]any
b, _ := io.ReadAll(r.Body)
json.Unmarshal(b, &m)
bodies, hdrs = append(bodies, m), append(hdrs, r.Header.Clone())
if refuse {
w.WriteHeader(http.StatusTooManyRequests)
io.WriteString(w, `{"detail":"usage limit reached"}`)
return
}
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, "event: response.completed\ndata: {\"type\":\"response.completed\"}\n\n")
default:
http.NotFound(w, r)
}
}))
defer fake.Close()
old := CodexBase
CodexBase = fake.URL + "/backend-api/codex"
t.Cleanup(func() { CodexBase = old })
sent := func() int { mu.Lock(); defer mu.Unlock(); return len(bodies) }
// the account as its name is typed, whatever its case
if err := WarmNow(context.Background(), "codex", "ME@example.com"); err != nil {
t.Fatalf("warm up now: %v", err)
}
if sent() != 1 {
t.Fatalf("%d requests, want 1", sent())
}
// the scheduled warm-up's own request, for the same account
w := codexWarmer{path: codexWarmPath(), now: time.Now, usage: codexWarmUsage, send: warmCodexLogin}
if rs := w.warmNow(context.Background(), "week", nil); len(rs) != 1 || rs[0].Err != "" {
t.Fatalf("scheduled: %+v", rs)
}
if sent() != 2 {
t.Fatalf("%d requests, want 2", sent())
}
now, scheduled := bodies[0], bodies[1]
if a, b := warmJSON(t, now), warmJSON(t, scheduled); a != b {
t.Fatalf("Warm up now sent\n%s\nthe scheduled warm-up sends\n%s", a, b)
}
if now["model"] != "gpt-5.5" || now["store"] != false || now["instructions"] == nil {
t.Fatalf("body: %v", now)
}
for _, h := range []string{"Authorization", "chatgpt-account-id", "originator", "User-Agent", "Content-Encoding"} {
if hdrs[0].Get(h) != hdrs[1].Get(h) {
t.Errorf("%s: %q, the scheduled warm-up sends %q", h, hdrs[0].Get(h), hdrs[1].Get(h))
}
}
// refused: the vendor's reason comes back
refuse = true
err := WarmNow(context.Background(), "codex", "me@example.com")
if err == nil || !strings.Contains(err.Error(), "429") || !strings.Contains(err.Error(), "usage limit reached") {
t.Fatalf("refused: %v", err)
}
// no such account, or no warm-up for the agent: nothing sent
n := sent()
if err := WarmNow(context.Background(), "codex", "other@example.com"); err == nil {
t.Fatal("warmed an account that isn't signed in")
}
if err := WarmNow(context.Background(), "copilot", "octocat"); err == nil {
t.Fatal("warmed a Copilot account")
}
if sent() != n {
t.Fatalf("%d requests for accounts that aren't there", sent()-n)
}
}
// A Claude account's Warm up now is Claude Code's run the scheduled
// warm-up makes (WarmClaudeVia), in that account's own config directory.
func TestWarmNowClaudeRunsClaudeCode(t *testing.T) {
_, side := claudeAuthFixture(t, "")
rememberLogins(true) // the one Claude Code is signed in to, listed beside it
old := claudeWarmSend
t.Cleanup(func() { claudeWarmSend = old })
claudeWarmSend = nil
if err := WarmNow(context.Background(), "claude", side.User); err == nil {
t.Fatal("warmed with no Claude Code to send it")
}
var mu sync.Mutex
var dirs []string
fail := error(nil)
WarmClaudeVia(func(_ context.Context, dir string) error {
mu.Lock()
defer mu.Unlock()
dirs = append(dirs, dir)
return fail
})
if err := WarmNow(context.Background(), "claude", side.User); err != nil {
t.Fatalf("saved account: %v", err)
}
if err := WarmNow(context.Background(), "claude", "own@example.com"); err != nil {
t.Fatalf("own account: %v", err)
}
if len(dirs) != 2 || dirs[0] == "" || dirs[1] != "" {
t.Fatalf("Claude Code run in %q, want the saved account's directory, then its own", dirs)
}
fail = errors.New("Claude Code: You've hit your session limit")
if err := WarmNow(context.Background(), "claude", "own@example.com"); err == nil || !strings.Contains(err.Error(), "session limit") {
t.Fatalf("failed run: %v", err)
}
}
// An account whose sign-in lapsed is sent nothing, and says so.
func TestWarmNowLapsedAccount(t *testing.T) {
_, side := claudeAuthFixture(t, "Failed to authenticate: OAuth token revoked")
old := claudeWarmSend
t.Cleanup(func() { claudeWarmSend = old })
ran := 0
WarmClaudeVia(func(context.Context, string) error { ran++; return nil })
err := WarmNow(context.Background(), "claude", side.User)
if err == nil || !strings.Contains(err.Error(), "signing in again") || ran != 0 {
t.Fatalf("lapsed: %v, %d runs", err, ran)
}
}
func warmJSON(t *testing.T, v any) string {
t.Helper()
b, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
return string(b)
}