Проекция событий в чаты подписывает то, что сделала фабрика или агент, «Peppa FACTORY»;
логин — только под словами человека. Слова агента — с кличкой (чат, карточка вопроса,
Telegram «🤖 Шустрик: …»), роли — «Аналитик» и «Продакт-агент». «Агент <кличка> взял
задачу в работу» ждёт запуска агента. Промпты ролей требуют «вы» (ADDRESS_RULE),
informalAddress проверяет ответы моков. Change pep-156-who-speaks в архиве, спека
project-chats, тест who-speaks.test.ts.
Rebased on main (one commit on top of 1074d276).
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
166 lines
11 KiB
TypeScript
166 lines
11 KiB
TypeScript
// PEP-139: free text of people and agents reaches the reader as written — the translation of
|
||
// rendered messages touches only the factory's own phrases. Unit checks of the marks, and the
|
||
// real bot against mock-telegram: a linked group and a private chat reading English.
|
||
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 { users } from "@peppa/db";
|
||
import { eq } from "drizzle-orm";
|
||
import { asIs, localizeRoleMessage, localizeText, m, stripAsIs, translator } from "@peppa/shared/i18n";
|
||
import type { Bot } from "@peppa/bot";
|
||
|
||
const { createBot } = await import("@peppa/bot");
|
||
const { TelegramApi } = await import("@peppa/bot/telegram");
|
||
const { renderAnswered, renderQuestion } = await import("@peppa/bot/render");
|
||
|
||
const FREE = "Сделано три задачи из пяти.";
|
||
const MARKS = /[]/;
|
||
|
||
describe("пометка свободного текста", () => {
|
||
test("общий перевод переписывает непомеченный свободный текст — причина стори", () => {
|
||
assert.notEqual(localizeText("en", FREE), FREE);
|
||
});
|
||
|
||
test("помеченный текст остаётся дословным, фразы вокруг переводятся", () => {
|
||
assert.equal(localizeText("en", asIs(FREE)), FREE);
|
||
assert.equal(localizeText("kk", asIs(FREE)), FREE);
|
||
assert.equal(localizeText("en", `${m("❓ Вопрос")}\n${asIs(FREE)}`), `❓ Question\n${FREE}`);
|
||
assert.equal(localizeText("en", m("Ошибка: {message}", { message: asIs(FREE) })), `Error: ${FREE}`);
|
||
// Several lines of free text are not split into lines and translated one by one.
|
||
assert.equal(localizeText("en", `<b>${asIs("anna")}</b>${m(" (веб): {text}", { text: asIs(`Проекты\n${FREE}`) })}`), `<b>anna</b> (web): Проекты\n${FREE}`);
|
||
});
|
||
|
||
test("русскому читателю и без перевода пометка снимается", () => {
|
||
assert.equal(localizeText("ru", `📈 ${asIs(FREE)}`), `📈 ${FREE}`);
|
||
assert.equal(stripAsIs(asIs(FREE)), FREE);
|
||
assert.equal(localizeRoleMessage("en", `📈 ${asIs(FREE)}`), `📈 ${FREE}`);
|
||
assert.equal(translator("en").text(asIs("Проекты")), "Проекты");
|
||
assert.equal(asIs(""), "");
|
||
assert.equal(asIs(null), "");
|
||
});
|
||
|
||
test("обрезанная пометка действует до конца текста, вложенная не ломает", () => {
|
||
const cut = `${m("❓ Вопрос")}\n${asIs(FREE).slice(0, -1)}`;
|
||
assert.equal(localizeText("en", cut), `❓ Question\n${FREE}`);
|
||
assert.equal(localizeText("en", asIs(`до ${asIs(FREE)} после`)), `до ${FREE} после`);
|
||
assert.equal(localizeText("en", `${FREE}`), localizeText("en", FREE));
|
||
});
|
||
});
|
||
|
||
describe("вопросы", () => {
|
||
const ctx = { taskKey: "DEMO-1", taskTitle: "Готово три задачи из пяти", session: null, webUrl: "http://peppa.test" };
|
||
const q = (over: Record<string, unknown>) => ({ id: 7, kind: "question", text: "Какой формат из двух оставить? Готово три задачи из пяти.", options: ["Задачи из списка", "Готово"], sessionId: 3, answer: null, answeredVia: null, ...over }) as never;
|
||
|
||
test("Scenario: Вопрос агента с вариантами", () => {
|
||
const r = renderQuestion(q({}), ctx);
|
||
const en = localizeText("en", r.text);
|
||
assert.match(en, /❓ Question/);
|
||
assert.ok(en.includes("Какой формат из двух оставить? Готово три задачи из пяти."), en);
|
||
assert.ok(en.includes("<i>Готово три задачи из пяти</i>"), en);
|
||
assert.deepEqual(r.buttons.map((b) => localizeText("en", b[0]!.text)), ["Задачи из списка", "Готово"]);
|
||
// The same button unmarked would be translated.
|
||
assert.notEqual(localizeText("en", "Готово"), "Готово");
|
||
});
|
||
|
||
test("Scenario: Вопрос фабрики по-прежнему переводится", () => {
|
||
const text = m("⚠️ {key}: изменения затрагивают проверки или обновление продукта — сама задача не закроется, нужно ваше «Принять».", { key: "DEMO-1" });
|
||
const r = renderQuestion(q({ sessionId: null, text, options: null }), { ...ctx, taskTitle: null });
|
||
assert.doesNotMatch(localizeText("en", r.text), /[А-Яа-яЁё]/);
|
||
assert.doesNotMatch(r.text, MARKS);
|
||
});
|
||
|
||
test("ответ человека под закрытым вопросом — дословно", () => {
|
||
const original = renderQuestion(q({}), ctx).text;
|
||
const en = localizeText("en", renderAnswered(original, q({ answer: FREE, answeredVia: "telegram" })));
|
||
assert.ok(en.includes(`<b>${FREE}</b>`), en);
|
||
assert.doesNotMatch(en.split("\n").at(-1)!.replace(FREE, ""), /[А-Яа-яЁё]/);
|
||
});
|
||
});
|
||
|
||
describe("бот: Telegram на английском", () => {
|
||
const tg = new MockTelegram();
|
||
const PM = { id: 801, chatId: 801, username: "pm" };
|
||
const BOB = { id: 802, chatId: 802, username: "bob" };
|
||
const GROUP = { id: -100900, title: "DEMO team" };
|
||
let bot: Bot;
|
||
let pm: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
let bob: typeof pm;
|
||
let p: Awaited<ReturnType<typeof core.createProject>>;
|
||
let chat: Awaited<ReturnType<typeof core.ensureProjectChat>>;
|
||
const group = () => tg.botMessages(GROUP.id);
|
||
const sentTo = (chatId: number) => tg.calls.filter((c) => c.params.chat_id === chatId);
|
||
|
||
before(async () => {
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
await tg.start();
|
||
pm = await core.upsertUserFromGitea(db, { id: 91, login: "mock-pm" }, { access_token: "x" });
|
||
bob = await core.upsertUserFromGitea(db, { id: 92, login: "mock-bob" }, { access_token: "y" });
|
||
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))!;
|
||
// The PM reads English (their private chat and the group they link); Bob reads Russian.
|
||
await core.setUserLocale(db, pm.id, "en");
|
||
p = await core.createProject(db, { slug: "demo", key: "DEMO", name: "Демо", giteaOwner: "test", workspacePath: "/tmp/none", ownerId: pm.id });
|
||
await core.addMember(db, p, bob.login, pm.id);
|
||
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: (x) => process.env.MOCK_DEBUG && console.log(x) });
|
||
await bot.start();
|
||
await bot.reconcile(); // first start: mirroring begins from here
|
||
tg.userSendsInGroup(PM, GROUP, `/link@mock_peppa_bot ${await core.createChatLinkCode(db, tg.token, pm, chat.id, { sharedBot: true })}`);
|
||
await waitFor("linked", async () => (await core.getChat(db, chat.id)).tgChatId === GROUP.id);
|
||
});
|
||
after(async () => {
|
||
await bot?.stop();
|
||
await tg.stop();
|
||
await teardown();
|
||
});
|
||
|
||
test("Scenario: Сообщение человека в Telegram-группе с английским языком", async () => {
|
||
await runner.postToChat(db, bob, { chatId: chat.id, threadKey: null, text: FREE, via: "web" });
|
||
const msg = await waitFor("mirrored", async () => group().find((x) => x.text.includes("mock-bob")));
|
||
assert.equal(msg.text, `<b>mock-bob</b> (web): ${FREE}`);
|
||
});
|
||
|
||
test("Scenario: Заметка агента о прогрессе", async () => {
|
||
const ref = await core.resolveTask(db, (await core.createTask(db, { projectId: p.id, title: "Готово три задачи из пяти" })).key);
|
||
const s = await core.createSession(db, { projectId: p.id, taskId: ref.task.id });
|
||
await core.reportProgress(db, ref, FREE, s.id);
|
||
const msg = await waitFor("progress mirrored", async () => group().find((x) => x.text.includes("📈")));
|
||
assert.ok(msg.text.endsWith(`📈 ${FREE}`), msg.text);
|
||
// The story title in the thread line is the person's own words too.
|
||
assert.ok(msg.text.includes("<i>DEMO-1 · Готово три задачи из пяти</i>"), msg.text);
|
||
assert.doesNotMatch(msg.text, MARKS);
|
||
});
|
||
|
||
test("Scenario: Вопрос агента с вариантами; русский читатель не видит служебных пометок", async () => {
|
||
const ref = await core.resolveTask(db, "DEMO-1");
|
||
const s = await core.createSession(db, { projectId: p.id, taskId: ref.task.id });
|
||
const text = "Какой формат из двух оставить? Готово три задачи из пяти.";
|
||
await core.askPm(db, ref, { kind: "question", text, options: ["Задачи из списка", "Готово"], sessionId: s.id });
|
||
const en = await waitFor("question to the PM", async () => tg.botMessages(PM.chatId).find((x) => x.text.includes("Какой формат")));
|
||
assert.match(en.text, /❓ Question/);
|
||
assert.ok(en.text.includes(text), en.text);
|
||
assert.deepEqual(en.reply_markup?.inline_keyboard.flat().map((b) => b.text), ["Задачи из списка", "Готово"]);
|
||
const ru = await waitFor("question to Bob", async () => tg.botMessages(BOB.chatId).find((x) => x.text.includes("Какой формат")));
|
||
assert.match(ru.text, /❓ Вопрос/);
|
||
assert.ok(ru.text.includes(text));
|
||
for (const c of [...sentTo(PM.chatId), ...sentTo(BOB.chatId), ...sentTo(GROUP.id)]) assert.doesNotMatch(JSON.stringify(c.params), MARKS, "the marks do not reach Telegram");
|
||
});
|
||
|
||
test("Scenario: Сообщение ИИ-роли в группе", async () => {
|
||
await runner.sayInDiscussion(db, p, chat.id, `${FREE}\n\n${m("Завёл в бэклог:")}\n• DEMO-2 «Экспорт в PDF»`);
|
||
const msg = await waitFor("role message mirrored", async () => group().find((x) => x.text.includes("Added to the backlog:")));
|
||
assert.equal(msg.text, `<b>🤖 Analyst</b>: ${FREE}\n\nAdded to the backlog:\n• DEMO-2 «Экспорт в PDF»`);
|
||
});
|
||
|
||
test("Scenario: Вопрос фабрики по-прежнему переводится", async () => {
|
||
const ref = await core.resolveTask(db, "DEMO-1");
|
||
await core.askPm(db, ref, { kind: "question", text: m("⚠️ {key}: изменения затрагивают проверки или обновление продукта — сама задача не закроется, нужно ваше «Принять».", { key: ref.key }) });
|
||
const msg = await waitFor("factory question", async () => tg.botMessages(PM.chatId).find((x) => x.text.includes("⚠️ DEMO-1")));
|
||
assert.doesNotMatch(msg.text.replace("Готово три задачи из пяти", ""), /[А-Яа-яЁё]/, msg.text);
|
||
});
|
||
});
|