// PEP-62: chats — a channel per project with threads (story / incident / release) and a master // chat per user. Messages are a short-lived projection (PEPPA_CHAT_TTL_DAYS) of events, // questions, releases and incidents, which stay in their own tables; people's messages are // stored here too. Telegram groups linked to chats are the bot's business (apps/bot). import { createHmac, randomBytes } from "node:crypto"; import { chatMessages, chats, events, incidents, projects, questions, releases, tasks, telegramOutbox, users, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, lt, lte, or, sql, type SQL } from "drizzle-orm"; import { PeppaError } from "./errors.ts"; import { getNotifyPrefs, projectAudience } from "./notifications.ts"; 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"; export type Chat = typeof chats.$inferSelect; export type ChatMessage = typeof chatMessages.$inferSelect; export type NewChatMessage = typeof chatMessages.$inferInsert; const DAY = 24 * 3600_000; export const chatTtlMs = () => Math.max(1, Number(process.env.PEPPA_CHAT_TTL_DAYS ?? 14) || 14) * DAY; // ── chats ────────────────────────────────────────────────────────────────────────── export async function ensureProjectChat(db: Db, projectId: number): Promise { await db.insert(chats).values({ kind: "project", projectId }).onConflictDoNothing(); const [c] = await db.select().from(chats).where(eq(chats.projectId, projectId)); return c!; } export async function ensureMasterChat(db: Db, userId: number): Promise { await db.insert(chats).values({ kind: "master", userId }).onConflictDoNothing(); const [c] = await db.select().from(chats).where(eq(chats.userId, userId)); return c!; } export async function getChat(db: Db, id: number): Promise { const [c] = await db.select().from(chats).where(eq(chats.id, id)); if (!c) throw new PeppaError("Чат не найден"); return c; } /** The chat if this user may read and write it: project chat — owner/members, master — its owner. */ export async function chatForUser(db: Db, user: Pick, chatId: number): Promise { const c = await getChat(db, chatId); if (c.kind === "master") { if (c.userId !== user.id) throw new PeppaError("Чат не найден"); } else await projectForUser(db, user.id, c.projectId!).catch(() => { throw new PeppaError("Чат не найден"); }); return c; } export async function chatByTelegram(db: Db, tgChatId: number): Promise { const [c] = await db.select().from(chats).where(eq(chats.tgChatId, tgChatId)); return c ?? null; } export interface ChatListItem { id: number; kind: Chat["kind"]; /** "master" or the project key — the URL segment of /chats/. */ slug: string; title: string; projectId: number | null; tgTitle: string | null; lastAt: Date | null; /** Open agent questions of the project (the master chat: all of the user's). */ open: number; } /** The master chat and the chats of the user's projects (created on first look). */ export async function listChats(db: Db, user: Pick): Promise { const master = await ensureMasterChat(db, user.id); const ids = await userProjectIds(db, user.id); const ps = ids.length ? await db.select().from(projects).where(inArray(projects.id, ids)).orderBy(asc(projects.key)) : []; const projectChats = new Map(); for (const p of ps) projectChats.set(p.id, await ensureProjectChat(db, p.id)); const chatIds = [master.id, ...[...projectChats.values()].map((c) => c.id)]; const last = new Map( (await db.select({ chatId: chatMessages.chatId, at: sql`max(${chatMessages.createdAt})` }).from(chatMessages).where(inArray(chatMessages.chatId, chatIds)).groupBy(chatMessages.chatId)).map((r) => [r.chatId, r.at ? new Date(Number(r.at)) : null]), ); const open = new Map( ids.length ? (await db.select({ p: questions.projectId, n: sql`count(*)` }).from(questions).where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt))).groupBy(questions.projectId)).map((r) => [r.p, Number(r.n)]) : [], ); const masterAt = [...last.values()].reduce((a, b) => (b && (!a || b > a) ? b : a), null); return [ { id: master.id, kind: "master", slug: "master", title: "Мастер-чат", projectId: null, tgTitle: master.tgTitle, lastAt: masterAt, open: [...open.values()].reduce((a, b) => a + b, 0) }, ...ps.map((p) => { const c = projectChats.get(p.id)!; return { id: c.id, kind: "project" as const, slug: p.key, title: `${p.key} · ${p.name}`, projectId: p.id, tgTitle: c.tgTitle, lastAt: last.get(c.id) ?? null, open: open.get(p.id) ?? 0 }; }), ]; } // ── messages ─────────────────────────────────────────────────────────────────────── /** Adds a message; with a `dedupeKey` seen before it is a no-op and returns null. */ export async function addChatMessage(db: Db, m: NewChatMessage): Promise { if (m.threadKey && m.threadTitle == null) { const [prev] = await db .select({ t: chatMessages.threadTitle }) .from(chatMessages) .where(and(eq(chatMessages.chatId, m.chatId), eq(chatMessages.threadKey, m.threadKey), isNotNull(chatMessages.threadTitle))) .orderBy(desc(chatMessages.id)) .limit(1); m = { ...m, threadTitle: prev?.t ?? (await threadTitle(db, m.threadKey)) }; } const [row] = await db.insert(chatMessages).values(m).onConflictDoNothing().returning(); return row ?? null; } /** A message in the user's master chat (monitoring, digest, command replies). */ export async function addMasterMessage(db: Db, userId: number, m: Omit): Promise { const chat = await ensureMasterChat(db, userId); const row = await addChatMessage(db, { ...m, chatId: chat.id }); if (row) await notify(db, { type: "chat_message", messageId: row.id }); return row; } /** Current title of a thread: "PAY-7 · Экспорт", "Ошибка: …", "Релиз staging abc1234". */ export async function threadTitle(db: Db, key: string): Promise { const [kind, raw] = key.split(":"); const id = Number(raw); if (kind === "task") { const [t] = await db.select({ key: projects.key, n: tasks.number, title: tasks.title }).from(tasks).innerJoin(projects, eq(tasks.projectId, projects.id)).where(eq(tasks.id, id)); return t ? `${formatTaskKey(t.key, t.n)} · ${t.title}` : null; } if (kind === "incident") { const [i] = await db.select({ title: incidents.title }).from(incidents).where(eq(incidents.id, id)); return i ? `Ошибка: ${i.title}` : null; } if (kind === "release") { const [r] = await db.select({ env: releases.env, sha: releases.sha }).from(releases).where(eq(releases.id, id)); return r ? `Релиз ${r.env} ${r.sha.slice(0, 7)}` : null; } return null; } export const THREAD_KEY = /^(task|incident|release):[1-9]\d{0,9}$/; export interface ChatMessageView { id: number; chatId: number; /** Project of the chat the message lives in (master feed mixes projects). */ projectKey: string | null; threadKey: string | null; threadTitle: string | null; kind: ChatMessage["kind"]; important: boolean; authorKind: ChatMessage["authorKind"]; authorUserId: number | null; authorLogin: string | null; via: ChatMessage["via"]; text: string; url: string | null; createdAt: Date; /** 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; } async function views(db: Db, where: SQL, limit: number, before?: number): Promise { const rows = await db .select({ m: chatMessages, projectKey: projects.key, q: questions }) .from(chatMessages) .innerJoin(chats, eq(chatMessages.chatId, chats.id)) .leftJoin(projects, eq(chats.projectId, projects.id)) .leftJoin(questions, eq(chatMessages.questionId, questions.id)) .where(before ? and(where, lt(chatMessages.id, before)) : where) .orderBy(desc(chatMessages.id)) .limit(Math.min(limit, 500)); return rows.reverse().map(({ m, projectKey, q }) => ({ id: m.id, chatId: m.chatId, projectKey, threadKey: m.threadKey, threadTitle: m.threadTitle, kind: m.kind, important: m.important, authorKind: m.authorKind, authorUserId: m.authorUserId, authorLogin: m.authorLogin, via: m.via, text: m.text, url: m.url, createdAt: m.createdAt, question: q ? { id: q.id, kind: q.kind, options: q.options ?? null, answer: q.answer, answeredVia: q.answeredVia, answeredAt: q.answeredAt } : null, })); } /** Messages of a chat: the whole stream, or one thread (`threadKey`), or the channel only (null). */ export async function chatMessagesView(db: Db, chatId: number, o: { threadKey?: string | null; limit?: number; before?: number } = {}): Promise { const w: SQL[] = [eq(chatMessages.chatId, chatId)]; if (o.threadKey === null) w.push(isNull(chatMessages.threadKey)); else if (o.threadKey) w.push(eq(chatMessages.threadKey, o.threadKey)); return views(db, and(...w)!, o.limit ?? 100, o.before); } // ── discussion (PEP-106) ──────────────────────────────────────────────────── /** People's messages in a project chat's channel: no agents, no events, no commands. */ const DISCUSSION = and(isNull(chatMessages.threadKey), eq(chatMessages.kind, "user"), sql`${chatMessages.text} NOT LIKE '/%'`)!; /** PEP-106: the project's discussion — a plain chat of its people, oldest first. */ export async function discussionMessages(db: Db, chatId: number, o: { limit?: number } = {}): Promise { return views(db, and(eq(chatMessages.chatId, chatId), DISCUSSION)!, o.limit ?? 200); } const readKey = (userId: number, chatId: number) => `chat.read:${userId}:${chatId}`; /** The user has seen the discussion up to its last message. */ export async function markDiscussionRead(db: Db, userId: number, chatId: number): Promise { const [last] = await db.select({ id: sql`max(${chatMessages.id})` }).from(chatMessages).where(and(eq(chatMessages.chatId, chatId), DISCUSSION)); const id = Number(last?.id ?? 0); if (id > ((await getSetting(db, readKey(userId, chatId))) ?? 0)) await setSetting(db, readKey(userId, chatId), id); } /** Messages of other people the user has not seen yet, per project chat (chatId → count). */ export async function discussionUnread(db: Db, userId: number): Promise> { const ids = await userProjectIds(db, userId); const out = new Map(); if (!ids.length) return out; const cs = await db.select({ id: chats.id }).from(chats).where(inArray(chats.projectId, ids)); for (const c of cs) { const seen = (await getSetting(db, readKey(userId, c.id))) ?? 0; const [r] = await db .select({ n: sql`count(*)` }) .from(chatMessages) .where(and(eq(chatMessages.chatId, c.id), DISCUSSION, gt(chatMessages.id, seen), or(isNull(chatMessages.authorUserId), sql`${chatMessages.authorUserId} <> ${userId}`))); if (Number(r?.n)) out.set(c.id, Number(r!.n)); } return out; } export interface ProjectChatCard { chatId: number; key: string; name: string; /** Messages of other people and the analyst the user has not read. */ unread: number; /** 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 } | null; } /** PEP-117: the user's project chats at a glance — what is new and what was said last. */ export async function chatOverview(db: Db, user: Pick): Promise { const list = (await listChats(db, user)).filter((c) => c.kind === "project"); const unread = await discussionUnread(db, user.id); const out: ProjectChatCard[] = []; for (const c of list) { const [m] = await db.select().from(chatMessages).where(and(eq(chatMessages.chatId, c.id), DISCUSSION)).orderBy(desc(chatMessages.id)).limit(1); out.push({ chatId: c.id, key: c.slug, 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 ?? "Аналитик") : (m.authorLogin ?? "Пеппа"), mine: m.authorUserId === user.id, text: m.text, at: m.createdAt } : null, }); } // What needs the person first: open questions, then unread, then the most recent talk. return out.sort((a, b) => b.open - a.open || b.unread - a.unread || (b.last?.at.getTime() ?? 0) - (a.last?.at.getTime() ?? 0)); } /** * The master feed: the user's own master messages and the important messages of the chats * of their projects (muted projects left out). `threadKey` narrows it to one project thread. */ export async function masterFeed(db: Db, user: Pick, o: { limit?: number; threadKey?: string; before?: number } = {}): Promise { const master = await ensureMasterChat(db, user.id); const muted = new Set((await getNotifyPrefs(db, user.id)).mutedProjects); const ids = (await userProjectIds(db, user.id)).filter((id) => !muted.has(id)); const projectChats = ids.length ? (await db.select({ id: chats.id }).from(chats).where(inArray(chats.projectId, ids))).map((c) => c.id) : []; const fromProjects = projectChats.length ? and(inArray(chatMessages.chatId, projectChats), eq(chatMessages.important, true)) : undefined; let where: SQL = fromProjects ? or(eq(chatMessages.chatId, master.id), fromProjects)! : eq(chatMessages.chatId, master.id); if (o.threadKey) where = and(where, eq(chatMessages.threadKey, o.threadKey))!; return views(db, where, o.limit ?? 100, o.before); } export interface ThreadView { key: string; title: string; count: number; lastAt: Date; /** Unanswered questions in the thread. */ open: number; } /** Threads of a project chat, most recently active first. */ export async function chatThreads(db: Db, chatId: number, limit = 50): Promise { const rows = await db .select({ key: chatMessages.threadKey, title: sql`max(${chatMessages.threadTitle})`, count: sql`count(*)`, lastId: sql`max(${chatMessages.id})`, lastAt: sql`max(${chatMessages.createdAt})`, open: sql`sum(CASE WHEN ${questions.id} IS NOT NULL AND ${questions.answeredAt} IS NULL THEN 1 ELSE 0 END)`, }) .from(chatMessages) .leftJoin(questions, eq(chatMessages.questionId, questions.id)) .where(and(eq(chatMessages.chatId, chatId), isNotNull(chatMessages.threadKey))) .groupBy(chatMessages.threadKey) .orderBy(desc(sql`max(${chatMessages.id})`)) .limit(limit); return rows.map((r) => ({ key: r.key!, title: r.title ?? r.key!, count: Number(r.count), lastAt: new Date(Number(r.lastAt)), open: Number(r.open) || 0 })); } // ── projection ───────────────────────────────────────────────────────────────────── const CURSOR_EVENTS = "chat.cursor.events"; const CURSOR_QUESTIONS = "chat.cursor.questions"; const CURSOR_OBJECTS = "chat.cursor.objects"; const BATCH = 500; const STATUS_RU: Record = { backlog: "бэклог", proposing: "составляет план", awaiting_approval: "ждёт одобрения", in_progress: "в работе", review: "ревью", done: "готово", blocked: "заблокирована", }; export const statusRu = (s: string) => STATUS_RU[s] ?? s; type P = Record; const s = (v: unknown) => (v == null ? "" : String(v)); const cut = (t: string, n = 600) => (t.length > n ? `${t.slice(0, n - 1)}…` : t); /** Event types that become chat messages: text, and whether the master chat shows it. */ const EVENT_TEXT: Record { text: string; important?: boolean; author?: "agent" } | null> = { task_updated: (p) => { const from = (p.from as P | undefined)?.status; const to = (p.to as P | undefined)?.status; if (!to || from === to) return null; // PEP-117: what happened to the story, in words — not «статус X → Y». const said: Record = { proposing: "📝 Агент составляет план стори", awaiting_approval: "⏸ План готов и ждёт вашего одобрения", in_progress: from === "review" ? "🔧 Стори вернулась агенту на доработку" : "▶️ Агент взял стори в работу", review: "👀 Стори готова — посмотрите результат и примите", done: "✅ Стори принята и закрыта", blocked: "⛔ Стори заблокирована — агент не может продолжать", backlog: "↩️ Стори вернулась в бэклог", }; return { text: said[String(to)] ?? `• Статус: ${statusRu(String(to))}`, important: ["review", "done", "blocked", "awaiting_approval"].includes(String(to)) }; }, progress: (p) => ({ text: `📈 ${cut(s(p.text), 1500)}`, author: "agent" }), pm_comment: () => null, // handled separately: a person's message // PEP-4: the project's repo moved to another Gitea namespace. repo_transferred: (p) => ({ text: `📦 Код проекта переехал: ${s(p.from)} → ${s(p.to)}` }), // PEP-84: «продакт» and «аналитик» talk to the PM in the story's thread. intake_note: (p) => ({ text: `${p.role === "product" ? "🧭 Продакт" : "🔎 Аналитик"}: ${cut(s(p.text), 3000)}`, important: true, author: "agent" }), pr_merged_in_gitea: (p) => ({ text: `🔀 Изменения стори приняты в код проекта${p.by ? ` (${s(p.by)})` : ""}` }), started: () => ({ text: "▶️ Агент начал работу" }), resumed: () => ({ text: "🔁 Агент продолжает работу" }), stopped: () => ({ text: "⏹ Агент остановлен" }), // Hiccups Peppa handles by itself are told calmly and are not «важное» for a product manager. stalled: (p) => ({ text: `⚠️ Агент давно молчит${p.idleMinutes ? ` (${s(p.idleMinutes)} мин)` : ""} — Peppa перезапустит его сама` }), stop_failure: (p) => ({ text: `⚠️ Агент споткнулся (${s(p.error) || "ошибка"}) — Peppa продолжит сама` }), exited: () => ({ text: "⚠️ Агент остановился раньше времени — Peppa перезапустит его сама" }), usage_limit: () => ({ text: "⏳ Подписка упёрлась в лимит — агент продолжит после сброса или на другой подписке", important: true }), auto_restarted: (p) => ({ text: `🔁 Агент перезапущен после сбоя${p.attempt ? ` (попытка ${s(p.attempt)} из ${s(p.of)})` : ""}` }), restart_failed: () => ({ text: "❌ Агента не удалось перезапустить — нужна ваша помощь: откройте стори", important: true }), budget_paused: () => ({ text: "💸 Бюджет стори исчерпан — агент на паузе, нужен ваш ответ", important: true }), subscription_switched: (p) => ({ text: `🔀 Агент перешёл на другую подписку${p.to ? ` (${s(p.to)})` : ""} и продолжает` }), model_escalated: () => ({ text: "⬆️ Задача оказалась сложнее — агент взял модель посильнее" }), }; const RELEASE_ICON: Record = { deploying: "⏳", healthy: "🚀", rolled_back: "↩️", failed: "❌", removed: "🧹" }; const RELEASE_RU: Record = { deploying: "выкатывается", healthy: "работает", rolled_back: "не прошла проверку — возвращена прежняя", failed: "не выкатилась", removed: "убрана" }; // PEP-111: what a release is, in words for a product manager. const ENV_RU: Record = { preview: "Черновой стенд стори", staging: "Версия для проверки", prod: "Рабочая версия продукта" }; const INCIDENT_RU: Record = { new: "новая", open: "открыта", pending: "ждёт решения", task: "заведена стори", ignored: "игнорируем", resolved: "исправлена", regressed: "вернулась" }; /** First id of rows newer than a day (a fresh install doesn't import the whole history). */ async function initialCursor(db: Db, table: typeof events | typeof questions, now: Date): Promise { const since = new Date(now.getTime() - DAY); const [r] = await db.select({ min: sql`min(${table.id})`, max: sql`max(${table.id})` }).from(table).where(gt(table.createdAt, since)); if (r?.min != null) return Number(r.min) - 1; const [all] = await db.select({ max: sql`max(${table.id})` }).from(table); return Number(all?.max ?? 0); } /** * 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. * Returns the number of new messages. */ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise { const now = o.now ?? new Date(); const chatOf = new Map(); const chatId = async (projectId: number) => { if (!chatOf.has(projectId)) chatOf.set(projectId, (await ensureProjectChat(db, projectId)).id); return chatOf.get(projectId)!; }; const titles = new Map(); const titleOf = async (key: string) => { if (!titles.has(key)) titles.set(key, await threadTitle(db, key)); return titles.get(key) ?? null; }; let added = 0; const add = async (m: NewChatMessage) => { if (m.threadKey) m.threadTitle = await titleOf(m.threadKey); if (await addChatMessage(db, m)) added++; }; // events // Cursors are written only when they move: a no-op sync doesn't wake the other processes. const savedEvents = await getSetting(db, CURSOR_EVENTS); let cursor = savedEvents ?? (await initialCursor(db, events, now)); for (;;) { // Read the newest id first: a row committed after it is picked up by the next call. const [top] = await db.select({ max: sql`max(${events.id})` }).from(events); const upTo = Number(top?.max ?? cursor); const rows = await db .select({ e: events, login: users.login }) .from(events) .leftJoin(users, eq(events.actorUserId, users.id)) .where(and(gt(events.id, cursor), lte(events.id, upTo), inArray(events.type, Object.keys(EVENT_TEXT)))) .orderBy(asc(events.id)) .limit(BATCH); for (const { e, login } of rows) { const p = (e.payload ?? {}) as P; const base = { chatId: await chatId(e.projectId), threadKey: e.taskId ? `task:${e.taskId}` : null, taskId: e.taskId, dedupeKey: `event:${e.id}`, createdAt: e.createdAt }; if (e.type === "pm_comment") { if (p.chatMessageId) continue; // written in a chat: already there await add({ ...base, kind: "user", authorKind: "user", authorUserId: (p.userId as number) ?? e.actorUserId, authorLogin: s(p.login) || login, via: e.actorChannel === "telegram" ? "telegram" : "web", text: s(p.text) }); continue; } const t = EVENT_TEXT[e.type]?.(p); if (!t) continue; const authorKind = t.author ?? (e.actorKind === "user" ? "user" : e.actorKind === "agent" ? "agent" : "system"); await add({ ...base, kind: "event", important: !!t.important, authorKind, authorUserId: e.actorUserId, authorLogin: authorKind === "user" ? login : null, text: t.text }); } // The cursor moves past filtered-out events too. cursor = rows.length === BATCH ? rows.at(-1)!.e.id : Math.max(cursor, upTo); if (rows.length < BATCH) break; } if (cursor !== savedEvents) await setSetting(db, CURSOR_EVENTS, cursor); // questions const savedQuestions = await getSetting(db, CURSOR_QUESTIONS); let qCursor = savedQuestions ?? (await initialCursor(db, questions, now)); for (;;) { const rows = await db.select().from(questions).where(gt(questions.id, qCursor)).orderBy(asc(questions.id)).limit(BATCH); for (const q of rows) { const head = q.kind === "approval" ? "🟡 Нужно одобрение" : q.kind === "permission" ? "🔐 Нужно разрешение" : q.kind === "question" ? "❓ Вопрос агента" : "🔔"; await add({ chatId: await chatId(q.projectId), threadKey: q.taskId ? `task:${q.taskId}` : null, taskId: q.taskId, kind: "question", important: true, authorKind: q.sessionId ? "agent" : "system", text: `${head}\n${cut(q.text, 3000)}`, questionId: q.id, dedupeKey: `question:${q.id}`, createdAt: q.createdAt, }); qCursor = q.id; } if (rows.length < BATCH) break; } if (qCursor !== savedQuestions) await setSetting(db, CURSOR_QUESTIONS, qCursor); // releases and incidents: one message per (id, status); the window overlaps a little. const savedObjects = await getSetting(db, CURSOR_OBJECTS); const since = new Date((savedObjects ?? now.getTime() - DAY) - 60_000); for (const r of await db.select().from(releases).where(gt(releases.updatedAt, since)).orderBy(asc(releases.id))) { // A story's draft stand coming and going is plumbing: only its failure is worth a message. if (r.env === "preview" && r.status !== "failed" && r.status !== "rolled_back") continue; const tasksIn = r.tasks.length ? ` · стори: ${r.tasks.slice(0, 8).join(", ")}` : ""; await add({ chatId: await chatId(r.projectId), threadKey: `release:${r.id}`, kind: "event", important: r.env !== "preview" || r.status === "failed" || r.status === "rolled_back", text: `${RELEASE_ICON[r.status] ?? "•"} ${ENV_RU[r.env] ?? r.env}: ${RELEASE_RU[r.status] ?? r.status}${tasksIn}${r.reason ? `\n${cut(r.reason, 300)}` : ""}`, url: r.host ? `https://${r.host}` : r.runUrl, dedupeKey: `release:${r.id}:${r.status}`, }); } for (const i of await db.select().from(incidents).where(gt(incidents.updatedAt, since)).orderBy(asc(incidents.id))) { await add({ chatId: await chatId(i.projectId), threadKey: `incident:${i.id}`, taskId: i.taskId, kind: "event", important: i.status === "new" || i.status === "regressed" || i.status === "pending", text: `🐞 ${INCIDENT_RU[i.status] ?? i.status}: ${cut(i.title, 300)}${i.culprit ? `\n${cut(i.culprit, 200)}` : ""}${i.environment ? ` · ${i.environment}` : ""}${i.events > 1 ? ` · ${i.events} раз` : ""}`, url: i.url, dedupeKey: `incident:${i.id}:${i.status}`, }); } // 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 }); return added; } /** Deletes chat messages older than the TTL (the stories, questions and events stay). */ export async function pruneChats(db: Db, o: { now?: Date } = {}): Promise { const before = new Date((o.now ?? new Date()).getTime() - chatTtlMs()); // PEP-106: what people wrote to each other in the discussion is kept; the projection is not. const stale = and(lt(chatMessages.createdAt, before), sql`NOT (${DISCUSSION})`)!; const old = db.select({ id: chatMessages.id }).from(chatMessages).where(stale); await db.update(telegramOutbox).set({ chatMessageId: null }).where(inArray(telegramOutbox.chatMessageId, old)); const rows = await db.delete(chatMessages).where(stale).returning({ id: chatMessages.id }); return rows.length; } // ── Telegram groups ──────────────────────────────────────────────────────────────── const LINK_TTL_MS = 10 * 60_000; const linkKey = (code: string, secret: string) => `chat.link:${createHmac("sha256", secret).update(`chat:${code}`).digest("hex")}`; const UNLINKED = { tgChatId: null, tgTitle: null, tgLinkedAt: null, tgLinkedBy: null, tgBotUserId: null }; /** * One-time code (10 minutes) that links a Telegram group to this chat. PEP-109: the group is * linked through the user's own bot — the code is bound to it and only that bot accepts it. * `sharedBot` (the superadmin without an own bot) binds the code to the platform's bot instead. */ export async function createChatLinkCode(db: Db, secret: string, user: Pick, chatId: number, o: { sharedBot?: boolean } = {}): Promise { await chatForUser(db, user, chatId); const [u] = await db.select({ own: users.telegramBotTokenEnc }).from(users).where(eq(users.id, user.id)); if (!u?.own && !o.sharedBot) throw new PeppaError("Чтобы связать чат с группой, подключите своего бота: Настройки → Telegram"); const code = `c${randomBytes(12).toString("base64url")}`; await setSetting(db, linkKey(code, secret), { chatId, userId: user.id, botUserId: u?.own ? user.id : null, expiresAt: Date.now() + LINK_TTL_MS }); return code; } /** Codes of chat links start with "c"; the personal pairing codes of PEP-2 never collide with them. */ export const isChatLinkCode = (code: string) => /^c[\w-]{16}$/.test(code); /** * Links the group the code was sent from. A group linked to another chat moves to this one. * `botUserId` — the owner of the bot the code came to (absent = the shared bot): a code is * accepted only by the bot it was issued for; another bot leaves it intact (a command without * @bot reaches every bot of the group). */ export async function acceptChatLink(db: Db, secret: string, code: string, group: { tgChatId: number; title: string | null; botUserId?: number }, now = Date.now()): Promise { const key = linkKey(code, secret); const saved = await getSetting<{ chatId: number; userId: number; botUserId?: number | null; expiresAt: number }>(db, key); if (!saved) return null; const botUserId = saved.botUserId ?? null; if (botUserId !== (group.botUserId ?? null)) return null; await deleteSetting(db, key); if (now >= saved.expiresAt) return null; return db.transaction((tx) => { tx.update(chats).set(UNLINKED).where(eq(chats.tgChatId, group.tgChatId)).run(); return tx.update(chats).set({ tgChatId: group.tgChatId, tgTitle: group.title, tgLinkedAt: new Date(now), tgLinkedBy: saved.userId, tgBotUserId: botUserId }).where(eq(chats.id, saved.chatId)).returning().get() ?? null; }); } export async function unlinkChat(db: Db, user: Pick, chatId: number): Promise { await chatForUser(db, user, chatId); await db.update(chats).set(UNLINKED).where(eq(chats.id, chatId)); } /** Whose bot a pending link code is for: a user id, null — the shared bot, undefined — no such code. */ export async function chatLinkCodeBot(db: Db, secret: string, code: string): Promise { const saved = await getSetting<{ botUserId?: number | null }>(db, linkKey(code, secret)); return saved ? (saved.botUserId ?? null) : undefined; } /** The @username of the own bot the chat's group is linked through (null — the shared bot). */ export async function chatGroupBotName(db: Db, chatId: number): Promise { const [u] = await db.select({ username: users.telegramBotUsername }).from(chats).innerJoin(users, eq(chats.tgBotUserId, users.id)).where(eq(chats.id, chatId)); return u?.username ?? null; } /** PEP-109: groups linked through users' own bots (the bot process routes their messages). */ export async function chatGroupBots(db: Db): Promise> { const rows = await db.select({ tgChatId: chats.tgChatId, botUserId: chats.tgBotUserId }).from(chats).where(and(isNotNull(chats.tgChatId), isNotNull(chats.tgBotUserId))); return rows.map((r) => ({ tgChatId: r.tgChatId!, botUserId: r.botUserId! })); } /** A group became a supergroup: Telegram gives it a new id. */ export async function migrateChatGroup(db: Db, from: number, to: number): Promise { await db.update(chats).set({ tgChatId: to }).where(eq(chats.tgChatId, from)); } /** The person writing in a linked group: a Peppa user with this personal Telegram account (PEP-2). */ export async function telegramAccountUser(db: Db, fromId: number): Promise { const rows = await db.select().from(users).where(eq(users.telegramUserId, fromId)); return rows.find((u) => !u.disabledAt) ?? null; } /** May this user write into the chat from Telegram (project access / the master chat's owner)? */ export async function mayWriteChat(db: Db, user: Pick, chat: Chat): Promise { return chatForUser(db, user, chat.id).then( () => true, () => false, ); } export interface MirrorTarget { tgChatId: number; /** The group of a master chat (a project's message reached it as an important one). */ master: boolean; } /** Messages after `afterId` with the chat they belong to (the bot mirrors them). */ export async function chatMessagesAfter(db: Db, afterId: number, limit = 100) { return db.select({ m: chatMessages, chat: chats }).from(chatMessages).innerJoin(chats, eq(chatMessages.chatId, chats.id)).where(gt(chatMessages.id, afterId)).orderBy(asc(chatMessages.id)).limit(limit); } export async function lastChatMessageId(db: Db): Promise { const [r] = await db.select({ max: sql`max(${chatMessages.id})` }).from(chatMessages); return Number(r?.max ?? 0); } /** Linked groups a message goes to: its chat's group, and for an important project message the master groups of the project's people. */ export async function mirrorTargets(db: Db, m: ChatMessage, chat: Chat): Promise { const out: MirrorTarget[] = []; if (chat.tgChatId && chat.tgChatId !== m.tgChatId) out.push({ tgChatId: chat.tgChatId, master: chat.kind === "master" }); if (chat.kind === "project" && m.important) { for (const u of await projectAudience(db, chat.projectId!)) { const [mc] = await db.select().from(chats).where(and(eq(chats.userId, u.id), isNotNull(chats.tgChatId))); if (!mc?.tgChatId || mc.tgChatId === m.tgChatId || out.some((t) => t.tgChatId === mc.tgChatId)) continue; if ((await getNotifyPrefs(db, u.id)).mutedProjects.includes(chat.projectId!)) continue; out.push({ tgChatId: mc.tgChatId, master: true }); } } return out; } /** The chat message a Telegram message in this group stands for (sent by the bot, or written there). */ export async function chatMessageByTelegram(db: Db, tgChatId: number, tgMessageId: number): Promise { const [sent] = await db .select({ m: chatMessages }) .from(telegramOutbox) .innerJoin(chatMessages, eq(telegramOutbox.chatMessageId, chatMessages.id)) .where(and(eq(telegramOutbox.telegramMessageId, tgMessageId), sql`cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${String(tgChatId)}`)); if (sent) return sent.m; const [own] = await db.select().from(chatMessages).where(and(eq(chatMessages.tgChatId, tgChatId), eq(chatMessages.tgMessageId, tgMessageId))); return own ?? null; } /** * The Telegram message a thread hangs on in this group: the first message of the thread * that reached the group (sent by the bot or written there). Null — this is the thread's first. */ export async function threadAnchor(db: Db, row: Pick): Promise { if (!row.chatMessageId) return null; const [m] = await db.select({ threadKey: chatMessages.threadKey }).from(chatMessages).where(eq(chatMessages.id, row.chatMessageId)); if (!m?.threadKey) return null; const group = String(row.params.chat_id); const [sent] = await db .select({ id: telegramOutbox.telegramMessageId }) .from(telegramOutbox) .innerJoin(chatMessages, eq(telegramOutbox.chatMessageId, chatMessages.id)) .where(and(eq(chatMessages.threadKey, m.threadKey), eq(telegramOutbox.status, "sent"), isNotNull(telegramOutbox.telegramMessageId), sql`cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${group}`)) .orderBy(asc(telegramOutbox.id)) .limit(1); if (sent?.id) return sent.id; const [own] = await db .select({ id: chatMessages.tgMessageId }) .from(chatMessages) .where(and(eq(chatMessages.threadKey, m.threadKey), eq(chatMessages.tgChatId, Number(group)), isNotNull(chatMessages.tgMessageId))) .orderBy(asc(chatMessages.id)) .limit(1); return own?.id ?? null; }