PEP-29/35/55: web — Settings → Notifications, Web Push in the browser (sw.js, PWA manifest), tab counter and sound; help, AGENTS.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-14 04:46:42 +05:00
parent ea4bdf38ff
commit 9f9358de2c
17 changed files with 507 additions and 27 deletions

View File

@ -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` (документ `<auth><challenge/><nonce/></auth>`, поток в `settings` `egov.flow:<hash>`, 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 <login> <ИИН|->`. Мок `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 <login> [--admin] [--name]`, `peppa user passwd|disable|enable <login>` (пароль из 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<id>`: Claude `claude setup-token` (ссылка → код → токен в `secret_enc`) или готовый токен; Codex `codex login --device-auth` (ссылка + код, страница опрашивает) или `--with-api-key`, вход живёт в своём `CODEX_HOME` = `$PEPPA_HOME/subscriptions/s<id>/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 <dir> --prompt`, правила и MCP из `OPENCODE_CONFIG` (opencode.json в каталоге запуска), хуков нет — статус по процессу. Миграция 0003 перенесла токены `users.claude_token_enc` (PEP-13, колонки больше не читаются) в подписки «Claude — <login>» и пулы проектов владельца. Моки: `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:<userId>` в `settings` (`getNotifyPrefs` с умолчаниями, всё включено, кроме дайджеста в браузер), тихие часы (Telegram с `disable_notification`, push пропускается), таймзона (по умолчанию сервера или `PEPPA_TZ`), выключенные проекты. Всё идёт через `deliverToUser` (core/notifications.ts): вопросы (бот `reconcile`, категория — `questionEvent`, получатели — `projectAudience`; ключи Telegram `q:<id>:<chat>` прежние), ошибки из прода, алерты мониторинга. 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:<userId>`), пустой не шлётся; `/digest` в боте. Мок — `mock-push` (testkit: проверяет VAPID и расшифровывает)
- **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:<service>`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon:<service>:…`. Упал бот — вачдог шлёт алерт прямо в 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 <KEY>` (ещё 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 задач в работе/ревью)

View File

@ -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) {

View File

@ -134,7 +134,20 @@ export default async function Help() {
<p className="m-0 text-muted-foreground">
Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с
кнопками; ответ реплаем уходит прямо в сессию агента. Новые ошибки из прода приходят туда же — по политике
проекта: сообщением, стори или с кнопками «В бэклог / В работу / Игнорировать».
проекта: сообщением, стори или с кнопками «В бэклог / В работу / Игнорировать». Команды бота: /status — что
сейчас происходит, /digest — сводка за сутки.
</p>
</Section>
<Section title="Уведомления">
<p className="m-0 text-muted-foreground">
В <Link href="/settings#notifications">Настройках → Уведомления</Link> для каждого события (вопросы агентов,
готово к ревью, сбои и лимиты, релизы, ошибки из прода, дайджест) выбирается, куда присылать: Telegram и/или
браузер. Тихие часы: Telegram приходит без звука, push не показываются. Снятые проекты не присылают ничего —
вопросы остаются в вебе. Push в браузере включаются там же кнопкой (Chrome спросит разрешение) и работают при
закрытой вкладке; клик открывает стори. Во вкладке Пеппы в заголовке и на значке приложения — сколько ждёт вас,
при новом вопросе звучит сигнал (если звук включён). Ежедневный дайджест приходит в выбранное время (по умолчанию
09:00): сделано за сутки, в работе, на ревью, ждёт вас, зависло, лимиты; пустой не приходит.
</p>
</Section>
</div>

View File

@ -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 (
<div className="min-h-dvh md:grid md:grid-cols-[232px_minmax(0,1fr)]">
<AttentionBadge count={counts.questions + counts.waitingRunners} sound={sound} />
<Sidebar login={user.login} avatarUrl={user.avatarUrl} counts={counts} superadmin={await isSuperadmin(db, user)} />
<div className="flex min-w-0 flex-col pb-16 md:pb-0">{children}</div>
</div>

View File

@ -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 (
<Workspace>
<div className="max-w-2xl">
@ -141,6 +147,98 @@ export default async function Settings({ searchParams }: { searchParams: Promise
</Row>
)}
</Section>
<Section title="Уведомления" id="notifications">
{notify === "saved" && <Notice>Настройки уведомлений сохранены</Notice>}
<Card>
<div className="flex flex-col gap-1">
<div className="font-medium">Браузер</div>
<p className="m-0 text-sm text-muted-foreground">
Push приходят и при закрытой вкладке; клик открывает стори или проект. Подписано браузеров: {pushSubs.length}. Пеппу можно установить как приложение (Chrome → «Установить»).
</p>
</div>
<PushNotifications vapidKey={vapid} known={pushSubs.map((s) => s.endpoint)} />
</Card>
<form action={saveNotifyPrefsAction} className="flex flex-col gap-4" aria-label="Настройки уведомлений">
<Hidden fields={back} />
<Card className="gap-0 p-0">
<table className="w-full text-sm">
<thead>
<tr className="border-b text-left text-muted-foreground">
<th className="px-4 py-2 font-normal">Событие</th>
<th className="w-24 px-2 py-2 text-center font-normal">Telegram</th>
<th className="w-24 px-2 py-2 text-center font-normal">Браузер</th>
</tr>
</thead>
<tbody>
{NOTIFY_EVENTS.filter((e) => e !== "monitoring" || superadmin).map((e) => (
<tr key={e} className="border-b last:border-0">
<td className="px-4 py-2">{NOTIFY_EVENT_NAMES[e]}</td>
<td className="px-2 py-2 text-center">
<input type="checkbox" name={`${e}.telegram`} defaultChecked={prefs.events[e].telegram} aria-label={`${NOTIFY_EVENT_NAMES[e]} — Telegram`} className="size-4 accent-primary" />
</td>
<td className="px-2 py-2 text-center">
<input type="checkbox" name={`${e}.push`} defaultChecked={prefs.events[e].push} aria-label={`${NOTIFY_EVENT_NAMES[e]} — браузер`} className="size-4 accent-primary" />
</td>
</tr>
))}
</tbody>
</table>
{!superadmin && (
<>
<input type="hidden" name="monitoring.telegram" value={prefs.events.monitoring.telegram ? "on" : ""} />
<input type="hidden" name="monitoring.push" value={prefs.events.monitoring.push ? "on" : ""} />
</>
)}
</Card>
<Card>
<label className="flex items-center gap-2 text-sm font-medium">
<input type="checkbox" name="quietOn" defaultChecked={!!prefs.quiet} className="size-4 accent-primary" />
Тихие часы
</label>
<div className="flex flex-wrap items-end gap-3">
<Label className="w-32">
С
<Input type="time" name="quietFrom" defaultValue={prefs.quiet?.from ?? "23:00"} />
</Label>
<Label className="w-32">
До
<Input type="time" name="quietTo" defaultValue={prefs.quiet?.to ?? "08:00"} />
</Label>
</div>
<p className="m-0 text-sm text-muted-foreground">В тихие часы Telegram приходит без звука, push в браузер не показываются. Дайджест приходит в своё время.</p>
<div className="flex flex-wrap items-end gap-3">
<Label className="w-32">
Дайджест в
<Input type="time" name="digestTime" defaultValue={prefs.digestTime} />
</Label>
<TimezoneField value={prefs.timezone} />
</div>
<p className="m-0 text-sm text-muted-foreground">
Сводка за сутки по вашим проектам: сделано, в работе, на ревью, ждёт вас, зависло, лимиты. Пустая не приходит. В боте — команда /digest.
</p>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="sound" defaultChecked={prefs.sound} className="size-4 accent-primary" />
Звук: сигнал в открытой вкладке при новом вопросе и звук у push
</label>
</Card>
{myProjects.length > 0 && (
<Card>
<div className="text-sm font-medium">Проекты</div>
<p className="m-0 text-sm text-muted-foreground">Из снятых проектов уведомления не приходят (вопросы остаются в вебе).</p>
<div className="flex flex-wrap gap-x-5 gap-y-2">
{myProjects.map((p) => (
<label key={p.id} className="flex items-center gap-2 text-sm">
<input type="hidden" name="projectShown" value={p.id} />
<input type="checkbox" name="project" value={p.id} defaultChecked={!prefs.mutedProjects.includes(p.id)} className="size-4 accent-primary" />
{p.name} <span className="font-mono text-xs text-muted-foreground">{p.key}</span>
</label>
))}
</div>
</Card>
)}
<Button variant="default" className="self-start">Сохранить уведомления</Button>
</form>
</Section>
<Section title="MCP для ChatGPT и других клиентов">
<p className="m-0 text-sm">Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент зарегистрируется сам, вы подтвердите доступ на экране Пеппы.</p>
<code className="block overflow-x-auto rounded-md border bg-muted px-3 py-2 font-mono text-sm">{origin}/mcp</code>

View File

@ -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" } });
}

View File

@ -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.

16
apps/web/app/manifest.ts Normal file
View File

@ -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" }],
};
}

View File

@ -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<void>; clearAppBadge?: () => Promise<void> };
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;
}

View File

@ -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<State>("loading");
const [endpoint, setEndpoint] = useState<string | null>(null);
const [msg, setMsg] = useState<string | null>(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 (
<div className="flex flex-col gap-2">
<div className="flex flex-wrap items-center gap-2">
{state === "on" ? (
<>
<span className="text-sm">Push в этом браузере включены.</span>
<Button size="sm" type="button" onClick={test} disabled={busy}>
<Send /> Проверить
</Button>
<Button size="sm" type="button" variant="destructive" onClick={disable} disabled={busy}>
<BellOff /> Отключить
</Button>
</>
) : state === "off" ? (
<Button size="sm" type="button" variant="default" onClick={enable} disabled={busy}>
<Bell /> Включить push в этом браузере
</Button>
) : state === "denied" ? (
<span className="text-sm text-muted-foreground">Уведомления для этого сайта запрещены в браузере — разрешите их в настройках сайта (значок слева от адреса) и обновите страницу.</span>
) : state === "unsupported" ? (
<span className="text-sm text-muted-foreground">Этот браузер не умеет Web Push. В Safari на iPhone — сначала «На экран Домой».</span>
) : (
<span className="text-sm text-muted-foreground">Проверяю…</span>
)}
</div>
{msg && <p className="m-0 text-sm text-muted-foreground">{msg}</p>}
</div>
);
}

View File

@ -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<string | null>(null);
const [zones, setZones] = useState<string[]>([]);
// 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 (
<div className="flex flex-wrap items-end gap-2">
<Label className="w-56">
Таймзона
<Input name="timezone" value={tz} onChange={(e) => setTz(e.target.value)} list="peppa-timezones" />
</Label>
<datalist id="peppa-timezones">
{zones.map((z) => (
<option key={z} value={z} />
))}
</datalist>
{browser && browser !== tz && (
<button type="button" className="mb-2 text-sm text-primary" onClick={() => setTz(browser)}>
как в браузере ({browser})
</button>
)}
</div>
);
}

View File

@ -1,7 +1,7 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
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.

View File

@ -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: {

1
apps/web/public/icon.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><rect width="512" height="512" rx="112" fill="#18181b"/><path d="M176 392V120h104c58 0 96 34 96 86s-38 86-96 86h-48v100z M232 244h44c26 0 42-14 42-38s-16-38-42-38h-44z" fill="#fafafa" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 274 B

41
apps/web/public/sw.js Normal file
View File

@ -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);
})(),
);
});

View File

@ -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 зелёный

View File

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