«Peppa FACTORY» → «FORGE» в экранах, сообщениях, словарях en/kk, шаблоне и тестах; «Пеппа» → «FORGE» в подсказках агентам и правилах; логотип, значок, версия кэша service worker; в словаре старые названия — в «Нельзя». Внутренние имена (CLI peppa, PEPPA_*, MCP-сервер peppa, ключи PEP-N) не меняются. Второй адрес — в mac-route.sh. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
164 lines
9.4 KiB
TypeScript
164 lines
9.4 KiB
TypeScript
// PEP-109: a chat's Telegram group is linked through the user's own bot (PEP-85) — the code is
|
||
// accepted only by that bot, the chat's messages and questions go out through it, replies and
|
||
// buttons of the group come back through it. Two mock-telegram instances: the platform's bot
|
||
// and the user's.
|
||
import assert from "node:assert/strict";
|
||
import { after, before, describe, test } from "node:test";
|
||
import { core, db, teardown, waitFor } from "./helpers.ts";
|
||
import { MockTelegram } from "../src/mock-telegram.ts";
|
||
import { 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 shared = await new MockTelegram().start();
|
||
const own = await new MockTelegram({ id: 4343, username: "mock_anna_factory_bot" }).start();
|
||
const OWN_TOKEN = "1234567891:" + "B".repeat(35);
|
||
const ANNA = { id: 801, chatId: 801, username: "anna" };
|
||
const BORIS = { id: 802, chatId: 802, username: "boris" };
|
||
const STRANGER = { id: 809, chatId: 809, username: "stranger" };
|
||
const GROUP = { id: -100900, title: "PAY team" };
|
||
let bot: Bot;
|
||
let anna: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
let boris: typeof anna;
|
||
let project: Awaited<ReturnType<typeof core.createProject>>;
|
||
let chat: Awaited<ReturnType<typeof core.ensureProjectChat>>;
|
||
|
||
const pause = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||
async function connectOwnBot() {
|
||
process.env.TELEGRAM_API_URL = own.url;
|
||
try {
|
||
await core.setUserBot(db, anna.id, OWN_TOKEN);
|
||
} finally {
|
||
delete process.env.TELEGRAM_API_URL;
|
||
}
|
||
await bot.syncOwnBots();
|
||
}
|
||
|
||
before(async () => {
|
||
anna = await core.upsertUserFromGitea(db, { id: 10901, login: "mock-anna" }, { access_token: "x" });
|
||
boris = await core.upsertUserFromGitea(db, { id: 10902, login: "mock-boris" }, { access_token: "y" });
|
||
// Boris paired his personal Telegram (through whatever bot): that is who he is in a group.
|
||
await db.update(users).set({ telegramChatId: BORIS.chatId, telegramUserId: BORIS.id }).where(eq(users.id, boris.id));
|
||
project = await core.createProject(db, { slug: "mock-pay109", key: "PAYG", name: "Pay", giteaOwner: "x", workspacePath: "/tmp/mock-pay109", ownerId: anna.id });
|
||
await core.addMember(db, project, boris.login, anna.id);
|
||
chat = await core.ensureProjectChat(db, project.id);
|
||
bot = createBot({
|
||
db,
|
||
api: new TelegramApi(shared.token, shared.url),
|
||
userApi: (token) => new TelegramApi(token, own.url),
|
||
secret: shared.token,
|
||
webUrl: "http://peppa.test",
|
||
pollTimeoutSec: 1,
|
||
outboxIntervalMs: 100,
|
||
reconcileIntervalMs: 300,
|
||
changesIntervalMs: 200,
|
||
userBotsIntervalMs: 200,
|
||
log: (m) => process.env.MOCK_DEBUG && console.log(m),
|
||
});
|
||
await bot.start();
|
||
await bot.reconcile(); // first start: mirroring begins from here
|
||
});
|
||
after(async () => {
|
||
await bot.stop();
|
||
await shared.stop();
|
||
await own.stop();
|
||
await teardown();
|
||
});
|
||
|
||
describe("Telegram-группа чата через свой бот", () => {
|
||
test("Scenario: Нет своего бота — код не выдан", async () => {
|
||
await assert.rejects(core.createChatLinkCode(db, shared.token, boris, chat.id), /подключите своего бота/);
|
||
await assert.rejects(core.createChatLinkCode(db, shared.token, anna, chat.id), /подключите своего бота/);
|
||
// The superadmin without an own bot links through the platform's bot, as before.
|
||
const code = await core.createChatLinkCode(db, shared.token, anna, chat.id, { sharedBot: true });
|
||
assert.equal(await core.chatLinkCodeBot(db, shared.token, code), null);
|
||
});
|
||
|
||
test("Scenario: Код в общем боте не принимается; Связать группу — через своего бота", async () => {
|
||
await connectOwnBot();
|
||
const code = await core.createChatLinkCode(db, shared.token, anna, chat.id);
|
||
assert.equal(await core.chatLinkCodeBot(db, shared.token, code), anna.id);
|
||
|
||
// Addressed to the platform's bot: refused, the code stays valid.
|
||
shared.userSendsInGroup(ANNA, GROUP, `/link@mock_peppa_bot ${code}`);
|
||
await waitFor("the shared bot refuses", async () => shared.botMessages(GROUP.id).some((m) => /неверный или истёк/.test(m.text)));
|
||
assert.equal((await core.getChat(db, chat.id)).tgChatId, null);
|
||
// Not addressed (every bot of the group gets it): the platform's bot keeps quiet.
|
||
const n = shared.botMessages(GROUP.id).length;
|
||
shared.userSendsInGroup(ANNA, GROUP, `/link ${code}`);
|
||
await pause(1500);
|
||
assert.equal(shared.botMessages(GROUP.id).length, n);
|
||
|
||
own.userSendsInGroup(ANNA, GROUP, `/start@mock_anna_factory_bot ${code}`);
|
||
await waitFor("linked through the own bot", async () => own.botMessages(GROUP.id).some((m) => /Группа связана с чатом проекта PAYG/.test(m.text)));
|
||
const linked = await core.getChat(db, chat.id);
|
||
assert.deepEqual([linked.tgChatId, linked.tgTitle, linked.tgBotUserId, linked.tgLinkedBy], [GROUP.id, GROUP.title, anna.id, anna.id]);
|
||
assert.equal(await core.chatGroupBotName(db, chat.id), "mock_anna_factory_bot");
|
||
assert.deepEqual(await core.chatGroupBots(db), [{ tgChatId: GROUP.id, botUserId: anna.id }]);
|
||
});
|
||
|
||
test("Scenario: Сообщения группы идут через бота связки; Ответ реплаем из группы; Посторонний в группе", async () => {
|
||
const sharedBefore = shared.botMessages(GROUP.id).length;
|
||
const ref = await core.resolveTask(db, (await core.createTask(db, { projectId: project.id, title: "Экспорт" })).key);
|
||
const q = await core.askPm(db, ref, { kind: "question", text: "Какой разделитель?", options: ["запятая", "точка с запятой"] });
|
||
const qMsg = await waitFor("question from the own bot", async () => own.botMessages(GROUP.id).find((m) => m.text.includes("Какой разделитель?")));
|
||
assert.equal(shared.botMessages(GROUP.id).length, sharedBefore, "nothing from the platform's bot");
|
||
|
||
// The same group seen by the platform's bot: not its group, the reply is ignored.
|
||
shared.userSendsInGroup(BORIS, GROUP, "запятая", qMsg.message_id);
|
||
await pause(1500);
|
||
assert.equal((await core.getQuestion(db, q.id)).answeredAt, null);
|
||
assert.equal(shared.botMessages(GROUP.id).length, sharedBefore);
|
||
|
||
own.userSendsInGroup(STRANGER, GROUP, "запятая", qMsg.message_id);
|
||
await waitFor("stranger hint", async () => own.botMessages(GROUP.id).some((m) => /Не нашёл вас в FORGE/.test(m.text)));
|
||
assert.equal((await core.getQuestion(db, q.id)).answeredAt, null);
|
||
|
||
own.userSendsInGroup(BORIS, 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.deepEqual([answered.answer, answered.answeredVia], ["точка с запятой", "telegram"]);
|
||
const thread = await core.chatMessagesView(db, chat.id, { threadKey: `task:${ref.task.id}` });
|
||
assert.ok(thread.some((m) => m.kind === "user" && m.via === "telegram" && m.authorLogin === boris.login));
|
||
// FORGE's note about the answer goes out through the same bot, into the thread.
|
||
const note = await waitFor("note in the thread", async () => own.botMessages(GROUP.id).find((m) => /Ответ (ушёл агенту|сохранён)/.test(m.text)));
|
||
assert.equal(note.reply_to, qMsg.message_id);
|
||
assert.equal(shared.botMessages(GROUP.id).length, sharedBefore);
|
||
});
|
||
|
||
test("Кнопка вопроса в группе своего бота", async () => {
|
||
const ref = await core.resolveTask(db, (await core.createTask(db, { projectId: project.id, title: "Кнопки" })).key);
|
||
const q = await core.askPm(db, ref, { kind: "question", text: "Кнопкой?", options: ["да", "нет"] });
|
||
const qMsg = await waitFor("question in the group", async () => own.botMessages(GROUP.id).find((m) => m.text.includes("Кнопкой?")));
|
||
own.userClicks(BORIS, 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("Scenario: Бот отключён или заменён — группа отвязана", async () => {
|
||
// Replaced: the stored bot is another one than the token's.
|
||
await db.update(users).set({ telegramBotUsername: "mock_old_bot" }).where(eq(users.id, anna.id));
|
||
await connectOwnBot();
|
||
assert.deepEqual([(await core.getChat(db, chat.id)).tgChatId, (await core.getChat(db, chat.id)).tgBotUserId], [null, null]);
|
||
|
||
// The same bot connected again keeps its groups; disconnecting drops them.
|
||
const code = await core.createChatLinkCode(db, shared.token, anna, chat.id);
|
||
assert.ok(await core.acceptChatLink(db, shared.token, code, { tgChatId: GROUP.id, title: GROUP.title, botUserId: anna.id }));
|
||
await connectOwnBot();
|
||
assert.equal((await core.getChat(db, chat.id)).tgChatId, GROUP.id);
|
||
await core.clearUserBot(db, anna.id);
|
||
const c = await core.getChat(db, chat.id);
|
||
assert.deepEqual([c.tgChatId, c.tgTitle, c.tgBotUserId], [null, null, null]);
|
||
assert.deepEqual(await core.chatGroupBots(db), []);
|
||
});
|
||
});
|