peppa/packages/testkit/test/codex-recovery.test.ts

167 lines
9.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-205: Codex's usage limit, its «Switch to <model>?» menu and its sign-in hiccup do not
// make the watchdog think the agent hung or crashed.
import assert from "node:assert/strict";
import { after, before, describe, test } from "node:test";
import { core, db, project, runner, setDefaultOwner, superadmin, teardown, waitFor } from "./helpers.ts";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
type User = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let pm: User;
before(async () => {
pm = await core.upsertUserFromGitea(db, { id: 205, login: "mock-pm-205" }, { access_token: "x" });
setDefaultOwner(pm.id);
});
after(teardown);
const { buildCommand } = await import("../../runner/src/providers.ts");
const MIN = 60_000;
const sess = (id: number) => core.getSession(db, id);
const tickAt = (now: Date) => runner.tick(db, { intervalMs: 0, stallMs: 3_600_000, now });
const codexSub = (name: string, tag: string) => runner.addSubscription(db, { provider: "codex", name, method: "api_key", secret: `mock-openai-key-${tag}`, createdBy: pm.id });
let seq = 0;
const poolFor = async (key: string, ids: number[]) => {
const pool = await core.createPool(db, { name: `Пул 205-${++seq}`, subscriptionIds: ids });
await core.setProjectPool(db, (await core.getProject(db, key)).id, pool.id);
};
const atWork = async (p: { taskKey: string }) => core.updateTask(db, await core.resolveTask(db, p.taskKey), { status: "in_progress" });
describe("Фразы лимита Codex", () => {
const real = "■ You’ve hit your usage limit. Upgrade to Pro (https://chatgpt.com/explore/pro), visit https://chatgpt.com/settings/usage to purchase more credits or try again at 8:47 PM.";
test("Настоящая фраза с типографским апострофом узнаётся", () => {
assert.ok(runner.LIMIT_SCREEN_RE.test(real));
assert.ok(runner.LIMIT_SCREEN_RE.test("■ You've hit your usage limit."));
assert.equal(runner.limitLines(`> работа\n${real}\n Approaching rate limits`).length, 1);
});
test("«try again at 8:47 PM» — сегодня вечером; дата с днём — по дате", () => {
const now = new Date("2026-11-17T18:00:00");
assert.equal(runner.parseResetTime(real, now)?.getTime(), new Date("2026-11-17T20:47:00").getTime());
assert.equal(runner.parseResetTime("You’ve hit your usage limit. Try again at Nov 18th, 2026 9:13 PM.", now)?.getTime(), new Date("2026-11-18T21:13:00").getTime());
});
test("«less than 5% of your 5h limit left» — предупреждение, не остановка", () => {
assert.equal(runner.LIMIT_SCREEN_RE.test("Heads up, you have less than 5% of your 5h limit left. Run /status for a breakdown."), false);
});
});
describe("Лимит Codex: пауза до сброса, перезапуски не тратятся", () => {
test("Экран лимита — агент ждёт сброса, а не «завис»", async () => {
const sent = await superadmin();
const p = await project({ turns: [[{ limit: { resetInSec: 600 } }]] });
await atWork(p);
const sid = await p.start({ provider: "codex" });
await waitFor("rate limited", async () => {
await tickAt(new Date());
return (await sess(sid)).status === "rate_limited";
});
const s = await sess(sid);
assert.ok(s.resumeAt && s.resumeAt.getTime() > Date.now() + 5 * MIN, "continues after the reset");
assert.deepEqual(s.watchState?.restarts ?? [], [], "no automatic restart spent");
assert.equal((await p.pending(sid)).length, 0, "nothing for the owner");
assert.ok((await waitFor("superadmin told", async () => (await sent())[0])).length > 0);
await tickAt(new Date(Date.now() + 3 * MIN));
assert.equal((await sess(sid)).status, "rate_limited", "still waiting");
await runner.stopSession(db, sid);
});
test("Есть вторая подписка в наборе — агент переезжает", async () => {
const c1 = await runner.addSubscription(db, { provider: "codex", name: "Codex 205a", method: "api_key", secret: "mock-limit-key-205a", createdBy: pm.id });
const c2 = await codexSub("Codex 205b", "205b");
const p = await project({ turns: [[{ limit: { resetInSec: 3600, credential: "limit" } }, { say: "Начал заново." }]] });
await poolFor(p.key, [c1.id, c2.id]);
await atWork(p);
const sid = await p.start({ provider: "codex" });
await waitFor("moved", async () => {
await tickAt(new Date());
return (await sess(sid)).subscriptionId === c2.id;
});
assert.deepEqual((await sess(sid)).watchState?.restarts ?? [], []);
await runner.stopSession(db, sid);
});
});
describe("Владелец на лимите", () => {
test("Одна строка со временем и советом, без текста из терминала", async () => {
const c1 = await codexSub("Codex 205 owner", "limit-205o");
const p = await project({ turns: [[{ limit: { resetInSec: 1800 } }]] });
await poolFor(p.key, [c1.id]);
await atWork(p);
const sid = await p.start({ provider: "codex" });
const { stripAsIs } = await import("@peppa/shared/i18n");
const owned = async () => (await core.pendingQuestions(db, (await core.getProject(db, p.key)).id)).filter((q) => q.sessionId === sid || q.taskId != null);
await waitFor("owner told", async () => {
await tickAt(new Date());
return (await owned()).length;
});
const all = await owned();
const text = all.map((q) => stripAsIs(q.text)).join("\n");
assert.match(text, /[Аа]генты продолжат в \d\d:\d\d\. Чтобы не ждать, добавьте вторую подписку/);
assert.doesNotMatch(text, /usage limit|Try again|■/i, "nothing from the terminal");
assert.equal(all.length, 1, "one line");
await runner.stopSession(db, sid);
});
});
describe("Меню «Switch to <model>?»", () => {
test("Сторож выбирает «Keep current model», агент продолжает", async () => {
const p = await project({ turns: [[{ menu: { afterLimit: false } }, { say: "Продолжил после меню." }]] });
await atWork(p);
const sid = await p.start({ provider: "codex" });
await waitFor("menu answered", async () => {
await tickAt(new Date());
return p.log().find((e) => e.ev === "menu");
});
assert.equal(p.log().find((e) => e.ev === "menu")!.key, "2", "keep the current model");
await p.waitLog("turn finished", (e) => e.ev === "turn_end");
assert.equal(p.log().some((e) => e.ev === "menu" && e.key === "1"), false);
await runner.stopSession(db, sid);
});
test("Codex запускается с настройкой, прячущей меню", () => {
const cmd = buildCommand("codex", { sessionId: 1, generation: 1, cwd: "/w", prompt: "p", rules: "r" }).join(" ");
assert.match(cmd, /notice\.hide_rate_limit_model_nudge=true/);
});
});
describe("Сбой входа «account/read failed»", () => {
test("Три повтора с растущей паузой без расхода перезапусков; потом подписка помечена, суперадмину одно сообщение", async () => {
const sent = await superadmin();
const c1 = await codexSub("Codex 205 вход", "205login");
const p = await project({ turns: [[{ loginFail: true }]], resumeTurns: [[{ loginFail: true }]] });
await poolFor(p.key, [c1.id]);
await atWork(p);
const sid = await p.start({ provider: "codex" });
const t0 = Date.now();
const failed = async (n: number) => waitFor(`failure ${n}`, async () => {
await tickAt(new Date(t0 + 0));
return (await sess(sid)).watchState?.loginFails === n ? await sess(sid) : null;
});
let s = await failed(1);
assert.equal(s.status, "failed");
assert.ok(s.watchState!.restartAt! - t0 < 2 * MIN && s.watchState!.restartAt! - t0 > 0, "first retry in a minute");
assert.equal(s.watchState!.restartFree, true);
assert.deepEqual(s.watchState?.restarts ?? [], [], "automatic restarts untouched");
for (const [n, wait] of [[2, 1], [3, 5]] as const) {
const at = s.watchState!.restartAt!;
await tickAt(new Date(at + 1000));
await waitFor(`restarted ${n}`, async () => p.log().filter((e) => e.ev === "start").length >= n);
s = await (async () => waitFor(`failure ${n}`, async () => {
await tickAt(new Date(at + 2000));
const x = await sess(sid);
return x.watchState?.loginFails === n ? x : null;
}))();
assert.ok(s.watchState!.restartAt! - (at + 2000) >= (wait === 1 ? 4 : 14) * MIN - 5000, `pause grows (${n})`);
assert.deepEqual(s.watchState?.restarts ?? [], []);
}
const at = s.watchState!.restartAt!;
await tickAt(new Date(at + 1000));
await waitFor("fourth start", async () => p.log().filter((e) => e.ev === "start").length >= 4);
await waitFor("subscription marked", async () => {
await tickAt(new Date(at + 2000));
return (await core.getSubscription(db, c1.id)).status === "auth_error";
});
const msgs = (await sent()).filter((x) => x.includes("проблема со входом"));
assert.equal(msgs.length, 1, "one message for the superadmin");
await tickAt(new Date(at + 3000));
assert.equal((await sent()).filter((x) => x.includes("проблема со входом")).length, 1, "and not more");
});
});