peppa/packages/testkit/test/limits.test.ts
Асель b5c0e704a5 PEP-150: сбои не идут пользователю — задержка на стороне платформы, одно сообщение суперадмину
platformDelay/sessionDelay вместо attention владельцу: падения и зависания агентов, лимиты,
красные и зависшие проверки, запуск агента, обновление версии, приёмка; guard конвейера —
вопрос суперадмину в платформенном проекте; строка задержки в задаче и на карточке;
список задержек на Главной суперадмина.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 14:09:30 +05:00

154 lines
7.7 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"],
["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 () => {
// 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("Отключение", () => {
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);
});
});