PEP-138: AI roles' chat messages go through the dictionary; strict line translation keeps the model's own words
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
a780516770
commit
e4f21a9a29
@ -2,7 +2,7 @@
|
||||
// alerts) to the paired chat and turns button presses / replies into answers delivered
|
||||
// back into the agent session. Telegram is an adapter over the DB, not a remote shell:
|
||||
// it can only answer a specific pending question or resume/stop the session it is about.
|
||||
import { localizeMessage, reportPlatformError, telegramChatLocale } from "@peppa/core";
|
||||
import { LOCALIZED_PARAM, localizeMessage, reportPlatformError, telegramChatLocale } from "@peppa/core";
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import {
|
||||
accountUsageForUser,
|
||||
@ -187,6 +187,11 @@ export function createBot(o: BotOptions) {
|
||||
// call the text, caption and button labels are translated for the chat's user.
|
||||
const readerChat = new AsyncLocalStorage<number>();
|
||||
const localizeParams = async (params: Record<string, unknown>): Promise<Record<string, unknown>> => {
|
||||
if (LOCALIZED_PARAM in params) {
|
||||
// PEP-138: written for this reader already (an AI role's message with free text inside).
|
||||
const { [LOCALIZED_PARAM]: _done, ...rest } = params;
|
||||
return rest;
|
||||
}
|
||||
const chatId = typeof params.chat_id === "number" ? params.chat_id : readerChat.getStore();
|
||||
if (chatId == null) return params;
|
||||
const locale = await telegramChatLocale(db, chatId).catch(() => "ru" as const);
|
||||
|
||||
@ -324,7 +324,7 @@ async function MessageItem({ m, q, back, showThread, masterView, mine = false }:
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
|
||||
{m.authorKind === "user" ? <UserIcon className="size-3.5" /> : m.authorKind === "agent" ? (m.authorLogin ? null : <Bot className="size-3.5" />) : <MessagesSquare className="size-3.5" />}
|
||||
{m.authorKind === "agent" && m.authorLogin ? (
|
||||
<AgentBadge name={m.authorLogin} className="text-foreground" />
|
||||
<AgentBadge name={t.role(m.authorLogin)} className="text-foreground" />
|
||||
) : (
|
||||
<span className="font-medium text-foreground">{m.authorKind === "user" ? (mine ? t("вы") : (m.authorLogin ?? "?")) : m.authorKind === "agent" ? t("агент") : PRODUCT_NAME}</span>
|
||||
)}
|
||||
@ -350,7 +350,7 @@ async function MessageItem({ m, q, back, showThread, masterView, mine = false }:
|
||||
return (
|
||||
<article className={cn("flex flex-col gap-1 rounded-lg border bg-card px-3 py-2", m.kind === "user" && "border-primary/30 bg-primary/5", m.kind === "system" && "border-dashed bg-transparent")}>
|
||||
{head}
|
||||
<p className="m-0 text-sm break-words whitespace-pre-wrap">{linkify(m.authorKind === "system" ? t.text(m.text) : m.text)}</p>
|
||||
<p className="m-0 text-sm break-words whitespace-pre-wrap">{linkify(m.authorKind === "system" ? t.text(m.text) : m.authorKind === "agent" ? t.role(m.text) : m.text)}</p>
|
||||
{m.url && (
|
||||
<a href={m.url} target="_blank" rel="noreferrer" className="truncate text-xs">
|
||||
{m.url}
|
||||
|
||||
@ -10,14 +10,12 @@ import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { inbox } from "@/lib/queries";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
return { title: t("Чаты — Peppa FACTORY") };
|
||||
}
|
||||
|
||||
const ANALYST = m("Аналитик");
|
||||
|
||||
/**
|
||||
* «Чаты» (PEP-117): the overview a product manager lands on — what waits for their answer and
|
||||
@ -62,10 +60,10 @@ export default async function Chats({ searchParams }: { searchParams: Promise<{
|
||||
{c.last ? (
|
||||
<span className="flex min-w-0 flex-col gap-0.5 text-sm">
|
||||
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
{c.last.who === ANALYST ? <AgentBadge name={t(ANALYST)} /> : <span>{c.last.mine ? t("вы") : c.last.who}</span>}
|
||||
{c.last.agent ? <AgentBadge name={t.role(c.last.who)} /> : <span>{c.last.mine ? t("вы") : c.last.who}</span>}
|
||||
<span>· {ago(c.last.at, t)}</span>
|
||||
</span>
|
||||
<span className="line-clamp-2 text-muted-foreground">{c.last.system ? t.text(c.last.text) : c.last.text}</span>
|
||||
<span className="line-clamp-2 text-muted-foreground">{c.last.system ? t.text(c.last.text) : c.last.agent ? t.role(c.last.text) : c.last.text}</span>
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground">{t("Здесь пока тихо. Спросите аналитика, что с проектом, или опишите новую задачу.")}</span>
|
||||
|
||||
@ -0,0 +1,25 @@
|
||||
## Context
|
||||
|
||||
Тексты без известного читателя (core/runner) помечаются `m()` и хранятся по-русски; слой доставки (бот, push, веб `t.text`) переводит их обратным сопоставлением `localizeText` — целиком, затем построчно. Сообщения ИИ-ролей смешивают постоянные фразы фабрики и свободный текст модели.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:** постоянные фразы сообщений аналитика, продакта и списка нужного от владельца приходят на языке читателя в вебе, Telegram и push.
|
||||
|
||||
**Non-Goals:** перевод свободного текста модели; язык, на котором модель отвечает; хранение сообщений на нескольких языках.
|
||||
|
||||
## Decisions
|
||||
|
||||
- **Одна постоянная фраза — одна строка сообщения.** `localizeText` надёжно сопоставляет строки; фраза внутри строки со свободным текстом («… . Где взять: …») не переводится. Поэтому «Где взять: {how}» в сообщении продакта вынесено на отдельную строку под пунктом (как уже сделано в списке от агента).
|
||||
- **Без склеивания падежей с плейсхолдером.** «Посмотрел {envLabel}» заменено двумя полными ключами («Посмотрел версию для проверки: {url}», «Посмотрел рабочую версию: {url}») — правило для казахского из памяти проекта.
|
||||
- **Строгий перевод для сообщений ИИ-ролей — `localizeRoleMessage`.** Первая попытка — пропустить сообщение роли через общий `localizeText` — провалилась на тесте: он выбирает вариант «меньше всего русских букв» и переписывает свободный текст модели («Сделано три задачи из пяти.» → «три задачи of пяти. done»). Поэтому для таких сообщений отдельная функция в `@peppa/shared/i18n`: переводит только целые строки, совпавшие с ключом из списка `ROLE_MESSAGE_KEYS` (отступ сохраняется, значения плейсхолдеров — как написаны), остальное не трогает. Новая постоянная строка в сообщении роли = ключ в этом списке. Альтернатива — признак «переводимая строка» в `chat_messages` — требует миграции и разметки внутри текста.
|
||||
- **Веб**: сообщение с `authorKind: agent` и подпись роли — через `t.role` (`Translator.role`); системные — по-прежнему `t.text`; сообщения людей не трогаем.
|
||||
- **Telegram и push** из `sayInDiscussion` собираются сразу на языке получателя (`getUserLocale`) и помечаются `Delivery.localized`: `deliverToUser` не переводит push повторно и кладёт в параметры outbox служебный признак `peppa_localized`, бот его снимает и текст не переводит. Без этого бот переписывал бы слова модели общим переводом.
|
||||
- **Подписи ролей** «Аналитик» / «Продакт» / «Агент {name}» хранятся по-русски (цвет значка считается от показанного имени).
|
||||
- **Сбой аналитика**: техническая причина в скобках убрана из текста для пользователя (правило «ошибка без кодов»), остаётся в логе вачдога.
|
||||
- Переводы — в раздел `runner` словарей en/kk.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- Строка модели, целиком совпавшая с постоянной строкой («Как пользоваться:»), переведётся — смысл тот же.
|
||||
- Зеркало чатов в Telegram-группы и события агентов со свободным текстом по-прежнему идут через общий перевод, который может переписать свободный текст, — вне этой стори, заведена отдельная.
|
||||
@ -0,0 +1,24 @@
|
||||
## Why
|
||||
|
||||
Сообщения, которые владелец продукта читает в обсуждении проекта и в Telegram, собираются в ядре без пометки для перевода и всегда приходят по-русски: ответы «Аналитика» при сбое и «Завёл в бэклог», сообщение «Продакта» после приёмки, список «чтобы заработало по-настоящему». При английском и казахском языке интерфейса пользователь видит русские фразы посреди переведённого экрана.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Постоянные фразы этих сообщений собираются через `m()` (одна фраза — одна строка сообщения) и получают переводы en/kk.
|
||||
- Обсуждение проекта и обзор чатов в вебе переводят постоянные фразы в сообщениях ИИ-ролей (раньше — только системные сообщения); подписи «Аналитик» и «Продакт» показываются на языке интерфейса.
|
||||
- Свободный текст модели (сам ответ аналитика, выводы продакта, названия пунктов) не переводится — он остаётся таким, каким написан.
|
||||
- Пометок `glossary-user` (PEP-129) в основной ветке нет — убирать нечего; тексты проходят общую проверку i18n-check.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
### Modified Capabilities
|
||||
- `interface-language`: сообщения ИИ-ролей в обсуждении проекта (аналитик, продакт, список нужного от владельца) приходят на языке читателя.
|
||||
|
||||
## Impact
|
||||
|
||||
- `packages/runner/src/analyst-chat.ts`, `packages/runner/src/product-review.ts`, `packages/core/src/product-review.ts`, `packages/core/src/product-needs.ts`, `packages/mcp/src/agent.ts`
|
||||
- `packages/shared/src/i18n/en/runner.ts`, `packages/shared/src/i18n/kk/runner.ts`
|
||||
- `apps/web/app/(app)/chats/page.tsx`, `apps/web/app/(app)/chats/[chat]/page.tsx`
|
||||
- тест `packages/testkit/test/i18n-role-messages.test.ts`
|
||||
@ -0,0 +1,44 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Сообщения ИИ-ролей в обсуждении на языке читателя
|
||||
Постоянные фразы сообщений, которые «Аналитик», «Продакт» и агенты пишут владельцу в обсуждение проекта (сбой ответа аналитика, «Завёл в бэклог», сообщение после приёмки, список «чтобы заработало по-настоящему», заметка о демо-режиме), SHALL показываться на выбранном языке интерфейса читателя — в вебе, Telegram и push. Свободный текст модели SHALL оставаться без изменений.
|
||||
|
||||
#### Scenario Outline: Аналитик завёл задачу
|
||||
- **GIVEN** пользователь с языком интерфейса `<язык>`
|
||||
- **AND** аналитик ответил «Готово.» и завёл задачу DEMO-5 «Экспорт в PDF»
|
||||
- **WHEN** пользователь открывает обсуждение проекта
|
||||
- **THEN** под ответом «Готово.» стоит строка `<строка>`
|
||||
- **AND** ниже — «• DEMO-5 «Экспорт в PDF»»
|
||||
|
||||
| язык | строка |
|
||||
|---|---|
|
||||
| ru | Завёл в бэклог: |
|
||||
| en | Added to the backlog: |
|
||||
| kk | Бэклогқа қостым: |
|
||||
|
||||
#### Scenario: Сообщение продакта после приёмки на английском
|
||||
- **GIVEN** пользователь с языком интерфейса English
|
||||
- **AND** продакт посмотрел версию для проверки https://demo-staging.telecom.quest и нашёл, что для работы нужен «Ключ Claude API»
|
||||
- **WHEN** пользователь получает сообщение продакта в Telegram
|
||||
- **THEN** сообщение начинается с «Looked at the review version: https://demo-staging.telecom.quest»
|
||||
- **AND** в нём есть заголовки «How to use it:» и «To make it work for real, we need from you:»
|
||||
- **AND** автор подписан «Product»
|
||||
|
||||
#### Scenario: Список нужного от владельца на казахском
|
||||
- **GIVEN** пользователь с языком интерфейса «Қазақша»
|
||||
- **AND** агент объявил, что продукту нужен «Ключ Claude API» с пояснением, где его взять
|
||||
- **WHEN** пользователь открывает обсуждение проекта
|
||||
- **THEN** в сообщении нет русских постоянных фраз «Где взять», «Куда вставить», «Ключи хранятся зашифрованными»
|
||||
- **AND** название пункта «Ключ Claude API» показано как написал агент
|
||||
|
||||
#### Scenario: Аналитик не смог ответить — английский
|
||||
- **GIVEN** пользователь с языком интерфейса English
|
||||
- **AND** у проекта не подключена подписка
|
||||
- **WHEN** он пишет в обсуждение проекта и открывает его снова
|
||||
- **THEN** он видит «The analyst answers on the project's subscription, and it is not connected.» и что сделать
|
||||
- **AND** в тексте нет русских слов
|
||||
|
||||
#### Scenario: Свободный текст не переводится
|
||||
- **GIVEN** пользователь с языком интерфейса English
|
||||
- **WHEN** аналитик отвечает «Сделано три задачи из пяти.»
|
||||
- **THEN** ответ показан как написан: «Сделано три задачи из пяти.»
|
||||
@ -0,0 +1,17 @@
|
||||
## 1. Тексты через словарь
|
||||
|
||||
- [x] 1.1 Сообщения аналитика (сбой, не по форме, «Завёл в бэклог») и уведомление «Ответить» — через `m()`
|
||||
- [x] 1.2 Сообщение продакта после приёмки — построчные ключи `m()`
|
||||
- [x] 1.3 Список «чтобы заработало по-настоящему», заметка о демо-режиме и сообщение агента — через `m()`
|
||||
- [x] 1.4 Переводы en и kk
|
||||
|
||||
## 2. Показ
|
||||
|
||||
- [x] 2.1 Веб: обсуждение и обзор чатов переводят сообщения и подписи ИИ-ролей
|
||||
|
||||
- [x] 2.2 Telegram и push: сообщение роли собирается на языке получателя, бот не переводит его повторно
|
||||
|
||||
## 3. Проверка
|
||||
|
||||
- [x] 3.1 Тест `i18n-role-messages.test.ts` по сценариям спеки
|
||||
- [ ] 3.2 Проверки проекта: lint, typecheck, test, build; сверка текстов со словарём
|
||||
@ -260,7 +260,7 @@ export interface ProjectChatCard {
|
||||
/** Agent questions of the project waiting for a person. */
|
||||
open: number;
|
||||
/** The last message of the chat with the analyst. */
|
||||
last: { who: string; mine: boolean; text: string; at: Date; /** Written by the factory itself (translatable text). */ system: boolean } | null;
|
||||
last: { who: string; mine: boolean; text: string; at: Date; /** Written by the factory itself (translatable text). */ system: boolean; /** Written by an AI role: the fixed phrases are translatable (PEP-138). */ agent: boolean } | null;
|
||||
}
|
||||
|
||||
/** PEP-117: the user's project chats at a glance — what is new and what was said last. */
|
||||
@ -276,7 +276,7 @@ export async function chatOverview(db: Db, user: Pick<User, "id">): Promise<Proj
|
||||
name: c.title.includes(" · ") ? c.title.split(" · ").slice(1).join(" · ") : c.title,
|
||||
unread: unread.get(c.id) ?? 0,
|
||||
open: c.open,
|
||||
last: m ? { who: m.authorKind === "agent" ? (m.authorLogin ?? tr("Аналитик")) : (m.authorLogin ?? PRODUCT_NAME), mine: m.authorUserId === user.id, text: m.text, at: m.createdAt, system: m.authorKind === "system" } : null,
|
||||
last: m ? { who: m.authorKind === "agent" ? (m.authorLogin ?? tr("Аналитик")) : (m.authorLogin ?? PRODUCT_NAME), mine: m.authorUserId === user.id, text: m.text, at: m.createdAt, system: m.authorKind === "system", agent: m.authorKind === "agent" } : null,
|
||||
});
|
||||
}
|
||||
// What needs the person first: open questions, then unread, then the most recent talk.
|
||||
|
||||
@ -159,6 +159,9 @@ export async function projectAudience(db: Db, projectId: number): Promise<User[]
|
||||
return (await db.select().from(users).where(inArray(users.id, ids))).filter((u) => !u.disabledAt);
|
||||
}
|
||||
|
||||
/** Private mark in outbox params: the text is already in the reader's language; the bot strips it before sending. */
|
||||
export const LOCALIZED_PARAM = "peppa_localized";
|
||||
|
||||
export interface Delivery {
|
||||
event: NotifyEvent;
|
||||
/** Muting a project silences it; null = not about a project (monitoring, digest). */
|
||||
@ -169,6 +172,8 @@ export interface Delivery {
|
||||
pushKey?: string;
|
||||
telegram?: { method?: OutboxRow["method"]; params: Record<string, unknown>; questionId?: number };
|
||||
push?: PushPayload;
|
||||
/** The texts are already in this user's language (free text inside): nobody translates them again (PEP-138). */
|
||||
localized?: boolean;
|
||||
urgency?: "normal" | "high";
|
||||
now?: Date;
|
||||
}
|
||||
@ -199,13 +204,13 @@ export async function deliverToUser(db: Db, user: User, d: Delivery, prefs?: Not
|
||||
dedupeKey: d.dedupeKey,
|
||||
method: d.telegram.method ?? "sendMessage",
|
||||
questionId: d.telegram.questionId,
|
||||
params: { ...d.telegram.params, chat_id: user.telegramChatId, ...(quiet ? { disable_notification: true } : {}) },
|
||||
params: { ...d.telegram.params, ...(d.localized ? { [LOCALIZED_PARAM]: true } : {}), chat_id: user.telegramChatId, ...(quiet ? { disable_notification: true } : {}) },
|
||||
});
|
||||
}
|
||||
if (ch.push && d.push && !quiet) {
|
||||
// PEP-98: push text in the user's language (Telegram is translated by the bot when sent).
|
||||
const locale = await getUserLocale(db, user.id);
|
||||
const push = locale === "ru" ? d.push : { ...d.push, title: localizeMessage(locale, d.push.title), body: localizeMessage(locale, d.push.body) };
|
||||
const push = locale === "ru" || d.localized ? d.push : { ...d.push, title: localizeMessage(locale, d.push.title), body: localizeMessage(locale, d.push.body) };
|
||||
out.push = await enqueuePush(db, user.id, { dedupeKey: d.pushKey ?? d.dedupeKey, payload: { ...push, sound: d.push.sound ?? p.sound }, urgency: d.urgency });
|
||||
}
|
||||
return out;
|
||||
|
||||
@ -1,4 +1,3 @@
|
||||
// glossary-user-file: список «чтобы заработало по-настоящему» уходит владельцу продукта в чат
|
||||
// PEP-112: «чтобы заработало по-настоящему» — what the project's owner has to give before the
|
||||
// product stops being a demo: a key, an account, a decision. The developer agent declares the
|
||||
// items (MCP `declare_needs`), the product agent adds what it saw on the deployed product, the
|
||||
@ -10,6 +9,7 @@ import { eq } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { secretNameError } from "./secrets.ts";
|
||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
|
||||
export type NeedSource = "agent" | "product";
|
||||
|
||||
@ -109,7 +109,7 @@ export async function declareNeeds(db: Db, projectId: number, inputs: NeedInput[
|
||||
export async function setNeedDone(db: Db, projectId: number, id: string, done: boolean, now = new Date()): Promise<void> {
|
||||
const list = await stored(db, projectId);
|
||||
const n = list.find((x) => x.id === id);
|
||||
if (!n) throw new PeppaError("Такого пункта нет");
|
||||
if (!n) throw new PeppaError(tr("Такого пункта нет"));
|
||||
n.doneAt = done ? now.toISOString() : null;
|
||||
await setSetting(db, key(projectId), list);
|
||||
}
|
||||
@ -125,11 +125,11 @@ export async function removeNeed(db: Db, projectId: number, id: string): Promise
|
||||
export function needsText(needs: ProductNeed[], webUrl: string, projectKey: string): string {
|
||||
const lines = needs.map((n, i) => {
|
||||
const parts = [`${i + 1}. ${n.title}${n.why ? ` — ${n.why}` : ""}`];
|
||||
if (n.how) parts.push(` Где взять: ${n.how}`);
|
||||
parts.push(n.secret ? " Куда вставить: страница проекта → карточка «Ваш продукт» → поле рядом с этим пунктом." : " Когда сделаете — отметьте «Сделано» в карточке «Ваш продукт».");
|
||||
if (n.how) parts.push(` ${tr("Где взять: {how}", { how: n.how })}`);
|
||||
parts.push(n.secret ? ` ${tr("Куда вставить: страница проекта → карточка «Ваш продукт» → поле рядом с этим пунктом.")}` : ` ${tr("Когда сделаете — отметьте «Сделано» в карточке «Ваш продукт».")}`);
|
||||
return parts.join("\n");
|
||||
});
|
||||
return [...lines, "", `Карточка «Ваш продукт»: ${webUrl}/p/${projectKey}`, "Ключи хранятся зашифрованными, Peppa FACTORY сама передаст их продукту и перезапустит его."].join("\n");
|
||||
return [...lines, "", tr("Карточка «Ваш продукт»: {url}", { url: `${webUrl}/p/${projectKey}` }), tr("Ключи хранятся зашифрованными, Peppa FACTORY сама передаст их продукту и перезапустит его.")].join("\n");
|
||||
}
|
||||
|
||||
/** One line for messages and the card: «нужно: Ключ Claude API, Аккаунт Stripe». */
|
||||
@ -138,5 +138,5 @@ export const needsLine = (needs: Pick<ProductNeed, "title">[]) => needs.map((n)
|
||||
/** A line for «готово к ревью»: the story is done, but the product is not real yet ("" when it is). */
|
||||
export async function demoNote(db: Db, projectId: number, projectKey: string, webUrl = process.env.PEPPA_WEB_URL ?? ""): Promise<string> {
|
||||
const open = await openNeeds(db, projectId).catch(() => []);
|
||||
return open.length ? `⚠️ Продукт пока работает в демо-режиме. Нужно от вас: ${needsLine(open)} — вставить можно в карточке «Ваш продукт»: ${webUrl}/p/${projectKey}` : "";
|
||||
return open.length ? `${tr("⚠️ Продукт пока работает в демо-режиме. Нужно от вас: {needs}", { needs: needsLine(open) })}\n${tr("Вставить можно в карточке «Ваш продукт»: {url}", { url: `${webUrl}/p/${projectKey}` })}` : "";
|
||||
}
|
||||
|
||||
@ -7,6 +7,7 @@
|
||||
import type { ProductNeedView } from "./product-needs.ts";
|
||||
import { getSetting, setSetting, deleteSetting } from "./settings.ts";
|
||||
import type { Db } from "@peppa/db";
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
|
||||
/** The product agent's name on its messages (an AI agent, shown with the robot badge). */
|
||||
export const PRODUCT_AGENT_NAME = "Продакт";
|
||||
@ -190,23 +191,19 @@ export function parseProductReview(text: string): ProductReviewReply | null {
|
||||
}
|
||||
|
||||
/** The product agent's message to the owner in the project's discussion. */
|
||||
export function productReviewMessage(r: ProductReviewReply, o: { envLabel: string; url: string; openNeeds: ProductNeedView[]; filed: string[]; webUrl: string; projectKey: string }): string {
|
||||
export function productReviewMessage(r: ProductReviewReply, o: { env: "prod" | "staging"; url: string; openNeeds: ProductNeedView[]; filed: string[]; webUrl: string; projectKey: string }): string {
|
||||
const steps = (items: string[]) => items.map((x, i) => `${i + 1}. ${x}`).join("\n");
|
||||
const bullets = (items: string[]) => items.map((x) => `• ${x}`).join("\n");
|
||||
return [
|
||||
// glossary-user: сообщение «Продакта» в обсуждение проекта
|
||||
`Посмотрел ${o.envLabel}: ${o.url}`,
|
||||
o.env === "prod" ? tr("Посмотрел рабочую версию: {url}", { url: o.url }) : tr("Посмотрел версию для проверки: {url}", { url: o.url }),
|
||||
r.summary,
|
||||
// glossary-user: сообщение «Продакта» в обсуждение проекта
|
||||
...(r.howto.length ? [`Как пользоваться:\n${steps(r.howto)}`] : []),
|
||||
...(r.notReal.length ? [`Пока не настоящее:\n${bullets(r.notReal)}`] : []),
|
||||
...(r.howto.length ? [`${tr("Как пользоваться:")}\n${steps(r.howto)}`] : []),
|
||||
...(r.notReal.length ? [`${tr("Пока не настоящее:")}\n${bullets(r.notReal)}`] : []),
|
||||
...(o.openNeeds.length
|
||||
? [
|
||||
// glossary-user: сообщение «Продакта» в обсуждение проекта
|
||||
`Чтобы заработало по-настоящему, нужно от вас:\n${bullets(o.openNeeds.map((n) => `${n.title}${n.why ? ` — ${n.why}` : ""}${n.how ? `. Где взять: ${n.how}` : ""}`))}\nВставить или отметить «Сделано» — в карточке «Ваш продукт»: ${o.webUrl}/p/${o.projectKey}`,
|
||||
`${tr("Чтобы заработало по-настоящему, нужно от вас:")}\n${bullets(o.openNeeds.map((n) => `${n.title}${n.why ? ` — ${n.why}` : ""}${n.how ? `\n ${tr("Где взять: {how}", { how: n.how })}` : ""}`))}\n${tr("Вставить или отметить «Сделано» — в карточке «Ваш продукт»: {url}", { url: `${o.webUrl}/p/${o.projectKey}` })}`,
|
||||
]
|
||||
: []),
|
||||
// glossary-user: сообщение «Продакта» в обсуждение проекта
|
||||
...(o.filed.length ? [`Завёл доработки в бэклог:\n${bullets(o.filed)}`] : []),
|
||||
...(o.filed.length ? [`${tr("Завёл доработки в бэклог:")}\n${bullets(o.filed)}`] : []),
|
||||
].join("\n\n");
|
||||
}
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
// Peppa MCP server of an agent: gives sessions inside a project access to its epics, stories
|
||||
// (tasks in the tool names) and the PM. Served over stdio (index.ts) or, for agents in a runner
|
||||
// container, over the agent relay (PEP-17) — then locked to the session's project.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import {
|
||||
askPm,
|
||||
@ -355,8 +356,8 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
|
||||
const { added, all } = await declareNeeds(db, p.id, needs, { source: "agent", story: ref?.key ?? null });
|
||||
if (added.length) {
|
||||
const chat = await ensureProjectChat(db, p.id);
|
||||
const text = ["Чтобы продукт заработал по-настоящему, а не в демо-режиме, нужно от вас:", "", needsText(added, process.env.PEPPA_WEB_URL ?? "", p.key)].join("\n");
|
||||
await sayInDiscussion(db, p, chat.id, text, session?.agentName ? `Агент ${session.agentName}` : "Агент");
|
||||
const text = [tr("Чтобы продукт заработал по-настоящему, а не в демо-режиме, нужно от вас:"), "", needsText(added, process.env.PEPPA_WEB_URL ?? "", p.key)].join("\n");
|
||||
await sayInDiscussion(db, p, chat.id, text, session?.agentName ? tr("Агент {name}", { name: session.agentName }) : tr("Агент"));
|
||||
}
|
||||
const line = (n: (typeof all)[number]) => `- ${n.open ? "⏳ ждёт владельца" : "✅ дано"}: ${n.title}${n.secret ? ` ($${n.secret})` : ""}`;
|
||||
return [`Список «чтобы заработало по-настоящему» проекта ${p.key}:`, ...all.map(line), added.length ? `Владельцу отправлено сообщение о новых пунктах (${added.length}).` : "Новых пунктов нет — владельцу ничего не отправлено.", "Пока пункт открыт, продукт работает на моке: в резюме PR и в сообщении о готовности так и скажи. Служебных полей (токены, ключи) на экране пользователя быть не должно."].join("\n");
|
||||
|
||||
@ -12,6 +12,7 @@ import {
|
||||
createTask,
|
||||
deliverToUser,
|
||||
discussionHistory,
|
||||
getUserLocale,
|
||||
notify,
|
||||
parseAnalystReply,
|
||||
projectAudience,
|
||||
@ -21,6 +22,7 @@ import {
|
||||
} from "@peppa/core";
|
||||
import { chatMessages, chats, projects, type Db } from "@peppa/db";
|
||||
import { and, desc, eq, gt, isNull } from "drizzle-orm";
|
||||
import { localizeRoleMessage, m as tr, t } from "@peppa/shared/i18n";
|
||||
import { claudePrint } from "./claude-print.ts";
|
||||
|
||||
const inFlight = new Set<number>();
|
||||
@ -87,15 +89,21 @@ export async function sayInDiscussion(db: Db, project: Project, chatId: number,
|
||||
const m = await addChatMessage(db, author ? { chatId, kind: "user", authorKind: "agent", authorLogin: author, text } : { chatId, kind: "user", authorKind: "system", text });
|
||||
await notify(db, { type: "chat_message", messageId: m?.id ?? 0 });
|
||||
if (author && m) {
|
||||
const short = text.length > 800 ? `${text.slice(0, 800)}…` : text;
|
||||
const cut = (s: string) => (s.length > 800 ? `${s.slice(0, 800)}…` : s);
|
||||
for (const u of await projectAudience(db, project.id)) {
|
||||
// In the reader's language here: only the fixed lines are translated, the model's own
|
||||
// words stay as written (the general translation on delivery would rewrite them).
|
||||
const locale = await getUserLocale(db, u.id);
|
||||
const short = cut(localizeRoleMessage(locale, text));
|
||||
const who = localizeRoleMessage(locale, author);
|
||||
await deliverToUser(db, u, {
|
||||
event: "chat",
|
||||
localized: true,
|
||||
projectId: project.id,
|
||||
dedupeKey: `chat:m${m.id}:${u.telegramChatId}`,
|
||||
pushKey: `chat:m${m.id}:u${u.id}`,
|
||||
telegram: { params: { text: `💬 <b>${esc(project.name)}</b> · ${esc(author)}:\n${esc(short)}\n\nОтветить: ${process.env.PEPPA_WEB_URL ?? ""}/chats/${project.key}`, parse_mode: "HTML", link_preview_options: { is_disabled: true } } },
|
||||
push: { title: `${project.name}: ${author}`, body: short.slice(0, 200), url: `/chats/${project.key}`, tag: `chat:${project.id}` },
|
||||
telegram: { params: { text: `💬 <b>${esc(project.name)}</b> · ${esc(who)}:\n${esc(short)}\n\n${t(locale, "Ответить: {url}", { url: `${process.env.PEPPA_WEB_URL ?? ""}/chats/${project.key}` })}`, parse_mode: "HTML", link_preview_options: { is_disabled: true } } },
|
||||
push: { title: `${project.name}: ${who}`, body: short.slice(0, 200), url: `/chats/${project.key}`, tag: `chat:${project.id}` },
|
||||
}).catch(() => null);
|
||||
}
|
||||
}
|
||||
@ -111,15 +119,13 @@ async function answer(db: Db, project: Project, chatId: number, upTo: number, lo
|
||||
await setAnalystCursor(db, chatId, upTo);
|
||||
if (!out.ok) {
|
||||
const noSub = /нет подписки/.test(out.error);
|
||||
// glossary-user: ответ «Аналитика» в обсуждение проекта
|
||||
await say(db, project, chatId, noSub ? "Аналитик отвечает на подписке проекта, а она не подключена. Подключите Claude в «⋯ Настройки проекта → Подписки» — и напишите ещё раз." : `Аналитик сейчас не смог ответить (${out.error.slice(0, 200)}). Напишите ещё раз чуть позже.`, false);
|
||||
await say(db, project, chatId, noSub ? tr("Аналитик отвечает на подписке проекта, а она не подключена. Подключите Claude в «⋯ Настройки проекта → Подписки» — и напишите ещё раз.") : tr("Аналитик сейчас не смог ответить. Напишите ещё раз чуть позже."), false);
|
||||
log(`analyst chat ${project.key}: ${out.error}`);
|
||||
return;
|
||||
}
|
||||
const reply = parseAnalystReply(out.text);
|
||||
if (!reply) {
|
||||
// glossary-user: ответ «Аналитика» в обсуждение проекта
|
||||
await say(db, project, chatId, "Аналитик ответил не по форме — напишите вопрос ещё раз, пожалуйста.", false);
|
||||
await say(db, project, chatId, tr("Аналитик ответил не по форме — напишите вопрос ещё раз, пожалуйста."), false);
|
||||
log(`analyst chat ${project.key}: unparsable answer`);
|
||||
return;
|
||||
}
|
||||
@ -130,7 +136,6 @@ async function answer(db: Db, project: Project, chatId: number, upTo: number, lo
|
||||
await setIntakeState(db, ref.task.id, { stage: "done", original: { title: s.title, description: s.description }, attempts: 0, note: "сформулирована с аналитиком в чате" });
|
||||
filed.push(`• ${ref.key} «${s.title}»`);
|
||||
}
|
||||
// glossary-user: ответ «Аналитика» в обсуждение проекта
|
||||
await say(db, project, chatId, filed.length ? `${reply.reply}\n\nЗавёл в бэклог:\n${filed.join("\n")}` : reply.reply);
|
||||
await say(db, project, chatId, filed.length ? `${reply.reply}\n\n${tr("Завёл в бэклог:")}\n${filed.join("\n")}` : reply.reply);
|
||||
log(`analyst chat ${project.key}: answered${filed.length ? `, filed ${filed.length}` : ""}`);
|
||||
}
|
||||
|
||||
@ -166,7 +166,6 @@ async function review(db: Db, project: Project, rel: Release, pending: PendingPr
|
||||
const stillOpen = await openNeeds(db, project.id);
|
||||
await saveProductReview(db, project.id, { at: new Date().toISOString(), env: rel.env as "staging" | "prod", sha: rel.sha, url, summary: reply.summary, howto: reply.howto, notReal: reply.notReal, filed: filed.map((f) => f.split(" ")[0]!) });
|
||||
const chat = await ensureProjectChat(db, project.id);
|
||||
// glossary-user: сообщение «Продакта» в обсуждение проекта
|
||||
await sayInDiscussion(db, project, chat.id, productReviewMessage(reply, { envLabel: rel.env === "prod" ? "рабочую версию" : "версию для проверки", url, openNeeds: stillOpen, filed, webUrl: process.env.PEPPA_WEB_URL ?? "", projectKey: project.key }), PRODUCT_AGENT_NAME);
|
||||
await sayInDiscussion(db, project, chat.id, productReviewMessage(reply, { env: rel.env === "prod" ? "prod" : "staging", url, openNeeds: stillOpen, filed, webUrl: process.env.PEPPA_WEB_URL ?? "", projectKey: project.key }), PRODUCT_AGENT_NAME);
|
||||
log(`product review ${project.key}: ${rel.env} ${rel.sha.slice(0, 7)} — needs ${stillOpen.length}, stories ${filed.length}`);
|
||||
}
|
||||
|
||||
@ -399,4 +399,24 @@ export const runner: Dict = {
|
||||
"не git-репозиторий": "not a git repository",
|
||||
"незакоммиченные изменения": "uncommitted changes",
|
||||
"незапушенных коммитов: {n}": "unpushed commits: {n}",
|
||||
// PEP-138: messages of the AI roles in the project's discussion (one key per line)
|
||||
"Такого пункта нет": "There is no such item",
|
||||
"Куда вставить: страница проекта → карточка «Ваш продукт» → поле рядом с этим пунктом.": "Where to paste it: project page → «Your product» card → the field next to this item.",
|
||||
"Когда сделаете — отметьте «Сделано» в карточке «Ваш продукт».": "When it is done, tick «Done» in the «Your product» card.",
|
||||
"Карточка «Ваш продукт»: {url}": "«Your product» card: {url}",
|
||||
"Ключи хранятся зашифрованными, Peppa FACTORY сама передаст их продукту и перезапустит его.": "Keys are stored encrypted; Peppa FACTORY will pass them to the product and restart it.",
|
||||
"⚠️ Продукт пока работает в демо-режиме. Нужно от вас: {needs}": "⚠️ The product is still running in demo mode. We need from you: {needs}",
|
||||
"Вставить можно в карточке «Ваш продукт»: {url}": "You can paste it in the «Your product» card: {url}",
|
||||
"Посмотрел рабочую версию: {url}": "Looked at the live version: {url}",
|
||||
"Посмотрел версию для проверки: {url}": "Looked at the review version: {url}",
|
||||
"Как пользоваться:": "How to use it:",
|
||||
"Пока не настоящее:": "Not real yet:",
|
||||
"Чтобы заработало по-настоящему, нужно от вас:": "To make it work for real, we need from you:",
|
||||
"Вставить или отметить «Сделано» — в карточке «Ваш продукт»: {url}": "Paste it or tick «Done» in the «Your product» card: {url}",
|
||||
"Завёл доработки в бэклог:": "Added improvements to the backlog:",
|
||||
"Аналитик отвечает на подписке проекта, а она не подключена. Подключите Claude в «⋯ Настройки проекта → Подписки» — и напишите ещё раз.": "The analyst answers on the project's subscription, and it is not connected. Connect Claude in «⋯ Project settings → Subscriptions» and write again.",
|
||||
"Аналитик сейчас не смог ответить. Напишите ещё раз чуть позже.": "The analyst could not answer right now. Please write again a little later.",
|
||||
"Аналитик ответил не по форме — напишите вопрос ещё раз, пожалуйста.": "The analyst's answer came out garbled — please write your question again.",
|
||||
"Завёл в бэклог:": "Added to the backlog:",
|
||||
"Чтобы продукт заработал по-настоящему, а не в демо-режиме, нужно от вас:": "For the product to work for real, not in demo mode, we need from you:",
|
||||
};
|
||||
|
||||
@ -95,6 +95,8 @@ export interface Translator {
|
||||
n: (n: number, one: string, few: string, many: string, vars?: Record<string, unknown>) => string;
|
||||
/** Translates already rendered Russian text (see localizeText). */
|
||||
text: (text: string | null | undefined) => string;
|
||||
/** Translates the fixed lines of an AI role's message, leaving its free text (see localizeRoleMessage). */
|
||||
role: (text: string | null | undefined) => string;
|
||||
}
|
||||
|
||||
export function translator(locale: Locale): Translator {
|
||||
@ -102,6 +104,7 @@ export function translator(locale: Locale): Translator {
|
||||
fn.locale = locale;
|
||||
fn.n = (n, one, few, many, vars) => tn(locale, n, one, few, many, vars);
|
||||
fn.text = (text) => localizeText(locale, text ?? "");
|
||||
fn.role = (text) => localizeRoleMessage(locale, text);
|
||||
return fn;
|
||||
}
|
||||
|
||||
@ -273,6 +276,78 @@ export function localizeText(locale: Locale, text: string): string {
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- Messages of the AI roles: fixed lines among free text (PEP-138) ----------------------
|
||||
|
||||
/**
|
||||
* The fixed lines of the messages AI roles write into a project's discussion (analyst, product
|
||||
* agent, the «чтобы заработало по-настоящему» list) and the roles' names. The rest of such a
|
||||
* message is the model's own text, which `localizeText` must not touch: its "least Russian
|
||||
* left" matching rewrites free sentences («Сделано три задачи из пяти.»).
|
||||
*/
|
||||
export const ROLE_MESSAGE_KEYS: readonly string[] = [
|
||||
"Аналитик",
|
||||
"Продакт",
|
||||
"Агент",
|
||||
"Агент {name}",
|
||||
"Завёл в бэклог:",
|
||||
"Посмотрел рабочую версию: {url}",
|
||||
"Посмотрел версию для проверки: {url}",
|
||||
"Как пользоваться:",
|
||||
"Пока не настоящее:",
|
||||
"Чтобы заработало по-настоящему, нужно от вас:",
|
||||
"Где взять: {how}",
|
||||
"Вставить или отметить «Сделано» — в карточке «Ваш продукт»: {url}",
|
||||
"Завёл доработки в бэклог:",
|
||||
"Чтобы продукт заработал по-настоящему, а не в демо-режиме, нужно от вас:",
|
||||
"Куда вставить: страница проекта → карточка «Ваш продукт» → поле рядом с этим пунктом.",
|
||||
"Когда сделаете — отметьте «Сделано» в карточке «Ваш продукт».",
|
||||
"Карточка «Ваш продукт»: {url}",
|
||||
"Ключи хранятся зашифрованными, Peppa FACTORY сама передаст их продукту и перезапустит его.",
|
||||
];
|
||||
|
||||
const roleLines = new Map<Locale, { exact: Map<string, string>; templates: { re: RegExp; names: string[]; out: string }[] }>();
|
||||
|
||||
function compileRoleLines(locale: Locale) {
|
||||
let c = roleLines.get(locale);
|
||||
if (c) return c;
|
||||
c = { exact: new Map(), templates: [] };
|
||||
for (const key of ROLE_MESSAGE_KEYS) {
|
||||
const out = entry(locale, key);
|
||||
if (out === undefined) continue;
|
||||
if (!key.includes("{")) {
|
||||
c.exact.set(key, out);
|
||||
continue;
|
||||
}
|
||||
const parts = key.split(/\{(\w+)\}/);
|
||||
c.templates.push({ re: new RegExp(`^${parts.map((p, i) => (i % 2 ? "(.+)" : escapeRe(p))).join("")}$`), names: parts.filter((_p, i) => i % 2), out });
|
||||
}
|
||||
roleLines.set(locale, c);
|
||||
return c;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates a message of an AI role: only whole lines that are one of ROLE_MESSAGE_KEYS
|
||||
* (indentation kept, placeholder values as written); every other line stays as it is.
|
||||
*/
|
||||
export function localizeRoleMessage(locale: Locale, text: string | null | undefined): string {
|
||||
if (!text || locale === "ru" || !CYR.test(text)) return text ?? "";
|
||||
const c = compileRoleLines(locale);
|
||||
return text
|
||||
.split("\n")
|
||||
.map((raw) => {
|
||||
const lead = /^\s*/.exec(raw)![0];
|
||||
const body = raw.slice(lead.length);
|
||||
const exact = c.exact.get(body);
|
||||
if (exact !== undefined) return lead + exact;
|
||||
for (const tpl of c.templates) {
|
||||
const mt = tpl.re.exec(body);
|
||||
if (mt) return lead + fill(tpl.out, Object.fromEntries(tpl.names.map((n, i) => [n, mt[i + 1]])));
|
||||
}
|
||||
return raw;
|
||||
})
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
/** BCP 47 tag for Intl / toLocaleString in `locale`. */
|
||||
export const intlLocale = (locale: Locale) => (locale === "en" ? "en-GB" : locale === "kk" ? "kk-KZ" : "ru-RU");
|
||||
|
||||
|
||||
@ -307,4 +307,24 @@ export const runner: Dict = {
|
||||
"не git-репозиторий": "git-репозиторий емес",
|
||||
"незакоммиченные изменения": "коммиттелмеген өзгерістер",
|
||||
"незапушенных коммитов: {n}": "пуш жасалмаған коммиттер: {n}",
|
||||
// PEP-138: messages of the AI roles in the project's discussion (one key per line)
|
||||
"Такого пункта нет": "Мұндай тармақ жоқ",
|
||||
"Куда вставить: страница проекта → карточка «Ваш продукт» → поле рядом с этим пунктом.": "Қайда қою керек: жоба беті → «Сіздің өніміңіз» карточкасы → осы тармақтың жанындағы өріс.",
|
||||
"Когда сделаете — отметьте «Сделано» в карточке «Ваш продукт».": "Орындаған соң «Сіздің өніміңіз» карточкасында «Орындалды» деп белгілеңіз.",
|
||||
"Карточка «Ваш продукт»: {url}": "«Сіздің өніміңіз» карточкасы: {url}",
|
||||
"Ключи хранятся зашифрованными, Peppa FACTORY сама передаст их продукту и перезапустит его.": "Кілттер шифрланған күйде сақталады, Peppa FACTORY оларды өнімге өзі беріп, оны қайта іске қосады.",
|
||||
"⚠️ Продукт пока работает в демо-режиме. Нужно от вас: {needs}": "⚠️ Өнім әзірге демо-режимде жұмыс істеп тұр. Сізден керек: {needs}",
|
||||
"Вставить можно в карточке «Ваш продукт»: {url}": "«Сіздің өніміңіз» карточкасына қоюға болады: {url}",
|
||||
"Посмотрел рабочую версию: {url}": "Жұмыс нұсқасын қарадым: {url}",
|
||||
"Посмотрел версию для проверки: {url}": "Тексеруге арналған нұсқаны қарадым: {url}",
|
||||
"Как пользоваться:": "Қалай пайдалану керек:",
|
||||
"Пока не настоящее:": "Әзірге шын емес:",
|
||||
"Чтобы заработало по-настоящему, нужно от вас:": "Шын жұмыс істеуі үшін сізден керек:",
|
||||
"Вставить или отметить «Сделано» — в карточке «Ваш продукт»: {url}": "Қою немесе «Орындалды» деп белгілеу — «Сіздің өніміңіз» карточкасында: {url}",
|
||||
"Завёл доработки в бэклог:": "Жетілдірулерді бэклогқа қостым:",
|
||||
"Аналитик отвечает на подписке проекта, а она не подключена. Подключите Claude в «⋯ Настройки проекта → Подписки» — и напишите ещё раз.": "Аналитик жобаның жазылымында жауап береді, ал ол қосылмаған. Claude-ты «⋯ Жоба баптаулары → Жазылымдар» бөлімінде қосып, қайта жазыңыз.",
|
||||
"Аналитик сейчас не смог ответить. Напишите ещё раз чуть позже.": "Аналитик қазір жауап бере алмады. Сәл кейінірек қайта жазыңыз.",
|
||||
"Аналитик ответил не по форме — напишите вопрос ещё раз, пожалуйста.": "Аналитиктің жауабы дұрыс шықпады — сұрағыңызды қайта жазыңызшы.",
|
||||
"Завёл в бэклог:": "Бэклогқа қостым:",
|
||||
"Чтобы продукт заработал по-настоящему, а не в демо-режиме, нужно от вас:": "Өнім демо-режимде емес, шын жұмыс істеуі үшін сізден керек:",
|
||||
};
|
||||
|
||||
142
packages/testkit/test/i18n-role-messages.test.ts
Normal file
142
packages/testkit/test/i18n-role-messages.test.ts
Normal file
@ -0,0 +1,142 @@
|
||||
// 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 } 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: Аналитик завёл задачу", 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(m.text, "Готово.\n\nЗавёл в бэклог:\n• DEMO-1 «Экспорт в PDF»");
|
||||
assert.equal(web("en", m.text), "Готово.\n\nAdded to the backlog:\n• DEMO-1 «Экспорт в PDF»");
|
||||
assert.equal(web("kk", m.text), "Готово.\n\nБэклогқа қостым:\n• DEMO-1 «Экспорт в PDF»");
|
||||
assert.equal(web("ru", m.text), m.text);
|
||||
assert.equal(web("en", m.authorLogin), "Analyst");
|
||||
// Telegram, Russian reader: as before.
|
||||
assert.match((await lastTelegram()).text, /Демо<\/b> · Аналитик:\nГотово\.\n\nЗавёл в бэклог:\n• DEMO-1[^]*Ответить: http:\/\/peppa\.test\/chats\/DEMO/);
|
||||
// Telegram, English reader: written in English when queued and marked, so the bot does not translate it again.
|
||||
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\nAdded to the backlog:\n• DEMO-2[^]*Reply: http:\/\/peppa\.test\/chats\/DEMO/);
|
||||
setScenario({});
|
||||
});
|
||||
|
||||
test("Scenario: Сообщение продакта после приёмки на английском", 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], "Looked at the review version: 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> · Product:\nLooked at the review version:[^]*\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" })), "Looked at the live 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 () => {
|
||||
setScenario({ fail: true });
|
||||
await post("Ты тут?");
|
||||
await tick();
|
||||
const fail = await last();
|
||||
assert.equal(fail.authorKind, "system");
|
||||
assert.equal(localizeText("en", fail.text), "The analyst could not answer right now. Please write again a little later.");
|
||||
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({});
|
||||
});
|
||||
});
|
||||
@ -117,6 +117,16 @@ describe("язык интерфейса", () => {
|
||||
assert.doesNotMatch(en, /[А-Яа-я]/, `untranslated: ${en}`);
|
||||
});
|
||||
|
||||
test("Scenario: Свободный текст не переводится — бот не трогает уже переведённое сообщение (PEP-138)", async () => {
|
||||
// Anna reads English (previous test). A role's message is queued in her language with the
|
||||
// model's own Russian words inside: the bot sends it as it is and strips the private mark.
|
||||
const text = "💬 <b>Демо</b> · Analyst:\nСделано три задачи из пяти.\n\nReply: http://peppa.test/chats/DEMO";
|
||||
await core.enqueueTelegram(db, { dedupeKey: "pep138:localized", method: "sendMessage", params: { chat_id: ANNA.chatId, text, parse_mode: "HTML", [core.LOCALIZED_PARAM]: true } });
|
||||
await waitFor("sent", async () => tg.botMessages(ANNA.chatId).some((m) => m.text.includes("Analyst")));
|
||||
assert.equal(tg.botMessages(ANNA.chatId).at(-1)!.text, text);
|
||||
assert.equal(core.LOCALIZED_PARAM in tg.calls.at(-1)!.params, false, "the mark does not reach Telegram");
|
||||
});
|
||||
|
||||
const check = (args: string[]) =>
|
||||
run("node", ["scripts/i18n-check.ts", ...args], { cwd: root }).then(
|
||||
(x) => ({ code: 0, out: x.stdout }),
|
||||
|
||||
Loading…
Reference in New Issue
Block a user