peppa/packages/testkit/test/project-pause.test.ts
2026-11-16 21:25:27 +05:00

180 lines
12 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-174: a project on pause — nothing happens: agents stop and do not start (board, dispatcher,
// watchdog restarts), the AI roles are not called, nobody gets notifications (Telegram, push,
// reminders); «Продолжить» resumes the stopped agents and what happened during the pause is not sent.
import assert from "node:assert/strict";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { after, afterEach, before, describe, test } from "node:test";
import { and, eq } from "drizzle-orm";
process.env.PEPPA_SECRET ??= "mock-secret-for-tests";
import { core, db, project, runner, setDefaultOwner, teardown, waitFor, type TestProject } from "./helpers.ts";
import { MockTelegram } from "../src/mock-telegram.ts";
const { events, pushOutbox, pushSubscriptions, telegramOutbox, users } = await import("@peppa/db");
const { createBot } = await import("@peppa/bot");
const { TelegramApi } = await import("@peppa/bot/telegram");
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
const TMP = mkdtempSync(join(tmpdir(), "peppa-pause-"));
const intakeScenario = join(TMP, "intake.json");
const intakeCalls = () => (existsSync(`${intakeScenario}.log.jsonl`) ? readFileSync(`${intakeScenario}.log.jsonl`, "utf8").trim().split("\n").filter(Boolean) : []);
const MIN = 60_000;
const NO_QUIET = { quietFrom: null, quietTo: null } as const;
const PM_CHAT = 17401;
type User = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let pm: User;
before(async () => {
process.env.PEPPA_INTAKE_BIN = join(ROOT, "packages/testkit/bin/mock-intake");
process.env.MOCK_INTAKE_SCENARIO = intakeScenario;
writeFileSync(intakeScenario, "{}");
pm = await core.upsertUserFromGitea(db, { id: 17401, login: "mock-pm-pause" }, { access_token: "x" });
await db.update(users).set({ telegramChatId: PM_CHAT, telegramUserId: PM_CHAT }).where(eq(users.id, pm.id));
pm = (await core.getUser(db, pm.id))!;
await core.savePushSubscription(db, pm.id, { endpoint: "https://push.example/mock-pause", keys: { p256dh: "BNcRdreALRFXTkOOUHK1EtK2wtaz5Ry4YfYCA_0QTpQtUbVlUls0VJXg7A8u-Ts1XbjhazAkj7I99e8QcYP7DkM", auth: "tBHItJI5svbpez7KI4CCXg" } });
setDefaultOwner(pm.id);
});
after(teardown);
afterEach(() => runner.setWatchdogSettings(db, ["reset"]));
const projectOf = (p: TestProject) => core.getProject(db, p.key);
const activeOf = async (projectId: number) => (await core.listSessions(db, { active: true })).filter((s) => s.projectId === projectId);
const tickAt = (now: Date) => runner.tick(db, { intervalMs: 0, stallMs: 3_600_000, now });
const outboxRows = async () => ({
telegram: (await db.select().from(telegramOutbox)).filter((r) => (r.params as { chat_id?: number }).chat_id === PM_CHAT).length,
push: (await db.select().from(pushOutbox).innerJoin(pushSubscriptions, eq(pushOutbox.subscriptionId, pushSubscriptions.id)).where(eq(pushSubscriptions.userId, pm.id))).length,
});
describe("Пауза проекта", () => {
test("Scenario: «Поставить на паузу» останавливает агентов, новые не запускаются; «Продолжить» возобновляет их и диспетчер снова берёт задачи", async () => {
const tp = await project({ turns: [[{ mcp: "update_task", args: { task: "1", status: "in_progress" } }, { say: "Работаю." }]], resumeTurns: [[{ say: "Продолжаю после паузы." }]] });
const p = await projectOf(tp);
const second = await core.createTask(db, { projectId: p.id, title: "вторая задача" });
const sid = await tp.start();
await tp.waitStatus(sid, "idle");
const r = await runner.pauseProject(db, p.id, pm.id);
assert.deepEqual(r, { stopped: 1, already: false });
assert.equal((await core.getSession(db, sid)).status, "done", "the live agent stopped");
assert.equal((await tp.task()).status, "in_progress", "the story stays at work");
assert.equal(await core.isProjectPaused(db, p.id), true);
assert.deepEqual(await runner.pauseProject(db, p.id, pm.id), { stopped: 0, already: true });
// Nothing starts: board, «Взять в работу», resume, dispatcher.
await assert.rejects(runner.moveTask(db, await core.resolveTask(db, second.key), "in_progress"), /Проект на паузе/);
assert.equal((await core.resolveTask(db, second.key)).task.status, "backlog", "the card did not move");
await assert.rejects(runner.startSession(db, second.key), /Проект на паузе/);
await assert.rejects(runner.resumeSession(db, sid), /Проект на паузе/);
await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET });
await runner.tick(db, { intervalMs: 0, stallMs: 600_000 });
assert.equal((await activeOf(p.id)).length, 0, "the dispatcher took nothing");
assert.equal((await core.resolveTask(db, second.key)).task.status, "backlog");
// «Продолжить»: the stopped agent continues the same story, the dispatcher takes stories again.
const res = await runner.resumeProject(db, p.id);
assert.deepEqual(res, { resumed: 1, was: true });
assert.equal(await core.isProjectPaused(db, p.id), false);
await tp.waitLog("resumed after the pause", (e) => e.ev === "prompt" && String(e.prompt).includes("на паузе"));
assert.equal((await activeOf(p.id)).map((s) => s.id).join(), String(sid), "the same agent is back");
await runner.stopSession(db, sid);
await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "done" });
await runner.tick(db, { intervalMs: 0, stallMs: 600_000 });
await waitFor("the dispatcher took the next story", async () => (await activeOf(p.id)).some((s) => s.taskKey === second.key));
for (const s of await activeOf(p.id)) await runner.stopSession(db, s.id);
const journal = await db.select().from(events).where(and(eq(events.projectId, p.id), eq(events.type, "project_resumed")));
assert.equal(journal.length, 1, "one line «Пауза: с … по …»");
await core.setAutonomy(db, p.id, { level: "manual" });
});
test("Scenario: на паузе вачдог не перезапускает упавшего агента; после «Продолжить» — перезапускает", async () => {
const tp = await project({ turns: [[{ crash: 1 }]], resumeTurns: [[{ say: "Поднялся." }]] });
await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "in_progress" });
const p = await projectOf(tp);
const sid = await tp.start();
await tp.waitLog("crashed", (e) => e.ev === "exit");
const t0 = new Date();
await waitFor("restart planned", async () => (await tickAt(t0), (await core.getSession(db, sid)).watchState?.restartAt));
await runner.pauseProject(db, p.id, pm.id);
await tickAt(new Date(t0.getTime() + 5 * MIN));
assert.equal((await core.getSession(db, sid)).status, "failed", "not restarted on pause");
assert.ok((await core.getSession(db, sid)).watchState?.restartAt, "the planned restart waits");
await runner.resumeProject(db, p.id);
await tickAt(new Date(t0.getTime() + 6 * MIN));
await tp.waitLog("restarted", (e) => e.ev === "prompt" && String(e.prompt).includes("перезапущен"));
await runner.stopSession(db, sid);
});
test("Scenario: агент, до которого не дошла остановка, останавливается вачдогом и возобновляется после «Продолжить»", async () => {
const tp = await project({ turns: [[{ say: "Работаю." }]], resumeTurns: [[{ say: "Снова в работе." }]] });
await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "in_progress" });
const p = await projectOf(tp);
const sid = await tp.start();
await tp.waitStatus(sid, "idle");
// Only the mark (the runner service was down when «Поставить на паузу» was pressed).
await core.setProjectPause(db, p.id, { since: Date.now(), by: pm.id, sessions: [] });
await runner.tick(db, { intervalMs: 0, stallMs: 600_000 });
assert.equal((await core.getSession(db, sid)).status, "done", "the watchdog stopped it");
assert.deepEqual((await core.getProjectPause(db, p.id))?.sessions, [sid], "remembered for «Продолжить»");
assert.deepEqual(await runner.resumeProject(db, p.id), { resumed: 1, was: true });
await runner.stopSession(db, sid);
});
test("Scenario: на паузе аналитик не вызывается — мок не получил запроса", async () => {
const ws = join(TMP, "intake");
mkdirSync(join(ws, ".peppa"), { recursive: true });
const p = await core.createProject(db, { slug: "mock-pause-intake", key: "PAI", name: "Intake", giteaOwner: "x", workspacePath: ws, ownerId: pm.id });
await core.setIntakeSettings(db, p.id, { enabled: true });
await core.createTask(db, { projectId: p.id, title: "Корзина", description: "Хочу складывать товары" });
await runner.pauseProject(db, p.id, pm.id);
await runner.intakeTick(db, { wait: true });
const r = await runner.claudePrint(db, p, { who: "Аналитик", bin: process.env.PEPPA_INTAKE_BIN!, model: "haiku", prompt: "x", timeoutMs: 5000 });
assert.equal(r.ok, false, "the last guard refuses too");
assert.equal(intakeCalls().length, 0, "the mock got no request");
await runner.resumeProject(db, p.id);
await runner.intakeTick(db, { wait: true });
assert.ok(intakeCalls().length > 0, "after «Продолжить» the analyst works again");
});
test("Scenario: на паузе ни одной записи в очередях Telegram и push, напоминания не уходят; накопленное после «Продолжить» не рассылается", async () => {
const tg = await new MockTelegram().start();
const bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 200, log: () => {} });
await bot.start();
try {
const tp = await project({ turns: [] });
const p = await projectOf(tp);
const ref = await core.resolveTask(db, tp.taskKey);
const t0 = new Date();
await runner.pauseProject(db, p.id, pm.id, t0);
const before = await outboxRows();
const q = await core.askPm(db, ref, { kind: "question", text: "Какой цвет кнопки?", options: ["Синий", "Зелёный"], msgType: "question", defaultOption: "Синий" });
await core.sendProjectMessage(db, p.id, "Агент переключился на другую подписку", `mock-pause:${p.id}`, { title: "x", url: "/" });
await runner.notifyPm(db, p.id, `mock-pause-notify:${p.id}`, "Задача закрыта автоматически");
// Forty minutes later a reminder would be due (remindMin 30).
await runner.remindTick(db, { now: new Date(Date.now() + 40 * MIN), cfg: await runner.getWatchdogSettings(db), log: () => {} });
await new Promise((r) => setTimeout(r, 800)); // a few reconcile rounds of the bot
assert.deepEqual(await outboxRows(), before, "nothing queued for the project");
assert.equal((await core.getQuestion(db, q.id)).reminders, 0, "no reminder");
assert.equal(tg.calls.filter((c) => c.params.chat_id === PM_CHAT).length, 0);
await runner.resumeProject(db, p.id);
await new Promise((r) => setTimeout(r, 800));
assert.equal(await core.duringPause(db, p.id, q.createdAt), true, "the question came up during the pause");
assert.equal(tg.calls.filter((c) => c.method === "sendMessage" && c.params.chat_id === PM_CHAT && String(c.params.text).includes("Какой цвет")).length, 0, "the question of the pause is not sent afterwards");
// A new question after «Продолжить» goes as usual.
const q2 = await core.askPm(db, ref, { kind: "question", text: "Какой шрифт?", options: ["Обычный", "Крупный"], msgType: "question", defaultOption: "Обычный" });
await waitFor("the new question reached Telegram", async () => tg.calls.some((c) => c.method === "sendMessage" && c.params.chat_id === PM_CHAT && String(c.params.text).includes("Какой шрифт")));
await core.answerQuestion(db, q2.id, "Обычный", "web");
} finally {
await bot.stop();
await tg.stop();
}
});
});