peppa/apps/bot/src/render.ts

98 lines
6.4 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.

// Telegram message texts and buttons for PM questions. HTML parse mode.
import { questionIsFreeText, questionText, questionType, splitForDisplay, stripServiceBlocks, userText, type Question, type SessionView } from "@peppa/core";
import type { InlineButton } from "./telegram.ts";
import { asIs, 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>" (resume|stop|ask) 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; /** PEP-154: the reader's view is «Инженер» — the terminal command is shown. */ engineer?: boolean; /** PEP-152: the message has technical details (kept on the site). */ details?: boolean },
): Rendered {
const head = ["<b>" + esc(ctx.taskKey ?? (q.sessionId ? tr("Агент №{id}", { id: q.sessionId }) : tr("Обновления продукта"))) + "</b>", ctx.taskTitle ? `<i>${asIs(esc(clip(ctx.taskTitle, 80)))}</i>` : null]
.filter(Boolean)
.join(" · ");
// PEP-154: no service text in the message (a permission request keeps its command, whole).
// PEP-152: the main text only — at most five lines; the rest and the details open on the site.
// PEP-139: what the agent wrote itself is free text (marked) — only the factory's phrases are translated.
const free = questionIsFreeText(q);
const shown = q.kind === "permission" ? { main: q.text, more: null } : splitForDisplay(questionText({ ...q, text: userText(q.text) || q.text }));
const body = esc(clip(shown.main, 3300));
const lines = [head, KIND[q.kind], "", body];
const buttons: InlineButton[][] = [];
const type = questionType(q, ctx.taskStatus);
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 (type === "question") {
// PEP-149: a question always comes with answers to tap; the default goes first.
(q.options ?? []).slice(0, 6).forEach((o, i) => buttons.push([{ text: free ? asIs(clip(o, 60)) : clip(o, 60), callback_data: `q:${q.id}:o${i}` }]));
if (q.kind === "attention") lines[1] = KIND.question;
lines.push("", italic(tr("Выберите вариант или ответьте на это сообщение своим текстом.")));
if (q.defaultOption) lines.push(italic(esc(tr("Если не ответите, агент продолжит по варианту «{option}».", { option: q.defaultOption }))));
} else if (type === "done") {
lines[1] = tr("✅ Готово к ревью");
buttons.push([{ text: tr("✅ Принять"), callback_data: `q:${q.id}:accept` }]);
lines.push("", italic(tr("Есть замечания — ответьте на это сообщение, агент доработает.")));
} else {
// A message of the factory itself (a failure, a limit): nothing to choose — no «continue» button.
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` },
]);
// PEP-186: agents stand on a limit of their subscription — ask the superadmin for one.
if (s.status === "rate_limited" && s.subscriptionId != null) buttons.push([{ text: tr("🙋 Попросить подписку у администратора"), callback_data: `s:${s.id}:ask` }]);
}
}
if (ctx.session && ctx.engineer) lines.push(`<code>tmux attach -t ${esc(ctx.session.tmuxName)}</code>`);
const web = ctx.webUrl.replace(/\/$/, "");
if ((ctx.details || shown.more) && ctx.taskKey && /^https?:\/\//.test(web)) buttons.push([{ text: tr("Подробнее"), url: `${web}/t/${ctx.taskKey}?more=1` }]);
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"];
// PEP-154: service blocks are nobody's answer.
const answer = stripServiceBlocks(q.answer ?? "");
// A person's answer is free text; a button of a factory question (and a system answer) is a phrase.
const own = q.answeredVia !== "system" && !(q.options ?? []).includes(q.answer ?? "") ? asIs : (x: string) => x;
const said = q.answeredVia === "system" ? esc(answer) : tr("Ответ {via}: <b>{answer}</b>", { via, answer: own(esc(clip(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;
// PEP-149: the «continue» button is gone — an old one on an earlier message answers nothing.
const m = /^o(\d+)$/.exec(choice);
if (m) return q.options?.[Number(m[1])] ?? null;
return null;
}