peppa/packages/core/src/chats.ts
Асель b4b31ea88c PEP-62: write chat cursors only when they move
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 19:21:23 +05:00

550 lines
29 KiB
TypeScript

// 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<Chat> {
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<Chat> {
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<Chat> {
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<User, "id">, chatId: number): Promise<Chat> {
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<Chat | null> {
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>. */
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<User, "id">): Promise<ChatListItem[]> {
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<number, Chat>();
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<number>`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<number>`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<Date | null>((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<ChatMessage | null> {
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<NewChatMessage, "chatId">): Promise<ChatMessage | null> {
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<string | null> {
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"];
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<ChatMessageView[]> {
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,
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<ChatMessageView[]> {
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);
}
/**
* 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<User, "id">, o: { limit?: number; threadKey?: string; before?: number } = {}): Promise<ChatMessageView[]> {
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<ThreadView[]> {
const rows = await db
.select({
key: chatMessages.threadKey,
title: sql<string | null>`max(${chatMessages.threadTitle})`,
count: sql<number>`count(*)`,
lastId: sql<number>`max(${chatMessages.id})`,
lastAt: sql<number>`max(${chatMessages.createdAt})`,
open: sql<number>`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<string, string> = {
backlog: "бэклог",
proposing: "proposal",
awaiting_approval: "ждёт одобрения",
in_progress: "в работе",
review: "ревью",
done: "готово",
blocked: "заблокирована",
};
export const statusRu = (s: string) => STATUS_RU[s] ?? s;
type P = Record<string, unknown>;
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<string, (p: P) => { 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;
const icon = to === "review" ? "👀" : to === "done" ? "✅" : to === "in_progress" ? "▶️" : to === "blocked" ? "⛔" : "•";
const tail = to === "review" ? " — готово к ревью" : "";
return { text: `${icon} Статус: ${from ? `${statusRu(String(from))} → ` : ""}${statusRu(String(to))}${tail}`, 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
pr_merged_in_gitea: (p) => ({ text: `🔀 PR #${s(p.pr)} смержен${p.by ? ` (${s(p.by)})` : ""}`, important: true }),
started: () => ({ text: "▶️ Агент запущен" }),
resumed: () => ({ text: "🔁 Агент продолжает работу" }),
stopped: () => ({ text: "⏹ Агент остановлен" }),
stalled: (p) => ({ text: `⚠️ Агент молчит${p.idleMinutes ? ` ${s(p.idleMinutes)} мин` : ""}`, important: true }),
stop_failure: (p) => ({ text: `❌ Ход агента прерван: ${s(p.error) || "ошибка"}`, important: true }),
exited: (p) => ({ text: `💀 Процесс агента завершился${p.exitStatus != null ? ` (код ${s(p.exitStatus)})` : ""}`, important: true }),
usage_limit: (p) => ({ text: `⏳ Лимит подписки${p.line ? `: ${cut(s(p.line), 200)}` : ""}`, important: true }),
auto_restarted: (p) => ({ text: `🔁 Перезапуск после сбоя${p.attempt ? ` (${s(p.attempt)} из ${s(p.of)})` : ""}`, important: true }),
restart_failed: (p) => ({ text: `❌ Перезапуск не удался${p.error ? `: ${cut(s(p.error), 200)}` : ""}`, important: true }),
budget_paused: () => ({ text: "💸 Бюджет стори исчерпан — агент на паузе", important: true }),
subscription_switched: (p) => ({ text: `🔀 Подписка переключена${p.to ? ` на ${s(p.to)}` : ""}`, important: true }),
model_escalated: (p) => ({ text: `⬆️ Модель усилена${p.model ? `: ${s(p.model)}` : ""}` }),
};
const RELEASE_ICON: Record<string, string> = { deploying: "⏳", healthy: "🚀", rolled_back: "↩️", failed: "❌", removed: "🧹" };
const RELEASE_RU: Record<string, string> = { deploying: "выкатывается", healthy: "здоров", rolled_back: "откатан", failed: "не выкатился", removed: "убран" };
const INCIDENT_RU: Record<string, string> = { 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<number> {
const since = new Date(now.getTime() - DAY);
const [r] = await db.select({ min: sql<number | null>`min(${table.id})`, max: sql<number | null>`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<number | null>`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<number> {
const now = o.now ?? new Date();
const chatOf = new Map<number, number>();
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<string, string | null>();
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<number>(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<number | null>`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<number>(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<number>(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))) {
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] ?? "•"} ${r.env} ${r.sha.slice(0, 7)}: ${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<number> {
const before = new Date((o.now ?? new Date()).getTime() - chatTtlMs());
const old = db.select({ id: chatMessages.id }).from(chatMessages).where(lt(chatMessages.createdAt, before));
await db.update(telegramOutbox).set({ chatMessageId: null }).where(inArray(telegramOutbox.chatMessageId, old));
const rows = await db.delete(chatMessages).where(lt(chatMessages.createdAt, before)).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")}`;
/** One-time code (10 minutes) that links a Telegram group to this chat. */
export async function createChatLinkCode(db: Db, secret: string, user: Pick<User, "id">, chatId: number): Promise<string> {
await chatForUser(db, user, chatId);
const code = `c${randomBytes(12).toString("base64url")}`;
await setSetting(db, linkKey(code, secret), { chatId, userId: user.id, 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. */
export async function acceptChatLink(db: Db, secret: string, code: string, group: { tgChatId: number; title: string | null }, now = Date.now()): Promise<Chat | null> {
const key = linkKey(code, secret);
const saved = await getSetting<{ chatId: number; userId: number; expiresAt: number }>(db, key);
if (!saved) return null;
await deleteSetting(db, key);
if (now >= saved.expiresAt) return null;
return db.transaction((tx) => {
tx.update(chats).set({ tgChatId: null, tgTitle: null, tgLinkedAt: null, tgLinkedBy: null }).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 }).where(eq(chats.id, saved.chatId)).returning().get() ?? null;
});
}
export async function unlinkChat(db: Db, user: Pick<User, "id">, chatId: number): Promise<void> {
await chatForUser(db, user, chatId);
await db.update(chats).set({ tgChatId: null, tgTitle: null, tgLinkedAt: null, tgLinkedBy: null }).where(eq(chats.id, chatId));
}
/** A group became a supergroup: Telegram gives it a new id. */
export async function migrateChatGroup(db: Db, from: number, to: number): Promise<void> {
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<User | null> {
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<User, "id">, chat: Chat): Promise<boolean> {
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<number> {
const [r] = await db.select({ max: sql<number | null>`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<MirrorTarget[]> {
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<ChatMessage | null> {
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<OutboxRow, "id" | "chatMessageId" | "params">): Promise<number | null> {
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;
}