peppa/packages/testkit/test/bot.test.ts
2026-11-18 18:02:09 +05:00

407 lines
24 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.

// Telegram journeys: the real bot against mock-telegram, with mock agents in tmux.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { after, before, describe, test } from "node:test";
// helpers must load first: it sets the isolated test env that runner modules read on load.
import { core, db, project, runner, setDefaultOwner, teardown, tick, waitFor } from "./helpers.ts";
import { MockTelegram, type MockTgMessage } from "../src/mock-telegram.ts";
import { MockTranscribe } from "../src/mock-transcribe.ts";
import type { Bot } from "@peppa/bot";
const { createBot } = await import("@peppa/bot");
const { TelegramApi } = await import("@peppa/bot/telegram");
const tg = await new MockTelegram().start();
const PM = { id: 501, chatId: 501, username: "pm" };
const STRANGER = { id: 777, chatId: 777, username: "stranger" };
const BOB = { id: 888, chatId: 888, username: "bob" };
let bot: Bot;
let pmUser: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let bobUser: typeof pmUser;
process.env.PEPPA_SECRET = "mock-secret-for-tests";
before(async () => {
pmUser = await core.upsertUserFromGitea(db, { id: 61, login: "mock-pm" }, { access_token: "x" });
bobUser = await core.upsertUserFromGitea(db, { id: 62, login: "mock-bob" }, { access_token: "y" });
setDefaultOwner(pmUser.id); // every project below belongs to the PM
bot = createBot({
db,
api: new TelegramApi(tg.token, tg.url),
secret: tg.token,
webUrl: "http://peppa.test",
pollTimeoutSec: 1,
outboxIntervalMs: 100,
reconcileIntervalMs: 400,
});
await bot.start();
});
after(async () => {
await bot.stop();
await tg.stop();
await teardown();
});
const isPrompt = (needle: string) => (e: { ev: string; prompt?: unknown }) => e.ev === "prompt" && String(e.prompt).includes(needle);
/** Waits for the bot message about a question (sent to the PM's chat). */
async function messageFor(questionId: number): Promise<MockTgMessage> {
const q = await waitFor(`telegram message for question #${questionId}`, async () => {
const row = await core.getQuestion(db, questionId);
return row.telegramMessageId ? row : null;
});
return tg.messages.get(q.telegramMessageId!)!;
}
const lastReplyTo = (chatId: number) => tg.botMessages(chatId).at(-1);
describe("pairing", () => {
test("only the /start code holder gets bound; strangers are ignored", async () => {
tg.userSends(STRANGER, "/status");
tg.userSends(PM, "/start wrong-code");
await waitFor("wrong code reply", async () => tg.botMessages(PM.chatId).some((m) => /неверный или истёк/.test(m.text)));
assert.equal(tg.botMessages(STRANGER.chatId).length, 0);
const code = await core.createPairingCode(db, tg.token, pmUser.id);
tg.userSends(PM, `/start ${code}`);
await waitFor("paired", async () => tg.botMessages(PM.chatId).some((m) => /Привязано/.test(m.text)));
assert.equal((await core.getUser(db, pmUser.id))?.telegramChatId, PM.chatId);
// The code is single-use; a stranger can't take over with it.
tg.userSends(STRANGER, `/start ${code}`);
await waitFor("stranger refused", async () => tg.botMessages(STRANGER.chatId).some((m) => /неверный/.test(m.text)));
assert.equal((await core.getUser(db, pmUser.id))?.telegramUserId, PM.id);
assert.equal((await core.telegramUser(db, STRANGER.chatId, STRANGER.id)), null);
tg.userSends(PM, "/status");
await waitFor("status", async () => tg.botMessages(PM.chatId).some((m) => /Агентов за работой/.test(m.text)));
});
});
describe("answering from Telegram", () => {
test("question with options: button press reaches the agent, message is closed", async () => {
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"], default: "Postgres" } }, { say: "Жду." }], [{ say: "Ок." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "question");
const m = await messageFor(q.id);
assert.match(m.text, /Какую БД взять/);
assert.match(m.text, new RegExp(p.taskKey));
assert.deepEqual(m.reply_markup!.inline_keyboard.map((r) => r[0]!.text), ["Postgres", "SQLite"]);
const cb = tg.userClicks(PM, m.message_id, `q:${q.id}:o0`);
await p.waitLog("answer delivered", isPrompt(`Ответ PM на вопрос #${q.id}: Postgres`));
await waitFor("toast", async () => tg.callbackAnswers.find((a) => a.id === cb && /Отправлено/.test(a.text ?? "")));
await waitFor("message closed", async () => /Ответ в Telegram: <b>Postgres<\/b>/.test(m.text) && m.reply_markup?.inline_keyboard.length === 0);
await runner.stopSession(db, sid);
});
test("approve button moves the task to in_progress", async () => {
const p = await project({ turns: [[{ mcp: "request_approval", args: { task: "1", summary: "План: сделать X. Риски: нет." } }], [{ say: "Делаю." }]] });
// PEP-94: approval is a project setting now (off by default).
await core.setAutonomy(db, (await core.getProject(db, p.key)).id, { proposal: "pm" });
const sid = await p.start();
const q = await p.waitQuestion(sid, "approval");
const m = await messageFor(q.id);
tg.userClicks(PM, m.message_id, `q:${q.id}:approve`);
await p.waitLog("approval delivered", isPrompt("одобрил proposal"));
assert.equal((await p.task()).status, "in_progress");
await runner.stopSession(db, sid);
});
test("reply with a comment rejects the proposal", async () => {
const p = await project({ turns: [[{ mcp: "request_approval", args: { task: "1", summary: "План Б для проверки реплая." } }], [{ say: "Переделываю." }]] });
// PEP-94: approval is a project setting now (off by default).
await core.setAutonomy(db, (await core.getProject(db, p.key)).id, { proposal: "pm" });
const sid = await p.start();
const q = await p.waitQuestion(sid, "approval");
const m = await messageFor(q.id);
tg.userSends(PM, "нет, без новых зависимостей", m.message_id);
await p.waitLog("rejection delivered", isPrompt("без новых зависимостей"));
assert.equal((await p.task()).status, "proposing");
await waitFor("ack reply", async () => tg.botMessages(PM.chatId).some((x) => x.reply_to && x.text.includes("Отправлено")));
await runner.stopSession(db, sid);
});
test("permission buttons answer the waiting hook", async () => {
const p = await project({ turns: [[{ permission: { tool: "Bash", input: { command: "npm publish" } } }, { say: "Опубликовал." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "permission");
const m = await messageFor(q.id);
assert.match(m.text, /npm publish/);
tg.userClicks(PM, m.message_id, `q:${q.id}:always`);
const e = await p.waitLog("hook decision", (x) => x.ev === "permission");
assert.equal(e.via, "hook");
assert.equal(e.behavior, "allow");
assert.equal(e.updatedPermissions, true);
await runner.stopSession(db, sid);
});
test("free-text reply to a 'session is waiting' alert is typed into the session", async () => {
const p = await project({ turns: [[{ say: "Сделал черновик. Что дальше?" }], [{ say: "Понял." }]] });
const sid = await p.start();
await p.waitStatus(sid, "idle");
// PEP-149: the end of a turn asks nobody — a message of the factory stands in for the old alert.
const q = await core.raiseSessionQuestion(db, await p.session(sid), "attention", "Сделал черновик. Что дальше?");
const m = await messageFor(q.id);
assert.match(m.text, /Что дальше/);
tg.userSends(PM, "добавь тесты\nи README", m.message_id);
const e = await p.waitLog("reply delivered", isPrompt("добавь тесты"));
assert.equal(e.prompt, "добавь тесты\nи README");
await runner.stopSession(db, sid);
});
});
describe("several users", () => {
test("questions go only to people with access; a member gets them too; foreign buttons do nothing", async () => {
tg.userSends(BOB, `/start ${await core.createPairingCode(db, tg.token, bobUser.id)}`);
await waitFor("bob paired", async () => (await core.getUser(db, bobUser.id))?.telegramChatId === BOB.chatId);
// PM's project: Bob has no access.
const mine = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Секрет проекта PM?", options: ["Да", "Нет"], default: "Да" } }], [{ say: "Ок." }]] });
const sid = await mine.start();
const q = await mine.waitQuestion(sid, "question");
const m = await messageFor(q.id);
assert.equal(m.chat_id, PM.chatId);
await new Promise((r) => setTimeout(r, 1200));
assert.ok(!tg.botMessages(BOB.chatId).some((x) => /Секрет проекта PM/.test(x.text)), "Bob must not see it");
const cb = tg.userClicks(BOB, m.message_id, `q:${q.id}:o0`);
await waitFor("refused", async () => tg.callbackAnswers.find((a) => a.id === cb && /не найден|Нет доступа/.test(a.text ?? "")));
assert.equal((await core.getQuestion(db, q.id)).answeredAt, null);
// Bob becomes a member: the open question reaches him too, and his answer closes both messages.
await core.addMember(db, await core.getProject(db, mine.key), "mock-bob", pmUser.id);
const bobMsg = await waitFor("bob gets the question", async () => tg.botMessages(BOB.chatId).find((x) => /Секрет проекта PM/.test(x.text)));
tg.userClicks(BOB, bobMsg.message_id, `q:${q.id}:o1`);
await mine.waitLog("member's answer delivered", isPrompt(`Ответ PM на вопрос #${q.id}: Нет`));
await waitFor("closed for both", async () => /Ответ в Telegram/.test(m.text) && /Ответ в Telegram/.test(bobMsg.text));
await runner.stopSession(db, sid);
// /status is scoped to the user's projects.
tg.userSends(BOB, "/status");
await waitFor("bob status", async () => tg.botMessages(BOB.chatId).some((x) => /Агентов за работой: 0/.test(x.text)));
});
});
describe("review", () => {
test("ready-for-review message: Accept closes the task", async () => {
const p = await project({ turns: [[{ mcp: "update_task", args: { task: "1", status: "review", pr_url: "https://git.example/pr/9" } }, { say: "PR открыт." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "attention");
const m = await messageFor(q.id);
assert.match(m.text, /Готово к ревью/);
const accept = m.reply_markup!.inline_keyboard.flat().find((b) => b.callback_data === `q:${q.id}:accept`);
assert.ok(accept, "accept button");
const cb = tg.userClicks(PM, m.message_id, accept.callback_data!);
await waitFor("accepted toast", async () => tg.callbackAnswers.find((a) => a.id === cb && /принята/.test(a.text ?? "")));
assert.equal((await p.task()).status, "done");
await p.waitStatus(sid, "done");
await waitFor("message closed", async () => /Принято/.test(m.text));
});
});
describe("staleness and reliability", () => {
test("answered in the terminal: Telegram message is closed and old buttons do nothing", async () => {
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Порт сервиса?", options: ["8080", "3000"], default: "8080" } }], [{ say: "Ок." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "question");
const m = await messageFor(q.id);
await runner.sendToSession(db, sid, "порт 9000", { person: true });
await waitFor("closed as answered in terminal", async () => /Ответ в терминале/.test(m.text));
const cb = tg.userClicks(PM, m.message_id, `q:${q.id}:o0`);
await waitFor("stale toast", async () => tg.callbackAnswers.find((a) => a.id === cb && /Уже отвечено/.test(a.text ?? "")));
assert.equal(p.log().filter((e) => e.ev === "prompt").length, 2, "no extra prompt from the stale button");
await runner.stopSession(db, sid);
});
test("an update re-delivered after a restart is not replayed", async () => {
const p = await project({ turns: [[{ say: "Жду указаний." }], [{ say: "Ок." }], [{ say: "лишний ход" }]] });
const sid = await p.start();
await p.waitStatus(sid, "idle");
// PEP-149: the end of a turn asks nobody — a message of the factory stands in for the old alert.
const q = await core.raiseSessionQuestion(db, await p.session(sid), "attention", "Жду указаний.");
const m = await messageFor(q.id);
const updateId = tg.userSends(PM, "сделай раз", m.message_id);
await p.waitLog("delivered once", isPrompt("сделай раз"));
// Simulate a crash before the offset was saved: Telegram sends the update again.
await core.setOffset(db, updateId);
await new Promise((r) => setTimeout(r, 2500));
assert.equal(p.log().filter(isPrompt("сделай раз")).length, 1);
await runner.stopSession(db, sid);
});
test("outbox retries after 429 (retry_after) and 5xx", async () => {
tg.failNext("sendMessage", 429, 1);
tg.failNext("sendMessage", 500);
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Проверка ретраев?", options: ["Да", "Нет"], default: "Да" } }], [{ say: "Ок." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "question");
const m = await messageFor(q.id);
assert.match(m.text, /Проверка ретраев/);
const row = await core.getOutbox(db, `q:${q.id}:${PM.chatId}`);
assert.ok(row && row.attempts >= 2, `expected retries, got ${row?.attempts}`);
await runner.stopSession(db, sid);
});
test("crash alert offers Resume; the button relaunches the session", async () => {
const { users } = await import("@peppa/db");
const { eq } = await import("drizzle-orm");
const [pm] = await db.select().from(users).where(eq(users.telegramChatId, PM.chatId));
const admins = await core.getSetting<string[]>(db, "platform.admins");
await core.setPlatformAdmins(db, [pm!.login]);
const p = await project({ turns: [[{ crash: 7 }]], resumeTurns: [[{ say: "Поднялся после падения." }]] });
const sid = await p.start();
await p.waitLog("crashed", (e) => e.ev === "exit");
await waitFor("failed", async () => {
await tick();
return (await p.session(sid)).status === "failed";
});
// PEP-150: the crash goes to the superadmin (here the PM is one), not to the owner as a question.
assert.equal((await p.pending(sid)).length, 0, "no question for the owner");
const m = await waitFor("crash message", async () => tg.botMessages(PM.chatId).find((x) => /код 7/.test(x.text)));
const resume = m.reply_markup!.inline_keyboard[0]!.find((b) => b.callback_data === `s:${sid}:resume`);
assert.ok(resume, "resume button");
const cb = tg.userClicks(PM, m.message_id, resume.callback_data!);
await waitFor("resumed toast", async () => tg.callbackAnswers.find((a) => a.id === cb && /Агент продолжил работу/.test(a.text ?? "")));
await p.waitLog("gen 2 running", (e) => e.ev === "turn_end" && e.gen === "2");
await core.setPlatformAdmins(db, admins);
await runner.stopSession(db, sid);
});
test("tmux killed while waiting: answer is saved, PM told the session is down", async () => {
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Что с API?", options: ["Да", "Нет"], default: "Да" } }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "question");
const m = await messageFor(q.id);
execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-session", "-t", `=${(await p.session(sid)).tmuxName}`]);
tg.userSends(PM, "используй v2", m.message_id);
await waitFor("down notice", async () => lastReplyTo(PM.chatId)?.text.includes("Агент сейчас не работает"));
assert.equal((await core.getQuestion(db, q.id)).answer, "используй v2");
});
});
// PEP-45, spec telegram-notifications: «Стори из сообщения боту».
describe("Стори из сообщения боту", () => {
const botMsg = (re: RegExp) => waitFor(`bot message ${re}`, async () => tg.botMessages(PM.chatId).filter((m) => re.test(m.text)).at(-1));
const button = (m: MockTgMessage, re: RegExp) => {
const b = m.reply_markup?.inline_keyboard.flat().find((x) => re.test(x.text));
assert.ok(b, `button ${re} in ${JSON.stringify(m.reply_markup)}`);
return b.callback_data!;
};
const storyByTitle = async (projectKey: string, title: string) => {
const proj = await core.getProject(db, projectKey);
return (await core.listTasks(db, { projectId: proj.id })).find((t) => t.title === title);
};
test("Scenario: Текст с проектом — «Создать», стори в бэклоге, предложение взять в работу", async () => {
const p = await project({ turns: [] });
tg.userSends(PM, `в ${p.key}: добавить экспорт в CSV`);
const ask = await botMsg(new RegExp(`Новая задача в <b>${p.key}</b>: «добавить экспорт в CSV»`));
assert.equal(await storyByTitle(p.key, "добавить экспорт в CSV"), undefined, "nothing is created before the button");
tg.userClicks(PM, ask.message_id, button(ask, new RegExp(`Создать в ${p.key}`)));
await waitFor("created", async () => /Создал <b>/.test(ask.text));
const t = await storyByTitle(p.key, "добавить экспорт в CSV");
assert.ok(t);
assert.equal(t.status, "backlog");
assert.match(t.description!, /Создано из Telegram \(mock-pm\)/);
assert.match(ask.text, new RegExp(`${t.key}`));
button(ask, /Взять в работу/);
tg.userClicks(PM, ask.message_id, button(ask, /Оставить в бэклоге/));
await waitFor("kept", async () => /В бэклоге/.test(ask.text) && ask.reply_markup?.inline_keyboard.length === 0);
assert.equal((await core.resolveTask(db, t.key)).task.status, "backlog");
});
test("Scenario: Выбор проекта и эпика", async () => {
await project({ turns: [] });
const p = await project({ turns: [] });
const proj = await core.getProject(db, p.key);
const epic = await core.createGoal(db, proj.id, "Отчёты");
tg.userSends(PM, "экспорт отчётов в xlsx");
const ask = await botMsg(/Новая задача «экспорт отчётов в xlsx»\nВ какой проект\?/);
tg.userClicks(PM, ask.message_id, button(ask, new RegExp(`^${p.key}$`)));
await waitFor("epic asked", async () => /Эпик\?/.test(ask.text));
button(ask, /Без эпика/);
tg.userClicks(PM, ask.message_id, button(ask, /^Отчёты$/));
await waitFor("created", async () => /Создал/.test(ask.text));
const t = await storyByTitle(p.key, "экспорт отчётов в xlsx");
assert.equal(t?.goalId, epic.id);
});
test("Scenario: Взять в работу — стори в работе, агент запущен", async () => {
const p = await project({ turns: [[{ say: "Беру стори." }]] });
tg.userSends(PM, `${p.key}: поправить опечатку`);
const ask = await botMsg(new RegExp(`Новая задача в <b>${p.key}</b>: «поправить опечатку»`));
tg.userClicks(PM, ask.message_id, button(ask, /Создать/));
await waitFor("created", async () => /Создал/.test(ask.text));
const cb = tg.userClicks(PM, ask.message_id, button(ask, /Взять в работу/));
await waitFor("taken", async () => tg.callbackAnswers.find((a) => a.id === cb && /агент взялся/.test(a.text ?? "")));
const t = (await storyByTitle(p.key, "поправить опечатку"))!;
assert.equal(t.status, "in_progress");
const sessions = await core.listSessions(db, { active: true, taskId: t.id });
assert.equal(sessions.length, 1);
for (const s of sessions) await runner.stopSession(db, s.id);
});
test("Scenario: Голосовое — расшифровка и предложение создать стори; без настройки — просьба написать текстом", async () => {
const p = await project({ turns: [] });
tg.userSendsVoice(PM, MockTranscribe.speech(`в ${p.key} добавить экспорт`));
await botMsg(/Голосовые сообщения пока не работают/);
// PEP-108: without speech to text /help does not promise voice notes.
tg.userSends(PM, "/help");
assert.doesNotMatch((await botMsg(/Я бот Peppa FACTORY/)).text, /голосом/);
const stt = await new MockTranscribe().start();
Object.assign(process.env, { PEPPA_TRANSCRIBE_URL: stt.url, PEPPA_TRANSCRIBE_KEY: stt.key });
try {
tg.userSendsVoice(PM, MockTranscribe.speech(`в ${p.key} добавить экспорт`));
await botMsg(new RegExp(`Расслышал: «в ${p.key} добавить экспорт»`));
const ask = await botMsg(new RegExp(`Новая задача в <b>${p.key}</b>: «добавить экспорт»`));
assert.deepEqual(stt.requests.at(-1), { model: "whisper-1", language: "ru", filename: stt.requests.at(-1)!.filename, bytes: MockTranscribe.speech(`в ${p.key} добавить экспорт`).length });
tg.userClicks(PM, ask.message_id, button(ask, /Создать/));
await waitFor("created", async () => /Создал/.test(ask.text));
assert.match((await storyByTitle(p.key, "добавить экспорт"))!.description!, /расшифровка голосового/);
// Scenario: Голосовое на казахском (PEP-131) — the recording goes in the language of the speaker's interface.
await core.setUserLocale(db, pmUser.id, "kk");
core.forgetChatLocales();
try {
tg.userSendsVoice(PM, MockTranscribe.speech("жобаға экспорт қосу"));
await botMsg(/«жобаға экспорт қосу»/);
assert.equal(stt.requests.at(-1)!.language, "kk");
} finally {
await core.setUserLocale(db, pmUser.id, null);
core.forgetChatLocales();
}
// Silence → nothing to create.
tg.userSendsVoice(PM, Buffer.from("ogg-opus-noise"));
await botMsg(/Не разобрал ни слова/);
// Wrong key → a plain message without the service code, no draft.
process.env.PEPPA_TRANSCRIBE_KEY = "wrong";
tg.userSendsVoice(PM, MockTranscribe.speech("что-то"));
await botMsg(/Не получилось расшифровать голосовое\. Напишите задачу текстом/);
} finally {
delete process.env.PEPPA_TRANSCRIBE_URL;
delete process.env.PEPPA_TRANSCRIBE_KEY;
await stt.stop();
}
});
test("Scenario: Чужой проект — не предлагается и не создаётся", async () => {
setDefaultOwner(bobUser.id);
const sec = await project({ turns: [] });
setDefaultOwner(pmUser.id);
const secProj = await core.getProject(db, sec.key);
tg.userSends(PM, `в ${sec.key}: украсть данные`);
// The key isn't one of the PM's projects: the whole text is the story, the project is asked.
const ask = await botMsg(new RegExp(`Новая задача «в ${sec.key}: украсть данные»`));
assert.ok(!ask.reply_markup!.inline_keyboard.flat().some((b) => b.text === sec.key), "someone else's project is not offered");
const draft = button(ask, /Отмена/).split(":")[1];
const cb = tg.userClicks(PM, ask.message_id, `d:${draft}:p:${secProj.id}`);
await waitFor("refused", async () => tg.callbackAnswers.find((a) => a.id === cb && /Проект не найден/.test(a.text ?? "")));
tg.userClicks(PM, ask.message_id, button(ask, /Отмена/));
await waitFor("cancelled", async () => /Отменено/.test(ask.text));
assert.equal((await core.listTasks(db, { projectId: secProj.id })).length, 1, "only the helper's own story");
// A stranger's message is ignored altogether.
tg.userSends(STRANGER, "в PAY: что-нибудь");
await new Promise((r) => setTimeout(r, 500));
assert.ok(!tg.botMessages(STRANGER.chatId).some((m) => /Новая задача/.test(m.text)));
});
});