254 lines
15 KiB
TypeScript
254 lines
15 KiB
TypeScript
// PEP-62: chats — events projected into project chats with threads, a reply in a story thread
|
||
// goes to the agent, the master feed and its commands, a linked Telegram group (the real bot
|
||
// against mock-telegram), and the short TTL.
|
||
import assert from "node:assert/strict";
|
||
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, runner, teardown, waitFor } from "./helpers.ts";
|
||
import { MockTelegram } from "../src/mock-telegram.ts";
|
||
import { chatMessages, users } from "@peppa/db";
|
||
import { eq } from "drizzle-orm";
|
||
import type { Bot } from "@peppa/bot";
|
||
|
||
const { createBot } = await import("@peppa/bot");
|
||
const { TelegramApi } = await import("@peppa/bot/telegram");
|
||
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
const tg = await new MockTelegram().start();
|
||
const PM = { id: 701, chatId: 701, username: "pm" };
|
||
const BOB = { id: 702, chatId: 702, username: "bob" };
|
||
const STRANGER = { id: 709, chatId: 709, username: "stranger" };
|
||
const GROUP = { id: -100500, title: "PAY team" };
|
||
let bot: Bot;
|
||
let pm: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
let bob: typeof pm;
|
||
let eve: typeof pm;
|
||
let seq = 0;
|
||
|
||
async function newProject() {
|
||
const key = `C${String.fromCharCode(65 + seq++)}`;
|
||
const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: `Проект ${key}`, giteaOwner: "test", workspacePath: "/tmp/none", ownerId: pm.id });
|
||
await core.addMember(db, p, bob.login, pm.id);
|
||
return p;
|
||
}
|
||
async function newTask(p: { id: number }, title = "Экспорт в CSV") {
|
||
const ref = await core.createTask(db, { projectId: p.id, title });
|
||
return core.resolveTask(db, ref.key);
|
||
}
|
||
const threadOf = (taskId: number) => `task:${taskId}`;
|
||
const groupMessages = () => tg.botMessages(GROUP.id);
|
||
|
||
before(async () => {
|
||
pm = await core.upsertUserFromGitea(db, { id: 81, login: "mock-pm" }, { access_token: "x" });
|
||
bob = await core.upsertUserFromGitea(db, { id: 82, login: "mock-bob" }, { access_token: "y" });
|
||
eve = await core.upsertUserFromGitea(db, { id: 83, login: "mock-eve" }, { access_token: "z" });
|
||
await db.update(users).set({ telegramChatId: PM.chatId, telegramUserId: PM.id }).where(eq(users.id, pm.id));
|
||
await db.update(users).set({ telegramChatId: BOB.chatId, telegramUserId: BOB.id }).where(eq(users.id, bob.id));
|
||
pm = (await core.getUser(db, pm.id))!;
|
||
bob = (await core.getUser(db, bob.id))!;
|
||
});
|
||
after(async () => {
|
||
await bot?.stop();
|
||
await tg.stop();
|
||
await teardown();
|
||
});
|
||
|
||
describe("project chat", () => {
|
||
test("Вопрос агента в треде стори; повторный перенос без дублей", async () => {
|
||
const p = await newProject();
|
||
const chat = await core.ensureProjectChat(db, p.id);
|
||
const ref = await newTask(p);
|
||
const q = await core.askPm(db, ref, { kind: "question", text: "Какой разделитель?", options: [";", ","] });
|
||
await core.syncChats(db);
|
||
await core.syncChats(db);
|
||
const msgs = await core.chatMessagesView(db, chat.id, { threadKey: threadOf(ref.task.id) });
|
||
const qs = msgs.filter((m) => m.question?.id === q.id);
|
||
assert.equal(qs.length, 1);
|
||
assert.equal(qs[0]!.threadTitle, `${ref.key} · Экспорт в CSV`);
|
||
const threads = await core.chatThreads(db, chat.id);
|
||
assert.equal(threads[0]!.key, threadOf(ref.task.id));
|
||
assert.equal(threads[0]!.open, 1);
|
||
// The question is still on the home page (pending questions).
|
||
assert.ok((await core.pendingQuestions(db)).some((x) => x.id === q.id));
|
||
});
|
||
|
||
test("Ответ на вопрос из треда уходит агенту", async () => {
|
||
const p = await newProject();
|
||
const chat = await core.ensureProjectChat(db, p.id);
|
||
const ref = await newTask(p);
|
||
const q = await core.askPm(db, ref, { kind: "question", text: "Какой разделитель?" });
|
||
const r = await runner.postToChat(db, bob, { chatId: chat.id, threadKey: threadOf(ref.task.id), text: "точка с запятой", via: "web" });
|
||
const fresh = await core.getQuestion(db, q.id);
|
||
assert.equal(fresh.answer, "точка с запятой");
|
||
assert.equal(fresh.answeredVia, "web");
|
||
assert.match(r.reply!.text, /сохранён|ушёл агенту/);
|
||
const thread = await core.chatMessagesView(db, chat.id, { threadKey: threadOf(ref.task.id) });
|
||
assert.ok(thread.some((m) => m.kind === "user" && m.authorLogin === bob.login && m.text === "точка с запятой"));
|
||
});
|
||
|
||
test("Комментарий без вопроса: у стори комментарий, в треде одно сообщение", async () => {
|
||
const p = await newProject();
|
||
const chat = await core.ensureProjectChat(db, p.id);
|
||
const ref = await newTask(p);
|
||
const r = await runner.postToChat(db, pm, { chatId: chat.id, threadKey: threadOf(ref.task.id), text: "не забудь заголовки", via: "web" });
|
||
assert.match(r.reply!.text, /Комментарий сохранён/);
|
||
const comments = await core.storyComments(db, ref.task.id);
|
||
assert.deepEqual(comments.map((c) => c.text), ["не забудь заголовки"]);
|
||
await core.syncChats(db);
|
||
const thread = await core.chatMessagesView(db, chat.id, { threadKey: threadOf(ref.task.id) });
|
||
assert.equal(thread.filter((m) => m.text === "не забудь заголовки").length, 1);
|
||
});
|
||
|
||
test("Чужой проект: запрос отклонён, сообщения нет", async () => {
|
||
const p = await newProject();
|
||
const chat = await core.ensureProjectChat(db, p.id);
|
||
await assert.rejects(runner.postToChat(db, eve, { chatId: chat.id, threadKey: null, text: "привет", via: "web" }), /не найден/);
|
||
assert.equal((await core.chatMessagesView(db, chat.id)).length, 0);
|
||
assert.equal((await core.listChats(db, eve)).filter((c) => c.kind === "project").length, 0);
|
||
});
|
||
|
||
test("Тред чужого проекта нельзя подставить", async () => {
|
||
const a = await newProject();
|
||
const b = await newProject();
|
||
const ref = await newTask(b);
|
||
const chat = await core.ensureProjectChat(db, a.id);
|
||
await assert.rejects(runner.postToChat(db, pm, { chatId: chat.id, threadKey: threadOf(ref.task.id), text: "x", via: "web" }), /не из этого чата/);
|
||
});
|
||
|
||
test("Релиз и инцидент — свои треды", async () => {
|
||
const p = await newProject();
|
||
const chat = await core.ensureProjectChat(db, p.id);
|
||
const { releases } = await import("@peppa/db");
|
||
const [rel] = await db.insert(releases).values({ projectId: p.id, env: "staging", sha: "abcdef1234567", status: "healthy", tasks: ["CX-1"] }).returning();
|
||
await core.syncChats(db);
|
||
const threads = await core.chatThreads(db, chat.id);
|
||
assert.ok(threads.some((t) => t.key === `release:${rel!.id}` && t.title === "Релиз staging abcdef1"));
|
||
});
|
||
});
|
||
|
||
describe("master chat", () => {
|
||
test("Сбой раннера в мастер-чате; команды /task и неизвестная", async () => {
|
||
const p = await newProject();
|
||
const ref = await newTask(p, "Платежи");
|
||
await core.logEvent(db, { projectId: p.id, taskId: ref.task.id, type: "stalled", payload: { idleMinutes: 15 } });
|
||
await core.logEvent(db, { projectId: p.id, taskId: ref.task.id, type: "progress", payload: { text: "половина готова" } });
|
||
await core.syncChats(db);
|
||
const feed = await core.masterFeed(db, pm);
|
||
assert.ok(feed.some((m) => /Агент молчит 15 мин/.test(m.text) && m.threadKey === threadOf(ref.task.id) && m.projectKey === p.key));
|
||
assert.ok(!feed.some((m) => /половина готова/.test(m.text)), "progress is not important");
|
||
|
||
const master = await core.ensureMasterChat(db, pm.id);
|
||
const r = await runner.postToChat(db, pm, { chatId: master.id, threadKey: null, text: `/task ${ref.key}`, via: "web" });
|
||
assert.match(r.reply!.text, new RegExp(`${ref.key}: Платежи[\\s\\S]*бэклог`));
|
||
const bad = await runner.postToChat(db, pm, { chatId: master.id, threadKey: null, text: "/deploy всё", via: "web" });
|
||
assert.match(bad.reply!.text, /Не знаю такую команду[\s\S]*\/move/);
|
||
// Bob's master chat is his own.
|
||
await assert.rejects(runner.postToChat(db, bob, { chatId: master.id, threadKey: null, text: "/status", via: "web" }), /не найден/);
|
||
});
|
||
|
||
test("Команда перемещения", async () => {
|
||
const p = await newProject();
|
||
const ref = await newTask(p);
|
||
const master = await core.ensureMasterChat(db, pm.id);
|
||
const r = await runner.postToChat(db, pm, { chatId: master.id, threadKey: null, text: `/move ${ref.key} done`, via: "web" });
|
||
assert.match(r.reply!.text, new RegExp(`${ref.key} → Готово`));
|
||
assert.equal((await core.resolveTask(db, ref.key)).task.status, "done");
|
||
});
|
||
});
|
||
|
||
describe("Telegram group", () => {
|
||
let p: Awaited<ReturnType<typeof newProject>>;
|
||
let chat: Awaited<ReturnType<typeof core.ensureProjectChat>>;
|
||
|
||
before(async () => {
|
||
p = await newProject();
|
||
chat = await core.ensureProjectChat(db, p.id);
|
||
bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 300, changesIntervalMs: 200, log: (m) => process.env.MOCK_DEBUG && console.log(m) });
|
||
await bot.start();
|
||
await bot.reconcile(); // first start: mirroring begins from here
|
||
});
|
||
|
||
test("Просроченный код и связка группы", async () => {
|
||
const code = await core.createChatLinkCode(db, tg.token, pm, chat.id, { sharedBot: true });
|
||
// A stale code: accepted 11 minutes later.
|
||
const stale = await core.createChatLinkCode(db, tg.token, pm, chat.id, { sharedBot: true });
|
||
assert.equal(await core.acceptChatLink(db, tg.token, stale, { tgChatId: -1, title: "x" }, Date.now() + 11 * 60_000), null);
|
||
tg.userSendsInGroup(PM, GROUP, `/link ${stale}`);
|
||
await waitFor("stale code reply", async () => groupMessages().some((m) => /неверный или истёк/.test(m.text)));
|
||
tg.userSendsInGroup(PM, GROUP, `/link@mock_peppa_bot ${code}`);
|
||
await waitFor("linked", async () => groupMessages().some((m) => /Группа связана с чатом проекта/.test(m.text)));
|
||
const linked = await core.getChat(db, chat.id);
|
||
assert.equal(linked.tgChatId, GROUP.id);
|
||
assert.equal(linked.tgTitle, GROUP.title);
|
||
});
|
||
|
||
test("Вопрос в группе, ответ реплаем, тред — цепочка ответов", async () => {
|
||
const ref = await newTask(p, "Экспорт отчёта");
|
||
const q = await core.askPm(db, ref, { kind: "question", text: "Какой формат даты?", options: ["ISO", "ДД.ММ.ГГГГ"] });
|
||
const qMsg = await waitFor("question in the group", async () => groupMessages().find((m) => m.text.includes("Какой формат даты?")));
|
||
assert.ok(qMsg.reply_markup?.inline_keyboard.flat().some((b) => b.callback_data === `q:${q.id}:o0`));
|
||
|
||
// Somebody without a Peppa account replies: ignored with a hint.
|
||
tg.userSendsInGroup(STRANGER, GROUP, "ISO конечно", qMsg.message_id);
|
||
await waitFor("stranger hint", async () => groupMessages().some((m) => /Не знаю тебя в Пеппе/.test(m.text)));
|
||
assert.equal((await core.getQuestion(db, q.id)).answeredAt, null);
|
||
|
||
tg.userSendsInGroup(BOB, GROUP, "ДД.ММ.ГГГГ", qMsg.message_id);
|
||
const answered = await waitFor("answered from the group", async () => {
|
||
const x = await core.getQuestion(db, q.id);
|
||
return x.answeredAt ? x : null;
|
||
});
|
||
assert.equal(answered.answer, "ДД.ММ.ГГГГ");
|
||
assert.equal(answered.answeredVia, "telegram");
|
||
const thread = await core.chatMessagesView(db, chat.id, { threadKey: threadOf(ref.task.id) });
|
||
assert.ok(thread.some((m) => m.kind === "user" && m.via === "telegram" && m.authorLogin === bob.login));
|
||
// Peppa's note about it hangs on the thread's first message; Bob's own message isn't echoed.
|
||
const note = await waitFor("reply note in the thread", async () => groupMessages().find((m) => /Ответ (ушёл агенту|сохранён)/.test(m.text)));
|
||
assert.equal(note.reply_to, qMsg.message_id);
|
||
assert.ok(!groupMessages().some((m) => m.text.includes("mock-bob") && m.text.includes("ДД.ММ.ГГГГ") && !m.text.includes("Какой формат")));
|
||
|
||
// A web message in the same thread reaches the group as a reply too.
|
||
await runner.postToChat(db, pm, { chatId: chat.id, threadKey: threadOf(ref.task.id), text: "и время в UTC", via: "web" });
|
||
const web = await waitFor("web message in the group", async () => groupMessages().find((m) => m.text.includes("и время в UTC")));
|
||
assert.equal(web.reply_to, qMsg.message_id);
|
||
assert.match(web.text, /mock-pm.*\(веб\)/);
|
||
});
|
||
|
||
test("Кнопка вопроса в группе", async () => {
|
||
const ref = await newTask(p, "Кнопки");
|
||
const q = await core.askPm(db, ref, { kind: "question", text: "Кнопкой?", options: ["да", "нет"] });
|
||
const qMsg = await waitFor("question in the group", async () => groupMessages().find((m) => m.text.includes("Кнопкой?")));
|
||
tg.userClicks(STRANGER, qMsg.message_id, `q:${q.id}:o0`);
|
||
await waitFor("stranger refused", async () => tg.callbackAnswers.some((c) => /Нет доступа/.test(c.text ?? "")));
|
||
tg.userClicks(BOB, qMsg.message_id, `q:${q.id}:o1`);
|
||
const x = await waitFor("answered by button", async () => {
|
||
const r = await core.getQuestion(db, q.id);
|
||
return r.answeredAt ? r : null;
|
||
});
|
||
assert.equal(x.answer, "нет");
|
||
});
|
||
|
||
test("Супергруппа сохраняет связку", async () => {
|
||
// Telegram sends migrate_to_chat_id when a group is upgraded.
|
||
await core.migrateChatGroup(db, GROUP.id, -1009999);
|
||
assert.equal((await core.getChat(db, chat.id)).tgChatId, -1009999);
|
||
await core.migrateChatGroup(db, -1009999, GROUP.id);
|
||
});
|
||
});
|
||
|
||
describe("TTL", () => {
|
||
test("Старые сообщения удалены, вопрос остаётся", async () => {
|
||
const p = await newProject();
|
||
const chat = await core.ensureProjectChat(db, p.id);
|
||
const ref = await newTask(p);
|
||
const q = await core.askPm(db, ref, { kind: "question", text: "Старый вопрос" });
|
||
await core.syncChats(db);
|
||
const old = new Date(Date.now() - 15 * 86_400_000);
|
||
await db.update(chatMessages).set({ createdAt: old }).where(eq(chatMessages.chatId, chat.id));
|
||
const n = await core.pruneChats(db);
|
||
assert.ok(n >= 1);
|
||
assert.equal((await core.chatMessagesView(db, chat.id)).length, 0);
|
||
assert.equal((await core.getQuestion(db, q.id)).text, "Старый вопрос");
|
||
});
|
||
});
|