peppa/apps/bot/src/render.ts
Асель 9052f3245f Merge main into task/pep-98: PEP-112…124 texts through the dictionary
Main's new wording (PEP-123 «Продакт» words) kept and wrapped in t()/m();
wording(mode, locale) gives English words for {task}/{runner} placeholders;
glossary check (pnpm lint) passes; English for all new keys (en/merge-*.ts).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 22:04:39 +05:00

83 lines
4.5 KiB
TypeScript

// Telegram message texts and buttons for PM questions. HTML parse mode.
import type { Question, SessionView } from "@peppa/core";
import type { InlineButton } from "./telegram.ts";
import { m as tr } from "@peppa/shared/i18n";
export const esc = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
const italic = (s: string) => `<i>${s}</i>`;
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s);
const KIND: Record<Question["kind"], string> = {
approval: tr("📝 Нужно одобрение плана"),
question: tr("❓ Вопрос"),
permission: tr("🔐 Нужно разрешение"),
attention: tr("👀 Сообщение от фабрики"),
};
export interface Rendered {
text: string;
buttons: InlineButton[][];
}
// callback_data (≤64 bytes): "q:<questionId>:<choice>", "s:<sessionId>:<action>" or "i:<incidentId>:<decision>" (core/incidents.ts)
export function renderQuestion(
q: Question,
ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string },
): Rendered {
const head = ["<b>" + esc(ctx.taskKey ?? (q.sessionId ? tr("Агент №{id}", { id: q.sessionId }) : tr("Обновления продукта"))) + "</b>", ctx.taskTitle ? `<i>${esc(clip(ctx.taskTitle, 80))}</i>` : null]
.filter(Boolean)
.join(" · ");
const body = esc(clip(q.text, 3300));
const lines = [head, KIND[q.kind], "", body];
const buttons: InlineButton[][] = [];
if (q.kind === "approval") {
buttons.push([{ text: tr("✅ Одобрить"), callback_data: `q:${q.id}:approve` }]);
lines.push("", italic(tr("Чтобы вернуть на доработку — ответьте на это сообщение комментарием.")));
} else if (q.kind === "permission") {
buttons.push([
{ text: tr("✅ Разрешить"), callback_data: `q:${q.id}:allow` },
{ text: tr("♾ Всегда"), callback_data: `q:${q.id}:always` },
{ text: tr("⛔ Запретить"), callback_data: `q:${q.id}:deny` },
]);
} else if (q.kind === "question") {
(q.options ?? []).slice(0, 6).forEach((o, i) => buttons.push([{ text: clip(o, 60), callback_data: `q:${q.id}:o${i}` }]));
lines.push("", italic(tr("Выберите вариант или ответьте на это сообщение своим текстом.")));
} else if (ctx.taskStatus === "review") {
lines[1] = tr("✅ Готово к ревью");
buttons.push([{ text: tr("✅ Принять"), callback_data: `q:${q.id}:accept` }]);
lines.push("", italic(tr("Есть замечания — ответьте на это сообщение, агент доработает.")));
} else {
const s = ctx.session;
if (s && ["failed", "rate_limited", "stalled"].includes(s.status)) {
buttons.push([
{ text: tr("🔁 Перезапустить"), callback_data: `s:${s.id}:resume` },
{ text: tr("⏹ Остановить"), callback_data: `s:${s.id}:stop` },
]);
} else {
buttons.push([{ text: tr("▶️ Продолжай"), callback_data: `q:${q.id}:cont` }]);
lines.push("", italic(tr("Или ответьте на это сообщение — текст уйдёт агенту.")));
}
}
if (ctx.session) lines.push(`<code>tmux attach -t ${esc(ctx.session.tmuxName)}</code>`);
return { text: lines.join("\n"), buttons };
}
/** Text after the question is closed: original + who answered what, no buttons. */
export function renderAnswered(original: string, q: Question): string {
const mark = q.answeredVia === "system" ? "⌛" : "✅";
const via = { telegram: tr("в Telegram"), web: tr("в вебе"), terminal: tr("в терминале"), system: "" }[q.answeredVia ?? "telegram"];
const said = q.answeredVia === "system" ? esc(q.answer ?? "") : tr("Ответ {via}: <b>{answer}</b>", { via, answer: esc(clip(q.answer ?? "", 500)) });
return `${original}\n\n${mark} ${said}`;
}
/** The answer text a button stands for. */
export function choiceToAnswer(q: Question, choice: string): string | null {
if (q.kind === "approval" && choice === "approve") return "ок"; // i18n-ignore: the answer goes to the agent
if (q.kind === "permission" && ["allow", "always", "deny"].includes(choice)) return choice;
if (q.kind === "attention" && choice === "cont") return "Продолжай."; // i18n-ignore: the answer goes to the agent
const m = /^o(\d+)$/.exec(choice);
if (q.kind === "question" && m) return q.options?.[Number(m[1])] ?? null;
return null;
}