peppa/packages/testkit/test/i18n-product-mode.test.ts
Асель b5c0e704a5 PEP-150: сбои не идут пользователю — задержка на стороне платформы, одно сообщение суперадмину
platformDelay/sessionDelay вместо attention владельцу: падения и зависания агентов, лимиты,
красные и зависшие проверки, запуск агента, обновление версии, приёмка; guard конвейера —
вопрос суперадмину в платформенном проекте; строка задержки в задаче и на карточке;
список задержек на Главной суперадмина.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 14:09:30 +05:00

137 lines
8.0 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-125: the texts of the «Продакт» view come from the dictionaries — Russian (the key),
// English and Kazakh; «Peppa FACTORY» is the same in every language.
import { test } from "node:test";
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
import { dictionary, t } from "@peppa/shared/i18n";
import { wording } from "@peppa/shared/wording";
const run = promisify(execFile);
const root = new URL("../../..", import.meta.url).pathname;
const placeholders = (s: string) => [...s.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort().join(",");
const check = (file: string) =>
run("node", ["scripts/i18n-check.ts", "--file", file], { cwd: root }).then(
(x) => ({ code: 0, out: x.stdout }),
(e: { code: number; stdout: string }) => ({ code: e.code, out: e.stdout }),
);
// Screens of the «Продакт» view; a story that adds one lists it here.
const SCREENS = ["apps/web/app/(app)/settings/page.tsx", "apps/web/app/(app)/p/[key]/page.tsx", "apps/web/components/ProductCard.tsx", "apps/web/components/Sidebar.tsx", "apps/web/components/Accounting.tsx", "apps/web/app/(app)/help/page.tsx", "apps/web/app/(app)/t/[key]/page.tsx", "apps/web/components/StoryProduct.tsx", "apps/web/components/FeedbackButton.tsx", "apps/web/components/Feedback.tsx", "apps/web/app/(app)/feedback/page.tsx", "apps/web/components/PublishPanel.tsx", "apps/web/components/ProgressOverview.tsx"];
// Texts only the «Продакт» / «Инженер» views show; a story that adds one lists it here.
const TEXTS = [
"Вид Peppa FACTORY",
"Сохранено. Сейчас у вас вид «{mode}».",
"Продакт",
"Инженер",
"Только главное: что делается, что нужно от вас и где результат. Для тех, кто придумывает продукт, а не пишет код.",
"Всё, что делают агенты: код, проверки, каждый шаг агента, расход. Для тех, кто хочет заглянуть под капот.",
"Показать всем",
"Посмотрите — и, если всё хорошо,",
// PEP-145: the product always opens by a link
"Показывать всем",
"Сам",
"По кнопке",
"Готовим ссылку на продукт",
"Агент уже этим занят:",
"Агент возьмёт это первым:",
"Ваш продукт готов — пока его видите только вы",
"Последнее обновление не запустилось — по ссылке открывается прежняя версия. Чиним.",
"Посмотреть результат",
"Когда задачи этой версии будут приняты, Peppa FACTORY сама покажет её всем.",
// PEP-121: one line instead of the limits bar.
"Агенты работают",
"Агенты продолжат в",
// PEP-112: demo mode and the product agent's acceptance in the «Ваш продукт» card.
"Работает в демо-режиме — чтобы заработало по-настоящему, нужно от вас:",
"Вставьте ключ сюда",
"Как пользоваться продуктом",
"Пока не настоящее",
// PEP-123: the word of the view is a placeholder filled by wording(mode, locale).
"Создать {task}",
"Новая {task}",
"{Tasks} пока нет.",
"Агенты ждут вашего решения — ответьте здесь или в Telegram.",
// PEP-120: the story page of the «Продакт» view.
"Что с задачей",
"Шаг {n} из {m}",
"Что нужно от вас",
"Работа готова — посмотрите результат",
"Поправить",
// PEP-143: «Сообщить о проблеме» and the user's own reports.
"Сообщить о проблеме",
"Спасибо, передали команде",
"Ваши обращения",
"Получено",
"Разбираем",
"Исправлено",
"Отклонено",
// PEP-150: a delay on the platform's side — a line on the story instead of a message.
"Небольшая задержка на нашей стороне, от вас ничего не нужно",
"Небольшая задержка на нашей стороне",
"Peppa FACTORY продолжит работу сама. Вы получите сообщение, когда работа будет готова.",
];
for (const [locale, title, product, engineer] of [
["ru", "Вид Peppa FACTORY", "Продакт", "Инженер"],
["en", "Peppa FACTORY view", "Product", "Engineer"],
["kk", "Peppa FACTORY көрінісі", "Продакт", "Инженер"],
] as const) {
test(`Scenario Outline: Выбор вида на языке пользователя — ${locale}`, () => {
assert.equal(t(locale, "Вид Peppa FACTORY"), title);
assert.equal(t(locale, "Продакт"), product);
assert.equal(t(locale, "Инженер"), engineer);
});
}
test("Scenario: Кнопка «Показать всем» на английском", () => {
assert.equal(t("en", "Показать всем"), "Show everyone");
assert.equal(t("kk", "Показать всем"), "Барлығына көрсету");
assert.equal(t("ru", "Показать всем"), "Показать всем");
});
test("Scenario Outline: «Создать задачу» в виде «Продакт» и «Создать стори» в виде «Инженер»", () => {
for (const [locale, product, engineer] of [
["ru", "Создать задачу", "Создать стори"],
["en", "Create task", "Create story"],
["kk", "Жаңа тапсырма жасау", "Жаңа стори жасау"],
] as const) {
assert.equal(t(locale, "Создать {task}", { task: wording("product", locale).task("acc") }), product);
assert.equal(t(locale, "Создать {task}", { task: wording("engineer", locale).task("acc") }), engineer);
}
});
test("Тексты режима есть на обоих языках, «Peppa FACTORY» не переводится", () => {
const en = dictionary("en");
const kk = dictionary("kk");
for (const key of TEXTS) {
assert.ok(en[key]?.trim(), `en: нет перевода «${key}»`);
assert.ok(kk[key]?.trim(), `kk: нет перевода «${key}»`);
assert.doesNotMatch(en[key]!, /[А-Яа-яЁё]/, `русский в английском: ${key}`);
for (const [lang, v] of [["en", en[key]!], ["kk", kk[key]!]] as const) {
assert.equal(placeholders(v), placeholders(key), `${lang}: плейсхолдеры «${key}»`);
assert.equal(v.includes("Peppa FACTORY"), key.includes("Peppa FACTORY"), `${lang}: название продукта в «${key}»`);
}
}
});
test("Экраны режима «Продакт»: все тексты через словарь", async () => {
for (const file of SCREENS) {
const r = await check(join(root, file));
assert.equal(r.code, 0, `${file}\n${r.out.split("\n").slice(-10).join("\n")}`);
}
});
test("Scenario: Текст режима без перевода не проходит проверку", async () => {
const file = join(mkdtempSync(join(tmpdir(), "mock-product-mode-")), "mock-screen.tsx");
writeFileSync(file, 'const t = (s: string) => s;\nexport const a = <b>{t("Вид для продакта без перевода")}</b>;\nexport const b = <p>Строка мимо словаря</p>;\n');
const r = await check(file);
assert.equal(r.code, 1);
assert.match(r.out, /нет перевода: .*mock-screen\.tsx:2 «Вид для продакта без перевода»/);
assert.match(r.out, /не через словарь: .*mock-screen\.tsx:3 «Строка мимо словаря»/);
});