Limit marks the subscription «лимит до …»; the watchdog relaunches the session on another usable subscription of the same provider (Claude/OpenCode resume the conversation, Codex starts afresh), threshold banner switches after the turn, max 3 switches/hour, simple fairness between projects, subscription_switched events + Telegram message, web shows subscription and switch history. Migration 0004 (sessions.rotate_reason). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
148 lines
7.3 KiB
TypeScript
148 lines
7.3 KiB
TypeScript
// 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");
|
||
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);
|
||
});
|
||
});
|