From 4bf482d79a73769a261421f0ba01371842efddb0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 11:29:01 +0500 Subject: [PATCH] =?UTF-8?q?PEP-151:=20one=20state=20=E2=80=94=20one=20mess?= =?UTF-8?q?age=20(fingerprint,=20chat,=20Telegram=20edit,=20card)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- apps/bot/src/bot.ts | 40 +++- apps/web/app/(app)/chats/[chat]/page.tsx | 4 +- apps/web/components/cards.tsx | 15 +- packages/core/src/chats.ts | 37 +++- packages/core/src/index.ts | 1 + packages/core/src/message-state.ts | 166 ++++++++++++++++ packages/core/src/review-card.ts | 4 +- packages/core/src/sessions.ts | 23 ++- packages/core/src/tasks.ts | 23 ++- packages/core/src/telegram.ts | 20 +- packages/runner/src/hook.ts | 3 +- packages/runner/src/recovery.ts | 3 + packages/shared/src/i18n/en/project.ts | 3 + packages/shared/src/i18n/kk/project.ts | 3 + packages/testkit/test/no-repeats.test.ts | 234 +++++++++++++++++++++++ 15 files changed, 555 insertions(+), 24 deletions(-) create mode 100644 packages/core/src/message-state.ts create mode 100644 packages/testkit/test/no-repeats.test.ts diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 26d65123..6f0f0cad 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -63,6 +63,12 @@ import { migrateChatGroup, mirrorTargets, syncChats, + isRepeatEdit, + getOutbox, + lastRepeatEdit, + questionStates, + repeatEditKey, + sentQuestionMessages, telegramAccountUser, threadAnchor, type Chat, @@ -94,6 +100,8 @@ export interface BotOptions { pollTimeoutSec?: number; outboxIntervalMs?: number; reconcileIntervalMs?: number; + /** PEP-151: a delivered message is refreshed for a repeated state at most this often (5 min). */ + repeatEditMs?: number; /** Heartbeat + check on the watchdog and the web (PEP-20). */ heartbeatIntervalMs?: number; // How often to check PRAGMA data_version for writes the notify() poke missed. @@ -292,6 +300,7 @@ export function createBot(o: BotOptions) { */ async function reconcile(): Promise { const open = await pendingQuestions(db); + const states = await questionStates(db, open.map((q) => q.id)); const projectsOf = new Map>(); const waitingFor = async (userId: number) => { if (!projectsOf.has(userId)) projectsOf.set(userId, new Set(await userProjectIds(db, userId))); @@ -318,17 +327,37 @@ export function createBot(o: BotOptions) { urgency: event === "questions" || event === "failures" ? "high" : "normal", }); } + // PEP-151: the same state came again — no new message; the one already delivered gets the + // fresh text and its buttons back, at most once in `repeatEditMs`. + const repeats = states.get(q.id)?.repeats ?? 0; + if (!repeats) continue; + for (const sent of await sentQuestionMessages(db, q.id)) { + const key = repeatEditKey(sent.id, repeats); + if (await getOutbox(db, key)) continue; + const last = await lastRepeatEdit(db, sent.id); + if (last && Date.now() - last.getTime() < (o.repeatEditMs ?? 5 * 60_000)) continue; + await enqueueTelegram(db, { + dedupeKey: key, + method: "editMessageText", + questionId: q.id, + params: { chat_id: sent.params.chat_id, message_id: sent.telegramMessageId, text: r.text, parse_mode: "HTML", link_preview_options: { is_disabled: true }, reply_markup: { inline_keyboard: r.buttons } }, + }); + } } await mirrorChats().catch((e) => log(`chats: ${(e as Error).message}`)); - for (const { sent, q } of await answeredQuestionMessages(db, new Date(Date.now() - 24 * 3600_000))) { + const answered = await answeredQuestionMessages(db, new Date(Date.now() - 24 * 3600_000)); + const answeredStates = await questionStates(db, answered.map((a) => a.q.id)); + for (const { sent, q } of answered) { + // PEP-151: a question that came again is answered again — each round closes the message anew. + const round = answeredStates.get(q.id)?.repeats ?? 0; await enqueueTelegram(db, { - dedupeKey: `qa:${q.id}:${sent.params.chat_id}`, + dedupeKey: round ? `qa:${q.id}:r${round}:${sent.params.chat_id}` : `qa:${q.id}:${sent.params.chat_id}`, method: "editMessageText", questionId: q.id, params: { chat_id: sent.params.chat_id, message_id: sent.telegramMessageId, - text: renderAnswered(String(sent.params.text), q), + text: renderAnswered(round ? renderQuestion(q, await context(q)).text : String(sent.params.text), q), parse_mode: "HTML", reply_markup: { inline_keyboard: [] }, }, @@ -406,6 +435,11 @@ export function createBot(o: BotOptions) { const q = await getQuestion(db, row.questionId).catch(() => null); if (q?.answeredAt) return markOutboxSent(db, { ...row, questionId: null }, null); } + if (isRepeatEdit(row) && row.questionId) { + // PEP-151: answered while the refresh waited — the buttons must not come back. + const q = await getQuestion(db, row.questionId).catch(() => null); + if (!q || q.answeredAt) return markOutboxSent(db, row, null); + } let params = row.params; if (row.method === "sendMessage" && row.chatMessageId && !params.reply_parameters) { // PEP-62: a thread in a group = a chain of replies to its first message. diff --git a/apps/web/app/(app)/chats/[chat]/page.tsx b/apps/web/app/(app)/chats/[chat]/page.tsx index 44b2648b..3250b222 100644 --- a/apps/web/app/(app)/chats/[chat]/page.tsx +++ b/apps/web/app/(app)/chats/[chat]/page.tsx @@ -334,7 +334,9 @@ async function MessageItem({ m, q, back, showThread, masterView, mine = false }: 🧵 {label} )} - {ago(m.createdAt, t)} + {/* PEP-151: the same event in a row is one line with a counter and the time of the last one. */} + {!q && m.repeats > 0 && ×{m.repeats + 1}} + {q ? ago(m.createdAt, t) : ago(m.updatedAt ?? m.createdAt, t)} ); if (q) { diff --git a/apps/web/components/cards.tsx b/apps/web/components/cards.tsx index 9264577b..ac09bb01 100644 --- a/apps/web/components/cards.tsx +++ b/apps/web/components/cards.tsx @@ -1,7 +1,8 @@ // Domain cards shared by pages: agent questions, runners, project list. import Link from "next/link"; import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square, SquareTerminal } from "lucide-react"; -import type { Project, Question, SessionView, StepView } from "@peppa/core"; +import { questionState, type Project, type Question, type SessionView, type StepView } from "@peppa/core"; +import { db } from "@/lib/db"; import { SubscriptionName } from "@/components/SubscriptionName"; import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions"; import { Button } from "@/components/ui/button"; @@ -38,6 +39,9 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal const answered = !!q.answeredAt; const k = KIND[q.kind]; const Icon = review ? CircleCheck : k.icon; + // PEP-151: the same state came again — one message with the time it was last refreshed. + const state = await questionState(db, q.id).catch(() => null); + const updatedAt = state?.updatedAt ? new Date(state.updatedAt) : null; return (
@@ -45,7 +49,7 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal {review ? t("Готово к ревью") : t(k.label)} {taskKey && {taskKey}} - {!plain && <>#{q.id} · }{ago(q.createdAt, t)} + {!plain && <>#{q.id} · }{updatedAt ? t("обновлено {ago}", { ago: ago(updatedAt, t) }) : ago(q.createdAt, t)}
{plain && q.kind === "permission" ? ( @@ -54,11 +58,18 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal
{t("Подробнее")}

{t.text(q.text)}

+ {!!state?.repeats &&

{t("Повторов: {n} · первое сообщение {ago}", { n: state.repeats, ago: ago(q.createdAt, t) })}

}
) : (

{t.text(q.text)}

)} + {!!state?.repeats && !(plain && q.kind === "permission") && ( +
+ {t("Подробнее")} +

{t("Повторов: {n} · первое сообщение {ago}", { n: state.repeats, ago: ago(q.createdAt, t) })}

+
+ )} {answered ? (

{q.answeredVia === "system" ? : } diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts index 240e9d94..c9d1bc4e 100644 --- a/packages/core/src/chats.ts +++ b/packages/core/src/chats.ts @@ -13,6 +13,7 @@ import { notify } from "./notify.ts"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; import { projectForUser, userProjectIds, type User } from "./users.ts"; import type { OutboxRow } from "./telegram.ts"; +import { chatRepeatKey, chatRepeats, normalizeMessage, pruneMessageStates, questionStates, type ChatRepeat } from "./message-state.ts"; export type Chat = typeof chats.$inferSelect; export type ChatMessage = typeof chatMessages.$inferSelect; @@ -159,6 +160,10 @@ export interface ChatMessageView { text: string; url: string | null; createdAt: Date; + /** PEP-151: how many more times the same thing came (a repeated state, the same event in a row). */ + repeats: number; + /** When it last came again or was reminded about; null — never. */ + updatedAt: Date | null; /** A question message: its live state (answered elsewhere shows here too). */ question: { id: number; kind: string; options: string[] | null; answer: string | null; answeredVia: string | null; answeredAt: Date | null } | null; } @@ -173,7 +178,16 @@ async function views(db: Db, where: SQL, limit: number, before?: number): Promis .where(before ? and(where, lt(chatMessages.id, before)) : where) .orderBy(desc(chatMessages.id)) .limit(Math.min(limit, 500)); + const qStates = await questionStates(db, rows.map((r) => r.q?.id).filter((x): x is number => x != null)); + const eRepeats = await chatRepeats(db, rows.filter((r) => r.m.kind === "event").map((r) => r.m.id)); + const again = (m: ChatMessage, q: { id: number } | null) => { + const st = q ? qStates.get(q.id) : undefined; + if (st) return { repeats: st.repeats, updatedAt: st.updatedAt ? new Date(st.updatedAt) : null }; + const r = eRepeats.get(m.id); + return r ? { repeats: r.n - 1, updatedAt: new Date(r.at) } : { repeats: 0, updatedAt: null }; + }; return rows.reverse().map(({ m, projectKey, q }) => ({ + ...again(m, q), id: m.id, chatId: m.chatId, projectKey, @@ -410,6 +424,23 @@ async function initialCursor(db: Db, table: typeof events | typeof questions, no return Number(all?.max ?? 0); } +/** + * PEP-151: is this event the same as the last line of its story thread? Then it is counted on + * that line (settings `chat.repeat:`) and not added — neither here nor in the linked + * Telegram group. + */ +async function repeatsLastEvent(db: Db, m: NewChatMessage): Promise { + const eventId = Number(/^event:(\d+)$/.exec(m.dedupeKey ?? "")?.[1]); + if (m.kind !== "event" || !m.threadKey?.startsWith("task:") || !eventId) return false; + const [last] = await db.select().from(chatMessages).where(and(eq(chatMessages.chatId, m.chatId), eq(chatMessages.threadKey, m.threadKey))).orderBy(desc(chatMessages.id)).limit(1); + if (!last || last.kind !== "event" || last.dedupeKey === m.dedupeKey || (last.authorKind ?? "system") !== (m.authorKind ?? "system")) return false; + if (normalizeMessage(last.text) !== normalizeMessage(m.text)) return false; + const st = await getSetting(db, chatRepeatKey(last.id)); + if (st && eventId <= st.last) return true; + await setSetting(db, chatRepeatKey(last.id), { n: (st?.n ?? 1) + 1, at: (m.createdAt ?? new Date()).getTime(), last: eventId } satisfies ChatRepeat); + return true; +} + /** * Moves new events, questions, releases and incidents into the project chats. Idempotent * (every message has a dedupe key), so the bot, the watchdog and the web may all call it. @@ -428,7 +459,10 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise return titles.get(key) ?? null; }; let added = 0; + let repeated = 0; const add = async (m: NewChatMessage) => { + // PEP-151: the same event of a story again in a row is a counter on the line already there. + if (await repeatsLastEvent(db, m)) return void repeated++; if (m.threadKey) m.threadTitle = await titleOf(m.threadKey); if (await addChatMessage(db, m)) added++; }; @@ -523,7 +557,7 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise } // Moved at most every 30 s (the window overlaps by a minute, so nothing is lost). if (savedObjects == null || now.getTime() - savedObjects >= 30_000) await setSetting(db, CURSOR_OBJECTS, now.getTime()); - if (added) await notify(db, { type: "chat_message", messageId: 0 }); + if (added || repeated) await notify(db, { type: "chat_message", messageId: 0 }); return added; } @@ -535,6 +569,7 @@ export async function pruneChats(db: Db, o: { now?: Date } = {}): Promise `${PREFIX}${id}`; + +/** Text without what changes between two reports of the same thing: numbers, times, hashes, punctuation. */ +export function normalizeMessage(text: string): string { + return text + .toLowerCase() + .replace(/\b(?=[0-9a-f]*\d)[0-9a-f]{7,40}\b/g, " ") + .replace(/\d+/g, " ") + .replace(/[^\p{L}]+/gu, " ") + .trim(); +} + +/** Fingerprint of the state a message reports: story, type, status, result, head commit, checks, text. */ +export async function messageFingerprint(db: Db, m: MessageScope): Promise { + let status = ""; + let pr = ""; + let head = m.head ?? ""; + let checks = ""; + if (m.taskId) { + const [t] = await db.select({ status: tasks.status, prUrl: tasks.prUrl }).from(tasks).where(eq(tasks.id, m.taskId)); + // «Готово» is sent around the move to review: the status of the moment must not split it. + status = m.topic === "review" ? "review" : (t?.status ?? ""); + pr = t?.prUrl ?? ""; + const runs = await db.select({ sha: checkRuns.sha, check: checkRuns.check, state: checkRuns.state }).from(checkRuns).where(eq(checkRuns.taskId, m.taskId)).orderBy(desc(checkRuns.id)).limit(60); + head ||= runs[0]?.sha ?? ""; + checks = runs.filter((r) => r.sha === head).map((r) => `${r.check}:${r.state}`).sort().join(","); + } + const scope = m.taskId ? `t${m.taskId}` : m.sessionId ? `s${m.sessionId}` : `p${m.projectId}`; + const said = m.topic ? "" : `${normalizeMessage(m.text)}|${(m.options ?? []).map(normalizeMessage).join("|")}`; + return createHash("sha1").update([scope, m.kind, m.topic ?? "", status, pr, head, checks, said].join("\n")).digest("hex"); +} + +export async function questionStates(db: Db, ids: number[]): Promise> { + const out = new Map(); + if (!ids.length) return out; + for (const r of await db.select().from(settings).where(inArray(settings.key, ids.map(key)))) out.set(Number(r.key.slice(PREFIX.length)), r.value as QuestionState); + return out; +} + +export const questionState = (db: Db, id: number) => getSetting(db, key(id)); + +/** + * The earlier message this one repeats: an open one with the same fingerprint, or the story's + * last message, or (for «готово») any message about the same result. Answered questions, + * permissions and approvals are never reused: asking again after an answer is a new question. + */ +export async function findRepeat(db: Db, m: MessageScope, fp: string, now = Date.now()): Promise { + const where = m.taskId ? eq(questions.taskId, m.taskId) : m.sessionId ? and(eq(questions.sessionId, m.sessionId), isNull(questions.taskId)) : null; + if (!where) return null; + const rows = await db.select().from(questions).where(and(where, gt(questions.createdAt, new Date(now - REPEAT_WINDOW_MS)))).orderBy(desc(questions.id)).limit(30); + const states = await questionStates(db, rows.map((r) => r.id)); + for (const [i, q] of rows.entries()) { + if (q.kind !== m.kind || states.get(q.id)?.fp !== fp) continue; + if (!q.answeredAt) return q; + if (m.kind === "attention" && (i === 0 || m.topic === "review")) return q; + } + return null; +} + +/** A new message: remembers its fingerprint so that a repeat finds it. */ +export const rememberState = (db: Db, questionId: number, fp: string) => setSetting(db, key(questionId), { fp, repeats: 0, updatedAt: null } satisfies QuestionState); + +/** The same state again: the earlier message takes the fresh text and waits for an answer again. */ +export async function bumpRepeat(db: Db, prev: Question, m: MessageScope, fp: string, now = Date.now()): Promise { + const st = await questionState(db, prev.id); + const [row] = await db + .update(questions) + .set({ text: m.text, options: m.options ?? null, sessionId: m.sessionId ?? prev.sessionId, awaitingHook: m.awaitingHook ?? false, answer: null, answeredVia: null, answeredAt: null }) + .where(eq(questions.id, prev.id)) + .returning(); + await setSetting(db, key(prev.id), { fp, repeats: (st?.repeats ?? 0) + 1, updatedAt: now } satisfies QuestionState); + return row!; +} + +/** A reminder about an open question refreshes its message instead of adding one. */ +export async function touchQuestion(db: Db, questionId: number, now = Date.now()): Promise { + const st = await questionState(db, questionId); + await setSetting(db, key(questionId), { fp: st?.fp ?? "", repeats: st?.repeats ?? 0, updatedAt: now } satisfies QuestionState); +} + +/** + * Creates the message unless it repeats an earlier one. Never fails because of the fingerprint: + * a message the user must get is worth more than a missed duplicate. + */ +export async function raiseOnce(db: Db, m: MessageScope, create: () => Promise): Promise { + let fp: string | null = null; + try { + fp = await messageFingerprint(db, m); + const prev = await findRepeat(db, m, fp); + if (prev) return await bumpRepeat(db, prev, m, fp); + } catch { + fp = null; + } + const row = await create(); + if (fp) await rememberState(db, row.id, fp).catch(() => {}); + return row; +} + +// ── repeated events of a chat thread ──────────────────────────────────────────────── + +export interface ChatRepeat { + /** How many events the line stands for. */ + n: number; + /** When the last of them happened (ms). */ + at: number; + /** Id of the last event counted (a re-run of the projection does not count it twice). */ + last: number; +} + +const CHAT_PREFIX = "chat.repeat:"; +export const chatRepeatKey = (messageId: number) => `${CHAT_PREFIX}${messageId}`; + +export async function chatRepeats(db: Db, messageIds: number[]): Promise> { + const out = new Map(); + if (!messageIds.length) return out; + for (const r of await db.select().from(settings).where(inArray(settings.key, messageIds.map(chatRepeatKey)))) out.set(Number(r.key.slice(CHAT_PREFIX.length)), r.value as ChatRepeat); + return out; +} + +/** Drops the state of messages nobody can repeat any more. */ +export async function pruneMessageStates(db: Db, before: Date): Promise { + await db.delete(settings).where(and(like(settings.key, `${PREFIX}%`), lt(settings.updatedAt, before))); + await db.delete(settings).where(and(like(settings.key, `${CHAT_PREFIX}%`), lt(settings.updatedAt, before))); +} diff --git a/packages/core/src/review-card.ts b/packages/core/src/review-card.ts index fa590a4c..42035ad0 100644 --- a/packages/core/src/review-card.ts +++ b/packages/core/src/review-card.ts @@ -49,7 +49,9 @@ export async function sendReviewCard(db: Db, ref: TaskRef, text: string, session const gate = await prGate(ref, gitea).catch(() => null); if (gate?.ok) { await clearReviewHold(db, ref.task.id); - return session ? raiseSessionQuestion(db, session, "attention", text) : askPm(db, ref, { kind: "attention", text }); + // PEP-151: «готово» for the same head commit is one message, however many times it is sent. + const state = { topic: "review" as const, head: gate.pull?.head.sha ?? null }; + return session ? raiseSessionQuestion(db, session, "attention", text, undefined, false, state) : askPm(db, ref, { kind: "attention", text, ...state }); } const prev = await getReviewHold(db, ref.task.id); await setReviewHold(db, ref.task.id, { ...prev, text, at: Date.now() }); diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts index 3a936761..92732119 100644 --- a/packages/core/src/sessions.ts +++ b/packages/core/src/sessions.ts @@ -6,6 +6,7 @@ import { notify } from "./notify.ts"; import { actorColumns } from "./actor.ts"; import type { Question, QuestionKind } from "./tasks.ts"; import { userProjectIds } from "./users.ts"; +import { raiseOnce, type MessageTopic } from "./message-state.ts"; export type Session = typeof sessions.$inferSelect; export type SessionStatus = (typeof sessionStatus.enumValues)[number]; @@ -163,7 +164,11 @@ export async function releaseHookQuestion(db: Db, id: number): Promise { - const [row] = await db - .insert(questions) - .values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook }) - .returning(); - await notify(db, { type: "question", questionId: row!.id }); - return row!; + const row = await raiseOnce(db, { projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook, ...o }, async () => { + const [created] = await db + .insert(questions) + .values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook }) + .returning(); + return created!; + }); + await notify(db, { type: "question", questionId: row.id }); + return row; } function sessionQuery(db: Db) { diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts index cd3e69ab..aeba839e 100644 --- a/packages/core/src/tasks.ts +++ b/packages/core/src/tasks.ts @@ -14,6 +14,7 @@ import { reviewPreview, type ReviewPreview } from "./preview.ts"; import { blockersOf, dependentsOf, type Blocker } from "./deps.ts"; import { taskBudgetView, type TaskBudgetView } from "./budgets.ts"; import { productNeeds, type ProductNeedView } from "./product-needs.ts"; +import { raiseOnce, type MessageTopic } from "./message-state.ts"; export type Task = typeof tasks.$inferSelect; export type TaskStatus = (typeof taskStatus.enumValues)[number]; @@ -301,17 +302,25 @@ export interface NewQuestion { text: string; options?: string[]; sessionId?: number; + /** PEP-151: the type of the message when its text cannot tell (see MessageTopic). */ + topic?: MessageTopic; + /** Head commit of the result, when the caller knows it. */ + head?: string | null; } /** Records a question for the PM and broadcasts it (the bot forwards it to Telegram). */ -export async function askPm(db: Db, ref: TaskRef, q: NewQuestion): Promise { - const [row] = await db - .insert(questions) - .values({ projectId: ref.project.id, taskId: ref.task.id, ...q }) - .returning(); +export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQuestion): Promise { + // PEP-151: the same state of the story again refreshes the earlier message instead of adding one. + const row = await raiseOnce(db, { projectId: ref.project.id, taskId: ref.task.id, sessionId: q.sessionId ?? null, kind: q.kind, text: q.text, options: q.options, topic, head }, async () => { + const [created] = await db + .insert(questions) + .values({ projectId: ref.project.id, taskId: ref.task.id, ...q }) + .returning(); + return created!; + }); if (q.kind === "approval") await updateTask(db, ref, { status: "awaiting_approval" }, q.sessionId); - await notify(db, { type: "question", questionId: row!.id }); - return row!; + await notify(db, { type: "question", questionId: row.id }); + return row; } /** A message for the PM about the project as a whole (releases), not about a task. */ diff --git a/packages/core/src/telegram.ts b/packages/core/src/telegram.ts index 35543d91..5b81207b 100644 --- a/packages/core/src/telegram.ts +++ b/packages/core/src/telegram.ts @@ -1,7 +1,7 @@ import { m as tr } from "@peppa/shared/i18n"; import { createHmac, randomBytes } from "node:crypto"; import { chats, projectMembers, projects, questions, telegramOutbox, telegramUpdates, users, type Db } from "@peppa/db"; -import { and, asc, eq, gt, inArray, isNotNull, lte, sql } from "drizzle-orm"; +import { and, asc, desc, eq, gt, inArray, isNotNull, like, lte, sql } from "drizzle-orm"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; import { decrypt, encrypt } from "./crypto.ts"; import { PeppaError } from "./errors.ts"; @@ -236,6 +236,24 @@ export async function questionByTelegramMessage(db: Db, chatId: number, messageI return row?.q ?? null; } +/** PEP-151: the Telegram messages a question was delivered as (personal chats and linked groups). */ +export async function sentQuestionMessages(db: Db, questionId: number): Promise { + return db + .select() + .from(telegramOutbox) + .where(and(eq(telegramOutbox.questionId, questionId), eq(telegramOutbox.method, "sendMessage"), eq(telegramOutbox.status, "sent"), isNotNull(telegramOutbox.telegramMessageId))); +} + +/** Key of the edit that refreshes a delivered message when its question's state came again. */ +export const repeatEditKey = (outboxId: number, repeats: number) => `qe:${outboxId}:${repeats}`; +export const isRepeatEdit = (row: Pick) => row.method === "editMessageText" && row.dedupeKey.startsWith("qe:"); + +/** When a delivered message was last queued for such a refresh (edits are rate-limited). */ +export async function lastRepeatEdit(db: Db, outboxId: number): Promise { + const [row] = await db.select({ at: telegramOutbox.createdAt }).from(telegramOutbox).where(like(telegramOutbox.dedupeKey, `qe:${outboxId}:%`)).orderBy(desc(telegramOutbox.id)).limit(1); + return row?.at ?? null; +} + /** Delivered question messages whose question got answered since `since` (to close them). */ export async function answeredQuestionMessages(db: Db, since: Date) { return db diff --git a/packages/runner/src/hook.ts b/packages/runner/src/hook.ts index 55da6311..c355aaa6 100644 --- a/packages/runner/src/hook.ts +++ b/packages/runner/src/hook.ts @@ -262,7 +262,8 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue: await logSessionEvent(db, s, "auto_continue", { n: s.autoNudges + 1 }); return { decision: "block", reason: NUDGE(s.taskKey ?? "стори") }; } - await raiseSessionQuestion(db, s, "attention", clip(text ?? m("Агент закончил ход и ждёт вашего ответа."))); + // PEP-151: the agent retells the same state in new words — one message, not one per turn. + await raiseSessionQuestion(db, s, "attention", clip(text ?? m("Агент закончил ход и ждёт вашего ответа.")), undefined, false, { topic: "turn" }); await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() }); return null; } diff --git a/packages/runner/src/recovery.ts b/packages/runner/src/recovery.ts index 6b1a5dd0..61a699a8 100644 --- a/packages/runner/src/recovery.ts +++ b/packages/runner/src/recovery.ts @@ -16,6 +16,7 @@ import { PeppaError, projectAudience, raiseSessionQuestion, + touchQuestion, sendProjectMessage, setSetting, updateSession, @@ -251,6 +252,8 @@ export async function remindTick(db: Db, o: { now: Date; cfg: WatchdogSettings; if (escalate) { await alertAdmins(db, `esc:q${q.id}`, `${m("🚨 {where}: {kind} #{id} без ответа {min} мин — агент ждёт.", { where, kind: KIND_RU[q.kind]?.toLowerCase() ?? "вопрос", id: q.id, min: ageMin })}\n\n${body}`, o.log); } else { + // PEP-151: in the chat a reminder refreshes the question's message, it is not a new one. + await touchQuestion(db, q.id, now); for (const u of await projectAudience(db, q.projectId)) { const text = `${m("⏰ {where}: {kind} #{id} ждёт ответа {min} мин.", { where, kind: KIND_RU[q.kind] ?? "Вопрос", id: q.id, min: ageMin })}\n\n${body}`; const r = await deliverToUser(db, u, { diff --git a/packages/shared/src/i18n/en/project.ts b/packages/shared/src/i18n/en/project.ts index 4ef8d6bc..bb1d263b 100644 --- a/packages/shared/src/i18n/en/project.ts +++ b/packages/shared/src/i18n/en/project.ts @@ -5,6 +5,9 @@ export const project: Dict = { // components/common.tsx — relative time "{n} с назад": "{n} s ago", "{n} мин назад": "{n} min ago", + "обновлено {ago}": "updated {ago}", + "Повторов: {n} · первое сообщение {ago}": "Repeated: {n} · first message {ago}", + "Повторов: {n}": "Repeated: {n}", "{n} ч назад": "{n} h ago", // Status labels (lib/status.ts), rendered by StatusBadge / ActivityAside "Ждёт одобрения": "Awaiting approval", diff --git a/packages/shared/src/i18n/kk/project.ts b/packages/shared/src/i18n/kk/project.ts index 0f768ba7..f5caee0d 100644 --- a/packages/shared/src/i18n/kk/project.ts +++ b/packages/shared/src/i18n/kk/project.ts @@ -4,6 +4,9 @@ import type { Dict } from "../index.ts"; export const project: Dict = { "{n} с назад": "{n} с бұрын", "{n} мин назад": "{n} мин бұрын", + "обновлено {ago}": "жаңартылды: {ago}", + "Повторов: {n} · первое сообщение {ago}": "Қайталанды: {n} · алғашқы хабарлама {ago}", + "Повторов: {n}": "Қайталанды: {n}", "{n} ч назад": "{n} сағ бұрын", "Ждёт одобрения": "Мақұлдауды күтуде", "Блок": "Блок", diff --git a/packages/testkit/test/no-repeats.test.ts b/packages/testkit/test/no-repeats.test.ts new file mode 100644 index 00000000..f5cec6e5 --- /dev/null +++ b/packages/testkit/test/no-repeats.test.ts @@ -0,0 +1,234 @@ +// PEP-151: one state — one message. The same state of a story reported again does not make a +// new question, chat message or Telegram message: the earlier one is refreshed. A changed state +// (another commit, checks, status) makes a new one. Tests are named after the spec scenarios. +import assert from "node:assert/strict"; +import { after, before, describe, test } from "node:test"; +// helpers must load first: it sets the isolated test env that runner modules read on load. +import { core, db, runner, teardown, waitFor } from "./helpers.ts"; +import { MockTelegram } from "../src/mock-telegram.ts"; +import { questions, sessions, users } from "@peppa/db"; +import { eq } from "drizzle-orm"; +import type { Bot } from "@peppa/bot"; + +const { createBot } = await import("@peppa/bot"); +const { TelegramApi } = await import("@peppa/bot/telegram"); + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const tg = await new MockTelegram().start(); +const PM = { id: 901, chatId: 901, username: "pm" }; +const EDIT_MS = 2500; +let bot: Bot; +let pm: Awaited>; +let seq = 0; + +// What the agent of PEP-147 told the user nine times in 18 minutes (questions #404–#421). +const PEP_147 = [ + "PEP-147 готова и открыта как PR #137: https://git.telecom.quest/peppa/peppa/pulls/137. Статус `review` поставить пока не удалось: проверки PR ещё идут (0 из 4), а на `review` Пеппа пускает только при зелёных.", + "PR #137 по PEP-147 открыт, но в `review` я его пока не перевёл. Пеппа пускает в `review` только при зелёных проверках, а они ещё идут (было 0 из 4).\n\nПроверю статус снова примерно через 10 минут.", + "Проверки PR #137 всё ещё показывают 0 из 4, поэтому `review` поставить нельзя: Пеппа его отклоняет. Больше я ничего не менял.\n\nПроверю снова примерно через 15 минут.", + "Стори PEP-147 остаётся в `in_progress`: Пеппа не принимает `review`, потому что проверки PR #137 показывают 0 из 4.\n\nВся работа по `tasks.md` сделана и запушена. Через 20 минут уже стоит запланированная повторная проверка.", + "Стори PEP-147 так и не в `review`: проверки PR #137 по-прежнему показывают 0 из 4.\n\nКак только проверки пройдут, достаточно вызвать `update_task(status: review)`.", + "PEP-147 всё ещё не в `review`: проверки PR #137 по-прежнему на 0 из 4, Пеппа отклоняет перевод.\n\nПроверки не стартуют: возможно, раннер `peppa-trusted` не подхватил PR #137 или не дошёл вебхук.", + "PEP-147 остаётся в `in_progress`: проверки PR #137 по-прежнему на 0 из 4, и Пеппа не принимает `review`.\n\nКогда проверки станут зелёными, достаточно вызвать `update_task(status: review)`.", + "Стори PEP-147 по-прежнему не в `review`: проверки PR #137 на 0 из 4, и Пеппа отклоняет перевод.\n\nРабота по `tasks.md` сделана и запушена, конфликтов с main нет.", + "PEP-147 пока не в `review`: проверки PR #137 по-прежнему на 0 из 4, и Пеппа отклоняет перевод.\n\nПродвинуть проверки из этой сессии нельзя, а раннер `peppa-trusted` и вебхук мне не видны.", +]; + +/** A story at work with its agent's session (no tmux: the messages are raised as the Stop hook does). */ +async function story(status: "in_progress" | "review" = "in_progress") { + const key = `N${String.fromCharCode(65 + seq++)}`; + const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: `Проект ${key}`, giteaOwner: "test", workspacePath: "/tmp/none", ownerId: pm.id }); + const created = await core.createTask(db, { projectId: p.id, title: "Telegram по желанию" }); + await core.updateTask(db, await core.resolveTask(db, created.key), { status }); + const [s] = await db.insert(sessions).values({ projectId: p.id, taskId: created.task.id, tmuxName: `mock-${key}`, status: "waiting_input" }).returning(); + const ref = () => core.resolveTask(db, created.key); + const session = () => core.getSession(db, s!.id); + return { + project: p, + taskId: created.task.id, + ref, + session, + /** The agent ended its turn with this text (the last branch of the Stop hook). */ + turnEnd: async (text: string) => core.raiseSessionQuestion(db, await session(), "attention", text, undefined, false, { topic: "turn" }), + asked: () => db.select().from(questions).where(eq(questions.taskId, created.task.id)).orderBy(questions.id), + check: (sha: string, state: "pending" | "success" | "failure") => core.upsertCheckRun(db, p, created.task.id, { sha, check: "test", state }), + thread: async () => { + await core.syncChats(db); + return core.chatMessagesView(db, (await core.ensureProjectChat(db, p.id)).id, { threadKey: `task:${created.task.id}` }); + }, + }; +} +const go = (questionId: number) => core.answerQuestion(db, questionId, "Продолжай.", "telegram"); +const tgAbout = (key: string) => tg.botMessages(PM.chatId).filter((m) => m.text.includes(`${key}-1`)); + +before(async () => { + pm = await core.upsertUserFromGitea(db, { id: 91, login: "mock-pm" }, { access_token: "x" }); + await db.update(users).set({ telegramChatId: PM.chatId, telegramUserId: PM.id }).where(eq(users.id, pm.id)); + bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 300, repeatEditMs: EDIT_MS }); + await bot.start(); +}); +after(async () => { + await bot?.stop(); + await tg.stop(); + await teardown(); +}); + +describe("Одно состояние — одно сообщение", () => { + test("Агент девять раз сообщает одно и то же; Telegram: девять повторов — одно сообщение", async () => { + const t = await story(); + const first = await t.turnEnd(PEP_147[0]!); + await waitFor("the message in Telegram", async () => tgAbout(t.project.key).length === 1); + for (const text of PEP_147.slice(1)) { + await go(first.id); + const again = await t.turnEnd(text); + assert.equal(again.id, first.id, "the same message, not a new one"); + } + const asked = await t.asked(); + assert.equal(asked.length, 1); + assert.equal(asked[0]!.text, PEP_147.at(-1)); + assert.equal(asked[0]!.answeredAt, null, "waits for an answer again"); + const st = await core.questionState(db, first.id); + assert.equal(st?.repeats, 8); + assert.ok(st?.updatedAt); + // «Ждут вашего ответа» and the story's thread: one message. + assert.equal((await core.pendingQuestions(db, t.project.id)).length, 1); + const inThread = (await t.thread()).filter((m) => m.kind === "question"); + assert.equal(inThread.length, 1); + assert.equal(inThread[0]!.repeats, 8); + assert.ok(inThread[0]!.updatedAt); + // Telegram: still one message, with the last text and the «Продолжай» button back. + const msg = await waitFor("the Telegram message refreshed", async () => { + const [m] = tgAbout(t.project.key); + return m && m.text.includes("Продвинуть проверки из этой сессии нельзя") && m.reply_markup?.inline_keyboard.flat().some((b) => /Продолжай/.test(b.text)) ? m : null; + }); + assert.equal(tgAbout(t.project.key).length, 1); + assert.ok(msg.edits >= 1); + }); + + test("Правки чаще раза в 5 минут", async () => { + const t = await story(); + const q = await t.turnEnd("Проверки ещё идут."); + await waitFor("sent", async () => tgAbout(t.project.key).length === 1); + await t.turnEnd("Проверки всё ещё идут — жду."); + const at = Date.now(); + await waitFor("first refresh", async () => tgAbout(t.project.key)[0]!.text.includes("всё ещё идут")); + await t.turnEnd("Проверки по-прежнему идут, ничего нового."); + await new Promise((r) => setTimeout(r, 900)); + assert.ok(!tgAbout(t.project.key)[0]!.text.includes("ничего нового"), "too early for another edit"); + await waitFor("second refresh after the pause", async () => tgAbout(t.project.key)[0]!.text.includes("ничего нового")); + assert.ok(Date.now() - at >= EDIT_MS - 400, "not earlier than the pause"); + assert.equal(tgAbout(t.project.key).length, 1); + assert.equal((await core.getQuestion(db, q.id)).answeredAt, null); + }); + + for (const [name, change] of [ + ["у результата появился новый коммит", async (t: Awaited>) => void (await t.check("bbb2222", "pending"))], + ["проверки прошли", async (t: Awaited>) => void (await t.check("aaa1111", "success"))], + ["задача перешла в другой статус", async (t: Awaited>) => void (await core.updateTask(db, await t.ref(), { status: "proposing" }))], + ] as const) { + test(`Состояние изменилось: ${name}`, async () => { + const t = await story(); + await t.check("aaa1111", "pending"); + const first = await t.turnEnd("Проверки ещё идут."); + await waitFor("the first Telegram message", async () => tgAbout(t.project.key).length === 1); + await go(first.id); + await change(t); + const next = await t.turnEnd("Проверки ещё идут."); + assert.notEqual(next.id, first.id); + assert.equal((await t.asked()).length, 2); + assert.ok((await core.getQuestion(db, first.id)).answeredAt, "the earlier message stays answered"); + await waitFor("a new Telegram message", async () => tgAbout(t.project.key).length === 2); + }); + } + + test("Повторное «готово» для того же результата", async () => { + const t = await story("review"); + await t.check("abc1230", "success"); + const card = await core.sendReviewCard(db, await t.ref(), "✅ Задача готова к ревью"); + assert.ok(card); + // Remarks send it back to work; a note of Peppa lands in between; back to review, no new commit. + await core.answerQuestion(db, card.id, "Поправьте заголовок", "web"); + await core.updateTask(db, await t.ref(), { status: "in_progress" }); + await t.turnEnd("Заголовок уже такой, как вы просили."); + await core.updateTask(db, await t.ref(), { status: "review" }); + const again = await core.sendReviewCard(db, await t.ref(), "✅ Задача готова к ревью\n\nЗаголовок проверил.", await t.session()); + assert.equal(again?.id, card.id); + assert.equal(again?.answeredAt, null); + assert.equal((await t.asked()).filter((q) => /готова к ревью/.test(q.text)).length, 1); + // A new commit is a new result: a new message. + await core.answerQuestion(db, card.id, "Ещё раз поправьте", "web"); + await t.check("def4560", "success"); + const fresh = await core.sendReviewCard(db, await t.ref(), "✅ Задача готова к ревью"); + assert.notEqual(fresh?.id, card.id); + }); + + test("Старое сообщение", async () => { + const t = await story(); + // Created before the rule: a question without a remembered state. + const [old] = await db.insert(questions).values({ projectId: t.project.id, taskId: t.taskId, sessionId: (await t.session()).id, kind: "attention", text: "Проверки ещё идут." }).returning(); + const next = await t.turnEnd("Проверки ещё идут."); + assert.notEqual(next.id, old!.id); + const kept = await core.getQuestion(db, old!.id); + assert.equal(kept.text, "Проверки ещё идут."); + assert.equal(await core.questionState(db, old!.id), null); + }); + + test("Вопрос агента: второй открытый с тем же текстом не заводится, после ответа — новый", async () => { + const t = await story(); + const q = await core.askPm(db, await t.ref(), { kind: "question", text: "Какой разделитель в файле?", options: [";", ","] }); + const same = await core.askPm(db, await t.ref(), { kind: "question", text: "Какой разделитель в файле?", options: [";", ","] }); + assert.equal(same.id, q.id); + const other = await core.askPm(db, await t.ref(), { kind: "question", text: "Какая кодировка файла?" }); + assert.notEqual(other.id, q.id); + await core.answerQuestion(db, q.id, ";", "web"); + const later = await core.askPm(db, await t.ref(), { kind: "question", text: "Какой разделитель в файле?", options: [";", ","] }); + assert.notEqual(later.id, q.id, "asked again after an answer — a new question"); + }); + + test("Сообщение фабрики по шаблону: то же — одно, другое — новое", async () => { + const t = await story(); + const s = await t.session(); + const a = await core.raiseSessionQuestion(db, s, "attention", "NA-1: лимит, свободных подписок нет — продолжит в 15:00 сам."); + const b = await core.raiseSessionQuestion(db, s, "attention", "NA-1: лимит, свободных подписок нет — продолжит в 17:30 сам."); + assert.equal(b.id, a.id, "only the time differs"); + const c = await core.raiseSessionQuestion(db, s, "attention", "NA-1: ход оборвался с ошибкой overloaded."); + assert.notEqual(c.id, a.id); + }); +}); + +describe("Одинаковые события подряд — одна строка", () => { + test("Десять «агент продолжает работу»; между повторами другое событие", async () => { + const t = await story(); + const s = await t.session(); + await core.logSessionEvent(db, s, "resumed", {}); + assert.equal((await t.thread()).filter((m) => /продолжает работу/.test(m.text)).length, 1); + for (let i = 0; i < 4; i++) await core.logSessionEvent(db, s, "resumed", {}); + await t.thread(); + for (let i = 0; i < 5; i++) await core.logSessionEvent(db, s, "resumed", {}); + await core.syncChats(db); + let lines = (await t.thread()).filter((m) => /продолжает работу/.test(m.text)); + assert.equal(lines.length, 1); + assert.equal(lines[0]!.repeats, 9, "×10"); + assert.ok(lines[0]!.updatedAt); + + await core.logSessionEvent(db, s, "stopped", {}); + await core.logSessionEvent(db, s, "resumed", {}); + lines = (await t.thread()).filter((m) => /продолжает работу/.test(m.text)); + assert.equal(lines.length, 2); + assert.equal(lines[1]!.repeats, 0); + }); +}); + +describe("Напоминание обновляет сообщение", () => { + test("Вопрос без ответа 30 минут; вопрос уже отвечен", async () => { + const t = await story(); + const q = await core.askPm(db, await t.ref(), { kind: "question", text: "Какой цвет кнопки?" }); + const done = await core.askPm(db, await t.ref(), { kind: "question", text: "Какой шрифт?" }); + await core.answerQuestion(db, done.id, "Обычный", "web"); + await runner.remindTick(db, { now: new Date(q.createdAt.getTime() + 31 * 60_000), cfg: { ...runner.WATCHDOG_DEFAULTS }, log: () => {} }); + const msgs = (await t.thread()).filter((m) => m.kind === "question"); + assert.equal(msgs.length, 2, "no new chat message"); + assert.ok(msgs.find((m) => m.question?.id === q.id)!.updatedAt); + assert.equal(msgs.find((m) => m.question?.id === done.id)!.updatedAt, null); + }); +});