From 06337e18dc429d0add4bf0cdf21083a46e26e736 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 04:36:51 +0500 Subject: [PATCH 1/5] PEP-29/35/55: OpenSpec change pep-29-35-55-notifications Co-Authored-By: Claude Opus 5.5 --- .../pep-29-35-55-notifications/design.md | 36 ++++++++++ .../pep-29-35-55-notifications/proposal.md | 56 +++++++++++++++ .../specs/user-notifications/spec.md | 70 +++++++++++++++++++ .../pep-29-35-55-notifications/tasks.md | 23 ++++++ 4 files changed, 185 insertions(+) create mode 100644 openspec/changes/pep-29-35-55-notifications/design.md create mode 100644 openspec/changes/pep-29-35-55-notifications/proposal.md create mode 100644 openspec/changes/pep-29-35-55-notifications/specs/user-notifications/spec.md create mode 100644 openspec/changes/pep-29-35-55-notifications/tasks.md diff --git a/openspec/changes/pep-29-35-55-notifications/design.md b/openspec/changes/pep-29-35-55-notifications/design.md new file mode 100644 index 00000000..1a3c8819 --- /dev/null +++ b/openspec/changes/pep-29-35-55-notifications/design.md @@ -0,0 +1,36 @@ +# Design: уведомления пользователя + +## Модель + +``` +событие (question/review/failures/releases/incidents/monitoring/digest) + → получатели (владелец + участники проекта; админы для monitoring; сам пользователь для digest) + → deliverToUser(user, event, projectId, {telegram, push, dedupeKey}) + prefs.mutedProjects ∋ projectId → ничего + prefs.events[event].telegram && chat → telegram_outbox (тихие часы: disable_notification) + prefs.events[event].push && подписки && !тихие часы → push_outbox +``` + +Категория вопроса (`questionEvent`): approval/question/permission → `questions`; +attention: стори в `review` → `review`; сессия failed/rate_limited/stalled → `failures`; +без стори и сессии (релизы проекта, «Выкатить в прод?») → `releases`; иначе `questions`. + +Ключи Telegram-outbox у вопросов не меняются (`q::`), чтобы после выката не +пришли повторы. Push-ключи: `:push:`. + +## Решения + +- **Prefs в `settings`, не колонкой** — меньше миграций в параллельных ветках; JSON + мёржится с умолчаниями при чтении, новые события получают значение по умолчанию. +- **Тихие часы не глушат, а приглушают Telegram**: вопрос-стоппер всё равно должен + дойти; push в тихие часы пропускается (уведомление на экране ночью — шум). +- **Свой Web Push на `node:crypto`**: протокол небольшой (ECDH P-256 + HKDF + AES-128-GCM, + ES256 JWT), зависимость `web-push` тянет устаревшие пакеты. Мок `mock-push` в testkit + расшифровывает тело и проверяет подпись VAPID — контракт настоящий. +- **Доставка push из бота**: у бота уже есть цикл outbox и пробуждение через notify(); + кнопка «Проверить» в вебе шлёт сразу из server action (не зависит от бота). +- **Дайджест из вачдога**: вачдог тикает постоянно; `digest.last:` = локальная + дата, чтобы не пересчитывать каждый тик; окно 3 часа — свежий выкат вечером не + присылает «утренний» дайджест. +- Таймзона по умолчанию — таймзона сервера (Mac PM); в настройках можно взять из + браузера. diff --git a/openspec/changes/pep-29-35-55-notifications/proposal.md b/openspec/changes/pep-29-35-55-notifications/proposal.md new file mode 100644 index 00000000..29b70e65 --- /dev/null +++ b/openspec/changes/pep-29-35-55-notifications/proposal.md @@ -0,0 +1,56 @@ +# Proposal: PEP-29 + PEP-35 + PEP-55 — уведомления пользователя + +Стори Пеппы: **PEP-29** (ежедневный дайджест), **PEP-35** (настройки уведомлений), +**PEP-55** (push в браузере и звук). Один change: все три стоят на одной модели +«событие → пользователь → каналы». + +## Why + +Все события летят одинаково и только в Telegram: нельзя выключить ненужное, нет тихих +часов, нет сводки за день, а в браузере ничего не видно, пока не обновишь страницу. + +## What Changes + +- **Маршрутизация (PEP-35)**: каждое уведомление относится к одному из событий — + вопросы агентов, готово к ревью, сбои и лимиты, релизы, ошибки из прода, мониторинг + (только админам), дайджест — и для каждого пользователь выбирает каналы: Telegram и + браузер. Тихие часы (в своей таймзоне): Telegram приходит без звука, push не + показывается. Выбор проектов: уведомления из выключенных проектов не приходят (вопросы + остаются в вебе). Хранится в `settings` (`notify.prefs:`), по умолчанию — всё + включено, как сейчас. Через одну функцию `deliverToUser` идут вопросы (бот), ошибки из + прода и алерты мониторинга. +- **Web Push (PEP-55)**: VAPID-ключи генерируются при первом обращении и лежат в + `settings` (`push.vapid`); подписки браузера — таблица `push_subscriptions`, доставка — + `push_outbox` с повторами (бот разбирает так же, как Telegram-outbox; 404/410 удаляют + подписку). Шифрование RFC 8291 (aes128gcm) и VAPID JWT (RFC 8292) — своё на `node:crypto`, + без зависимостей. Service worker `apps/web/public/sw.js`: показывает уведомление, клик + открывает стори/раннер/проект. Манифест PWA (`app/manifest.ts`) — ставится как + приложение. «Настройки → Уведомления»: включить в этом браузере, проверить, отключить. +- **Счётчик и звук (PEP-55)**: в заголовке вкладки «(N) …» и на значке приложения + (`navigator.setAppBadge`) — сколько ждёт пользователя; при росте счётчика — короткий + звук (WebAudio), если включён в настройках. Push без звука, если звук выключен. +- **Дайджест (PEP-29)**: раз в день в выбранное время (по умолчанию 09:00 в таймзоне + пользователя; по умолчанию таймзона сервера) — по каждому своему проекту: сделано за + сутки, в работе, на ревью, ждёт тебя, зависло/заблокировано, лимиты (раннеры ждут + сброса, авто-продолжения за сутки). Пустой дайджест не шлётся. Из вачдога `tick` + (`digestTick`), окно 3 часа после времени, дедуп по локальной дате. Команда `/digest` + в боте — сводка сейчас. Отключение и время — в настройках. + +## Не делаем + +- Канал платформы и дайджест обновлений Пеппы (PEP-60) — отдельно; личный дайджест + PEP-60 закрывается этим change. +- Алерт «бот упал» вачдог по-прежнему шлёт прямо в Bot API, мимо настроек (бот не + работает — некому разбирать outbox). + +## Capabilities + +### New Capabilities +- `user-notifications`: настройки уведомлений, браузерные push, счётчик и звук, дайджест. + +## Impact + +`packages/db` (миграция: `push_subscriptions`, `push_outbox`), `packages/core` +(`notifications.ts`, `webpush.ts`, `digest.ts`), `apps/bot` (маршрутизация вопросов, +push-outbox, `/digest`), `packages/runner` (`digestTick` в `tick`), `apps/web` (Настройки, +sw.js, манифест, счётчик), `packages/testkit` (`mock-push`, тесты). diff --git a/openspec/changes/pep-29-35-55-notifications/specs/user-notifications/spec.md b/openspec/changes/pep-29-35-55-notifications/specs/user-notifications/spec.md new file mode 100644 index 00000000..87869628 --- /dev/null +++ b/openspec/changes/pep-29-35-55-notifications/specs/user-notifications/spec.md @@ -0,0 +1,70 @@ +# Spec Delta: user-notifications + +## ADDED Requirements + +### Requirement: Настройки уведомлений +Пользователь SHALL выбирать в «Настройках → Уведомления» для каждого события (вопросы +агентов, готово к ревью, сбои и лимиты, релизы, ошибки из прода, мониторинг — только +админам, дайджест) каналы Telegram и браузер, а также проекты, из которых уведомления не +нужны. По умолчанию включено всё, кроме дайджеста в браузер. + +#### Scenario: Выключены вопросы агентов в Telegram +- **GIVEN** PM выключил «Вопросы агентов» для Telegram +- **WHEN** агент задаёт вопрос в проекте PM +- **THEN** сообщение в Telegram не приходит, вопрос виден в вебе + +#### Scenario: Проект выключен +- **GIVEN** PM снял галочку с проекта «Demo» +- **WHEN** в «Demo» приходит «готово к ревью» +- **THEN** PM не получает ни Telegram, ни push; участники с включённым проектом получают + +### Requirement: Тихие часы +В тихие часы (в таймзоне пользователя, интервал может переходить через полночь) Telegram +SHALL приходить без звука, браузерные push SHALL не показываться. + +#### Scenario: Ночной вопрос +- **GIVEN** тихие часы 23:00–08:00, сейчас 02:00 у PM +- **WHEN** агент просит разрешение +- **THEN** сообщение приходит в Telegram без звука, push не отправляется + +### Requirement: Push в браузере +Пользователь SHALL включать push в браузере из «Настроек» (разрешение браузера, подписка +Web Push с ключами VAPID Пеппы), проверять тестовым уведомлением и отключать. Уведомление +SHALL открывать по клику стори, раннер или проект. Подписка, которую сервис push +отклонил как несуществующую (404/410), SHALL удаляться. + +#### Scenario: Готово к ревью в браузер +- **GIVEN** PM включил push в Chrome +- **WHEN** стори переходит в ревью +- **THEN** приходит уведомление «Готово к ревью», клик открывает страницу стори + +#### Scenario: Подписка протухла +- **GIVEN** сервис push отвечает 410 на подписку +- **WHEN** Пеппа пытается доставить уведомление +- **THEN** подписка удаляется, повторов нет + +### Requirement: Счётчик и звук +Вкладка Пеппы SHALL показывать в заголовке и на значке приложения число того, что ждёт +пользователя, и при его росте проигрывать короткий звук, если звук включён. + +#### Scenario: Новый вопрос при открытой вкладке +- **GIVEN** открыта Пеппа, ждут 2 вопроса, звук включён +- **WHEN** приходит третий вопрос +- **THEN** заголовок становится «(3) …» и звучит сигнал + +### Requirement: Ежедневный дайджест +Каждый день в выбранное время (по умолчанию 09:00 в таймзоне пользователя) Пеппа SHALL +присылать сводку по проектам пользователя: сделано за сутки, в работе, на ревью, ждёт +пользователя, зависло или заблокировано, лимиты. Не больше одной сводки в день; пустая +сводка не отправляется; дайджест отключается в настройках. Команда `/digest` в боте +SHALL присылать сводку сейчас. + +#### Scenario: Утренний дайджест +- **GIVEN** у PM вчера смержена PEP-5, PEP-6 в работе, ждёт 1 вопрос; время дайджеста 09:00 +- **WHEN** вачдог тикает в 09:01 и ещё раз в 09:30 +- **THEN** PM получает одну сводку с PEP-5 в «Сделано», PEP-6 в «В работе» и «Ждёт тебя: 1» + +#### Scenario: Выкат вечером +- **GIVEN** время дайджеста 09:00, сейчас 20:00 и сегодня сводки не было +- **WHEN** вачдог тикает +- **THEN** сводка не отправляется до завтрашних 09:00 diff --git a/openspec/changes/pep-29-35-55-notifications/tasks.md b/openspec/changes/pep-29-35-55-notifications/tasks.md new file mode 100644 index 00000000..5fd4de9f --- /dev/null +++ b/openspec/changes/pep-29-35-55-notifications/tasks.md @@ -0,0 +1,23 @@ +# Tasks: PEP-29, PEP-35, PEP-55 + +## 1. Данные и core +- [ ] 1.1 Схема `push_subscriptions`, `push_outbox` + миграция +- [ ] 1.2 core/notifications.ts: prefs (чтение с умолчаниями, сохранение), тихие часы, `questionEvent`, `projectAudience`, `deliverToUser` +- [ ] 1.3 core/webpush.ts: VAPID-ключи в settings, шифрование aes128gcm, JWT, отправка, push-outbox (очередь, ретраи, 404/410) +- [ ] 1.4 core/digest.ts: сбор и текст сводки, `digestTick` (время, таймзона, окно, дедуп) + +## 2. Доставка +- [ ] 2.1 Бот: вопросы через `deliverToUser`, разбор push-outbox, `/digest` +- [ ] 2.2 Ошибки из прода и мониторинг через `deliverToUser` +- [ ] 2.3 Вачдог: `digestTick` в `tick` + +## 3. Веб +- [ ] 3.1 «Настройки → Уведомления»: события × каналы, тихие часы, таймзона, дайджест, звук, проекты +- [ ] 3.2 Push в браузере: sw.js, манифест PWA, включить/проверить/отключить +- [ ] 3.3 Счётчик в заголовке и значке, звук; `/api/attention` +- [ ] 3.4 Помощь + +## 4. Тесты и документация +- [ ] 4.1 testkit: mock-push, notifications.test.ts (сценарии спеки) +- [ ] 4.2 AGENTS.md +- [ ] 4.3 pnpm run ci зелёный From ea4bdf38fff5245a9ffe870da2f9fdcc8b7775a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 04:42:50 +0500 Subject: [PATCH 2/5] PEP-29/35/55: notification prefs and routing, Web Push outbox, daily digest; mock-push, tests Co-Authored-By: Claude Opus 5.5 --- apps/bot/src/bot.ts | 81 +- packages/core/src/digest.ts | 173 + packages/core/src/incidents.ts | 31 +- packages/core/src/index.ts | 3 + packages/core/src/monitor.ts | 26 +- packages/core/src/notifications.ts | 176 + packages/core/src/webpush.ts | 203 ++ .../db/migrations/0005_push_notifications.sql | 29 + .../db/migrations/meta/0005_snapshot.json | 2967 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 27 + packages/runner/src/watchdog.ts | 3 + packages/testkit/src/mock-push.ts | 118 + packages/testkit/test/notifications.test.ts | 235 ++ 14 files changed, 4048 insertions(+), 31 deletions(-) create mode 100644 packages/core/src/digest.ts create mode 100644 packages/core/src/notifications.ts create mode 100644 packages/core/src/webpush.ts create mode 100644 packages/db/migrations/0005_push_notifications.sql create mode 100644 packages/db/migrations/meta/0005_snapshot.json create mode 100644 packages/testkit/src/mock-push.ts create mode 100644 packages/testkit/test/notifications.test.ts diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 930188f3..e4c85b05 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -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 = `Я бот Пеппы. Присылаю вопросы от аге • Кнопки под сообщением — быстрый ответ. • Ответ реплаем на сообщение — свой текст, он уйдёт прямо в сессию. -• /status — активные сессии и открытые вопросы.`; +• /status — активные сессии и открытые вопросы. +• /digest — сводка за сутки по твоим проектам (каждый день приходит сама; время и что присылать — в Настройках → Уведомления).`; + +const PUSH_MAX_AGE_MS = 30 * 60_000; + +const PUSH_TITLE: Record = { + 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 { - 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>(); + 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 { + 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 { 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); diff --git a/packages/core/src/digest.ts b/packages/core/src/digest.ts new file mode 100644 index 00000000..69218583 --- /dev/null +++ b/packages/core/src/digest.ts @@ -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, o: { now?: Date; prefs?: NotifyPrefs } = {}): Promise { + 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, ">"); +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) => `${esc(t.key)} ${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 = [`${esc(o.title ?? "☀️ Сводка за сутки")}`]; + if (!d.projects.length) { + lines.push("", "Всё тихо: за сутки ничего не сделано, ничего не в работе и ничего не ждёт тебя."); + return lines.join("\n"); + } + for (const p of d.projects) { + lines.push("", `${esc(p.name)} (${esc(p.key)}) — доска`); + 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("", `Открыть Пеппу — ответить на ${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 { + 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(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; +} diff --git a/packages/core/src/incidents.ts b/packages/core/src/incidents.ts index bf7f6eb3..8cea68c5 100644 --- a/packages/core/src/incidents.ts +++ b/packages/core/src/incidents.ts @@ -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, 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 { - 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. */ diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index e42317b0..8a0aea00 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -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"; diff --git a/packages/core/src/monitor.ts b/packages/core/src/monitor.ts index ba584c31..1f67aeb3 100644 --- a/packages/core/src/monitor.ts +++ b/packages/core/src/monitor.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 { // ── checks ───────────────────────────────────────────────────────────────────────── export async function alertAdmins(db: Db, key: string, text: string, log: (m: string) => void): Promise { - 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; } diff --git a/packages/core/src/notifications.ts b/packages/core/src/notifications.ts new file mode 100644 index 00000000..8b8cdcd0 --- /dev/null +++ b/packages/core/src/notifications.ts @@ -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 = { + questions: "Вопросы агентов (одобрения, вопросы, разрешения)", + review: "Готово к ревью", + failures: "Сбои, зависания и лимиты раннеров", + releases: "Релизы и выкаты", + incidents: "Ошибки из прода", + monitoring: "Мониторинг Пеппы (админам)", + digest: "Ежедневный дайджест", +}; + +export interface Channels { + telegram: boolean; + push: boolean; +} + +export interface NotifyPrefs { + events: Record; + /** "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 { + const d = defaultPrefs(); + const s = (await getSetting>(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 { + 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, 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, 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 { + 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; 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 { + 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; +} diff --git a/packages/core/src/webpush.ts b/packages/core/src/webpush.ts new file mode 100644 index 00000000..cd3632d0 --- /dev/null +++ b/packages/core/src/webpush.ts @@ -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 { + const saved = await getSetting(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(db, VAPID))!; +} + +export const vapidPublicKey = async (db: Db) => (await vapidKeys(db)).publicKey; + +/** `Authorization: vapid t=, k=` 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, + payload: PushPayload, + o: { urgency?: "normal" | "high"; ttlSec?: number } = {}, +): Promise { + 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 { + 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 { + await db.delete(pushSubscriptions).where(and(eq(pushSubscriptions.userId, userId), eq(pushSubscriptions.endpoint, endpoint))); +} + +export async function userPushSubscriptions(db: Db, userId: number): Promise { + 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 { + 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 { + 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; +} diff --git a/packages/db/migrations/0005_push_notifications.sql b/packages/db/migrations/0005_push_notifications.sql new file mode 100644 index 00000000..eff8f95e --- /dev/null +++ b/packages/db/migrations/0005_push_notifications.sql @@ -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`); \ No newline at end of file diff --git a/packages/db/migrations/meta/0005_snapshot.json b/packages/db/migrations/meta/0005_snapshot.json new file mode 100644 index 00000000..f0ca33b9 --- /dev/null +++ b/packages/db/migrations/meta/0005_snapshot.json @@ -0,0 +1,2967 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "01595f06-03c2-470a-8d64-60ecf41afd6d", + "prevId": "e01baa2c-52bb-40aa-b39c-2490acbcd458", + "tables": { + "check_runs": { + "name": "check_runs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check": { + "name": "check", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration_sec": { + "name": "duration_sec", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'report'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "check_runs_project_sha_check": { + "name": "check_runs_project_sha_check", + "columns": [ + "project_id", + "sha", + "check" + ], + "isUnique": true + } + }, + "foreignKeys": { + "check_runs_project_id_projects_id_fk": { + "name": "check_runs_project_id_projects_id_fk", + "tableFrom": "check_runs", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "check_runs_task_id_tasks_id_fk": { + "name": "check_runs_task_id_tasks_id_fk", + "tableFrom": "check_runs", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "code_reviews": { + "name": "code_reviews", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "verdict": { + "name": "verdict", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "findings": { + "name": "findings", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "code_reviews_project_id_projects_id_fk": { + "name": "code_reviews_project_id_projects_id_fk", + "tableFrom": "code_reviews", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "code_reviews_task_id_tasks_id_fk": { + "name": "code_reviews_task_id_tasks_id_fk", + "tableFrom": "code_reviews", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "error_sources": { + "name": "error_sources", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_project_id": { + "name": "bugsink_project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dsn": { + "name": "dsn", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "error_sources_bugsink_project_id_unique": { + "name": "error_sources_bugsink_project_id_unique", + "columns": [ + "bugsink_project_id" + ], + "isUnique": true + }, + "error_sources_project_kind": { + "name": "error_sources_project_kind", + "columns": [ + "project_id", + "kind" + ], + "isUnique": true + } + }, + "foreignKeys": { + "error_sources_project_id_projects_id_fk": { + "name": "error_sources_project_id_projects_id_fk", + "tableFrom": "error_sources", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "events": { + "name": "events", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "goals": { + "name": "goals", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incident_settings": { + "name": "incident_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "hook_secret": { + "name": "hook_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "triage_prompt": { + "name": "triage_prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environments": { + "name": "environments", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[\"prod\",\"production\"]'" + }, + "daily_limit": { + "name": "daily_limit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 5 + }, + "ignore_pattern": { + "name": "ignore_pattern", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "webhook_auto": { + "name": "webhook_auto", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incident_settings_hook_secret_unique": { + "name": "incident_settings_hook_secret_unique", + "columns": [ + "hook_secret" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incident_settings_project_id_projects_id_fk": { + "name": "incident_settings_project_id_projects_id_fk", + "tableFrom": "incident_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incident_settings_goal_id_goals_id_fk": { + "name": "incident_settings_goal_id_goals_id_fk", + "tableFrom": "incident_settings", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incidents": { + "name": "incidents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_issue_id": { + "name": "bugsink_issue_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "friendly_id": { + "name": "friendly_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "culprit": { + "name": "culprit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_release": { + "name": "first_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_release": { + "name": "last_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "first_seen": { + "name": "first_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen": { + "name": "last_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'new'" + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_created_at": { + "name": "task_created_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_release": { + "name": "resolved_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "regressions": { + "name": "regressions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incidents_bugsink_issue_id_unique": { + "name": "incidents_bugsink_issue_id_unique", + "columns": [ + "bugsink_issue_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incidents_project_id_projects_id_fk": { + "name": "incidents_project_id_projects_id_fk", + "tableFrom": "incidents", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incidents_task_id_tasks_id_fk": { + "name": "incidents_task_id_tasks_id_fk", + "tableFrom": "incidents", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_clients": { + "name": "oauth_clients", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_codes": { + "name": "oauth_codes", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "used_at": { + "name": "used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_tokens": { + "name": "oauth_tokens", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_invites": { + "name": "project_invites", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invited_by": { + "name": "invited_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_invites_project_id_projects_id_fk": { + "name": "project_invites_project_id_projects_id_fk", + "tableFrom": "project_invites", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_invites_invited_by_users_id_fk": { + "name": "project_invites_invited_by_users_id_fk", + "tableFrom": "project_invites", + "tableTo": "users", + "columnsFrom": [ + "invited_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_invites_project_id_login_pk": { + "columns": [ + "project_id", + "login" + ], + "name": "project_invites_project_id_login_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_members": { + "name": "project_members", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "added_by": { + "name": "added_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_members_project_id_projects_id_fk": { + "name": "project_members_project_id_projects_id_fk", + "tableFrom": "project_members", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_user_id_users_id_fk": { + "name": "project_members_user_id_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_added_by_users_id_fk": { + "name": "project_members_added_by_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "added_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_members_project_id_user_id_pk": { + "columns": [ + "project_id", + "user_id" + ], + "name": "project_members_project_id_user_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "subscription_pool_id": { + "name": "subscription_pool_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "columns": [ + "slug" + ], + "isUnique": true + }, + "projects_key_unique": { + "name": "projects_key_unique", + "columns": [ + "key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "projects_owner_id_users_id_fk": { + "name": "projects_owner_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "projects_subscription_pool_id_subscription_pools_id_fk": { + "name": "projects_subscription_pool_id_subscription_pools_id_fk", + "tableFrom": "projects", + "tableTo": "subscription_pools", + "columnsFrom": [ + "subscription_pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_outbox": { + "name": "push_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "urgency": { + "name": "urgency", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'normal'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_outbox_dedupe_key_unique": { + "name": "push_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_outbox_subscription_id_push_subscriptions_id_fk": { + "name": "push_outbox_subscription_id_push_subscriptions_id_fk", + "tableFrom": "push_outbox", + "tableTo": "push_subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_subscriptions": { + "name": "push_subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "endpoint": { + "name": "endpoint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "p256dh": { + "name": "p256dh", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth": { + "name": "auth", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_ok_at": { + "name": "last_ok_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_subscriptions_endpoint_unique": { + "name": "push_subscriptions_endpoint_unique", + "columns": [ + "endpoint" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_subscriptions_user_id_users_id_fk": { + "name": "push_subscriptions_user_id_users_id_fk", + "tableFrom": "push_subscriptions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "questions": { + "name": "questions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "options": { + "name": "options", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "answered_at": { + "name": "answered_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "releases": { + "name": "releases", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "env": { + "name": "env", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_sha": { + "name": "previous_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tasks": { + "name": "tasks", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'deploying'" + }, + "deployed_by": { + "name": "deployed_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'ci'" + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "releases_project_id_projects_id_fk": { + "name": "releases_project_id_projects_id_fk", + "tableFrom": "releases", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "review_settings": { + "name": "review_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "max_iterations": { + "name": "max_iterations", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 2 + }, + "rules": { + "name": "rules", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "review_settings_project_id_projects_id_fk": { + "name": "review_settings_project_id_projects_id_fk", + "tableFrom": "review_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'claude'" + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "resume_at": { + "name": "resume_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_probe_min": { + "name": "limit_probe_min", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumes": { + "name": "limit_resumes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "limit_resumes_day": { + "name": "limit_resumes_day", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumed_at": { + "name": "limit_resumed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "columns": [ + "tmux_name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_subscription_id_subscriptions_id_fk": { + "name": "sessions_subscription_id_subscriptions_id_fk", + "tableFrom": "sessions", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pool_members": { + "name": "subscription_pool_members", + "columns": { + "pool_id": { + "name": "pool_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "subscription_pool_members_pool_id_subscription_pools_id_fk": { + "name": "subscription_pool_members_pool_id_subscription_pools_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscription_pools", + "columnsFrom": [ + "pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "subscription_pool_members_subscription_id_subscriptions_id_fk": { + "name": "subscription_pool_members_subscription_id_subscriptions_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "subscription_pool_members_pool_id_subscription_id_pk": { + "columns": [ + "pool_id", + "subscription_id" + ], + "name": "subscription_pool_members_pool_id_subscription_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pools": { + "name": "subscription_pools", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "subscription_pools_name_unique": { + "name": "subscription_pools_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "subscription_pools_created_by_users_id_fk": { + "name": "subscription_pools_created_by_users_id_fk", + "tableFrom": "subscription_pools", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscriptions": { + "name": "subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth_kind": { + "name": "auth_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret_enc": { + "name": "secret_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "key_provider": { + "name": "key_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "limited_until": { + "name": "limited_until", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "activated_at": { + "name": "activated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "subscriptions_created_by_users_id_fk": { + "name": "subscriptions_created_by_users_id_fk", + "tableFrom": "subscriptions", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tasks": { + "name": "tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ci_attempts": { + "name": "ci_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ci_failed_sha": { + "name": "ci_failed_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + "project_id", + "number" + ], + "isUnique": true + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_outbox": { + "name": "telegram_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "params": { + "name": "params", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "telegram_outbox_question_id_questions_id_fk": { + "name": "telegram_outbox_question_id_questions_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_updates": { + "name": "telegram_updates", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_enc": { + "name": "claude_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_set_at": { + "name": "claude_token_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_chat_id": { + "name": "telegram_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_user_id": { + "name": "telegram_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_username": { + "name": "telegram_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_paired_at": { + "name": "telegram_paired_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_iin": { + "name": "egov_iin", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_linked_at": { + "name": "egov_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_set_at": { + "name": "password_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_login_at": { + "name": "last_login_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "columns": [ + "gitea_id" + ], + "isUnique": true + }, + "users_login_unique": { + "name": "users_login_unique", + "columns": [ + "login" + ], + "isUnique": true + }, + "users_telegram_chat_id_unique": { + "name": "users_telegram_chat_id_unique", + "columns": [ + "telegram_chat_id" + ], + "isUnique": true + }, + "users_egov_iin_unique": { + "name": "users_egov_iin_unique", + "columns": [ + "egov_iin" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 3345217f..f19de56e 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -36,6 +36,13 @@ "when": 1794613008393, "tag": "0004_code_reviewer", "breakpoints": true + }, + { + "idx": 5, + "version": "6", + "when": 1794614987778, + "tag": "0005_push_notifications", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index e0bd7cb7..daf06b76 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -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>().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(), diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts index 6c985242..7f6616f6 100644 --- a/packages/runner/src/watchdog.ts +++ b/packages/runner/src/watchdog.ts @@ -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 { } // 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) { diff --git a/packages/testkit/src/mock-push.ts b/packages/testkit/src/mock-push.ts new file mode 100644 index 00000000..ca70aa98 --- /dev/null +++ b/packages/testkit/src/mock-push.ts @@ -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; + urgency: string | null; + ttl: string | null; +} + +interface MockSub { + ecdh: ReturnType; + 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(); + private server: Server | null = null; + url = ""; + + async start(): Promise { + 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((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((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); + } +} diff --git a/packages/testkit/test/notifications.test.ts b/packages/testkit/test/notifications.test.ts new file mode 100644 index 00000000..c4b0396a --- /dev/null +++ b/packages/testkit/test/notifications.test.ts @@ -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>; +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>>) { + 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))); + }); +}); From 9f9358de2cede2032f57e514be3f33b909171b98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 04:46:42 +0500 Subject: [PATCH 3/5] =?UTF-8?q?PEP-29/35/55:=20web=20=E2=80=94=20Settings?= =?UTF-8?q?=20=E2=86=92=20Notifications,=20Web=20Push=20in=20the=20browser?= =?UTF-8?q?=20(sw.js,=20PWA=20manifest),=20tab=20counter=20and=20sound;=20?= =?UTF-8?q?help,=20AGENTS.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + apps/web/app/(app)/actions.ts | 68 +++++++++++ apps/web/app/(app)/help/page.tsx | 15 ++- apps/web/app/(app)/layout.tsx | 5 +- apps/web/app/(app)/settings/page.tsx | 106 ++++++++++++++++- apps/web/app/api/attention/route.ts | 15 +++ apps/web/app/layout.tsx | 2 +- apps/web/app/manifest.ts | 16 +++ apps/web/components/AttentionBadge.tsx | 78 +++++++++++++ apps/web/components/PushNotifications.tsx | 110 ++++++++++++++++++ apps/web/components/TimezoneField.tsx | 34 ++++++ apps/web/next-env.d.ts | 4 +- apps/web/next.config.ts | 4 +- apps/web/public/icon.svg | 1 + apps/web/public/sw.js | 41 +++++++ .../pep-29-35-55-notifications/tasks.md | 28 ++--- packages/testkit/test/notifications.test.ts | 6 +- 17 files changed, 507 insertions(+), 27 deletions(-) create mode 100644 apps/web/app/api/attention/route.ts create mode 100644 apps/web/app/manifest.ts create mode 100644 apps/web/components/AttentionBadge.tsx create mode 100644 apps/web/components/PushNotifications.tsx create mode 100644 apps/web/components/TimezoneField.tsx create mode 100644 apps/web/public/icon.svg create mode 100644 apps/web/public/sw.js diff --git a/AGENTS.md b/AGENTS.md index 5d496303..21d2a368 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,6 +31,7 @@ - **Вход через eGov QR (PEP-65)**: relay KazEDS `sign.aitu.uz` (`KAZEDS_RELAY_BASE`, уже доверенный в eGov), `EGOV_ORGANISATION_NAME`/`EGOV_ORGANISATION_BIN` (БИН сгенерирован). `core/egov.ts`: `startEgovFlow` (документ ``, поток в `settings` `egov.flow:`, 5 мин) → `egovFlowStatus` → `completeEgovFlow` (сверка challenge+nonce, ИИН из сертификата — свой разбор DER, `users.egov_iin`). **Подпись XMLDSig не проверяется — доверяем relay (решение PM)**. Веб: `/auth/egov/{start,status,complete}`, handle только в httpOnly cookie `peppa_egov`; `EgovSign` на странице входа и в «Настройках → eGov» (привязать/отвязать). Войти может только пользователь с привязанным ИИН и доступом (PEP-16). CLI `peppa user egov <ИИН|->`. Мок `mock-kazeds-relay` (testkit; подписывает на 3-м опросе поддельным сертификатом). Пример интеграции от PM — `docs/egov-reference/` - **Локальные пользователи (PEP-68)**: `users.gitea_id < 0`, вход по логину и паролю (`POST /auth/password` → `passwordLogin` в `core/local-users.ts`: scrypt `users.password_hash`, одна ошибка «Неверный логин или пароль», 5 неудач на логин / 20 на IP за 15 мин → пауза 15 мин, счётчики в `settings` `auth.fail:*`). Суперадмин = `platform.admins` (`isSuperadmin(db, user)` в core/monitor.ts): раздел `/users` — создать (временный пароль), сбросить пароль, отключить/включить (`users.disabled_at`: `isUserAllowed` → false для любого пользователя, сессии веба и MCP гаснут сразу); смена своего пароля — «Настройки». Вход через Gitea с логином локального пользователя отклоняется (`giteaLoginRefusal`), привязки Gitea к локальному аккаунту нет. Проект локального — в пространстве peppa-bot (`projectNamespace` в runner/provision.ts), участником он добавляется без соавторства в Gitea. CLI `peppa user add [--admin] [--name]`, `peppa user passwd|disable|enable ` (пароль из stdin или сгенерированный) - **Подписки (PEP-67)**: раздел `/subscriptions` только для суперадмина (`isSuperadmin(db, user)` в core/monitor.ts = логин из `platform.admins`; остальным пункта меню нет, URL → 404, actions в `app/(app)/subscriptions/actions.ts` через `requireSuperadmin`). Таблицы `subscriptions` (claude|codex|opencode, статус pending/active/limited/auth_error), `subscription_pools` + `subscription_pool_members`, `projects.subscription_pool_id` (пул проекта, «⋯ Настройки проекта»), `sessions.subscription_id`. Вход — runner/subscription-login.ts в tmux `peppa-auth-sub`: Claude `claude setup-token` (ссылка → код → токен в `secret_enc`) или готовый токен; Codex `codex login --device-auth` (ссылка + код, страница опрашивает) или `--with-api-key`, вход живёт в своём `CODEX_HOME` = `$PEPPA_HOME/subscriptions/s/codex` (0700); OpenCode — ключ провайдера (anthropic/openai/openrouter) зашифрован. «Проверить» — `checkSubscription` (runner/subscriptions.ts: `claude -p` / `codex exec` / `opencode run`). Раннер: `startSession(…, { subscriptionIds, poolId, provider })` → `pickSubscription` (отмеченные → пул → пул проекта; первая свободная активная, иначе наименее занятая; нет пула — вход машины), провайдер сессии = провайдер подписки, env подписки (`CLAUDE_CODE_OAUTH_TOKEN` / `CODEX_HOME` / ключ), resume — на той же. Ротации при лимите нет (PEP-39). Провайдер OpenCode (`providers.ts`): `opencode --prompt`, правила и MCP из `OPENCODE_CONFIG` (opencode.json в каталоге запуска), хуков нет — статус по процессу. Миграция 0003 перенесла токены `users.claude_token_enc` (PEP-13, колонки больше не читаются) в подписки «Claude — » и пулы проектов владельца. Моки: `mock-claude setup-token|-p`, `mock-codex login|exec`, `mock-opencode` +- **Уведомления (PEP-29/35/55)**: события `questions`/`review`/`failures`/`releases`/`incidents`/`monitoring`/`digest` × каналы Telegram/push на пользователя — `notify.prefs:` в `settings` (`getNotifyPrefs` с умолчаниями, всё включено, кроме дайджеста в браузер), тихие часы (Telegram с `disable_notification`, push пропускается), таймзона (по умолчанию сервера или `PEPPA_TZ`), выключенные проекты. Всё идёт через `deliverToUser` (core/notifications.ts): вопросы (бот `reconcile`, категория — `questionEvent`, получатели — `projectAudience`; ключи Telegram `q::` прежние), ошибки из прода, алерты мониторинга. Web Push — свой на `node:crypto` (core/webpush.ts: VAPID в `settings` `push.vapid`, aes128gcm), таблицы `push_subscriptions` + `push_outbox` (разбирает бот вместе с Telegram-outbox, 404/410 удаляют подписку; push только для вопросов моложе 30 мин). Веб: «Настройки → Уведомления», `public/sw.js`, `app/manifest.ts` (PWA), `AttentionBadge` (счётчик в заголовке и значке, звук; `/api/attention`). Дайджест (core/digest.ts): `digestTick` в `tick` вачдога — в выбранное время (окно 3 ч, `digest.last:`), пустой не шлётся; `/digest` в боте. Мок — `mock-push` (testkit: проверяет VAPID и расшифровывает) - **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon::…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД), `peppa status`, `peppa platform admins [логины|-]` - **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (сервис `act-runner` в `infra/docker-compose.yml`, конфиг `infra/act-runner/`, контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect ` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`) - Обратная связь: `POST /api/hooks/gitea` (веб, без входа, подпись `X-Gitea-Signature` секретом проекта) → `handleGiteaHook` (runner/ci-feedback.ts): `X-Peppa-Event: check` — отчёт шага CI → `check_runs` → красное уходит в живой раннер (шаг + хвост лога) или задача возвращается в работу с новым раннером; счётчик `tasks.ci_attempts` по разным SHA, на 3-м — вопрос PM; остальные события Gitea (pull_request, push) — в обработчики `onGiteaEvent`. Запасной путь — `pollChecks` в вачдоге раз в минуту (статусы `peppa/*` PR задач в работе/ревью) diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index c43aca28..5418fb8b 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -26,6 +26,15 @@ import { isSuperadmin, setUserDisabled, setUserPassword, + NOTIFY_EVENTS, + defaultPrefs, + deletePushSubscription, + getNotifyPrefs, + isValidTimezone, + savePushSubscription, + sendWebPush, + setNotifyPrefs, + userPushSubscriptions, } from "@peppa/core"; import { bugsinkFromEnv } from "@peppa/bugsink"; import { loadEnv } from "@peppa/shared"; @@ -254,6 +263,65 @@ export async function unpairTelegramAction(f: FormData) { }); } +// ── notifications (PEP-35, PEP-55) ────────────────────────────────────────────── + +/** «Настройки → Уведомления»: events × channels, quiet hours, timezone, digest, sound, projects. */ +export async function saveNotifyPrefsAction(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + const cur = await getNotifyPrefs(db, user.id); + const d = defaultPrefs(); + const events = { ...d.events }; + for (const e of NOTIFY_EVENTS) events[e] = { telegram: f.get(`${e}.telegram`) === "on", push: f.get(`${e}.push`) === "on" }; + const tz = str(f, "timezone") || cur.timezone; + if (!isValidTimezone(tz)) throw new PeppaError(`Неизвестная таймзона: ${tz}`); + const shown = f.getAll("projectShown").map(Number); + const enabled = new Set(f.getAll("project").map(Number)); + // Projects not on the form (no access any more) keep their old state. + const muted = [...cur.mutedProjects.filter((id) => !shown.includes(id)), ...shown.filter((id) => !enabled.has(id))]; + try { + await setNotifyPrefs(db, user.id, { + events, + quiet: f.get("quietOn") === "on" ? { from: str(f, "quietFrom"), to: str(f, "quietTo") } : null, + timezone: tz, + digestTime: str(f, "digestTime") || cur.digestTime, + sound: f.get("sound") === "on", + mutedProjects: muted, + }); + } catch (e) { + throw new PeppaError((e as Error).message); + } + return "/settings?notify=saved#notifications"; + }); +} + +/** The browser subscribed to Web Push (called from the client with PushSubscription.toJSON()). */ +export async function savePushSubscriptionAction(sub: { endpoint: string; keys: { p256dh: string; auth: string } }, userAgent: string | null) { + const user = await requireUser(); + await savePushSubscription(db, user.id, { ...sub, userAgent }); + revalidatePath("/settings"); + return { ok: true }; +} + +export async function deletePushSubscriptionAction(endpoint: string) { + const user = await requireUser(); + await deletePushSubscription(db, user.id, endpoint); + revalidatePath("/settings"); + return { ok: true }; +} + +/** Test notification to this browser, sent right away (doesn't depend on the bot). */ +export async function testPushAction(endpoint: string): Promise<{ ok: boolean; error?: string }> { + const user = await requireUser(); + const sub = (await userPushSubscriptions(db, user.id)).find((s) => s.endpoint === endpoint); + if (!sub) return { ok: false, error: "Этот браузер не подписан" }; + const prefs = await getNotifyPrefs(db, user.id); + const r = await sendWebPush(db, sub, { title: "Пеппа", body: "Уведомления в этом браузере работают ✅", url: "/settings#notifications", tag: "test", sound: prefs.sound }); + if (r.ok) return { ok: true }; + if (r.gone) await deletePushSubscription(db, user.id, endpoint); + return { ok: false, error: r.error }; +} + // ── errors from running products (PEP-58) ─────────────────────────────────────── async function incidentInProject(userId: number, f: FormData) { diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index 4df796e6..e682313f 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -134,7 +134,20 @@ export default async function Help() {

Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с кнопками; ответ реплаем уходит прямо в сессию агента. Новые ошибки из прода приходят туда же — по политике - проекта: сообщением, стори или с кнопками «В бэклог / В работу / Игнорировать». + проекта: сообщением, стори или с кнопками «В бэклог / В работу / Игнорировать». Команды бота: /status — что + сейчас происходит, /digest — сводка за сутки. +

