- users.telegram_* replace the single global binding; one-time /start code per user (web Settings → Telegram, or peppa telegram pair <login>); a chat belongs to one user - agent questions go to the project's owner and members who paired; an answer (button or reply) is accepted only from someone with access to the project; messages are closed for every recipient; /status is scoped - CLI: telegram pair|status|unpair <login>, user ensure mock-<name>; dev stand pairs its test PM per user - tests: several-users journey (bob without access, then as a member); 70 e2e total, green - BREAKING: the old global binding is removed; users pair again in Settings Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
267 lines
15 KiB
TypeScript
267 lines
15 KiB
TypeScript
// 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 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"] } }, { 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: "Делаю." }]] });
|
||
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: "Переделываю." }]] });
|
||
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();
|
||
const q = await p.waitQuestion(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: ["Да", "Нет"] } }], [{ 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"] } }], [{ 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");
|
||
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();
|
||
const q = await p.waitQuestion(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: "Проверка ретраев?" } }], [{ 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 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";
|
||
});
|
||
const q = await p.waitQuestion(sid, "attention");
|
||
const m = await messageFor(q.id);
|
||
assert.match(m.text, /код 7/);
|
||
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");
|
||
// The old alert is closed as no longer relevant.
|
||
await waitFor("old alert closed", async () => /неактуально/.test(m.text));
|
||
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?" } }]] });
|
||
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");
|
||
});
|
||
});
|