peppa/packages/testkit/test/limits.test.ts
Асель 1b2d784a64 PEP-150: merge main (PEP-163 project trash, PEP-171)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:31:30 +05:00

197 lines
11 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-56: the runner continues on its own after its usage limit resets.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { after, describe, test } from "node:test";
import { core, db, project, runner, superadmin, teardown, tick, waitFor } from "./helpers.ts";
after(teardown);
const at = (s: string) => new Date(s);
const sess = (id: number) => core.getSession(db, id);
const tickAt = (now: Date) => runner.tick(db, { intervalMs: 0, stallMs: 3_600_000, now });
const isPrompt = (needle: string) => (e: { ev: string; prompt?: unknown }) => e.ev === "prompt" && String(e.prompt).includes(needle);
describe("Время сброса лимита", () => {
// Scenario Outline: Форматы времени сброса (now = 2026-11-12 22:40 local)
const now = at("2026-11-12T22:40:00");
for (const [text, expected] of [
["resets 5pm", "2026-11-13T17:00:00"],
["resets at 3:10 AM", "2026-11-13T03:10:00"],
["resets in 2h 15m", "2026-11-13T00:55:00"],
["try again at 23:30", "2026-11-12T23:30:00"],
// PEP-166: Claude Code's newer banner — the time was not read, a 30-minute probe made the
// subscription look free again while it stayed limited until the evening.
["⏺ Usage limit reached · continuing automatically at 6pm · esc to cancel", "2026-11-13T18:00:00"],
["continuing automatically at 9:30 AM", "2026-11-13T09:30:00"],
["continuing work on the task", null],
["limit reached", null],
] as const) {
test(`Форматы времени сброса: «${text}»`, () => {
const r = runner.parseResetTime(text, now);
assert.equal(r?.getTime() ?? null, expected ? at(expected).getTime() : null);
});
}
test("PEP-166: баннер лимита из истории возобновлённого разговора — не новый лимит", () => {
const old = "⏺ Usage limit reached · continuing automatically at 6pm · esc to cancel";
const resumed = `> продолжай\n${old}\n⏺ Продолжаю работу над задачей…`;
assert.equal(runner.freshLimitLine(resumed, 1), null, "the old account's banner was there when the generation started");
assert.equal(runner.freshLimitLine(`${resumed}\n⏺ Usage limit reached · resets 9pm`, 1), "⏺ Usage limit reached · resets 9pm", "a new banner after it counts");
assert.equal(runner.freshLimitLine("⏺ Работаю…", 0), null);
assert.equal(runner.freshLimitLine(old, 0), old, "a generation that started clean sees its first banner");
});
test("Время сброса указано", async () => {
// PEP-150: a limit is not the owner's to fix — the superadmin is told, the owner is not asked.
const sent = await superadmin();
const p = await project({ turns: [[{ limit: { resetInSec: 120 } }], [{ say: "Продолжаю после лимита." }]] });
const sid = await p.start();
await p.waitStatus(sid, "rate_limited");
const s = await sess(sid);
assert.ok(s.resumeAt && s.resumeAt.getTime() > Date.now() + 60_000, "resume time = reset + grace");
assert.equal(s.limitProbeMin, null);
assert.match(await waitFor("superadmin told", async () => (await sent())[0]), /продолжит в \d\d:\d\d сам/);
assert.equal((await p.pending(sid)).length, 0, "no message for the owner");
// Сброс ещё не наступил
await tickAt(new Date(s.resumeAt!.getTime() - 60_000));
assert.equal((await sess(sid)).status, "rate_limited");
assert.ok(!p.log().some(isPrompt("Лимит сброшен")));
// Процесс агента жив
await tickAt(new Date(s.resumeAt!.getTime() + 1000));
await p.waitLog("nudged after reset", isPrompt("Лимит сброшен"));
const after = await sess(sid);
assert.equal(after.generation, 1, "same generation");
assert.equal(after.limitResumes, 1);
assert.equal((await p.pending(sid)).length, 0, "no new ping");
assert.equal((await sent()).length, 1, "one message for the superadmin");
await runner.stopSession(db, sid);
});
test("Процесс агента завершён", async () => {
const p = await project({ turns: [[{ limit: { resetInSec: 120 } }]], resumeTurns: [[{ say: "Вернулся." }]] });
const sid = await p.start();
await p.waitStatus(sid, "rate_limited");
const s = await sess(sid);
execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-session", "-t", `=${s.tmuxName}`]);
await tick(); // a dead/vanished rate-limited runner is not marked failed while it waits
assert.equal((await sess(sid)).status, "rate_limited");
await tickAt(new Date(s.resumeAt!.getTime() + 1000));
const start = await p.waitLog("relaunched", (e) => e.ev === "start" && e.gen === "2");
assert.equal(start.resume, s.conversationId, "continues the same conversation");
await runner.stopSession(db, sid);
});
});
describe("Неизвестное время сброса", () => {
test("Проба удалась, а при повторном лимите интервал растёт", async () => {
const sent = await superadmin();
const p = await project({ turns: [[{ limit: { reset: "unknown" } }], [{ limit: { reset: "unknown" } }], [{ say: "ok" }]] });
const sid = await p.start();
await p.waitStatus(sid, "rate_limited");
const s = await sess(sid);
assert.equal(s.limitProbeMin, 30);
assert.ok(Math.abs(s.resumeAt!.getTime() - (Date.now() + 30 * 60_000)) < 60_000);
assert.match(await waitFor("superadmin told", async () => (await sent())[0]), /время сброса неизвестно/);
await tickAt(new Date(s.resumeAt!.getTime() + 1000));
await p.waitLog("probe", isPrompt("Лимит сброшен"));
// Лимит ещё действует: the agent hits it again right away → next probe in 1 hour.
await waitFor("limited again", async () => (await sess(sid)).limitProbeMin === 60);
assert.equal((await sess(sid)).status, "rate_limited");
await runner.stopSession(db, sid);
});
});
describe("Защита от зацикливания", () => {
test("Предел достигнут", async () => {
const sent = await superadmin();
const p = await project({ turns: [[{ say: "работаю" }], [{ limit: { resetInSec: 120 } }]] });
const sid = await p.start();
await p.waitStatus(sid, "idle");
await core.updateSession(db, sid, { limitResumes: runner.MAX_LIMIT_RESUMES_PER_DAY, limitResumesDay: new Date().toLocaleDateString("sv-SE") });
await runner.sendToSession(db, sid, "дальше");
await p.waitStatus(sid, "rate_limited");
const s = await sess(sid);
assert.equal(s.resumeAt, null, "no more auto-resumes today");
assert.match(await waitFor("superadmin told", async () => (await sent()).find((t) => t.includes("нужны вы"))), /автопродолжений сегодня уже/);
assert.equal((await p.pending(sid)).length, 0, "the owner is not asked to press anything");
await runner.stopSession(db, sid);
});
test("Человек вмешался раньше", async () => {
const p = await project({ turns: [[{ limit: { resetInSec: 120 } }], [{ say: "ok" }], [{ say: "лишнее" }]] });
const sid = await p.start();
await p.waitStatus(sid, "rate_limited");
const due = (await sess(sid)).resumeAt!;
await runner.sendToSession(db, sid, "продолжай сейчас");
await p.waitLog("manual answer", isPrompt("продолжай сейчас"));
await tickAt(new Date(due.getTime() + 1000));
await new Promise((r) => setTimeout(r, 800));
assert.ok(!p.log().some(isPrompt("Лимит сброшен")), "watchdog sends nothing");
await runner.stopSession(db, sid);
});
});
describe("Новая фраза Claude (PEP-166)", () => {
// Scenario: Новая фраза Claude — подписка в лимите до вечера
test("Новая фраза Claude — подписка в лимите до вечера", async () => {
const p = await project({ turns: [] });
const sub = await core.createSubscription(db, { provider: "claude", name: "Claude — mock-asel", authKind: "oauth" });
await core.updateSubscription(db, sub.id, { status: "active" });
const sid = (await core.createSession(db, { projectId: (await core.getProject(db, p.key)).id, subscriptionId: sub.id })).id;
const now = at("2026-11-16T13:34:00");
const text = await runner.recordLimit(db, await sess(sid), "Usage limit reached · continuing automatically at 6pm", now);
const s = await sess(sid);
assert.equal(s.status, "rate_limited");
assert.equal(s.resumeAt?.getTime(), at("2026-11-16T18:01:00").getTime(), "continues at the reset time + grace");
assert.equal(s.limitProbeMin, null, "no 30-minute probe");
assert.match(text ?? "", /продолжит в 18:01 сам/);
const limited = await core.getSubscription(db, sub.id);
assert.equal(limited.status, "limited");
assert.equal(limited.limitedUntil?.getTime(), at("2026-11-16T18:00:00").getTime(), "limited until 18:00");
assert.equal(core.isUsable(limited, at("2026-11-16T14:04:00")), false, "still limited half an hour later");
assert.equal(core.isUsable(limited, at("2026-11-16T18:00:00")), true);
});
});
describe("Отключение", () => {
test("Выключено", async () => {
const p = await project({ turns: [] });
const sid = (await core.createSession(db, { projectId: (await core.getProject(db, p.key)).id })).id;
process.env.PEPPA_LIMIT_AUTORESUME = "off";
try {
const text = await runner.recordLimit(db, await sess(sid), "Usage limit reached, resets 5pm");
assert.equal((await sess(sid)).resumeAt, null);
assert.match(text ?? "", /упёрся в лимит/);
} finally {
delete process.env.PEPPA_LIMIT_AUTORESUME;
}
});
});
describe("Codex", () => {
test("banner with a time → watchdog continues the live agent after reset", async () => {
const p = await project({ turns: [[{ limit: { resetInSec: 120 } }], [{ say: "Codex продолжил." }]] });
const sid = await p.start({ provider: "codex" });
await p.waitLog("banner", (e) => e.ev === "limit");
const s = await waitFor("rate_limited", async () => {
await tick();
const x = await sess(sid);
return x.status === "rate_limited" && x;
});
assert.ok(s.resumeAt);
await tickAt(new Date(s.resumeAt!.getTime() + 1000));
await p.waitLog("codex nudged", isPrompt("Лимит сброшен"));
await runner.stopSession(db, sid);
});
});
describe("PEP-171: запуск Codex без удалённого флага", () => {
test("по умолчанию — без подтверждений и песочницы, флага --full-auto нет", () => {
assert.equal(runner.CODEX_DEFAULT_MODE, "--sandbox danger-full-access --ask-for-approval never");
assert.ok(!runner.CODEX_DEFAULT_MODE.includes("--full-auto"));
});
});