PEP-29/35/55: notification prefs and routing, Web Push outbox, daily digest; mock-push, tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
06337e18dc
commit
ea4bdf38ff
@ -13,7 +13,13 @@ import {
|
||||
listenEvents,
|
||||
answeredQuestionMessages,
|
||||
projectForUser,
|
||||
questionRecipients,
|
||||
buildDigest,
|
||||
deliverToUser,
|
||||
flushPushOutbox,
|
||||
projectAudience,
|
||||
questionEvent,
|
||||
renderDigest,
|
||||
type NotifyEvent,
|
||||
telegramUser,
|
||||
userProjectIds,
|
||||
type User,
|
||||
@ -59,7 +65,27 @@ const HELP = `Я бот Пеппы. Присылаю вопросы от аге
|
||||
|
||||
• Кнопки под сообщением — быстрый ответ.
|
||||
• Ответ <b>реплаем</b> на сообщение — свой текст, он уйдёт прямо в сессию.
|
||||
• /status — активные сессии и открытые вопросы.`;
|
||||
• /status — активные сессии и открытые вопросы.
|
||||
• /digest — сводка за сутки по твоим проектам (каждый день приходит сама; время и что присылать — в Настройках → Уведомления).`;
|
||||
|
||||
const PUSH_MAX_AGE_MS = 30 * 60_000;
|
||||
|
||||
const PUSH_TITLE: Record<NotifyEvent, string> = {
|
||||
questions: "Агент ждёт ответа",
|
||||
review: "Готово к ревью",
|
||||
failures: "Раннер остановился",
|
||||
releases: "Релиз",
|
||||
incidents: "Ошибка в проде",
|
||||
monitoring: "Мониторинг",
|
||||
digest: "Сводка",
|
||||
};
|
||||
|
||||
/** Browser notification text for a question. */
|
||||
function pushFor(q: Question, event: NotifyEvent, ctx: { taskKey: string | null; taskTitle: string | null }): { title: string; body: string } {
|
||||
const title = `${ctx.taskKey ? `${ctx.taskKey}: ` : ""}${q.kind === "approval" ? "нужно одобрение" : q.kind === "permission" ? "нужно разрешение" : PUSH_TITLE[event]}`;
|
||||
const body = q.text.length > 200 ? `${q.text.slice(0, 199)}…` : q.text;
|
||||
return { title, body };
|
||||
}
|
||||
|
||||
export function createBot(o: BotOptions) {
|
||||
const { db, api } = o;
|
||||
@ -86,19 +112,36 @@ export function createBot(o: BotOptions) {
|
||||
return { taskKey: null, taskTitle: null, session: null, webUrl: o.webUrl };
|
||||
}
|
||||
|
||||
/** Makes sure every open question has a message and every closed one an edit. */
|
||||
/** Makes sure every open question has a message for each recipient, and every closed one an edit. */
|
||||
/**
|
||||
* Makes sure every open question reaches each person of its project by their notification
|
||||
* settings (PEP-35): a Telegram message and/or a browser push; every closed one gets an edit.
|
||||
*/
|
||||
async function reconcile(): Promise<void> {
|
||||
for (const q of await pendingQuestions(db)) {
|
||||
const recipients = await questionRecipients(db, q.projectId);
|
||||
if (!recipients.length) continue;
|
||||
const r = renderQuestion(q, await context(q));
|
||||
for (const u of recipients) {
|
||||
await enqueueTelegram(db, {
|
||||
const open = await pendingQuestions(db);
|
||||
const projectsOf = new Map<number, Set<number>>();
|
||||
const waitingFor = async (userId: number) => {
|
||||
if (!projectsOf.has(userId)) projectsOf.set(userId, new Set(await userProjectIds(db, userId)));
|
||||
const ids = projectsOf.get(userId)!;
|
||||
return open.filter((x) => ids.has(x.projectId)).length;
|
||||
};
|
||||
for (const q of open) {
|
||||
const audience = await projectAudience(db, q.projectId);
|
||||
if (!audience.length) continue;
|
||||
const ctx = await context(q);
|
||||
const event = questionEvent(q, { taskStatus: ctx.taskStatus, sessionStatus: ctx.session?.status });
|
||||
const r = renderQuestion(q, ctx);
|
||||
// A push is a "now" signal: questions older than this don't pop up on a fresh subscription.
|
||||
const fresh = Date.now() - q.createdAt.getTime() < PUSH_MAX_AGE_MS;
|
||||
const url = ctx.taskKey ? `/t/${ctx.taskKey}` : `/p/${await projectKey(q.projectId)}`;
|
||||
for (const u of audience) {
|
||||
await deliverToUser(db, u, {
|
||||
event,
|
||||
projectId: q.projectId,
|
||||
dedupeKey: `q:${q.id}:${u.telegramChatId}`,
|
||||
method: "sendMessage",
|
||||
questionId: q.id,
|
||||
params: { chat_id: u.telegramChatId, text: r.text, parse_mode: "HTML", reply_markup: { inline_keyboard: r.buttons } },
|
||||
pushKey: `q:${q.id}:u${u.id}`,
|
||||
telegram: { questionId: q.id, params: { text: r.text, parse_mode: "HTML", reply_markup: { inline_keyboard: r.buttons } } },
|
||||
push: fresh ? { ...pushFor(q, event, ctx), url, tag: `q:${q.id}`, count: await waitingFor(u.id) } : undefined,
|
||||
urgency: event === "questions" || event === "failures" ? "high" : "normal",
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -119,6 +162,11 @@ export function createBot(o: BotOptions) {
|
||||
wakeOutbox?.();
|
||||
}
|
||||
|
||||
async function projectKey(projectId: number): Promise<string> {
|
||||
const [p] = await db.select({ key: projects.key }).from(projects).where(eq(projects.id, projectId));
|
||||
return p?.key ?? "";
|
||||
}
|
||||
|
||||
function scheduleReconcile() {
|
||||
if (reconcileQueued) return;
|
||||
reconcileQueued = true;
|
||||
@ -150,6 +198,8 @@ export function createBot(o: BotOptions) {
|
||||
|
||||
async function flushOutbox(): Promise<void> {
|
||||
for (const row of await dueOutbox(db)) await deliver(row);
|
||||
// Browser pushes (PEP-55) go out of the same loop.
|
||||
await flushPushOutbox(db, { log });
|
||||
}
|
||||
|
||||
// ── Telegram → answers ─────────────────────────────────────────────────────────
|
||||
@ -199,6 +249,11 @@ export function createBot(o: BotOptions) {
|
||||
|
||||
if (/^\/(start|help)\b/.test(text)) return reply(m.chat.id, HELP).then(() => "done");
|
||||
if (/^\/status\b/.test(text)) return reply(m.chat.id, await status(user)).then(() => "done");
|
||||
if (/^\/digest\b/.test(text)) {
|
||||
const d = await buildDigest(db, user);
|
||||
await api.sendMessage(m.chat.id, renderDigest(d, { webUrl: o.webUrl, title: "Сводка за сутки" }), { link_preview_options: { is_disabled: true } }).catch((e) => log(`digest: ${e.message}`));
|
||||
return "done";
|
||||
}
|
||||
|
||||
if (m.reply_to_message) {
|
||||
const q = await questionByTelegramMessage(db, m.chat.id, m.reply_to_message.message_id);
|
||||
|
||||
173
packages/core/src/digest.ts
Normal file
173
packages/core/src/digest.ts
Normal file
@ -0,0 +1,173 @@
|
||||
// Daily digest (PEP-29): per user, per project — done in the last day, in progress, in
|
||||
// review, waiting for the user, stuck, limits. Sent from the watchdog tick at the user's
|
||||
// time; /digest in the bot renders it on demand.
|
||||
import { projects, pushSubscriptions, questions, sessions, tasks, users, type Db } from "@peppa/db";
|
||||
import { formatTaskKey, loadEnv } from "@peppa/shared";
|
||||
import { and, asc, gte, inArray, isNull, notInArray } from "drizzle-orm";
|
||||
import { deliverToUser, getNotifyPrefs, hhmmToMinutes, localClock, type NotifyPrefs } from "./notifications.ts";
|
||||
import { FINISHED_SESSION_STATUSES } from "./sessions.ts";
|
||||
import { getSetting, setSetting } from "./settings.ts";
|
||||
import { listUserProjects, type User } from "./users.ts";
|
||||
|
||||
const DAY = 24 * 3600_000;
|
||||
/** After the chosen time the digest may still go out for this long (a watchdog restart). */
|
||||
const WINDOW_MIN = 180;
|
||||
|
||||
type TaskLine = { key: string; title: string };
|
||||
|
||||
export interface ProjectDigest {
|
||||
key: string;
|
||||
name: string;
|
||||
done: TaskLine[];
|
||||
inProgress: TaskLine[];
|
||||
review: TaskLine[];
|
||||
blocked: TaskLine[];
|
||||
waiting: number;
|
||||
stalled: number;
|
||||
rateLimited: number;
|
||||
limitResumes: number;
|
||||
}
|
||||
|
||||
export interface Digest {
|
||||
projects: ProjectDigest[];
|
||||
totals: { done: number; inProgress: number; review: number; waiting: number; stuck: number };
|
||||
}
|
||||
|
||||
/** What happened in the user's projects (muted ones left out) since `now - 24h`. */
|
||||
export async function buildDigest(db: Db, user: Pick<User, "id">, o: { now?: Date; prefs?: NotifyPrefs } = {}): Promise<Digest> {
|
||||
const now = o.now ?? new Date();
|
||||
const since = new Date(now.getTime() - DAY);
|
||||
const prefs = o.prefs ?? (await getNotifyPrefs(db, user.id));
|
||||
const list = (await listUserProjects(db, user.id)).filter((p) => !prefs.mutedProjects.includes(p.id));
|
||||
const out: Digest = { projects: [], totals: { done: 0, inProgress: 0, review: 0, waiting: 0, stuck: 0 } };
|
||||
if (!list.length) return out;
|
||||
const ids = list.map((p) => p.id);
|
||||
const taskRows = await db
|
||||
.select({ projectId: tasks.projectId, number: tasks.number, title: tasks.title, status: tasks.status, updatedAt: tasks.updatedAt })
|
||||
.from(tasks)
|
||||
.where(and(inArray(tasks.projectId, ids), inArray(tasks.status, ["done", "proposing", "in_progress", "review", "blocked"])))
|
||||
.orderBy(asc(tasks.number));
|
||||
const open = await db
|
||||
.select({ projectId: questions.projectId })
|
||||
.from(questions)
|
||||
.where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt)));
|
||||
const runners = await db
|
||||
.select({ projectId: sessions.projectId, status: sessions.status, limitResumes: sessions.limitResumes, limitResumedAt: sessions.limitResumedAt })
|
||||
.from(sessions)
|
||||
.where(and(inArray(sessions.projectId, ids), notInArray(sessions.status, FINISHED_SESSION_STATUSES)));
|
||||
const resumed = await db
|
||||
.select({ projectId: sessions.projectId })
|
||||
.from(sessions)
|
||||
.where(and(inArray(sessions.projectId, ids), gte(sessions.limitResumedAt, since)));
|
||||
|
||||
for (const p of list) {
|
||||
const line = (t: { number: number; title: string }) => ({ key: formatTaskKey(p.key, t.number), title: t.title });
|
||||
const mine = taskRows.filter((t) => t.projectId === p.id);
|
||||
const d: ProjectDigest = {
|
||||
key: p.key,
|
||||
name: p.name,
|
||||
done: mine.filter((t) => t.status === "done" && t.updatedAt >= since).map(line),
|
||||
inProgress: mine.filter((t) => t.status === "in_progress" || t.status === "proposing").map(line),
|
||||
review: mine.filter((t) => t.status === "review").map(line),
|
||||
blocked: mine.filter((t) => t.status === "blocked").map(line),
|
||||
waiting: open.filter((q) => q.projectId === p.id).length,
|
||||
stalled: runners.filter((s) => s.projectId === p.id && s.status === "stalled").length,
|
||||
rateLimited: runners.filter((s) => s.projectId === p.id && s.status === "rate_limited").length,
|
||||
limitResumes: resumed.filter((s) => s.projectId === p.id).length,
|
||||
};
|
||||
const any = d.done.length + d.inProgress.length + d.review.length + d.blocked.length + d.waiting + d.stalled + d.rateLimited + d.limitResumes;
|
||||
if (!any) continue;
|
||||
out.projects.push(d);
|
||||
out.totals.done += d.done.length;
|
||||
out.totals.inProgress += d.inProgress.length;
|
||||
out.totals.review += d.review.length;
|
||||
out.totals.waiting += d.waiting;
|
||||
out.totals.stuck += d.blocked.length + d.stalled + d.rateLimited;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const esc = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s);
|
||||
|
||||
function taskList(webUrl: string, items: TaskLine[], max = 8): string {
|
||||
const shown = items.slice(0, max).map((t) => `<a href="${esc(`${webUrl}/t/${t.key}`)}">${esc(t.key)}</a> ${esc(clip(t.title, 60))}`);
|
||||
if (items.length > max) shown.push(`…и ещё ${items.length - max}`);
|
||||
return shown.map((s) => ` • ${s}`).join("\n");
|
||||
}
|
||||
|
||||
/** Telegram HTML text of the digest. */
|
||||
export function renderDigest(d: Digest, o: { webUrl: string; title?: string }): string {
|
||||
const lines = [`<b>${esc(o.title ?? "☀️ Сводка за сутки")}</b>`];
|
||||
if (!d.projects.length) {
|
||||
lines.push("", "Всё тихо: за сутки ничего не сделано, ничего не в работе и ничего не ждёт тебя.");
|
||||
return lines.join("\n");
|
||||
}
|
||||
for (const p of d.projects) {
|
||||
lines.push("", `<b>${esc(p.name)}</b> (${esc(p.key)}) — <a href="${esc(`${o.webUrl}/p/${p.key}`)}">доска</a>`);
|
||||
if (p.done.length) lines.push(`✅ Сделано: ${p.done.length}`, taskList(o.webUrl, p.done));
|
||||
if (p.inProgress.length) lines.push(`🔨 В работе: ${p.inProgress.length}`, taskList(o.webUrl, p.inProgress, 5));
|
||||
if (p.review.length) lines.push(`👀 На ревью: ${p.review.length}`, taskList(o.webUrl, p.review));
|
||||
if (p.waiting) lines.push(`⏳ Ждёт тебя: ${p.waiting}`);
|
||||
if (p.blocked.length) lines.push(`⛔ Заблокировано: ${p.blocked.length}`, taskList(o.webUrl, p.blocked));
|
||||
if (p.stalled) lines.push(`🧊 Зависло раннеров: ${p.stalled}`);
|
||||
if (p.rateLimited || p.limitResumes) {
|
||||
lines.push(`⌛ Лимит: ${[p.rateLimited ? `ждут сброса ${p.rateLimited}` : null, p.limitResumes ? `авто-продолжений за сутки ${p.limitResumes}` : null].filter(Boolean).join(", ")}`);
|
||||
}
|
||||
}
|
||||
if (d.totals.waiting) lines.push("", `<a href="${esc(o.webUrl)}">Открыть Пеппу</a> — ответить на ${d.totals.waiting}.`);
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/** One-line summary for a push notification. */
|
||||
export function digestSummary(d: Digest): string {
|
||||
const t = d.totals;
|
||||
return [t.done && `сделано ${t.done}`, t.inProgress && `в работе ${t.inProgress}`, t.review && `на ревью ${t.review}`, t.waiting && `ждёт тебя ${t.waiting}`, t.stuck && `зависло ${t.stuck}`]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
}
|
||||
|
||||
const lastKey = (userId: number) => `digest.last:${userId}`;
|
||||
|
||||
/**
|
||||
* Sends today's digest to every user whose time has come (watchdog tick). At most one per
|
||||
* local day; an empty digest isn't sent. Returns the number of users it went to.
|
||||
*/
|
||||
export async function digestTick(db: Db, o: { now?: Date; log?: (m: string) => void } = {}): Promise<number> {
|
||||
const now = o.now ?? new Date();
|
||||
const webUrl = loadEnv().PEPPA_WEB_URL;
|
||||
const withPush = new Set((await db.selectDistinct({ id: pushSubscriptions.userId }).from(pushSubscriptions)).map((r) => r.id));
|
||||
const all = (await db.select().from(users)).filter((u) => !u.disabledAt && (u.telegramChatId || withPush.has(u.id)));
|
||||
let sent = 0;
|
||||
for (const u of all) {
|
||||
try {
|
||||
const prefs = await getNotifyPrefs(db, u.id);
|
||||
const ch = prefs.events.digest;
|
||||
if (!ch.telegram && !ch.push) continue;
|
||||
const clock = localClock(now, prefs.timezone);
|
||||
const target = hhmmToMinutes(prefs.digestTime);
|
||||
if (clock.minutes < target || clock.minutes >= target + WINDOW_MIN) continue;
|
||||
if ((await getSetting<string>(db, lastKey(u.id))) === clock.date) continue;
|
||||
await setSetting(db, lastKey(u.id), clock.date);
|
||||
const d = await buildDigest(db, u, { now, prefs });
|
||||
if (!d.projects.length) continue;
|
||||
const r = await deliverToUser(
|
||||
db,
|
||||
u,
|
||||
{
|
||||
event: "digest",
|
||||
dedupeKey: `digest:u${u.id}:${clock.date}`,
|
||||
telegram: { params: { text: renderDigest(d, { webUrl }), parse_mode: "HTML", link_preview_options: { is_disabled: true } } },
|
||||
push: { title: "Сводка за сутки", body: digestSummary(d), url: "/", tag: "digest" },
|
||||
now,
|
||||
},
|
||||
prefs,
|
||||
);
|
||||
if (r.telegram || r.push) sent++;
|
||||
} catch (e) {
|
||||
o.log?.(`digest u${u.id}: ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
if (sent) o.log?.(`digest: sent to ${sent}`);
|
||||
return sent;
|
||||
}
|
||||
@ -10,7 +10,8 @@ import { PeppaError } from "./errors.ts";
|
||||
import { notify } from "./notify.ts";
|
||||
import { createGoal, listGoals, type Project } from "./projects.ts";
|
||||
import { createTask, type TaskRef } from "./tasks.ts";
|
||||
import { enqueueTelegram, questionRecipients } from "./telegram.ts";
|
||||
import { enqueueTelegram } from "./telegram.ts";
|
||||
import { deliverToUser, projectAudience } from "./notifications.ts";
|
||||
|
||||
export type Incident = typeof incidents.$inferSelect;
|
||||
export type IncidentStatus = Incident["status"];
|
||||
@ -313,24 +314,36 @@ export function renderIncidentMessage(project: Pick<Project, "key" | "name">, i:
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/** Sends an incident message to everyone who gets the project's questions in Telegram. */
|
||||
/** Sends an incident message to the project's people by their notification settings (PEP-35). */
|
||||
export async function sendIncidentMessage(db: Db, i: Incident, m: IncidentMessage): Promise<number> {
|
||||
const recipients = await questionRecipients(db, i.projectId);
|
||||
if (!recipients.length) return 0;
|
||||
const audience = await projectAudience(db, i.projectId);
|
||||
if (!audience.length) return 0;
|
||||
const [project] = await db.select().from(projects).where(eq(projects.id, i.projectId));
|
||||
if (!project) return 0;
|
||||
const text = renderIncidentMessage(project, i, m, loadEnv().PEPPA_WEB_URL);
|
||||
const markup = m.kind === "ask" || (m.kind === "regressed" && !m.task) ? { inline_keyboard: incidentButtons(i.id) } : undefined;
|
||||
const kind = m.kind === "ask" || markup ? "ask" : m.kind;
|
||||
for (const u of recipients) {
|
||||
await enqueueTelegram(db, {
|
||||
const taskKey = m.kind === "task" ? m.task.key : m.kind === "regressed" ? m.task?.key : null;
|
||||
let sent = 0;
|
||||
for (const u of audience) {
|
||||
const r = await deliverToUser(db, u, {
|
||||
event: "incidents",
|
||||
projectId: i.projectId,
|
||||
dedupeKey: `inc:${i.id}:${kind}:r${i.regressions}:${u.telegramChatId}`,
|
||||
method: "sendMessage",
|
||||
params: { chat_id: u.telegramChatId, text, parse_mode: "HTML", link_preview_options: { is_disabled: true }, ...(markup ? { reply_markup: markup } : {}) },
|
||||
pushKey: `inc:${i.id}:${kind}:r${i.regressions}:u${u.id}`,
|
||||
telegram: { params: { text, parse_mode: "HTML", link_preview_options: { is_disabled: true }, ...(markup ? { reply_markup: markup } : {}) } },
|
||||
push: {
|
||||
title: `${m.kind === "regressed" ? "Ошибка вернулась" : "Ошибка"} в ${project.name}`,
|
||||
body: clip(i.title, 200),
|
||||
url: taskKey ? `/t/${taskKey}` : `/p/${project.key}`,
|
||||
tag: `inc:${i.id}`,
|
||||
},
|
||||
urgency: kind === "ask" ? "high" : "normal",
|
||||
});
|
||||
if (r.telegram || r.push) sent++;
|
||||
}
|
||||
await notify(db, { type: "incident", incidentId: i.id });
|
||||
return recipients.length;
|
||||
return sent;
|
||||
}
|
||||
|
||||
/** Closes delivered decision messages: original text + the decision, buttons removed. */
|
||||
|
||||
@ -22,3 +22,6 @@ export * from "./local-users.ts";
|
||||
export * from "./specs.ts";
|
||||
export * from "./subscriptions.ts";
|
||||
export * from "./reviews.ts";
|
||||
export * from "./webpush.ts";
|
||||
export * from "./notifications.ts";
|
||||
export * from "./digest.ts";
|
||||
|
||||
@ -8,7 +8,7 @@ import { fileURLToPath } from "node:url";
|
||||
import { telegramOutbox, users, type Db } from "@peppa/db";
|
||||
import { and, count, eq, inArray, isNotNull, sql } from "drizzle-orm";
|
||||
import { allowedLogins } from "./access.ts";
|
||||
import { enqueueTelegram } from "./telegram.ts";
|
||||
import { deliverToUser } from "./notifications.ts";
|
||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||
import type { User } from "./users.ts";
|
||||
|
||||
@ -128,16 +128,24 @@ export async function adminRecipients(db: Db): Promise<User[]> {
|
||||
// ── checks ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function alertAdmins(db: Db, key: string, text: string, log: (m: string) => void): Promise<number> {
|
||||
const to = await adminRecipients(db);
|
||||
if (!to.length) {
|
||||
log(`monitor: ${text} (нет админа с Telegram)`);
|
||||
return 0;
|
||||
}
|
||||
const logins = await platformAdmins(db);
|
||||
const admins = logins.length ? (await db.select().from(users).where(inArray(users.login, logins))).filter((u) => !u.disabledAt) : [];
|
||||
let queued = 0;
|
||||
for (const u of to) {
|
||||
if (await enqueueTelegram(db, { dedupeKey: `${key}:${u.telegramChatId}`, method: "sendMessage", params: { chat_id: u.telegramChatId, text } })) queued++;
|
||||
let reached = 0;
|
||||
for (const u of admins) {
|
||||
// Monitoring goes by each admin's notification settings (PEP-35).
|
||||
const r = await deliverToUser(db, u, {
|
||||
event: "monitoring",
|
||||
dedupeKey: `${key}:${u.telegramChatId}`,
|
||||
pushKey: `${key}:u${u.id}`,
|
||||
telegram: { params: { text } },
|
||||
push: { title: "Мониторинг Пеппы", body: text, url: "/", tag: key.split(":").slice(0, 2).join(":") },
|
||||
urgency: "high",
|
||||
});
|
||||
if (r.telegram) queued++;
|
||||
if (r.telegram || r.push || (u.telegramChatId && !r.muted)) reached++;
|
||||
}
|
||||
log(`monitor: ${text}`);
|
||||
log(reached ? `monitor: ${text}` : `monitor: ${text} (нет админа с Telegram)`);
|
||||
return queued;
|
||||
}
|
||||
|
||||
|
||||
176
packages/core/src/notifications.ts
Normal file
176
packages/core/src/notifications.ts
Normal file
@ -0,0 +1,176 @@
|
||||
// Notification preferences and routing (PEP-35): every notification belongs to an event,
|
||||
// the user picks channels per event (Telegram, browser push), quiet hours and projects.
|
||||
import { projectMembers, projects, users, type Db } from "@peppa/db";
|
||||
import { eq, inArray } from "drizzle-orm";
|
||||
import { getSetting, setSetting } from "./settings.ts";
|
||||
import { enqueueTelegram, type OutboxRow } from "./telegram.ts";
|
||||
import type { Question } from "./tasks.ts";
|
||||
import type { User } from "./users.ts";
|
||||
import { enqueuePush, type PushPayload } from "./webpush.ts";
|
||||
|
||||
export const NOTIFY_EVENTS = ["questions", "review", "failures", "releases", "incidents", "monitoring", "digest"] as const;
|
||||
export type NotifyEvent = (typeof NOTIFY_EVENTS)[number];
|
||||
|
||||
export const NOTIFY_EVENT_NAMES: Record<NotifyEvent, string> = {
|
||||
questions: "Вопросы агентов (одобрения, вопросы, разрешения)",
|
||||
review: "Готово к ревью",
|
||||
failures: "Сбои, зависания и лимиты раннеров",
|
||||
releases: "Релизы и выкаты",
|
||||
incidents: "Ошибки из прода",
|
||||
monitoring: "Мониторинг Пеппы (админам)",
|
||||
digest: "Ежедневный дайджест",
|
||||
};
|
||||
|
||||
export interface Channels {
|
||||
telegram: boolean;
|
||||
push: boolean;
|
||||
}
|
||||
|
||||
export interface NotifyPrefs {
|
||||
events: Record<NotifyEvent, Channels>;
|
||||
/** "HH:MM"–"HH:MM" in `timezone`; may cross midnight. null = off. */
|
||||
quiet: { from: string; to: string } | null;
|
||||
/** IANA zone for quiet hours and the digest. */
|
||||
timezone: string;
|
||||
/** "HH:MM" local time of the daily digest. */
|
||||
digestTime: string;
|
||||
/** Sound for browser notifications and the open tab. */
|
||||
sound: boolean;
|
||||
/** Projects the user doesn't want notifications from. */
|
||||
mutedProjects: number[];
|
||||
}
|
||||
|
||||
const prefsKey = (userId: number) => `notify.prefs:${userId}`;
|
||||
|
||||
export const serverTimezone = () => process.env.PEPPA_TZ || Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
||||
|
||||
export function defaultPrefs(): NotifyPrefs {
|
||||
const on = { telegram: true, push: true };
|
||||
return {
|
||||
events: { questions: on, review: on, failures: on, releases: on, incidents: on, monitoring: on, digest: { telegram: true, push: false } },
|
||||
quiet: null,
|
||||
timezone: serverTimezone(),
|
||||
digestTime: "09:00",
|
||||
sound: true,
|
||||
mutedProjects: [],
|
||||
};
|
||||
}
|
||||
|
||||
const HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
|
||||
|
||||
export function isValidTimezone(tz: string): boolean {
|
||||
try {
|
||||
new Intl.DateTimeFormat("en-US", { timeZone: tz });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Saved preferences merged over the defaults (new events get their default). */
|
||||
export async function getNotifyPrefs(db: Db, userId: number): Promise<NotifyPrefs> {
|
||||
const d = defaultPrefs();
|
||||
const s = (await getSetting<Partial<NotifyPrefs>>(db, prefsKey(userId))) ?? {};
|
||||
const events = { ...d.events };
|
||||
for (const e of NOTIFY_EVENTS) if (s.events?.[e]) events[e] = { ...d.events[e], ...s.events[e] };
|
||||
return {
|
||||
events,
|
||||
quiet: s.quiet && HHMM.test(s.quiet.from) && HHMM.test(s.quiet.to) ? s.quiet : null,
|
||||
timezone: s.timezone && isValidTimezone(s.timezone) ? s.timezone : d.timezone,
|
||||
digestTime: s.digestTime && HHMM.test(s.digestTime) ? s.digestTime : d.digestTime,
|
||||
sound: s.sound ?? d.sound,
|
||||
mutedProjects: Array.isArray(s.mutedProjects) ? s.mutedProjects.filter((n) => Number.isInteger(n)) : [],
|
||||
};
|
||||
}
|
||||
|
||||
export async function setNotifyPrefs(db: Db, userId: number, p: NotifyPrefs): Promise<NotifyPrefs> {
|
||||
if (p.quiet && (!HHMM.test(p.quiet.from) || !HHMM.test(p.quiet.to))) throw new Error("Тихие часы: время в формате ЧЧ:ММ");
|
||||
if (p.quiet && p.quiet.from === p.quiet.to) throw new Error("Тихие часы: начало и конец совпадают");
|
||||
if (!HHMM.test(p.digestTime)) throw new Error("Время дайджеста: формат ЧЧ:ММ");
|
||||
if (!isValidTimezone(p.timezone)) throw new Error(`Неизвестная таймзона: ${p.timezone}`);
|
||||
await setSetting(db, prefsKey(userId), p);
|
||||
return getNotifyPrefs(db, userId);
|
||||
}
|
||||
|
||||
/** Local wall clock of `now` in `tz`: date "YYYY-MM-DD" and minutes since midnight. */
|
||||
export function localClock(now: Date, tz: string): { date: string; minutes: number; hhmm: string } {
|
||||
const parts = Object.fromEntries(
|
||||
new Intl.DateTimeFormat("en-CA", { timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" })
|
||||
.formatToParts(now)
|
||||
.map((p) => [p.type, p.value]),
|
||||
);
|
||||
const minutes = Number(parts.hour) * 60 + Number(parts.minute);
|
||||
return { date: `${parts.year}-${parts.month}-${parts.day}`, minutes, hhmm: `${parts.hour}:${parts.minute}` };
|
||||
}
|
||||
|
||||
export const hhmmToMinutes = (s: string) => Number(s.slice(0, 2)) * 60 + Number(s.slice(3, 5));
|
||||
|
||||
export function inQuietHours(prefs: Pick<NotifyPrefs, "quiet" | "timezone">, now = new Date()): boolean {
|
||||
if (!prefs.quiet) return false;
|
||||
const m = localClock(now, prefs.timezone).minutes;
|
||||
const from = hhmmToMinutes(prefs.quiet.from);
|
||||
const to = hhmmToMinutes(prefs.quiet.to);
|
||||
return from < to ? m >= from && m < to : m >= from || m < to;
|
||||
}
|
||||
|
||||
/** Which event a PM question stands for. */
|
||||
export function questionEvent(q: Pick<Question, "kind" | "taskId" | "sessionId">, ctx: { taskStatus?: string | null; sessionStatus?: string | null }): NotifyEvent {
|
||||
if (q.kind !== "attention") return q.taskId == null && q.sessionId == null ? "releases" : "questions";
|
||||
if (ctx.taskStatus === "review") return "review";
|
||||
if (ctx.sessionStatus && ["failed", "rate_limited", "stalled"].includes(ctx.sessionStatus)) return "failures";
|
||||
if (q.taskId == null && q.sessionId == null) return "releases";
|
||||
return "questions";
|
||||
}
|
||||
|
||||
/** Owner and members of a project (whether or not they paired Telegram). */
|
||||
export async function projectAudience(db: Db, projectId: number): Promise<User[]> {
|
||||
const [p] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, projectId));
|
||||
const members = await db.select({ id: projectMembers.userId }).from(projectMembers).where(eq(projectMembers.projectId, projectId));
|
||||
const ids = [...new Set([p?.ownerId, ...members.map((m) => m.id)].filter((x): x is number => x != null))];
|
||||
if (!ids.length) return [];
|
||||
return (await db.select().from(users).where(inArray(users.id, ids))).filter((u) => !u.disabledAt);
|
||||
}
|
||||
|
||||
export interface Delivery {
|
||||
event: NotifyEvent;
|
||||
/** Muting a project silences it; null = not about a project (monitoring, digest). */
|
||||
projectId?: number | null;
|
||||
/** Telegram outbox key for this user's message (push keys derive from it). */
|
||||
dedupeKey: string;
|
||||
/** Push outbox key prefix if it must not depend on the Telegram key (default: dedupeKey). */
|
||||
pushKey?: string;
|
||||
telegram?: { method?: OutboxRow["method"]; params: Record<string, unknown>; questionId?: number };
|
||||
push?: PushPayload;
|
||||
urgency?: "normal" | "high";
|
||||
now?: Date;
|
||||
}
|
||||
|
||||
export interface Delivered {
|
||||
telegram: boolean;
|
||||
push: number;
|
||||
/** Skipped by preferences (muted project / event off). */
|
||||
muted: boolean;
|
||||
}
|
||||
|
||||
/** Routes one notification to one user by their preferences. */
|
||||
export async function deliverToUser(db: Db, user: User, d: Delivery, prefs?: NotifyPrefs): Promise<Delivered> {
|
||||
const p = prefs ?? (await getNotifyPrefs(db, user.id));
|
||||
const out: Delivered = { telegram: false, push: 0, muted: false };
|
||||
if (d.projectId != null && p.mutedProjects.includes(d.projectId)) return { ...out, muted: true };
|
||||
const ch = p.events[d.event];
|
||||
if (!ch.telegram && !ch.push) return { ...out, muted: true };
|
||||
// The digest comes at a time the user picked, so quiet hours don't apply to it.
|
||||
const quiet = d.event !== "digest" && inQuietHours(p, d.now);
|
||||
if (ch.telegram && d.telegram && user.telegramChatId) {
|
||||
out.telegram = await enqueueTelegram(db, {
|
||||
dedupeKey: d.dedupeKey,
|
||||
method: d.telegram.method ?? "sendMessage",
|
||||
questionId: d.telegram.questionId,
|
||||
params: { ...d.telegram.params, chat_id: user.telegramChatId, ...(quiet ? { disable_notification: true } : {}) },
|
||||
});
|
||||
}
|
||||
if (ch.push && d.push && !quiet) {
|
||||
out.push = await enqueuePush(db, user.id, { dedupeKey: d.pushKey ?? d.dedupeKey, payload: { ...d.push, sound: d.push.sound ?? p.sound }, urgency: d.urgency });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
203
packages/core/src/webpush.ts
Normal file
203
packages/core/src/webpush.ts
Normal file
@ -0,0 +1,203 @@
|
||||
// Web Push (PEP-55) on node:crypto: VAPID (RFC 8292) + aes128gcm payload encryption
|
||||
// (RFC 8291 / RFC 8188), a durable outbox delivered by the bot, and the subscriptions table.
|
||||
import { createECDH, createPrivateKey, generateKeyPairSync, hkdfSync, randomBytes, createCipheriv, sign } from "node:crypto";
|
||||
import { pushOutbox, pushSubscriptions, type Db } from "@peppa/db";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { and, asc, eq, lte } from "drizzle-orm";
|
||||
import { getSetting, setSetting } from "./settings.ts";
|
||||
|
||||
export type PushSubscriptionRow = typeof pushSubscriptions.$inferSelect;
|
||||
export type PushOutboxRow = typeof pushOutbox.$inferSelect;
|
||||
|
||||
/** What the service worker shows (apps/web/public/sw.js). */
|
||||
export interface PushPayload {
|
||||
title: string;
|
||||
body: string;
|
||||
/** Opened on click (path on the Peppa web). */
|
||||
url: string;
|
||||
/** Same tag replaces the previous notification. */
|
||||
tag?: string;
|
||||
/** Play the system sound (user preference «звук»). */
|
||||
sound?: boolean;
|
||||
/** Waiting items for the app badge. */
|
||||
count?: number;
|
||||
}
|
||||
|
||||
const VAPID = "push.vapid";
|
||||
const b64u = (b: Buffer) => b.toString("base64url");
|
||||
const fromB64u = (s: string) => Buffer.from(s, "base64url");
|
||||
|
||||
interface VapidKeys {
|
||||
/** Uncompressed P-256 point, base64url (applicationServerKey in the browser). */
|
||||
publicKey: string;
|
||||
/** PKCS#8 PEM. */
|
||||
privateKey: string;
|
||||
}
|
||||
|
||||
/** VAPID key pair of this Peppa: created on first use, kept in settings. */
|
||||
export async function vapidKeys(db: Db): Promise<VapidKeys> {
|
||||
const saved = await getSetting<VapidKeys>(db, VAPID);
|
||||
if (saved) return saved;
|
||||
const { publicKey, privateKey } = generateKeyPairSync("ec", { namedCurve: "prime256v1" });
|
||||
const jwk = publicKey.export({ format: "jwk" });
|
||||
const raw = Buffer.concat([Buffer.from([4]), fromB64u(jwk.x!), fromB64u(jwk.y!)]);
|
||||
const keys = { publicKey: b64u(raw), privateKey: privateKey.export({ format: "pem", type: "pkcs8" }).toString() };
|
||||
await setSetting(db, VAPID, keys);
|
||||
// Another process may have raced us: whoever wrote last wins, read it back.
|
||||
return (await getSetting<VapidKeys>(db, VAPID))!;
|
||||
}
|
||||
|
||||
export const vapidPublicKey = async (db: Db) => (await vapidKeys(db)).publicKey;
|
||||
|
||||
/** `Authorization: vapid t=<JWT>, k=<public key>` for the push service at `endpoint`. */
|
||||
export function vapidAuthorization(keys: VapidKeys, endpoint: string, subject: string, now = Date.now()): string {
|
||||
const header = b64u(Buffer.from(JSON.stringify({ typ: "JWT", alg: "ES256" })));
|
||||
const claims = b64u(Buffer.from(JSON.stringify({ aud: new URL(endpoint).origin, exp: Math.floor(now / 1000) + 12 * 3600, sub: subject })));
|
||||
const data = `${header}.${claims}`;
|
||||
const sig = sign("sha256", Buffer.from(data), { key: createPrivateKey(keys.privateKey), dsaEncoding: "ieee-p1363" });
|
||||
return `vapid t=${data}.${b64u(sig)}, k=${keys.publicKey}`;
|
||||
}
|
||||
|
||||
/** RFC 8291 aes128gcm body for the subscription's keys (one record). */
|
||||
export function encryptPayload(plaintext: Buffer, p256dh: string, auth: string): Buffer {
|
||||
const uaPublic = fromB64u(p256dh);
|
||||
const authSecret = fromB64u(auth);
|
||||
const ecdh = createECDH("prime256v1");
|
||||
const asPublic = ecdh.generateKeys();
|
||||
const shared = ecdh.computeSecret(uaPublic);
|
||||
const keyInfo = Buffer.concat([Buffer.from("WebPush: info\0"), uaPublic, asPublic]);
|
||||
const ikm = Buffer.from(hkdfSync("sha256", shared, authSecret, keyInfo, 32));
|
||||
const salt = randomBytes(16);
|
||||
const cek = Buffer.from(hkdfSync("sha256", ikm, salt, Buffer.from("Content-Encoding: aes128gcm\0"), 16));
|
||||
const nonce = Buffer.from(hkdfSync("sha256", ikm, salt, Buffer.from("Content-Encoding: nonce\0"), 12));
|
||||
const cipher = createCipheriv("aes-128-gcm", cek, nonce);
|
||||
// 0x02 = padding delimiter of the last (only) record.
|
||||
const body = Buffer.concat([cipher.update(Buffer.concat([plaintext, Buffer.from([2])])), cipher.final(), cipher.getAuthTag()]);
|
||||
const rs = Buffer.alloc(4);
|
||||
rs.writeUInt32BE(4096);
|
||||
return Buffer.concat([salt, rs, Buffer.from([asPublic.length]), asPublic, body]);
|
||||
}
|
||||
|
||||
export type PushResult = { ok: true } | { ok: false; gone: boolean; retryAfterSec?: number; status: number; error: string };
|
||||
|
||||
/** One push to one subscription. `gone` = the subscription no longer exists (404/410). */
|
||||
export async function sendWebPush(
|
||||
db: Db,
|
||||
sub: Pick<PushSubscriptionRow, "endpoint" | "p256dh" | "auth">,
|
||||
payload: PushPayload,
|
||||
o: { urgency?: "normal" | "high"; ttlSec?: number } = {},
|
||||
): Promise<PushResult> {
|
||||
const keys = await vapidKeys(db);
|
||||
const body = encryptPayload(Buffer.from(JSON.stringify(payload)), sub.p256dh, sub.auth);
|
||||
try {
|
||||
const res = await fetch(sub.endpoint, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: vapidAuthorization(keys, sub.endpoint, loadEnv().PEPPA_WEB_URL),
|
||||
"Content-Encoding": "aes128gcm",
|
||||
"Content-Type": "application/octet-stream",
|
||||
TTL: String(o.ttlSec ?? 24 * 3600),
|
||||
Urgency: o.urgency ?? "normal",
|
||||
},
|
||||
body: new Uint8Array(body),
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
});
|
||||
if (res.ok) return { ok: true };
|
||||
const text = (await res.text().catch(() => "")).slice(0, 300);
|
||||
const retryAfter = Number(res.headers.get("retry-after"));
|
||||
return {
|
||||
ok: false,
|
||||
gone: res.status === 404 || res.status === 410,
|
||||
status: res.status,
|
||||
retryAfterSec: Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : undefined,
|
||||
error: `${res.status} ${text}`.trim(),
|
||||
};
|
||||
} catch (e) {
|
||||
return { ok: false, gone: false, status: 0, error: (e as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
// ── subscriptions ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function savePushSubscription(
|
||||
db: Db,
|
||||
userId: number,
|
||||
s: { endpoint: string; keys: { p256dh: string; auth: string }; userAgent?: string | null },
|
||||
): Promise<PushSubscriptionRow> {
|
||||
if (!/^https:\/\//.test(s.endpoint) && !/^http:\/\/(127\.0\.0\.1|localhost)[:/]/.test(s.endpoint)) throw new Error("Неверный адрес push-подписки");
|
||||
if (fromB64u(s.keys.p256dh).length !== 65 || fromB64u(s.keys.auth).length < 16) throw new Error("Неверные ключи push-подписки");
|
||||
const values = { userId, endpoint: s.endpoint, p256dh: s.keys.p256dh, auth: s.keys.auth, userAgent: s.userAgent?.slice(0, 300) ?? null };
|
||||
const [row] = await db
|
||||
.insert(pushSubscriptions)
|
||||
.values(values)
|
||||
// The same browser re-subscribing (or another user on it) takes the endpoint over.
|
||||
.onConflictDoUpdate({ target: pushSubscriptions.endpoint, set: values })
|
||||
.returning();
|
||||
return row!;
|
||||
}
|
||||
|
||||
export async function deletePushSubscription(db: Db, userId: number, endpoint: string): Promise<void> {
|
||||
await db.delete(pushSubscriptions).where(and(eq(pushSubscriptions.userId, userId), eq(pushSubscriptions.endpoint, endpoint)));
|
||||
}
|
||||
|
||||
export async function userPushSubscriptions(db: Db, userId: number): Promise<PushSubscriptionRow[]> {
|
||||
return db.select().from(pushSubscriptions).where(eq(pushSubscriptions.userId, userId)).orderBy(asc(pushSubscriptions.id));
|
||||
}
|
||||
|
||||
// ── outbox ──────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Queues a push for every subscription of the user. Returns the number queued. */
|
||||
export async function enqueuePush(db: Db, userId: number, m: { dedupeKey: string; payload: PushPayload; urgency?: "normal" | "high" }): Promise<number> {
|
||||
let queued = 0;
|
||||
for (const s of await userPushSubscriptions(db, userId)) {
|
||||
const rows = await db
|
||||
.insert(pushOutbox)
|
||||
.values({ dedupeKey: `${m.dedupeKey}:push:${s.id}`, subscriptionId: s.id, payload: { ...m.payload }, urgency: m.urgency ?? "normal" })
|
||||
.onConflictDoNothing()
|
||||
.returning();
|
||||
queued += rows.length;
|
||||
}
|
||||
return queued;
|
||||
}
|
||||
|
||||
const MAX_ATTEMPTS = 6;
|
||||
|
||||
/** Delivers due pushes; called from the bot's outbox loop. Returns the number delivered. */
|
||||
export async function flushPushOutbox(db: Db, o: { log?: (m: string) => void; limit?: number } = {}): Promise<number> {
|
||||
const due = await db
|
||||
.select({ row: pushOutbox, sub: pushSubscriptions })
|
||||
.from(pushOutbox)
|
||||
.leftJoin(pushSubscriptions, eq(pushOutbox.subscriptionId, pushSubscriptions.id))
|
||||
.where(and(eq(pushOutbox.status, "pending"), lte(pushOutbox.nextAttemptAt, new Date())))
|
||||
.orderBy(asc(pushOutbox.id))
|
||||
.limit(o.limit ?? 20);
|
||||
let sent = 0;
|
||||
for (const { row, sub } of due) {
|
||||
if (!sub) {
|
||||
await db.update(pushOutbox).set({ status: "failed", error: "subscription removed" }).where(eq(pushOutbox.id, row.id));
|
||||
continue;
|
||||
}
|
||||
const r = await sendWebPush(db, sub, row.payload as unknown as PushPayload, { urgency: row.urgency });
|
||||
const attempts = row.attempts + 1;
|
||||
if (r.ok) {
|
||||
sent++;
|
||||
await db.update(pushOutbox).set({ status: "sent", sentAt: new Date(), attempts, error: null }).where(eq(pushOutbox.id, row.id));
|
||||
await db.update(pushSubscriptions).set({ lastOkAt: new Date() }).where(eq(pushSubscriptions.id, sub.id));
|
||||
continue;
|
||||
}
|
||||
o.log?.(`push #${row.id}: ${r.error}`);
|
||||
if (r.gone) {
|
||||
// The browser unsubscribed or the subscription expired: forget it (and its queue).
|
||||
await db.update(pushOutbox).set({ status: "failed", attempts, error: r.error }).where(eq(pushOutbox.subscriptionId, sub.id));
|
||||
await db.delete(pushSubscriptions).where(eq(pushSubscriptions.id, sub.id));
|
||||
continue;
|
||||
}
|
||||
const permanent = r.status >= 400 && r.status < 500 && r.status !== 429;
|
||||
const delayMs = r.retryAfterSec != null ? r.retryAfterSec * 1000 : Math.min(10 * 60_000, 2000 * 2 ** attempts);
|
||||
await db
|
||||
.update(pushOutbox)
|
||||
.set({ attempts, error: r.error, status: permanent || attempts >= MAX_ATTEMPTS ? "failed" : "pending", nextAttemptAt: new Date(Date.now() + delayMs) })
|
||||
.where(eq(pushOutbox.id, row.id));
|
||||
}
|
||||
return sent;
|
||||
}
|
||||
29
packages/db/migrations/0005_push_notifications.sql
Normal file
29
packages/db/migrations/0005_push_notifications.sql
Normal file
@ -0,0 +1,29 @@
|
||||
CREATE TABLE `push_outbox` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`dedupe_key` text NOT NULL,
|
||||
`subscription_id` integer,
|
||||
`payload` text NOT NULL,
|
||||
`urgency` text DEFAULT 'normal' NOT NULL,
|
||||
`status` text DEFAULT 'pending' NOT NULL,
|
||||
`attempts` integer DEFAULT 0 NOT NULL,
|
||||
`next_attempt_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
|
||||
`error` text,
|
||||
`created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
|
||||
`sent_at` integer,
|
||||
FOREIGN KEY (`subscription_id`) REFERENCES `push_subscriptions`(`id`) ON UPDATE no action ON DELETE set null
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `push_outbox_dedupe_key_unique` ON `push_outbox` (`dedupe_key`);--> statement-breakpoint
|
||||
CREATE TABLE `push_subscriptions` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` integer NOT NULL,
|
||||
`endpoint` text NOT NULL,
|
||||
`p256dh` text NOT NULL,
|
||||
`auth` text NOT NULL,
|
||||
`user_agent` text,
|
||||
`created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
|
||||
`last_ok_at` integer,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `push_subscriptions_endpoint_unique` ON `push_subscriptions` (`endpoint`);
|
||||
2967
packages/db/migrations/meta/0005_snapshot.json
Normal file
2967
packages/db/migrations/meta/0005_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@ -36,6 +36,13 @@
|
||||
"when": 1794613008393,
|
||||
"tag": "0004_code_reviewer",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 5,
|
||||
"version": "6",
|
||||
"when": 1794614987778,
|
||||
"tag": "0005_push_notifications",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -325,6 +325,33 @@ export const telegramUpdates = sqliteTable("telegram_updates", {
|
||||
createdAt: createdAt(),
|
||||
});
|
||||
|
||||
/** PEP-55: a browser's Web Push subscription (PushSubscription.toJSON()). */
|
||||
export const pushSubscriptions = sqliteTable("push_subscriptions", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
|
||||
endpoint: text("endpoint").notNull().unique(),
|
||||
p256dh: text("p256dh").notNull(),
|
||||
auth: text("auth").notNull(),
|
||||
userAgent: text("user_agent"),
|
||||
createdAt: createdAt(),
|
||||
lastOkAt: integer("last_ok_at", { mode: "timestamp_ms" }),
|
||||
});
|
||||
|
||||
/** PEP-55: durable Web Push outbox, delivered by the bot with retries (like telegram_outbox). */
|
||||
export const pushOutbox = sqliteTable("push_outbox", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
dedupeKey: text("dedupe_key").notNull().unique(),
|
||||
subscriptionId: integer("subscription_id").references(() => pushSubscriptions.id, { onDelete: "set null" }),
|
||||
payload: text("payload", { mode: "json" }).$type<Record<string, unknown>>().notNull(),
|
||||
urgency: text("urgency", { enum: ["normal", "high"] }).notNull().default("normal"),
|
||||
status: text("status", { enum: ["pending", "sent", "failed"] }).notNull().default("pending"),
|
||||
attempts: integer("attempts").notNull().default(0),
|
||||
nextAttemptAt: integer("next_attempt_at", { mode: "timestamp_ms" }).notNull().default(nowMs),
|
||||
error: text("error"),
|
||||
createdAt: createdAt(),
|
||||
sentAt: integer("sent_at", { mode: "timestamp_ms" }),
|
||||
});
|
||||
|
||||
/** OAuth clients registered dynamically (RFC 7591), e.g. ChatGPT connectors. */
|
||||
export const oauthClients = sqliteTable("oauth_clients", {
|
||||
id: text("id").primaryKey(),
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
backupDb,
|
||||
digestTick,
|
||||
expireSessionQuestions,
|
||||
listSessions,
|
||||
logSessionEvent,
|
||||
@ -52,6 +53,8 @@ export async function tick(db: Db, opts: WatchdogOptions): Promise<void> {
|
||||
}
|
||||
// Errors of running products (PEP-58): Bugsink poll + incident policies.
|
||||
await incidentTick(db, { now: opts.now, log }).catch((e) => log(`incidents: ${(e as Error).message}`));
|
||||
// Daily digest at each user's time (PEP-29); a no-op outside their window.
|
||||
await digestTick(db, { now: opts.now, log }).catch((e) => log(`digest: ${(e as Error).message}`));
|
||||
}
|
||||
|
||||
async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log: (m: string) => void) {
|
||||
|
||||
118
packages/testkit/src/mock-push.ts
Normal file
118
packages/testkit/src/mock-push.ts
Normal file
@ -0,0 +1,118 @@
|
||||
// Mock Web Push service (PEP-55) for tests: plays the browser + push service (FCM) side.
|
||||
// `subscribe()` returns what PushSubscription.toJSON() gives in a browser; POSTs to the
|
||||
// endpoint are checked like a real push service does (VAPID JWT signed by `k`, aud,
|
||||
// exp, aes128gcm) and decrypted with the subscription's private key (RFC 8291).
|
||||
import { createDecipheriv, createECDH, createPublicKey, hkdfSync, randomBytes, randomUUID, verify } from "node:crypto";
|
||||
import { createServer, type Server } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
|
||||
export interface MockPushMessage {
|
||||
subscription: string;
|
||||
payload: Record<string, unknown>;
|
||||
urgency: string | null;
|
||||
ttl: string | null;
|
||||
}
|
||||
|
||||
interface MockSub {
|
||||
ecdh: ReturnType<typeof createECDH>;
|
||||
auth: Buffer;
|
||||
/** Answer with this status instead of 201 (e.g. 410 = unsubscribed). */
|
||||
status?: number;
|
||||
}
|
||||
|
||||
export class MockPushService {
|
||||
readonly messages: MockPushMessage[] = [];
|
||||
readonly rejected: Array<{ subscription: string; reason: string }> = [];
|
||||
private subs = new Map<string, MockSub>();
|
||||
private server: Server | null = null;
|
||||
url = "";
|
||||
|
||||
async start(): Promise<this> {
|
||||
this.server = createServer((req, res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
req.on("data", (c) => chunks.push(c));
|
||||
req.on("end", () => {
|
||||
const id = /^\/push\/([\w-]+)$/.exec(req.url ?? "")?.[1] ?? "";
|
||||
const sub = this.subs.get(id);
|
||||
const fail = (status: number, reason: string) => {
|
||||
this.rejected.push({ subscription: id, reason });
|
||||
res.writeHead(status).end(reason);
|
||||
};
|
||||
if (req.method !== "POST" || !sub) return fail(404, "no such subscription");
|
||||
if (sub.status) return fail(sub.status, "mock status");
|
||||
try {
|
||||
this.checkVapid(String(req.headers.authorization ?? ""));
|
||||
if (req.headers["content-encoding"] !== "aes128gcm") throw new Error("Content-Encoding must be aes128gcm");
|
||||
if (!req.headers.ttl) throw new Error("TTL header required");
|
||||
const payload = JSON.parse(this.decrypt(sub, Buffer.concat(chunks)).toString("utf8"));
|
||||
this.messages.push({ subscription: id, payload, urgency: (req.headers.urgency as string) ?? null, ttl: (req.headers.ttl as string) ?? null });
|
||||
res.writeHead(201).end();
|
||||
} catch (e) {
|
||||
fail(400, (e as Error).message);
|
||||
}
|
||||
});
|
||||
});
|
||||
await new Promise<void>((r) => this.server!.listen(0, "127.0.0.1", r));
|
||||
this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`;
|
||||
return this;
|
||||
}
|
||||
|
||||
async stop() {
|
||||
await new Promise<void>((r) => this.server?.close(() => r()) ?? r());
|
||||
}
|
||||
|
||||
/** A new browser subscription: { endpoint, keys: { p256dh, auth } }. */
|
||||
subscribe(): { id: string; endpoint: string; keys: { p256dh: string; auth: string } } {
|
||||
const id = randomUUID();
|
||||
const ecdh = createECDH("prime256v1");
|
||||
ecdh.generateKeys();
|
||||
const auth = randomBytes(16);
|
||||
this.subs.set(id, { ecdh, auth });
|
||||
return { id, endpoint: `${this.url}/push/${id}`, keys: { p256dh: ecdh.getPublicKey().toString("base64url"), auth: auth.toString("base64url") } };
|
||||
}
|
||||
|
||||
/** From now on the push service answers `status` for this subscription (410 = gone). */
|
||||
setStatus(id: string, status: number | undefined) {
|
||||
const s = this.subs.get(id);
|
||||
if (s) s.status = status;
|
||||
}
|
||||
|
||||
for(id: string) {
|
||||
return this.messages.filter((m) => m.subscription === id);
|
||||
}
|
||||
|
||||
private checkVapid(authorization: string) {
|
||||
const m = /^vapid t=([\w-]+\.[\w-]+\.[\w-]+), k=([\w-]+)$/.exec(authorization);
|
||||
if (!m) throw new Error("Authorization must be 'vapid t=…, k=…'");
|
||||
const [h, c, s] = m[1]!.split(".") as [string, string, string];
|
||||
const raw = Buffer.from(m[2]!, "base64url");
|
||||
if (raw.length !== 65 || raw[0] !== 4) throw new Error("k must be an uncompressed P-256 point");
|
||||
const key = createPublicKey({ key: { kty: "EC", crv: "P-256", x: raw.subarray(1, 33).toString("base64url"), y: raw.subarray(33).toString("base64url") }, format: "jwk" });
|
||||
if (!verify("sha256", Buffer.from(`${h}.${c}`), { key, dsaEncoding: "ieee-p1363" }, Buffer.from(s, "base64url"))) throw new Error("bad VAPID signature");
|
||||
const header = JSON.parse(Buffer.from(h, "base64url").toString());
|
||||
const claims = JSON.parse(Buffer.from(c, "base64url").toString());
|
||||
if (header.alg !== "ES256") throw new Error("alg must be ES256");
|
||||
if (claims.aud !== this.url) throw new Error(`aud ${claims.aud} != ${this.url}`);
|
||||
if (!(claims.exp > Date.now() / 1000) || claims.exp > Date.now() / 1000 + 24 * 3600) throw new Error("bad exp");
|
||||
if (!/^(https?:|mailto:)/.test(String(claims.sub))) throw new Error("sub must be a URL or mailto:");
|
||||
}
|
||||
|
||||
private decrypt(sub: MockSub, body: Buffer): Buffer {
|
||||
const salt = body.subarray(0, 16);
|
||||
const idlen = body[20]!;
|
||||
const asPublic = body.subarray(21, 21 + idlen);
|
||||
const ct = body.subarray(21 + idlen);
|
||||
const uaPublic = sub.ecdh.getPublicKey();
|
||||
const shared = sub.ecdh.computeSecret(asPublic);
|
||||
const ikm = Buffer.from(hkdfSync("sha256", shared, sub.auth, Buffer.concat([Buffer.from("WebPush: info\0"), uaPublic, asPublic]), 32));
|
||||
const cek = Buffer.from(hkdfSync("sha256", ikm, salt, Buffer.from("Content-Encoding: aes128gcm\0"), 16));
|
||||
const nonce = Buffer.from(hkdfSync("sha256", ikm, salt, Buffer.from("Content-Encoding: nonce\0"), 12));
|
||||
const d = createDecipheriv("aes-128-gcm", cek, nonce);
|
||||
d.setAuthTag(ct.subarray(ct.length - 16));
|
||||
const plain = Buffer.concat([d.update(ct.subarray(0, ct.length - 16)), d.final()]);
|
||||
let end = plain.length - 1;
|
||||
while (end >= 0 && plain[end] === 0) end--;
|
||||
if (plain[end] !== 2) throw new Error("bad padding delimiter");
|
||||
return plain.subarray(0, end);
|
||||
}
|
||||
}
|
||||
235
packages/testkit/test/notifications.test.ts
Normal file
235
packages/testkit/test/notifications.test.ts
Normal file
@ -0,0 +1,235 @@
|
||||
// PEP-29 / PEP-35 / PEP-55: notification settings, quiet hours, browser push and the daily
|
||||
// digest — the real bot against mock-telegram and mock-push, controlled clock for the digest.
|
||||
import assert from "node:assert/strict";
|
||||
import { after, before, beforeEach, describe, test } from "node:test";
|
||||
// helpers must load first: it sets the isolated test env that runner modules read on load.
|
||||
import { core, db, teardown, waitFor } from "./helpers.ts";
|
||||
import { MockTelegram } from "../src/mock-telegram.ts";
|
||||
import { MockPushService } from "../src/mock-push.ts";
|
||||
import { projects, pushOutbox, pushSubscriptions, questions, sessions, settings, tasks, telegramOutbox, users } from "@peppa/db";
|
||||
import { eq, like, sql } 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 TZ = "Europe/Moscow"; // UTC+3, no DST
|
||||
const tg = await new MockTelegram().start();
|
||||
const push = await new MockPushService().start();
|
||||
const PM = { id: 601, chatId: 601 };
|
||||
const BOB = { id: 602, chatId: 602 };
|
||||
let bot: Bot;
|
||||
let pm: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||
let bob: typeof pm;
|
||||
let seq = 0;
|
||||
|
||||
async function newProject(name: string) {
|
||||
const key = `N${String.fromCharCode(65 + seq++)}`;
|
||||
const p = await core.createProject(db, { slug: key.toLowerCase(), key, name, giteaOwner: "test", workspacePath: "/tmp/none", ownerId: pm.id });
|
||||
await core.addMember(db, p, bob.login, pm.id);
|
||||
return p;
|
||||
}
|
||||
async function newTask(p: { id: number; key: string }, title = "Стори") {
|
||||
const ref = await core.createTask(db, { projectId: p.id, title });
|
||||
return core.resolveTask(db, ref.key);
|
||||
}
|
||||
const prefs = (u: { id: number }) => core.getNotifyPrefs(db, u.id);
|
||||
async function setPrefs(u: { id: number }, patch: Partial<Awaited<ReturnType<typeof prefs>>>) {
|
||||
await core.setNotifyPrefs(db, u.id, { ...(await prefs(u)), ...patch });
|
||||
}
|
||||
const sentTo = (chatId: number, needle: string) => tg.calls.filter((c) => c.method === "sendMessage" && c.params.chat_id === chatId && String(c.params.text).includes(needle));
|
||||
|
||||
before(async () => {
|
||||
pm = await core.upsertUserFromGitea(db, { id: 71, login: "mock-pm" }, { access_token: "x" });
|
||||
bob = await core.upsertUserFromGitea(db, { id: 72, login: "mock-bob" }, { access_token: "y" });
|
||||
await db.update(users).set({ telegramChatId: PM.chatId, telegramUserId: PM.id }).where(eq(users.id, pm.id));
|
||||
await db.update(users).set({ telegramChatId: BOB.chatId, telegramUserId: BOB.id }).where(eq(users.id, bob.id));
|
||||
pm = (await core.getUser(db, pm.id))!;
|
||||
bob = (await core.getUser(db, bob.id))!;
|
||||
bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 300, log: (m) => process.env.MOCK_DEBUG && console.log(m) });
|
||||
await bot.start();
|
||||
});
|
||||
after(async () => {
|
||||
await bot.stop();
|
||||
await tg.stop();
|
||||
await push.stop();
|
||||
await teardown();
|
||||
});
|
||||
beforeEach(async () => {
|
||||
// Earlier tests' open questions would pop up on a fresh push subscription.
|
||||
await db.delete(questions);
|
||||
await db.delete(pushSubscriptions);
|
||||
for (const u of [pm, bob]) await core.setNotifyPrefs(db, u.id, { ...core.defaultPrefs(), timezone: TZ });
|
||||
});
|
||||
|
||||
describe("settings", () => {
|
||||
test("defaults: everything on except the digest in the browser; garbage is rejected", async () => {
|
||||
const p = await prefs(pm);
|
||||
assert.deepEqual(p.events.questions, { telegram: true, push: true });
|
||||
assert.deepEqual(p.events.digest, { telegram: true, push: false });
|
||||
assert.equal(p.digestTime, "09:00");
|
||||
await assert.rejects(core.setNotifyPrefs(db, pm.id, { ...p, quiet: { from: "25:00", to: "08:00" } }), /ЧЧ:ММ/);
|
||||
await assert.rejects(core.setNotifyPrefs(db, pm.id, { ...p, timezone: "Mars/Olympus" }), /таймзона/);
|
||||
});
|
||||
|
||||
test("quiet hours cross midnight in the user's timezone", () => {
|
||||
const q = { quiet: { from: "23:00", to: "08:00" }, timezone: TZ };
|
||||
assert.equal(core.inQuietHours(q, new Date("2026-03-01T23:00:00Z")), true); // 02:00 MSK
|
||||
assert.equal(core.inQuietHours(q, new Date("2026-03-01T19:59:00Z")), false); // 22:59 MSK
|
||||
assert.equal(core.inQuietHours(q, new Date("2026-03-01T05:00:00Z")), false); // 08:00 MSK
|
||||
assert.equal(core.inQuietHours({ quiet: null, timezone: TZ }, new Date()), false);
|
||||
});
|
||||
|
||||
test("question events", () => {
|
||||
const base = { taskId: 1, sessionId: 1 };
|
||||
assert.equal(core.questionEvent({ ...base, kind: "approval" }, {}), "questions");
|
||||
assert.equal(core.questionEvent({ ...base, kind: "attention" }, { taskStatus: "review" }), "review");
|
||||
assert.equal(core.questionEvent({ ...base, kind: "attention" }, { sessionStatus: "rate_limited" }), "failures");
|
||||
assert.equal(core.questionEvent({ kind: "question", taskId: null, sessionId: null }, {}), "releases");
|
||||
});
|
||||
});
|
||||
|
||||
describe("routing in the bot", () => {
|
||||
test("Сценарий: выключены вопросы агентов в Telegram — сообщения нет, у участника есть", async () => {
|
||||
await setPrefs(pm, { events: { ...(await prefs(pm)).events, questions: { telegram: false, push: true } } });
|
||||
const p = await newProject("Routing");
|
||||
const ref = await newTask(p);
|
||||
const q = await core.askPm(db, ref, { kind: "question", text: "Какую БД взять?" });
|
||||
await waitFor("bob got the question", async () => sentTo(BOB.chatId, "Какую БД взять").length > 0);
|
||||
await new Promise((r) => setTimeout(r, 800)); // a couple of reconcile rounds
|
||||
assert.equal(sentTo(PM.chatId, "Какую БД взять").length, 0);
|
||||
assert.equal((await core.pendingQuestions(db, p.id)).some((x) => x.id === q.id), true, "still visible in the web");
|
||||
});
|
||||
|
||||
test("Сценарий: проект выключен — ни Telegram, ни push; участник получает", async () => {
|
||||
const p = await newProject("Demo");
|
||||
const sub = push.subscribe();
|
||||
await core.savePushSubscription(db, pm.id, sub);
|
||||
await setPrefs(pm, { mutedProjects: [p.id] });
|
||||
const ref = await newTask(p, "Ревью-стори");
|
||||
await core.updateTask(db, ref, { status: "review" });
|
||||
await core.askPm(db, ref, { kind: "attention", text: "Готово, проверь." });
|
||||
await waitFor("bob got review", async () => sentTo(BOB.chatId, "Готово, проверь").length > 0);
|
||||
await new Promise((r) => setTimeout(r, 800));
|
||||
assert.equal(sentTo(PM.chatId, "Готово, проверь").length, 0);
|
||||
assert.equal(push.for(sub.id).length, 0);
|
||||
await db.delete(pushSubscriptions);
|
||||
});
|
||||
|
||||
test("Сценарий: тихие часы — Telegram без звука, push не отправляется", async () => {
|
||||
const sub = push.subscribe();
|
||||
await core.savePushSubscription(db, pm.id, sub);
|
||||
// Quiet the whole day around now, whatever the clock says.
|
||||
const now = core.localClock(new Date(), TZ).minutes;
|
||||
const hh = (m: number) => `${String(Math.floor(((m + 1440) % 1440) / 60)).padStart(2, "0")}:${String(((m + 1440) % 1440) % 60).padStart(2, "0")}`;
|
||||
await setPrefs(pm, { quiet: { from: hh(now - 60), to: hh(now + 60) } });
|
||||
const p = await newProject("Night");
|
||||
const ref = await newTask(p);
|
||||
await core.askPm(db, ref, { kind: "permission", text: "Можно rm -rf node_modules?" });
|
||||
const [msg] = await waitFor("silent message", async () => { const a = sentTo(PM.chatId, "rm -rf node_modules"); return a.length && a; });
|
||||
assert.equal(msg!.params.disable_notification, true);
|
||||
assert.equal(sentTo(BOB.chatId, "rm -rf node_modules")[0]?.params.disable_notification, undefined, "bob has no quiet hours");
|
||||
await new Promise((r) => setTimeout(r, 600));
|
||||
assert.equal(push.for(sub.id).length, 0);
|
||||
await db.delete(pushSubscriptions);
|
||||
});
|
||||
|
||||
test("Сценарий: готово к ревью в браузер — уведомление со ссылкой на стори", async () => {
|
||||
const sub = push.subscribe();
|
||||
await core.savePushSubscription(db, pm.id, { ...sub, userAgent: "Mock Chrome" });
|
||||
const p = await newProject("Push");
|
||||
const ref = await newTask(p, "Кнопка входа");
|
||||
await core.updateTask(db, ref, { status: "review" });
|
||||
await core.askPm(db, ref, { kind: "attention", text: "PR готов." });
|
||||
const [m] = await waitFor("push delivered", async () => { const a = push.for(sub.id); return a.length && a; });
|
||||
assert.equal(m!.payload.url, `/t/${ref.project.key}-${ref.task.number}`);
|
||||
assert.match(String(m!.payload.title), /Готово к ревью/);
|
||||
assert.equal(m!.payload.body, "PR готов.");
|
||||
assert.equal(m!.payload.sound, true);
|
||||
assert.ok(Number(m!.payload.count) >= 1);
|
||||
assert.equal(push.rejected.length, 0, JSON.stringify(push.rejected));
|
||||
// One push per question, not one per reconcile round.
|
||||
await new Promise((r) => setTimeout(r, 800));
|
||||
assert.equal(push.for(sub.id).filter((x) => x.payload.body === "PR готов.").length, 1);
|
||||
await db.delete(pushSubscriptions);
|
||||
});
|
||||
|
||||
test("Сценарий: подписка протухла — 410 удаляет её, повторов нет", async () => {
|
||||
const sub = push.subscribe();
|
||||
await core.savePushSubscription(db, pm.id, sub);
|
||||
push.setStatus(sub.id, 410);
|
||||
const p = await newProject("Gone");
|
||||
const ref = await newTask(p);
|
||||
await core.askPm(db, ref, { kind: "question", text: "Есть кто?" });
|
||||
await waitFor("subscription removed", async () => (await core.userPushSubscriptions(db, pm.id)).length === 0);
|
||||
const rows = await db.select().from(pushOutbox).where(like(pushOutbox.dedupeKey, "q:%"));
|
||||
assert.ok(rows.every((r) => r.status !== "pending"));
|
||||
const n = push.rejected.filter((r) => r.subscription === sub.id).length;
|
||||
await new Promise((r) => setTimeout(r, 800));
|
||||
assert.equal(push.rejected.filter((r) => r.subscription === sub.id).length, n, "no retries");
|
||||
});
|
||||
|
||||
test("a test push straight from the web action path (sendWebPush)", async () => {
|
||||
const sub = push.subscribe();
|
||||
const r = await core.sendWebPush(db, { endpoint: sub.endpoint, ...sub.keys }, { title: "Пеппа", body: "Проверка", url: "/settings" });
|
||||
assert.deepEqual(r, { ok: true });
|
||||
assert.equal(push.for(sub.id)[0]?.payload.body, "Проверка");
|
||||
});
|
||||
});
|
||||
|
||||
describe("incidents and monitoring follow the settings", () => {
|
||||
test("monitoring off in Telegram → admin gets no message", async () => {
|
||||
await core.setPlatformAdmins(db, [pm.login, bob.login]);
|
||||
await setPrefs(pm, { events: { ...(await prefs(pm)).events, monitoring: { telegram: false, push: false } } });
|
||||
const n = await core.alertAdmins(db, "mon:test:1", "Бот молчит 6 мин", () => {});
|
||||
assert.equal(n, 1);
|
||||
const rows = await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, "mon:test:1:%"));
|
||||
assert.deepEqual(rows.map((r) => r.params.chat_id), [BOB.chatId]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("daily digest", () => {
|
||||
// 2026-03-10 09:01 MSK = 06:01 UTC
|
||||
const at = (hhmm: string, day = 10) => new Date(`2026-03-${String(day).padStart(2, "0")}T${String(Number(hhmm.slice(0, 2)) - 3).padStart(2, "0")}:${hhmm.slice(3)}:00Z`);
|
||||
|
||||
test("Сценарий: утренний дайджест — одна сводка за день с сделанным, в работе и ждущим", async () => {
|
||||
await db.delete(questions);
|
||||
await db.delete(settings).where(like(settings.key, "digest.last:%"));
|
||||
// Only this project counts for the digest (older ones are muted for the PM).
|
||||
await setPrefs(pm, { mutedProjects: (await db.select({ id: projects.id }).from(projects)).map((p) => p.id) });
|
||||
const p = await newProject("Digest");
|
||||
const done = await newTask(p, "Вход через Gitea");
|
||||
const wip = await newTask(p, "Доска");
|
||||
await core.updateTask(db, done, { status: "done" });
|
||||
await db.update(tasks).set({ updatedAt: at("20:00", 9) }).where(eq(tasks.id, done.task.id));
|
||||
await core.updateTask(db, wip, { status: "in_progress" });
|
||||
await core.askPm(db, wip, { kind: "question", text: "Цвет кнопки?" });
|
||||
|
||||
const before = tg.calls.length;
|
||||
assert.equal(await core.digestTick(db, { now: at("08:59") }), 0, "too early");
|
||||
assert.ok((await core.digestTick(db, { now: at("09:01") })) >= 1);
|
||||
assert.equal(await core.digestTick(db, { now: at("09:30") }), 0, "once a day");
|
||||
const [m] = await waitFor("digest delivered", async () => { const a = sentTo(PM.chatId, "Сводка за сутки").filter((c) => tg.calls.indexOf(c) >= before); return a.length && a; });
|
||||
const text = String(m!.params.text);
|
||||
assert.match(text, /Digest/);
|
||||
assert.match(text, new RegExp(`Сделано: 1[\\s\\S]*${done.project.key}-${done.task.number}`));
|
||||
assert.match(text, new RegExp(`В работе: 1[\\s\\S]*${wip.project.key}-${wip.task.number}`));
|
||||
assert.match(text, /Ждёт тебя: 1/);
|
||||
// The next day it comes again.
|
||||
assert.ok((await core.digestTick(db, { now: at("09:05", 11) })) >= 1);
|
||||
});
|
||||
|
||||
test("Сценарий: выкат вечером — до завтрашних 09:00 сводки нет; выключенный дайджест не приходит", async () => {
|
||||
await db.delete(settings).where(like(settings.key, "digest.last:%"));
|
||||
assert.equal(await core.digestTick(db, { now: at("20:00", 12) }), 0);
|
||||
await setPrefs(pm, { events: { ...(await prefs(pm)).events, digest: { telegram: false, push: false } } });
|
||||
await setPrefs(bob, { events: { ...(await prefs(bob)).events, digest: { telegram: false, push: false } } });
|
||||
assert.equal(await core.digestTick(db, { now: at("09:10", 13) }), 0);
|
||||
});
|
||||
|
||||
test("/digest in the bot answers right away", async () => {
|
||||
tg.userSends({ id: PM.id, chatId: PM.chatId, username: "pm" }, "/digest");
|
||||
await waitFor("digest reply", async () => tg.botMessages(PM.chatId).some((m) => /Сводка за сутки/.test(m.text)));
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user