// PEP-205: Codex's usage limit, its «Switch to ?» 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 { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { eq } from "drizzle-orm"; import { schema } from "@peppa/db"; import { core, db, project, runner, setDefaultOwner, superadmin, teardown, waitFor } from "./helpers.ts"; process.env.PEPPA_SECRET = "mock-secret-for-tests"; type User = Awaited>; 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 ?»", () => { 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("PEP-241: экран доверия папке", () => { test("Экран Codex 0.171 о рабочей папке агента — сторож жмёт «Trust and continue», агент работает", async () => { const p = await project({ turns: [[{ trust: true }, { say: "Начал работу." }]] }); await atWork(p); const sid = await p.start({ provider: "codex" }); await waitFor("trust answered", async () => { await tickAt(new Date()); return p.log().find((e) => e.ev === "trust"); }); assert.equal(p.log().find((e) => e.ev === "trust")!.key, "1"); await p.waitLog("turn finished", (e) => e.ev === "turn_end"); const evs = await db.select().from(schema.events).where(eq(schema.events.sessionId, sid)); assert.ok(evs.some((e) => e.type === "trust_dismissed")); await runner.stopSession(db, sid); }); test("Вопрос о чужой папке — сторож ничего не нажимает", async () => { const p = await project({ turns: [[{ trust: { path: "/etc" } }, { say: "не должно" }]] }); await atWork(p); const sid = await p.start({ provider: "codex" }); await p.waitLog("trust screen", (e) => e.ev === "dialog"); for (let i = 0; i < 3; i++) await tickAt(new Date(Date.now() + i * 3 * MIN)); assert.equal(p.log().some((e) => e.ev === "trust"), false); const evs = await db.select().from(schema.events).where(eq(schema.events.sessionId, sid)); assert.ok(evs.some((e) => e.type === "trust_foreign")); await runner.stopSession(db, sid); }); test("Экран узнаётся: старый и новый текст, пути на экране", () => { const { codexTrustPrompt } = runner; assert.deepEqual(codexTrustPrompt(" Folder access\n\n Trust this folder?\n /w/s1\n\n› 1. Trust and continue\n 2. Back to Agent Command Center\n"), { digit: "1", paths: ["/w/s1"] }); assert.equal(codexTrustPrompt("Do you trust the contents of this directory?\n 1. Yes, continue\n 2. No, quit\n")!.digit, "1"); assert.equal(codexTrustPrompt("• Working on /w/s1"), null); }); test("Worktree: команда доверяет и папке, и корню основного репозитория; config.toml подписки дописывается один раз", () => { const base = mkdtempSync(join(tmpdir(), "pep241-")); const repo = join(base, "repo"); const wt = join(base, ".peppa", "wt"); mkdirSync(join(repo, ".git", "worktrees", "wt"), { recursive: true }); writeFileSync(join(repo, ".git", "worktrees", "wt", "commondir"), "../..\n"); mkdirSync(wt, { recursive: true }); writeFileSync(join(wt, ".git"), `gitdir: ${join(repo, ".git", "worktrees", "wt")}\n`); assert.deepEqual(runner.codexTrustRoots(wt), [wt, repo]); const cmd = buildCommand("codex", { sessionId: 1, generation: 1, cwd: wt, prompt: "p", rules: "r" }); assert.ok(cmd.includes(`projects.${JSON.stringify(wt)}.trust_level="trusted"`)); assert.ok(cmd.includes(`projects.${JSON.stringify(repo)}.trust_level="trusted"`)); const home = join(base, "codex"); mkdirSync(home); writeFileSync(join(home, "config.toml"), 'model = "gpt-5"'); assert.deepEqual(runner.trustCodexFolders(home, [wt, repo]), [wt, repo]); assert.deepEqual(runner.trustCodexFolders(home, [wt, repo]), []); const toml = readFileSync(join(home, "config.toml"), "utf8"); assert.match(toml, /^model = "gpt-5"\n/); assert.equal(toml.split(`[projects.${JSON.stringify(wt)}]`).length, 2); assert.match(toml, /trust_level = "trusted"/); }); }); 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"); }); });