peppa/packages/testkit/test/limits.test.ts
peppa-bot fd56afdbf3
Some checks failed
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 48с
peppa/build build: success за 35с
peppa/test test: failure за 1531с
peppa-ci / ci (pull_request) Failing after 27m42s
PEP-300: плашка лимита с прошедшим временем — не новый лимит
25.11.2026 три рабочие подписки получили отметку «лимит» на сутки вперёд.
Claude Code при лимите ждёт сброса сам («set to continue automatically at
6:50pm») и продолжает, плашка остаётся на экране. Вачдог читал её после
конца хода, в 18:51, и время без даты выходило завтрашним.

- passedReset (runner/limits.ts): время на плашке уже прошло (не больше
  4 часов назад, сегодня или вчера сразу после полуночи; полная дата в
  прошлом) — лимит за плашкой кончился.
- Вачдог по такой плашке подписку не помечает и агента не останавливает,
  событие usage_limit_passed раз на плашку; упавший процесс со старой
  плашкой в хвосте — сбой, а не лимит.
- parseResetTime не меняется: им читают свежие сообщения (хук, «Проверить»).
- Время в сообщениях о лимите — в поясе платформы (PEPPA_TZ), а не сервера.

Тесты: limits.test.ts (PEP-300) — падали до исправления.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-26 13:53:56 +05:00

290 lines
17 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, 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);
});
});
// PEP-300: 25.11.2026 three working subscriptions were marked «лимит» for a day. Claude Code waited
// for the reset itself («set to continue automatically at 6:50pm»), went on at 18:50, and the
// watchdog read the banner — still on the screen — at 18:51: «6:50pm» came out as tomorrow's reset.
describe("PEP-300: плашка лимита, время на которой уже прошло", () => {
const banner = "● Usage limit reached · set to continue automatically at 6:50pm";
const codexDated = "You’ve hit your usage limit. Try again at Nov 18th, 2026 9:13 PM.";
for (const [text, now, expected, why] of [
[banner, "2026-11-25T18:51:36", "2026-11-25T18:50:00", "the live case: read 96 s after the reset"],
[banner, "2026-11-25T18:30:00", null, "still ahead — a limit"],
[banner, "2026-11-25T22:49:00", "2026-11-25T18:50:00", "inside the window"],
[banner, "2026-11-25T22:51:00", null, "later than the window: the next day's reset, as before"],
["You've hit your 5-hour limit · resets 11:50pm (UTC)", "2026-11-26T00:01:00", "2026-11-25T23:50:00", "just after midnight — yesterday's time"],
["resets 1am", "2026-11-25T22:00:00", null, "across midnight, ahead"],
[codexDated, "2026-11-19T10:00:00", "2026-11-18T21:13:00", "a full date in the past"],
[codexDated, "2026-11-18T10:00:00", null, "a full date ahead"],
["resets in 2h 15m", "2026-11-25T18:51:00", null, "a relative time is always ahead"],
["limit reached", "2026-11-25T18:51:00", null, "no time in the text"],
] as const) {
test(`Прошло ли время сброса: «${text.slice(0, 48)}» в ${now.slice(11, 16)} — ${why}`, () => {
assert.equal(runner.passedReset(text, at(now))?.getTime() ?? null, expected ? at(expected).getTime() : null);
});
}
/** «6:50pm» for a moment — the way Claude Code prints a clock time. */
const clock = (d: Date) => d.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" }).replace(/\s/g, "").toLowerCase();
const count = (sid: number, type: string) => (db.$client.prepare("SELECT count(*) AS n FROM events WHERE session_id = ? AND type = ?").get(sid, type) as { n: number }).n;
const workingSub = async (name: string) => {
const sub = await core.createSubscription(db, { provider: "claude", name, authKind: "oauth" });
await core.updateSubscription(db, sub.id, { status: "active" });
return sub;
};
/** A live agent of the mock with `text` on its screen, running on a subscription. */
const agentWith = async (text: string, name: string) => {
const p = await project({ turns: [[{ say: text }, { say: "Продолжил после сброса лимита." }]] });
const sub = await workingSub(name);
const sid = await p.start();
db.$client.prepare("UPDATE sessions SET subscription_id = ? WHERE id = ?").run(sub.id, sid);
await waitFor("banner on screen", async () => (await runner.tmux.capturePane((await sess(sid)).tmuxName)).includes("Usage limit reached"));
return { p, sid, sub };
};
test("Claude сам дождался сброса и продолжил: подписка не помечена, агент не остановлен", async () => {
const sent = await superadmin();
const reset = new Date(Date.now() - 60_000);
reset.setSeconds(0, 0);
const { sid, sub } = await agentWith(`● Usage limit reached · set to continue automatically at ${clock(reset)}`, "Claude — mock-300 прошло");
await tick();
const s = await sess(sid);
assert.notEqual(s.status, "rate_limited", "the agent is not stopped");
assert.equal(s.resumeAt, null, "nothing to continue later");
const after = await core.getSubscription(db, sub.id);
assert.equal(after.status, "active", "the subscription is not marked «лимит» for a day");
assert.equal(after.limitedUntil, null);
assert.equal(count(sid, "usage_limit"), 0, "not a limit");
assert.equal(count(sid, "usage_limit_passed"), 1, "the journal says what was seen");
assert.equal(s.watchState?.limitGen, undefined, "the generation's fallback is kept for a real limit");
await tick();
assert.equal(count(sid, "usage_limit_passed"), 1, "noted once, not on every pass");
assert.equal((await sent()).length, 0, "nobody is told about a limit that is over");
await runner.stopSession(db, sid);
});
test("Время на плашке ещё впереди — лимит записан до этого времени, как раньше", async () => {
const reset = new Date(Date.now() + 2 * 3_600_000);
reset.setSeconds(0, 0);
const { sid, sub } = await agentWith(`● Usage limit reached · set to continue automatically at ${clock(reset)}`, "Claude — mock-300 впереди");
await tick();
assert.equal((await sess(sid)).status, "rate_limited");
const after = await core.getSubscription(db, sub.id);
assert.equal(after.status, "limited");
assert.equal(after.limitedUntil?.getTime(), reset.getTime(), "until the time on the banner, not a day later");
assert.equal(count(sid, "usage_limit"), 1);
assert.equal(count(sid, "usage_limit_passed"), 0);
await runner.stopSession(db, sid);
});
test("Время в сообщении о лимите — в поясе платформы, а не сервера", async () => {
const prev = process.env.PEPPA_TZ;
process.env.PEPPA_TZ = "Pacific/Kiritimati"; // UTC+14, no DST: never the zone the tests run in
try {
const p = await project({ turns: [] });
const sid = (await core.createSession(db, { projectId: (await core.getProject(db, p.key)).id })).id;
const text = await runner.recordLimit(db, await sess(sid), "Usage limit reached · continuing automatically at 6pm", at("2026-11-16T13:34:00"));
const want = (await sess(sid)).resumeAt!.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: "Pacific/Kiritimati" });
assert.match(text ?? "", new RegExp(`продолжит в ${want} сам`), "the people of the platform read their own time");
} finally {
if (prev === undefined) delete process.env.PEPPA_TZ;
else process.env.PEPPA_TZ = prev;
}
});
});
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, "--dangerously-bypass-approvals-and-sandbox");
assert.ok(!runner.CODEX_DEFAULT_MODE.includes("--full-auto"));
});
});