peppa/apps/web/app/(app)/settings/page.tsx
Асель 01d58973ab PEP-85: every user's own Telegram bot — token from BotFather, polled and answered through it
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 22:57:07 +05:00

344 lines
19 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core";
import { Hidden } from "@/components/cards";
import { ago, Disclosure, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input, Label } from "@/components/ui/input";
import { EgovSign } from "@/components/EgovSign";
import { Workspace } from "@/components/Workspace";
import { publicOrigin, requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { connectOwnBotAction, disconnectOwnBotAction, pairTelegram, revokeConnectedApp, saveNotifyPrefsAction, unpairTelegramAction } from "../actions";
import { PushNotifications } from "@/components/PushNotifications";
import { TimezoneField } from "@/components/TimezoneField";
const back = { back: "/settings" };
function StepNum({ n, done }: { n: number; done: boolean }) {
return (
<span aria-hidden className={done ? "mt-0.5 grid size-5.5 shrink-0 place-items-center rounded-full bg-ok/20 text-xs font-semibold text-ok" : "mt-0.5 grid size-5.5 shrink-0 place-items-center rounded-full bg-primary/15 text-xs font-semibold text-primary"}>
{done ? "✓" : n}
</span>
);
}
/** A connected thing: title + details on the left, actions on the right. */
function Row({ title, children, actions }: { title: React.ReactNode; children?: React.ReactNode; actions?: React.ReactNode }) {
return (
<Card className="flex-row flex-wrap items-center gap-3">
<div className="min-w-0 flex-[1_1_16rem]">
<div className="font-medium">{title}</div>
{children && <div className="text-sm text-muted-foreground">{children}</div>}
</div>
{actions && <div className="flex gap-2">{actions}</div>}
</Card>
);
}
export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; egov?: string; notify?: string; bot?: string }> }) {
const user = await requireUser();
const { error, egov, notify, bot } = await searchParams;
const hasBot = !!user.telegramBotUsername;
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);
// PEP-85: the three steps of connecting an own bot (shown when Telegram is not paired, or to switch).
const ownBotSteps = (
<Card className="gap-4">
<p className="m-0 text-sm">
Через Telegram фабрика зовёт вас, когда агенту нужен ответ или работа готова, — отвечать можно кнопками с телефона. У каждого пользователя свой бот: вы создаёте его за две минуты, без программирования.
</p>
<ol className="m-0 flex list-none flex-col gap-3 p-0 text-sm">
<li className="flex gap-2.5">
<StepNum n={1} done={hasBot} />
<div className="flex min-w-0 flex-col items-start gap-1.5">
<span className="font-medium">Создайте бота в Telegram</span>
<span className="text-muted-foreground">
Откройте <b>@BotFather</b> (официальный бот Telegram), отправьте ему <span className="font-mono">/newbot</span>, придумайте название и адрес — адрес должен заканчиваться на <span className="font-mono">bot</span>, например{" "}
<span className="font-mono">my_factory_bot</span>.
</span>
{!hasBot && (
<Button asChild size="sm" variant="outline">
<a href="https://t.me/BotFather" target="_blank" rel="noreferrer">Открыть BotFather</a>
</Button>
)}
</div>
</li>
<li className="flex gap-2.5">
<StepNum n={2} done={hasBot} />
<div className="flex min-w-0 flex-1 flex-col items-start gap-1.5">
<span className="font-medium">Вставьте токен бота</span>
{hasBot ? (
<span className="text-muted-foreground">
Подключён <span className="font-mono">@{user.telegramBotUsername}</span>. Токен хранится зашифрованным.
</span>
) : (
<>
<span className="text-muted-foreground">BotFather пришлёт сообщение с длинной строкой вида <span className="font-mono">1234567890:AAH…</span> — это токен. Скопируйте его сюда. Пеппа хранит его зашифрованным и никому не показывает.</span>
<form action={connectOwnBotAction} className="flex w-full flex-wrap gap-2">
<Hidden fields={back} />
<Input name="token" type="password" required autoComplete="off" placeholder="Токен от BotFather" aria-label="Токен бота" className="h-9 min-w-48 flex-1 font-mono" />
<Button variant="default">Подключить бота</Button>
</form>
</>
)}
</div>
</li>
<li className="flex gap-2.5">
<StepNum n={3} done={false} />
<div className="flex min-w-0 flex-col items-start gap-1.5">
<span className="font-medium">Откройте своего бота и нажмите Start</span>
<span className="text-muted-foreground">Так бот узнает, куда вам писать. Удобнее сделать это на телефоне — там и будут приходить сообщения.</span>
{hasBot && (
<form action={pairTelegram}>
<Hidden fields={back} />
<Button variant="default" size="sm">Открыть @{user.telegramBotUsername}</Button>
</form>
)}
</div>
</li>
</ol>
{hasBot ? (
<form action={disconnectOwnBotAction}>
<Hidden fields={back} />
<Button size="xs" variant="ghost" className="text-muted-foreground">Отключить этого бота</Button>
</form>
) : (
<form action={pairTelegram} className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
<Hidden fields={back} />
Не хотите создавать бота?
<Button size="xs" variant="ghost">Использовать общего бота Пеппы</Button>
</form>
)}
</Card>
);
return (
<Workspace>
<div className="max-w-2xl">
<Flash error={error} />
<PageHeader title="Настройки" />
<Section title="Учётная запись">
<Card>
<p className="m-0 text-sm">
Логин <span className="font-mono">{user.login}</span>
{user.name ? <> · {user.name}</> : null}. Вход в Пеппу — только через eGov QR
{user.egovIin ? (
<>
, ИИН <span className="font-mono">{maskIin(user.egovIin)}</span>.
</>
) : (
<>. <b>ИИН ещё не привязан</b> — привяжите его ниже, иначе после выхода вы не сможете войти.</>
)}
</p>
{local && (
<p className="m-0 text-sm text-muted-foreground">
Аккаунта Gitea нет: код проектов — через Пеппу (агенты, PR, проверки), новые проекты создаются в пространстве <span className="font-mono">peppa-bot</span>.
</p>
)}
</Card>
{superadmin && (
<Row
title="Суперадмин"
actions={
<>
<Button asChild size="sm">
<a href="/users">Пользователи</a>
</Button>
<Button asChild size="sm">
<a href="/subscriptions">Подписки</a>
</Button>
<Button asChild size="sm">
<a href="/secrets">Секреты</a>
</Button>
<Button asChild size="sm">
<a href="/hosts">Хосты</a>
</Button>
<Button asChild size="sm">
<a href="/journal">Журнал</a>
</Button>
<Button asChild size="sm">
<a href="/platform">Платформа</a>
</Button>
</>
}
>
Пользователи: кто зарегистрировался через eGov, отключить и включить. Подписки агентов и пулы для ротации. Журнал: кто что сделал.
</Row>
)}
</Section>
<Section title="Агенты">
<p className="m-0 text-sm text-muted-foreground">
Подписки Claude Code, Codex и OpenCode, на которых работают агенты, ведёт суперадмин в разделе «Подписки»; проект запускает раннеры на своём пуле подписок.
</p>
</Section>
{!user.egovIin && (
<Section title="eGov" id="egov">
{egov === "linked" && <Notice>eGov привязан — теперь можно входить по QR</Notice>}
<Card>
<p className="m-0 text-sm">Привяжите свой ИИН: отсканируйте QR в eGov Mobile и подпишите. Вход в Пеппу — только через eGov.</p>
<div className="max-w-xs">
<EgovSign purpose="link" label="Привязать eGov" />
</div>
</Card>
</Section>
)}
{user.egovIin && egov === "linked" && <Notice>eGov привязан — теперь можно входить по QR</Notice>}
<Section title="Telegram" id="telegram">
{bot === "connected" && <Notice>Бот @{user.telegramBotUsername} подключён — остался последний шаг: откройте его и нажмите Start.</Notice>}
{user.telegramChatId ? (
<Row
title={`Telegram привязан${user.telegramUsername ? ` (@${user.telegramUsername})` : ""}`}
actions={
<form action={unpairTelegramAction}>
<Hidden fields={back} />
<Button size="sm" variant="destructive">Отвязать</Button>
</form>
}
>
Вопросы агентов и «готово к ревью» приходят вам {user.telegramBotUsername ? <>от вашего бота <span className="font-mono">@{user.telegramBotUsername}</span></> : "от общего бота Пеппы"}. Новую задачу можно просто написать боту.
</Row>
) : (
ownBotSteps
)}
{user.telegramChatId && !hasBot && (
<Disclosure summary="Перейти на своего бота">
<div className="px-4 pb-4">{ownBotSteps}</div>
</Disclosure>
)}
{user.telegramChatId && hasBot && (
<form action={disconnectOwnBotAction}>
<Hidden fields={back} />
<Button size="xs" variant="ghost" className="text-muted-foreground">Отключить бота @{user.telegramBotUsername}</Button>
</form>
)}
</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>
<p className="m-0 text-sm text-muted-foreground">
Как подключить и что спрашивать — в <a href="/help" className="text-primary">Помощи</a>.
</p>
</Section>
<Section title="Подключённые приложения">
{apps.length === 0 ? (
<Empty>Нет подключённых приложений.</Empty>
) : (
apps.map((a) => (
<Row
key={a.clientId}
title={a.name}
actions={
<form action={revokeConnectedApp}>
<Hidden fields={{ clientId: a.clientId, ...back }} />
<Button size="sm" variant="destructive">Отозвать</Button>
</form>
}
>
с {a.since.toLocaleDateString("ru-RU")} · последний запрос {ago(a.lastUsedAt)}
</Row>
))
)}
</Section>
</div>
</Workspace>
);
}