+ + +
+

+ В Настройках → Уведомления для каждого события (вопросы агентов, + готово к ревью, сбои и лимиты, релизы, ошибки из прода, дайджест) выбирается, куда присылать: Telegram и/или + браузер. Тихие часы: Telegram приходит без звука, push не показываются. Снятые проекты не присылают ничего — + вопросы остаются в вебе. Push в браузере включаются там же кнопкой (Chrome спросит разрешение) и работают при + закрытой вкладке; клик открывает стори. Во вкладке Пеппы в заголовке и на значке приложения — сколько ждёт вас, + при новом вопросе звучит сигнал (если звук включён). Ежедневный дайджест приходит в выбранное время (по умолчанию + 09:00): сделано за сутки, в работе, на ревью, ждёт вас, зависло, лимиты; пустой не приходит.

diff --git a/apps/web/app/(app)/layout.tsx b/apps/web/app/(app)/layout.tsx index e3205fb0..40729924 100644 --- a/apps/web/app/(app)/layout.tsx +++ b/apps/web/app/(app)/layout.tsx @@ -1,9 +1,10 @@ import type { ReactNode } from "react"; -import { isSuperadmin } from "@peppa/core"; +import { getNotifyPrefs, isSuperadmin } from "@peppa/core"; import { db } from "@/lib/db"; import { requireUser } from "@/lib/auth"; import { navCounts } from "@/lib/queries"; import { Sidebar } from "@/components/Sidebar"; +import { AttentionBadge } from "@/components/AttentionBadge"; export const dynamic = "force-dynamic"; @@ -11,8 +12,10 @@ export const dynamic = "force-dynamic"; export default async function AppLayout({ children }: { children: ReactNode }) { const user = await requireUser(); const counts = await navCounts(user.id); + const { sound } = await getNotifyPrefs(db, user.id); return (
+
{children}
diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index 02ced8fd..3347e870 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -1,4 +1,4 @@ -import { connectedApps, isLocalUser, isSuperadmin, maskIin, MIN_PASSWORD } from "@peppa/core"; +import { connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, MIN_PASSWORD, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core"; import { Hidden } from "@/components/cards"; import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common"; import { Button } from "@/components/ui/button"; @@ -8,7 +8,9 @@ import { EgovSign } from "@/components/EgovSign"; import { Workspace } from "@/components/Workspace"; import { publicOrigin, requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; -import { changePasswordAction, pairTelegram, revokeConnectedApp, unlinkEgov, unpairTelegramAction } from "../actions"; +import { changePasswordAction, pairTelegram, revokeConnectedApp, saveNotifyPrefsAction, unlinkEgov, unpairTelegramAction } from "../actions"; +import { PushNotifications } from "@/components/PushNotifications"; +import { TimezoneField } from "@/components/TimezoneField"; const back = { back: "/settings" }; @@ -25,13 +27,17 @@ function Row({ title, children, actions }: { title: React.ReactNode; children?: ); } -export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; egov?: string; password?: string }> }) { +export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; egov?: string; password?: string; notify?: string }> }) { const user = await requireUser(); - const { error, egov, password } = await searchParams; + const { error, egov, password, notify } = await searchParams; const local = isLocalUser(user); const superadmin = await isSuperadmin(db, user); const apps = await connectedApps(db, user.id); const origin = await publicOrigin(); + const prefs = await getNotifyPrefs(db, user.id); + const myProjects = await listUserProjects(db, user.id); + const pushSubs = await userPushSubscriptions(db, user.id); + const vapid = await vapidPublicKey(db); return (
@@ -141,6 +147,98 @@ export default async function Settings({ searchParams }: { searchParams: Promise )} +
+ {notify === "saved" && Настройки уведомлений сохранены} + +
+
Браузер
+

+ Push приходят и при закрытой вкладке; клик открывает стори или проект. Подписано браузеров: {pushSubs.length}. Пеппу можно установить как приложение (Chrome → «Установить»). +

+
+ s.endpoint)} /> +
+
+ + + + + + + + + + + + {NOTIFY_EVENTS.filter((e) => e !== "monitoring" || superadmin).map((e) => ( + + + + + + ))} + +
СобытиеTelegramБраузер
{NOTIFY_EVENT_NAMES[e]} + + + +
+ {!superadmin && ( + <> + + + + )} +
+ + +
+ + +
+

