peppa/packages/testkit/test/limits.test.ts
Асель 685810eb80 PEP-56: runner continues on its own after the usage limit resets
- parseResetTime: 'resets 5pm', 'resets at 3:10 AM', 'resets in 2h 15m',
  'try again at 23:30'; nearest future time, local clock
- recordLimit (hook StopFailure and the watchdog's banner path): status
  rate_limited, resume_at = reset + 60 s, or probes 30 → 60 → 120 min when
  unknown or the limit came back right after a resume; cap 6/day;
  PEPPA_LIMIT_AUTORESUME=off; PM is told 'continues at HH:MM'
- watchdog: at resume_at nudges the live agent or relaunches it with
  resume (vanished/dead rate-limited runners wait instead of failing); the
  limit message is closed as resolved; tick(db, { now }) for tests
- mocks: limit with resetInSec / unknown reset (claude and codex)
- tests: one per spec scenario + Codex (82 e2e total, green)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 03:50:58 +05:00

147 lines
7.3 KiB
TypeScript
Raw Permalink 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, 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"],
["limit reached", null],
] as const) {
test(`Форматы времени сброса: «${text}»`, () => {
const r = runner.parseResetTime(text, now);
assert.equal(r?.getTime() ?? null, expected ? at(expected).getTime() : null);
});
}
test("Время сброса указано", async () => {
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);
const q = await p.waitQuestion(sid, "attention");
assert.match(q.text, /продолжит в \d\d:\d\d сам/);
// Сброс ещё не наступил
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 core.getQuestion(db, q.id)).answeredVia, "system", "limit message closed, no new ping");
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 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 p.waitQuestion(sid, "attention")).text, /время сброса неизвестно/);
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 p = await project({ turns: [[{ say: "работаю" }], [{ limit: { resetInSec: 120 } }]] });
const sid = await p.start();
await p.waitQuestion(sid, "attention");
await core.updateSession(db, sid, { limitResumes: runner.MAX_LIMIT_RESUMES_PER_DAY, limitResumesDay: new Date().toLocaleDateString("sv-SE") });
await runner.answerAndDeliver(db, (await p.waitQuestion(sid, "attention")).id, "дальше", "web");
await p.waitStatus(sid, "rate_limited");
const s = await sess(sid);
assert.equal(s.resumeAt, null, "no more auto-resumes today");
assert.match((await p.waitQuestion(sid, "attention")).text, /нужен ты/);
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.answerAndDeliver(db, (await p.waitQuestion(sid, "attention")).id, "продолжай сейчас", "web");
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("Отключение", () => {
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");
await new Promise((r) => setTimeout(r, 300));
await tick();
const s = await sess(sid);
assert.equal(s.status, "rate_limited");
assert.ok(s.resumeAt);
await tickAt(new Date(s.resumeAt!.getTime() + 1000));
await p.waitLog("codex nudged", isPrompt("Лимит сброшен"));
await runner.stopSession(db, sid);
});
});