peppa/packages/testkit/test/i18n-role-messages.test.ts
peppa-bot 575c31ac42 PEP-198: тесты под голос Аналитика
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:30:16 +05:00

143 lines
11 KiB
TypeScript
Raw 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.

// PEP-138: the fixed phrases of the AI roles' messages in the project's discussion (analyst,
// product agent, the «чтобы заработало по-настоящему» list) reach the reader in their language.
// Tests are named after the scenarios of the `interface-language` spec.
import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { after, before, describe, test } from "node:test";
import { sql } from "drizzle-orm";
import { localizeRoleMessage, localizeText, stripAsIs } from "@peppa/shared/i18n";
import { core, db, runner, teardown } from "./helpers.ts";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
process.env.PEPPA_WEB_URL = "http://peppa.test";
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
const TMP = mkdtempSync(join(tmpdir(), "peppa-role-messages-"));
const scenario = join(TMP, "scenario.json");
const setScenario = (s: object) => writeFileSync(scenario, JSON.stringify(s));
const tick = () => runner.analystChatTick(db, { wait: true });
/** Russian letters that are not Kazakh-only: a rough «no Russian fixed phrase is left» for en. */
const RU = /[А-Яа-яЁё]/;
type User = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let pm: User;
let project: Awaited<ReturnType<typeof core.createProject>>;
let chat: Awaited<ReturnType<typeof core.ensureProjectChat>>;
const post = (text: string) => runner.postToChat(db, pm, { chatId: chat.id, threadKey: null, text, via: "web" });
const last = async () => (await core.discussionMessages(db, chat.id)).at(-1)!;
const lastTelegram = async () => {
const out = await db.all<{ params: string }>(sql`select params from telegram_outbox where dedupe_key like 'chat:m%' order by id desc limit 1`);
return JSON.parse(out[0]!.params) as { text: string; peppa_localized?: boolean };
};
/** What the web shows for an AI role's message (`t.role`). */
const web = localizeRoleMessage;
before(async () => {
process.env.PEPPA_INTAKE_BIN = join(ROOT, "packages/testkit/bin/mock-intake");
process.env.MOCK_INTAKE_SCENARIO = scenario;
setScenario({});
pm = await core.upsertUserFromGitea(db, { id: 1381, login: "asel" }, { access_token: "x" });
db.run(sql`update users set telegram_chat_id = 9138 where id = ${pm.id}`);
const ws = join(TMP, "ws");
mkdirSync(join(ws, ".peppa"), { recursive: true });
project = await core.createProject(db, { slug: "mock-roles", key: "DEMO", name: "Демо", giteaOwner: "x", workspacePath: ws, ownerId: pm.id });
chat = await core.ensureProjectChat(db, project.id);
});
after(teardown);
const need = { id: "n1", title: "Ключ Claude API", why: "без него ответы — вымышленные примеры", how: "console.anthropic.com → API Keys", secret: "ANTHROPIC_API_KEY", source: "agent" as const, story: null, doneAt: null };
describe("PEP-138: AI roles' messages in the reader's language", () => {
test("Scenario Outline: Аналитик предложил задачу (PEP-198: заводит человек кнопкой)", async () => {
setScenario({ chat: { reply: "Готово.", create: [{ title: "Экспорт в PDF", description: "Кнопка «Скачать PDF»." }] } });
await post("Заведи экспорт в PDF");
await tick();
const m = await last();
assert.equal(m.authorKind, "agent");
assert.equal(stripAsIs(m.text), "Готово.\n\nПредлагаю завести:\n• Экспорт в PDF");
assert.equal(stripAsIs(web("en", m.text)), "Готово.\n\nI suggest filing:\n• Экспорт в PDF");
assert.equal(stripAsIs(web("kk", m.text)), "Готово.\n\nҚосуды ұсынамын:\n• Экспорт в PDF");
assert.equal(web("en", m.authorLogin), "Analyst");
assert.match((await lastTelegram()).text, /Демо<\/b> · Аналитик:\nГотово\.\n\nПредлагаю завести:\n• Экспорт в PDF[^]*Ответить: http:\/\/peppa\.test\/chats\/DEMO/);
await core.setUserLocale(db, pm.id, "en");
await post("И ещё раз");
await tick();
const tg = await lastTelegram();
assert.equal(tg.peppa_localized, true);
assert.match(tg.text, /Демо<\/b> · Analyst:\nГотово\.\n\nI suggest filing:\n• Экспорт в PDF[^]*Reply: http:\/\/peppa\.test\/chats\/DEMO/);
setScenario({});
});
test("Scenario: Находки агента приёмки — от Аналитика, на английском (PEP-198)", async () => {
const text = core.productReviewMessage(
{ summary: "Продукт показывает список стажировок.", howto: ["Откройте адрес.", "Нажмите «Найти»."], notReal: ["Ответы — вымышленные примеры."], needs: [], stories: [] },
{ env: "staging", url: "https://demo-staging.telecom.quest", openNeeds: [{ ...need, open: true }], filed: ["DEMO-9 «Убрать служебное поле»"], webUrl: "http://peppa.test", projectKey: "DEMO" },
);
await runner.sayInDiscussion(db, project, chat.id, text, core.PRODUCT_AGENT_NAME);
const en = web("en", (await last()).text).split("\n");
assert.equal(en[0], "The acceptance agent looked at the version to check: https://demo-staging.telecom.quest");
for (const line of ["How to use it:", "Not real yet:", "To make it work for real, we need from you:", " Where to get it: console.anthropic.com → API Keys", "Paste it or tick «Done» in the «Your product» card: http://peppa.test/p/DEMO", "Added improvements to the backlog:"]) assert.ok(en.includes(line), `${line}\n— in —\n${en.join("\n")}`);
assert.ok(en.includes("Продукт показывает список стажировок."), "the model's own text is left as written");
assert.match((await lastTelegram()).text, /Демо<\/b> · Analyst:\nThe acceptance agent looked at the version to check:[^]*\nПродукт показывает список стажировок\./);
assert.equal(web("en", core.productReviewMessage({ summary: "Ок.", howto: [], notReal: [], needs: [], stories: [] }, { env: "prod", url: "https://demo-prod.telecom.quest", openNeeds: [], filed: [], webUrl: "", projectKey: "DEMO" })), "The acceptance agent looked at the working version: https://demo-prod.telecom.quest\n\nОк.");
});
test("Scenario: Список нужного от владельца на казахском", () => {
const ru = ["Чтобы продукт заработал по-настоящему, а не в демо-режиме, нужно от вас:", "", core.needsText([need, { ...need, id: "n2", title: "Аккаунт Stripe", why: "", how: "", secret: null }], "http://peppa.test", "DEMO")].join("\n");
const kk = web("kk", ru);
assert.doesNotMatch(kk, /Где взять|Куда вставить|Когда сделаете|Ключи хранятся зашифрованными|нужно от вас|Карточка/);
assert.match(kk, /^Өнім демо-режимде емес, шын жұмыс істеуі үшін сізден керек:/);
assert.match(kk, /1\. Ключ Claude API — без него ответы — вымышленные примеры\n {3}Қайдан алуға болады: console\.anthropic\.com → API Keys\n {3}Қайда қою керек:/);
assert.match(kk, /2\. Аккаунт Stripe\n {3}Орындаған соң/);
assert.match(kk, /«Сіздің өніміңіз» карточкасы: http:\/\/peppa\.test\/p\/DEMO/);
const en = web("en", ru);
assert.match(en, /Where to paste it: project page → «Your product» card/);
assert.match(en, /Keys are stored encrypted; Peppa FACTORY will pass them to the product and restart it\./);
});
test("Scenario: Заметка о демо-режиме в «готово к ревью»", async () => {
await core.declareNeeds(db, project.id, [{ title: "Ключ Claude API", secret: "ANTHROPIC_API_KEY" }], { source: "agent" });
const note = await core.demoNote(db, project.id, "DEMO", "http://peppa.test");
assert.equal(localizeText("en", note), "⚠️ The product is still running in demo mode. We need from you: Ключ Claude API\nYou can paste it in the «Your product» card: http://peppa.test/p/DEMO");
assert.match(localizeText("kk", note), /^⚠️ Өнім әзірге демо-режимде жұмыс істеп тұр\. Сізден керек: Ключ Claude API\n«Сіздің өніміңіз» карточкасына қоюға болады:/);
});
test("Scenario: Аналитик не смог ответить — английский", async () => {
const RU_PICK = /Ответить по данным проекта/;
setScenario({ fail: true });
await post("Ты тут?");
await tick();
const fail = await last();
assert.equal(fail.authorKind, "system");
// PEP-153: the note also offers to answer from the data or file a task — both lines are translated.
assert.equal(localizeText("en", fail.text), "The analyst could not answer right now. Please write again a little later.\nAnswer from the project's data or file a task? Pick with a button.");
assert.doesNotMatch(localizeText("kk", fail.text), RU_PICK);
assert.doesNotMatch(localizeText("kk", fail.text), /не смог/);
setScenario({ garbage: true });
await post("А теперь?");
await tick();
assert.doesNotMatch(localizeText("en", (await last()).text), RU);
setScenario({});
const noSub = "Аналитик отвечает на подписке проекта, а она не подключена. Подключите Claude в «⋯ Настройки проекта → Подписки» — и напишите ещё раз.";
assert.match(localizeText("en", noSub), /^The analyst answers on the project's subscription, and it is not connected\./);
assert.doesNotMatch(localizeText("en", noSub), RU);
});
test("Scenario: Свободный текст не переводится", async () => {
setScenario({ chat: { reply: "Сделано три задачи из пяти.", create: [] } });
await post("Что сделано?");
await tick();
const m = await last();
assert.equal(m.text, "Сделано три задачи из пяти.");
assert.equal(web("en", m.text), "Сделано три задачи из пяти.");
assert.equal(web("kk", m.text), "Сделано три задачи из пяти.");
// Telegram for an English reader: the model's words are not rewritten either.
const tg = await lastTelegram();
assert.equal(tg.peppa_localized, true);
assert.match(tg.text, /Analyst:\nСделано три задачи из пяти\.\n\nReply:/);
setScenario({});
});
});