В тихие часы Telegram приходит без звука, push в браузер не показываются. Дайджест приходит в своё время.

+
+ + +
+

+ Сводка за сутки по вашим проектам: сделано, в работе, на ревью, ждёт вас, зависло, лимиты. Пустая не приходит. В боте — команда /digest. +

+ +
+ {myProjects.length > 0 && ( + +
Проекты
+

Из снятых проектов уведомления не приходят (вопросы остаются в вебе).

+
+ {myProjects.map((p) => ( + + ))} +
+
+ )} + + +

Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент зарегистрируется сам, вы подтвердите доступ на экране Пеппы.

{origin}/mcp diff --git a/apps/web/app/api/attention/route.ts b/apps/web/app/api/attention/route.ts new file mode 100644 index 00000000..105ad5cd --- /dev/null +++ b/apps/web/app/api/attention/route.ts @@ -0,0 +1,15 @@ +import { getNotifyPrefs } from "@peppa/core"; +import { currentUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { navCounts } from "@/lib/queries"; + +export const dynamic = "force-dynamic"; + +/** What waits for the signed-in user (tab title counter and app badge, PEP-55). */ +export async function GET() { + const user = await currentUser(); + if (!user) return Response.json({ error: "unauthorized" }, { status: 401 }); + const c = await navCounts(user.id); + const { sound } = await getNotifyPrefs(db, user.id); + return Response.json({ count: c.questions + c.waitingRunners, sound }, { headers: { "Cache-Control": "no-store" } }); +} diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx index 368ed35a..5259483f 100644 --- a/apps/web/app/layout.tsx +++ b/apps/web/app/layout.tsx @@ -6,7 +6,7 @@ import { cn } from "@/lib/utils"; import { THEME_COOKIE } from "@/lib/theme"; import "./app.css"; -export const metadata = { title: "Peppa", description: "Софтвейр-фабрика: проекты, стори и агенты" }; +export const metadata = { title: "Peppa", description: "Софтвейр-фабрика: проекты, стори и агенты", icons: { icon: "/icon.svg" } }; export default async function RootLayout({ children }: { children: ReactNode }) { // Dark by default; the cookie is read on the server so a light choice renders without a dark flash. diff --git a/apps/web/app/manifest.ts b/apps/web/app/manifest.ts new file mode 100644 index 00000000..9a0fba3c --- /dev/null +++ b/apps/web/app/manifest.ts @@ -0,0 +1,16 @@ +import type { MetadataRoute } from "next"; + +/** Installable as an app (PEP-55): Chrome «Установить Пеппу», badge on the app icon. */ +export default function manifest(): MetadataRoute.Manifest { + return { + name: "Peppa — софтвейр-фабрика", + short_name: "Peppa", + description: "Проекты, стори и агенты", + start_url: "/", + scope: "/", + display: "standalone", + background_color: "#0a0a0a", + theme_color: "#0a0a0a", + icons: [{ src: "/icon.svg", sizes: "any", type: "image/svg+xml", purpose: "any" }], + }; +} diff --git a/apps/web/components/AttentionBadge.tsx b/apps/web/components/AttentionBadge.tsx new file mode 100644 index 00000000..b17effab --- /dev/null +++ b/apps/web/components/AttentionBadge.tsx @@ -0,0 +1,78 @@ +"use client"; + +import { useEffect, useRef } from "react"; + +const PREFIX = /^\(\d+\) /; + +/** Short two-tone chime (WebAudio, no asset). Browsers allow it after any click on the page. */ +function chime() { + try { + const ctx = new AudioContext(); + [880, 660].forEach((f, i) => { + const o = ctx.createOscillator(); + const g = ctx.createGain(); + o.frequency.value = f; + const t = ctx.currentTime + i * 0.16; + g.gain.setValueAtTime(0.0001, t); + g.gain.exponentialRampToValueAtTime(0.2, t + 0.02); + g.gain.exponentialRampToValueAtTime(0.0001, t + 0.15); + o.connect(g).connect(ctx.destination); + o.start(t); + o.stop(t + 0.16); + }); + setTimeout(() => ctx.close(), 600); + } catch {} +} + +/** + * «(N) …» in the tab title and the app badge (PEP-55): what waits for the user. Polls + * /api/attention; a growing count plays a chime if sound is on in the settings. + */ +export function AttentionBadge({ count: initial, sound: initialSound, everyMs = 20_000 }: { count: number; sound: boolean; everyMs?: number }) { + const count = useRef(initial); + const sound = useRef(initialSound); + + useEffect(() => { + const apply = () => { + const base = document.title.replace(PREFIX, ""); + const want = count.current > 0 ? `(${count.current}) ${base}` : base; + if (document.title !== want) document.title = want; + const nav = navigator as Navigator & { setAppBadge?: (n?: number) => Promise; clearAppBadge?: () => Promise }; + if (count.current > 0) nav.setAppBadge?.(count.current).catch(() => {}); + else nav.clearAppBadge?.().catch(() => {}); + }; + apply(); + // Next sets the title on navigation: put the counter back. + const titleObserver = new MutationObserver(apply); + titleObserver.observe(document.head, { subtree: true, childList: true, characterData: true }); + + const poll = async () => { + if (document.visibilityState !== "visible") return; + try { + const r = await fetch("/api/attention", { cache: "no-store" }); + if (!r.ok) return; + const j = (await r.json()) as { count: number; sound: boolean }; + sound.current = j.sound; + if (j.count > count.current && sound.current) chime(); + count.current = j.count; + apply(); + } catch {} + }; + const id = setInterval(poll, everyMs); + document.addEventListener("visibilitychange", poll); + return () => { + clearInterval(id); + titleObserver.disconnect(); + document.removeEventListener("visibilitychange", poll); + }; + }, [everyMs]); + + // A server re-render (router.refresh) brings a fresh count too. + useEffect(() => { + if (initial > count.current && sound.current) chime(); + count.current = initial; + document.title = initial > 0 ? `(${initial}) ${document.title.replace(PREFIX, "")}` : document.title.replace(PREFIX, ""); + }, [initial]); + + return null; +} diff --git a/apps/web/components/PushNotifications.tsx b/apps/web/components/PushNotifications.tsx new file mode 100644 index 00000000..da9d64cd --- /dev/null +++ b/apps/web/components/PushNotifications.tsx @@ -0,0 +1,110 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { Bell, BellOff, Send } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { deletePushSubscriptionAction, savePushSubscriptionAction, testPushAction } from "@/app/(app)/actions"; + +type State = "loading" | "unsupported" | "denied" | "off" | "on"; + +const toBytes = (b64u: string) => { + const s = atob(b64u.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (b64u.length % 4)) % 4)); + return Uint8Array.from(s, (c) => c.charCodeAt(0)); +}; + +async function registration() { + await navigator.serviceWorker.register("/sw.js", { scope: "/" }); + return navigator.serviceWorker.ready; +} + +/** «Push в этом браузере» (PEP-55): permission, Web Push subscription, test, unsubscribe. */ +export function PushNotifications({ vapidKey, known }: { vapidKey: string; known: string[] }) { + const [state, setState] = useState("loading"); + const [endpoint, setEndpoint] = useState(null); + const [msg, setMsg] = useState(null); + const [busy, setBusy] = useState(false); + + useEffect(() => { + (async () => { + if (!("serviceWorker" in navigator) || !("PushManager" in window) || !("Notification" in window)) return setState("unsupported"); + if (Notification.permission === "denied") return setState("denied"); + const reg = await navigator.serviceWorker.getRegistration("/"); + const sub = await reg?.pushManager.getSubscription(); + if (!sub) return setState("off"); + setEndpoint(sub.endpoint); + // Subscribed in the browser but unknown to Peppa (e.g. removed after a 410): tell it again. + if (!known.includes(sub.endpoint)) await savePushSubscriptionAction(sub.toJSON() as never, navigator.userAgent); + setState("on"); + })().catch((e) => (setMsg(String(e?.message ?? e)), setState("off"))); + }, [known]); + + async function enable() { + setBusy(true); + setMsg(null); + try { + if ((await Notification.requestPermission()) !== "granted") return setState("denied"); + const reg = await registration(); + const sub = (await reg.pushManager.getSubscription()) ?? (await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: toBytes(vapidKey) })); + await savePushSubscriptionAction(sub.toJSON() as never, navigator.userAgent); + setEndpoint(sub.endpoint); + setState("on"); + } catch (e) { + setMsg(`Не удалось включить: ${(e as Error).message}`); + } finally { + setBusy(false); + } + } + + async function disable() { + setBusy(true); + try { + const reg = await navigator.serviceWorker.getRegistration("/"); + const sub = await reg?.pushManager.getSubscription(); + if (sub) { + await deletePushSubscriptionAction(sub.endpoint); + await sub.unsubscribe(); + } + setEndpoint(null); + setState("off"); + } finally { + setBusy(false); + } + } + + async function test() { + if (!endpoint) return; + setBusy(true); + const r = await testPushAction(endpoint).catch((e) => ({ ok: false, error: String(e) })); + setMsg(r.ok ? "Отправлено — уведомление должно появиться через пару секунд." : `Не дошло: ${r.error}`); + setBusy(false); + } + + return ( +
+
+ {state === "on" ? ( + <> + Push в этом браузере включены. + + + + ) : state === "off" ? ( + + ) : state === "denied" ? ( + Уведомления для этого сайта запрещены в браузере — разрешите их в настройках сайта (значок слева от адреса) и обновите страницу. + ) : state === "unsupported" ? ( + Этот браузер не умеет Web Push. В Safari на iPhone — сначала «На экран Домой». + ) : ( + Проверяю… + )} +
+ {msg &&

{msg}

} +
+ ); +} diff --git a/apps/web/components/TimezoneField.tsx b/apps/web/components/TimezoneField.tsx new file mode 100644 index 00000000..c224bf7d --- /dev/null +++ b/apps/web/components/TimezoneField.tsx @@ -0,0 +1,34 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { Input, Label } from "@/components/ui/input"; + +/** IANA timezone for quiet hours and the digest, with «как в браузере» (PEP-35). */ +export function TimezoneField({ value }: { value: string }) { + const [tz, setTz] = useState(value); + const [browser, setBrowser] = useState(null); + const [zones, setZones] = useState([]); + // Client-only: the server's and the browser's lists may differ (no hydration mismatch). + useEffect(() => { + setBrowser(Intl.DateTimeFormat().resolvedOptions().timeZone); + setZones(typeof Intl.supportedValuesOf === "function" ? Intl.supportedValuesOf("timeZone") : []); + }, []); + return ( +
+ + + {zones.map((z) => ( + + {browser && browser !== tz && ( + + )} +
+ ); +} diff --git a/apps/web/next-env.d.ts b/apps/web/next-env.d.ts index ce4e94a6..a419cbe4 100644 --- a/apps/web/next-env.d.ts +++ b/apps/web/next-env.d.ts @@ -1,7 +1,7 @@ /// /// -import "./.next/types/routes.d.ts"; -import "./.next/types/root-params.d.ts"; +import "./.next/dev/types/routes.d.ts"; +import "./.next/dev/types/root-params.d.ts"; // NOTE: This file should not be edited // see https://nextjs.org/docs/app/api-reference/config/typescript for more information. diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index 0c238560..1b1e3359 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -22,7 +22,9 @@ const config: NextConfig = { // Dev chunks keep their names between edits; Cloudflare turns the dev server's `no-cache` into a // 4 h browser cache, so a reload ran stale code. `private, no-store` is passed through as is. async headers() { - return process.env.NODE_ENV === "development" ? [{ source: "/_next/static/:path*", headers: [{ key: "Cache-Control", value: "private, no-store" }] }] : []; + // The service worker must not sit in a browser/CDN cache, or fixes to it never arrive (PEP-55). + const sw = { source: "/sw.js", headers: [{ key: "Cache-Control", value: "private, no-cache, max-age=0" }] }; + return process.env.NODE_ENV === "development" ? [{ source: "/_next/static/:path*", headers: [{ key: "Cache-Control", value: "private, no-store" }] }, sw] : [sw]; }, transpilePackages: ["@peppa/db", "@peppa/shared", "@peppa/core", "@peppa/runner", "@peppa/mcp"], env: { diff --git a/apps/web/public/icon.svg b/apps/web/public/icon.svg new file mode 100644 index 00000000..0a70f27f --- /dev/null +++ b/apps/web/public/icon.svg @@ -0,0 +1 @@ + diff --git a/apps/web/public/sw.js b/apps/web/public/sw.js new file mode 100644 index 00000000..416deed2 --- /dev/null +++ b/apps/web/public/sw.js @@ -0,0 +1,41 @@ +// Peppa service worker (PEP-55): shows Web Push notifications and opens the right page +// on click. Payload (core/webpush.ts PushPayload): { title, body, url, tag?, sound?, count? }. +self.addEventListener("install", () => self.skipWaiting()); +self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim())); + +self.addEventListener("push", (event) => { + let p = {}; + try { + p = event.data ? event.data.json() : {}; + } catch { + p = { title: "Пеппа", body: event.data ? event.data.text() : "" }; + } + const shown = self.registration.showNotification(p.title || "Пеппа", { + body: p.body || "", + tag: p.tag, + renotify: Boolean(p.tag), + silent: p.sound === false, + icon: "/icon.svg", + badge: "/icon.svg", + data: { url: p.url || "/" }, + }); + const badge = typeof p.count === "number" && self.navigator.setAppBadge ? self.navigator.setAppBadge(p.count).catch(() => {}) : Promise.resolve(); + event.waitUntil(Promise.all([shown, badge])); +}); + +self.addEventListener("notificationclick", (event) => { + event.notification.close(); + const url = new URL((event.notification.data && event.notification.data.url) || "/", self.location.origin).href; + event.waitUntil( + (async () => { + const tabs = await self.clients.matchAll({ type: "window", includeUncontrolled: true }); + const same = tabs.find((c) => c.url === url) || tabs.find((c) => new URL(c.url).origin === self.location.origin); + if (same) { + await same.focus(); + if (same.url !== url && "navigate" in same) await same.navigate(url).catch(() => {}); + return; + } + await self.clients.openWindow(url); + })(), + ); +}); diff --git a/openspec/changes/pep-29-35-55-notifications/tasks.md b/openspec/changes/pep-29-35-55-notifications/tasks.md index 5fd4de9f..e454871a 100644 --- a/openspec/changes/pep-29-35-55-notifications/tasks.md +++ b/openspec/changes/pep-29-35-55-notifications/tasks.md @@ -1,23 +1,23 @@ # Tasks: PEP-29, PEP-35, PEP-55 ## 1. Данные и core -- [ ] 1.1 Схема `push_subscriptions`, `push_outbox` + миграция -- [ ] 1.2 core/notifications.ts: prefs (чтение с умолчаниями, сохранение), тихие часы, `questionEvent`, `projectAudience`, `deliverToUser` -- [ ] 1.3 core/webpush.ts: VAPID-ключи в settings, шифрование aes128gcm, JWT, отправка, push-outbox (очередь, ретраи, 404/410) -- [ ] 1.4 core/digest.ts: сбор и текст сводки, `digestTick` (время, таймзона, окно, дедуп) +- [x] 1.1 Схема `push_subscriptions`, `push_outbox` + миграция +- [x] 1.2 core/notifications.ts: prefs (чтение с умолчаниями, сохранение), тихие часы, `questionEvent`, `projectAudience`, `deliverToUser` +- [x] 1.3 core/webpush.ts: VAPID-ключи в settings, шифрование aes128gcm, JWT, отправка, push-outbox (очередь, ретраи, 404/410) +- [x] 1.4 core/digest.ts: сбор и текст сводки, `digestTick` (время, таймзона, окно, дедуп) ## 2. Доставка -- [ ] 2.1 Бот: вопросы через `deliverToUser`, разбор push-outbox, `/digest` -- [ ] 2.2 Ошибки из прода и мониторинг через `deliverToUser` -- [ ] 2.3 Вачдог: `digestTick` в `tick` +- [x] 2.1 Бот: вопросы через `deliverToUser`, разбор push-outbox, `/digest` +- [x] 2.2 Ошибки из прода и мониторинг через `deliverToUser` +- [x] 2.3 Вачдог: `digestTick` в `tick` ## 3. Веб -- [ ] 3.1 «Настройки → Уведомления»: события × каналы, тихие часы, таймзона, дайджест, звук, проекты -- [ ] 3.2 Push в браузере: sw.js, манифест PWA, включить/проверить/отключить -- [ ] 3.3 Счётчик в заголовке и значке, звук; `/api/attention` -- [ ] 3.4 Помощь +- [x] 3.1 «Настройки → Уведомления»: события × каналы, тихие часы, таймзона, дайджест, звук, проекты +- [x] 3.2 Push в браузере: sw.js, манифест PWA, включить/проверить/отключить +- [x] 3.3 Счётчик в заголовке и значке, звук; `/api/attention` +- [x] 3.4 Помощь ## 4. Тесты и документация -- [ ] 4.1 testkit: mock-push, notifications.test.ts (сценарии спеки) -- [ ] 4.2 AGENTS.md -- [ ] 4.3 pnpm run ci зелёный +- [x] 4.1 testkit: mock-push, notifications.test.ts (сценарии спеки) +- [x] 4.2 AGENTS.md +- [x] 4.3 pnpm run ci зелёный diff --git a/packages/testkit/test/notifications.test.ts b/packages/testkit/test/notifications.test.ts index c4b0396a..9e2719c5 100644 --- a/packages/testkit/test/notifications.test.ts +++ b/packages/testkit/test/notifications.test.ts @@ -127,7 +127,7 @@ describe("routing in the bot", () => { 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; }); + const [msg] = await waitFor("silent message", async () => { const a = sentTo(PM.chatId, "rm -rf node_modules"); return a.length ? a : null; }); 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)); @@ -142,7 +142,7 @@ describe("routing in the bot", () => { 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; }); + const [m] = await waitFor("push delivered", async () => { const a = push.for(sub.id); return a.length ? a : null; }); assert.equal(m!.payload.url, `/t/${ref.project.key}-${ref.task.number}`); assert.match(String(m!.payload.title), /Готово к ревью/); assert.equal(m!.payload.body, "PR готов."); @@ -210,7 +210,7 @@ describe("daily digest", () => { 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 [m] = await waitFor("digest delivered", async () => { const a = sentTo(PM.chatId, "Сводка за сутки").filter((c) => tg.calls.indexOf(c) >= before); return a.length ? a : null; }); const text = String(m!.params.text); assert.match(text, /Digest/); assert.match(text, new RegExp(`Сделано: 1[\\s\\S]*${done.project.key}-${done.task.number}`)); From 9d8851b0b447ff851eb864fa8ec3f6f435eee73f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 04:51:14 +0500 Subject: [PATCH 4/5] PEP-29/35/55: archive OpenSpec change pep-29-35-55-notifications Co-Authored-By: Claude Opus 5.5 --- apps/web/next-env.d.ts | 4 +- .../design.md | 0 .../proposal.md | 0 .../specs/user-notifications/spec.md | 0 .../tasks.md | 0 openspec/specs/user-notifications/spec.md | 73 +++++++++++++++++++ 6 files changed, 75 insertions(+), 2 deletions(-) rename openspec/changes/{pep-29-35-55-notifications => archive/2026-11-14-pep-29-35-55-notifications}/design.md (100%) rename openspec/changes/{pep-29-35-55-notifications => archive/2026-11-14-pep-29-35-55-notifications}/proposal.md (100%) rename openspec/changes/{pep-29-35-55-notifications => archive/2026-11-14-pep-29-35-55-notifications}/specs/user-notifications/spec.md (100%) rename openspec/changes/{pep-29-35-55-notifications => archive/2026-11-14-pep-29-35-55-notifications}/tasks.md (100%) create mode 100644 openspec/specs/user-notifications/spec.md diff --git a/apps/web/next-env.d.ts b/apps/web/next-env.d.ts index a419cbe4..ce4e94a6 100644 --- a/apps/web/next-env.d.ts +++ b/apps/web/next-env.d.ts @@ -1,7 +1,7 @@ /// /// -import "./.next/dev/types/routes.d.ts"; -import "./.next/dev/types/root-params.d.ts"; +import "./.next/types/routes.d.ts"; +import "./.next/types/root-params.d.ts"; // NOTE: This file should not be edited // see https://nextjs.org/docs/app/api-reference/config/typescript for more information. diff --git a/openspec/changes/pep-29-35-55-notifications/design.md b/openspec/changes/archive/2026-11-14-pep-29-35-55-notifications/design.md similarity index 100% rename from openspec/changes/pep-29-35-55-notifications/design.md rename to openspec/changes/archive/2026-11-14-pep-29-35-55-notifications/design.md diff --git a/openspec/changes/pep-29-35-55-notifications/proposal.md b/openspec/changes/archive/2026-11-14-pep-29-35-55-notifications/proposal.md similarity index 100% rename from openspec/changes/pep-29-35-55-notifications/proposal.md rename to openspec/changes/archive/2026-11-14-pep-29-35-55-notifications/proposal.md diff --git a/openspec/changes/pep-29-35-55-notifications/specs/user-notifications/spec.md b/openspec/changes/archive/2026-11-14-pep-29-35-55-notifications/specs/user-notifications/spec.md similarity index 100% rename from openspec/changes/pep-29-35-55-notifications/specs/user-notifications/spec.md rename to openspec/changes/archive/2026-11-14-pep-29-35-55-notifications/specs/user-notifications/spec.md diff --git a/openspec/changes/pep-29-35-55-notifications/tasks.md b/openspec/changes/archive/2026-11-14-pep-29-35-55-notifications/tasks.md similarity index 100% rename from openspec/changes/pep-29-35-55-notifications/tasks.md rename to openspec/changes/archive/2026-11-14-pep-29-35-55-notifications/tasks.md diff --git a/openspec/specs/user-notifications/spec.md b/openspec/specs/user-notifications/spec.md new file mode 100644 index 00000000..a3cab759 --- /dev/null +++ b/openspec/specs/user-notifications/spec.md @@ -0,0 +1,73 @@ +# user-notifications Specification + +## Purpose +TBD - created by archiving change pep-29-35-55-notifications. Update Purpose after archive. + +## Requirements + +### Requirement: Настройки уведомлений +Пользователь SHALL выбирать в «Настройках → Уведомления» для каждого события (вопросы +агентов, готово к ревью, сбои и лимиты, релизы, ошибки из прода, мониторинг — только +админам, дайджест) каналы Telegram и браузер, а также проекты, из которых уведомления не +нужны. По умолчанию включено всё, кроме дайджеста в браузер. + +#### Scenario: Выключены вопросы агентов в Telegram +- **GIVEN** PM выключил «Вопросы агентов» для Telegram +- **WHEN** агент задаёт вопрос в проекте PM +- **THEN** сообщение в Telegram не приходит, вопрос виден в вебе + +#### Scenario: Проект выключен +- **GIVEN** PM снял галочку с проекта «Demo» +- **WHEN** в «Demo» приходит «готово к ревью» +- **THEN** PM не получает ни Telegram, ни push; участники с включённым проектом получают + +### Requirement: Тихие часы +В тихие часы (в таймзоне пользователя, интервал может переходить через полночь) Telegram +SHALL приходить без звука, браузерные push SHALL не показываться. + +#### Scenario: Ночной вопрос +- **GIVEN** тихие часы 23:00–08:00, сейчас 02:00 у PM +- **WHEN** агент просит разрешение +- **THEN** сообщение приходит в Telegram без звука, push не отправляется + +### Requirement: Push в браузере +Пользователь SHALL включать push в браузере из «Настроек» (разрешение браузера, подписка +Web Push с ключами VAPID Пеппы), проверять тестовым уведомлением и отключать. Уведомление +SHALL открывать по клику стори, раннер или проект. Подписка, которую сервис push +отклонил как несуществующую (404/410), SHALL удаляться. + +#### Scenario: Готово к ревью в браузер +- **GIVEN** PM включил push в Chrome +- **WHEN** стори переходит в ревью +- **THEN** приходит уведомление «Готово к ревью», клик открывает страницу стори + +#### Scenario: Подписка протухла +- **GIVEN** сервис push отвечает 410 на подписку +- **WHEN** Пеппа пытается доставить уведомление +- **THEN** подписка удаляется, повторов нет + +### Requirement: Счётчик и звук +Вкладка Пеппы SHALL показывать в заголовке и на значке приложения число того, что ждёт +пользователя, и при его росте проигрывать короткий звук, если звук включён. + +#### Scenario: Новый вопрос при открытой вкладке +- **GIVEN** открыта Пеппа, ждут 2 вопроса, звук включён +- **WHEN** приходит третий вопрос +- **THEN** заголовок становится «(3) …» и звучит сигнал + +### Requirement: Ежедневный дайджест +Каждый день в выбранное время (по умолчанию 09:00 в таймзоне пользователя) Пеппа SHALL +присылать сводку по проектам пользователя: сделано за сутки, в работе, на ревью, ждёт +пользователя, зависло или заблокировано, лимиты. Не больше одной сводки в день; пустая +сводка не отправляется; дайджест отключается в настройках. Команда `/digest` в боте +SHALL присылать сводку сейчас. + +#### Scenario: Утренний дайджест +- **GIVEN** у PM вчера смержена PEP-5, PEP-6 в работе, ждёт 1 вопрос; время дайджеста 09:00 +- **WHEN** вачдог тикает в 09:01 и ещё раз в 09:30 +- **THEN** PM получает одну сводку с PEP-5 в «Сделано», PEP-6 в «В работе» и «Ждёт тебя: 1» + +#### Scenario: Выкат вечером +- **GIVEN** время дайджеста 09:00, сейчас 20:00 и сегодня сводки не было +- **WHEN** вачдог тикает +- **THEN** сводка не отправляется до завтрашних 09:00 From ce3e33dc5fc8b7f63f88f1855ed509323e68fb18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 04:51:20 +0500 Subject: [PATCH 5/5] PEP-29/35/55: user-notifications spec purpose Co-Authored-By: Claude Opus 5.5 --- openspec/specs/user-notifications/spec.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openspec/specs/user-notifications/spec.md b/openspec/specs/user-notifications/spec.md index a3cab759..f7f57eef 100644 --- a/openspec/specs/user-notifications/spec.md +++ b/openspec/specs/user-notifications/spec.md @@ -1,7 +1,7 @@ # user-notifications Specification ## Purpose -TBD - created by archiving change pep-29-35-55-notifications. Update Purpose after archive. +Уведомления пользователя (PEP-29, PEP-35, PEP-55): что и куда присылать (Telegram, браузер), тихие часы, выбор проектов, Web Push, счётчик и звук во вкладке, ежедневный дайджест. ## Requirements