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}`));