Merge pull request 'PEP-85: свой Telegram-бот у каждого пользователя' (#77) from task/pep-85 into main
This commit is contained in:
commit
3abac8f316
@ -41,6 +41,7 @@
|
|||||||
- **Своя подписка (PEP-80)**: `connectOwnSubscription(db, user, project, kind, secret)` — `claude` (токен), `codex_login` (ChatGPT, device-вход; `ownPendingLogins` отдаёт ссылку и код панели «Подписки» проекта), `codex_key`, `existing`; личный пул «Подписки — <логин>»; общий пул на живой системе выключен (`peppa platform shared-pool -`)
|
- **Своя подписка (PEP-80)**: `connectOwnSubscription(db, user, project, kind, secret)` — `claude` (токен), `codex_login` (ChatGPT, device-вход; `ownPendingLogins` отдаёт ссылку и код панели «Подписки» проекта), `codex_key`, `existing`; личный пул «Подписки — <логин>»; общий пул на живой системе выключен (`peppa platform shared-pool -`)
|
||||||
- **Мастер подписки (PEP-82)**: `components/SubscriptionSetup.tsx` на странице проекта без подписки (владелец/суперадмин): «Подключить Claude» (`claude_login`: `claude setup-token` на сервере → ссылка → код → `finishOwnClaudeLogin`) / «Подключить ChatGPT» (`codex_login`); `cancelOwnLogin` удаляет ожидающую подписку; `ownPendingLogins` — входы Claude и Codex пула
|
- **Мастер подписки (PEP-82)**: `components/SubscriptionSetup.tsx` на странице проекта без подписки (владелец/суперадмин): «Подключить Claude» (`claude_login`: `claude setup-token` на сервере → ссылка → код → `finishOwnClaudeLogin`) / «Подключить ChatGPT» (`codex_login`); `cancelOwnLogin` удаляет ожидающую подписку; `ownPendingLogins` — входы Claude и Codex пула
|
||||||
- **Продакт и аналитик (PEP-84)**: роли перед бэклогом — `core/intake.ts` (настройка `project.intake:<id>` {enabled, waitMin, since}, состояние `intake.task:<id>`: product → analyst → waiting|finalize → done; `intakeContext` = AGENTS.md + память + эпики + стори; `productPrompt`/`analystPrompt` с тоном «без похвалы, без разрешений»; `intakeDescription` — текст стори для разработчика) и `runner/intake.ts` (`intakeTick` в тике вачдога, вызовы `claudePrint` в фоне, `PEPPA_INTAKE_BIN`/`_MODEL`/`_TIMEOUT_MS`; вопросы — обычный `askPm`, ответ ловит `onIntakeAnswer`, срок `waitMin` сдвигается за тихие часы автономности; 2 неудачи → стори идёт как есть; `releaseIntake` в `moveTask`). `readyBacklog` исключает `intakePendingTasks`. Реплики — событие `intake_note` (`storyComments` с `role`, чат проекта, `get_task`). Новый проект: включено; `ownPool` владельца назначается сам. Мок `mock-intake` (`MOCK_INTAKE_SCENARIO`)
|
- **Продакт и аналитик (PEP-84)**: роли перед бэклогом — `core/intake.ts` (настройка `project.intake:<id>` {enabled, waitMin, since}, состояние `intake.task:<id>`: product → analyst → waiting|finalize → done; `intakeContext` = AGENTS.md + память + эпики + стори; `productPrompt`/`analystPrompt` с тоном «без похвалы, без разрешений»; `intakeDescription` — текст стори для разработчика) и `runner/intake.ts` (`intakeTick` в тике вачдога, вызовы `claudePrint` в фоне, `PEPPA_INTAKE_BIN`/`_MODEL`/`_TIMEOUT_MS`; вопросы — обычный `askPm`, ответ ловит `onIntakeAnswer`, срок `waitMin` сдвигается за тихие часы автономности; 2 неудачи → стори идёт как есть; `releaseIntake` в `moveTask`). `readyBacklog` исключает `intakePendingTasks`. Реплики — событие `intake_note` (`storyComments` с `role`, чат проекта, `get_task`). Новый проект: включено; `ownPool` владельца назначается сам. Мок `mock-intake` (`MOCK_INTAKE_SCENARIO`)
|
||||||
|
- **Свой Telegram-бот (PEP-85)**: `users.telegram_bot_token_enc` (в `encryptedColumns`) + `telegram_bot_username` (миграция 0016). core/telegram.ts: `verifyBotToken`, `setUserBot`/`clearUserBot`, `userBots`; `acceptPairing(…, { botUserId })` — свой бот привязывает только владельца, общий не привязывает того, у кого есть свой; `getOffset`/`claimUpdate` принимают `botUserId` (ключ обновления `userId·2^36 + update_id`). apps/bot: `syncOwnBots` (раз в `userBotsIntervalMs`), `ownPollLoop`, обработка внутри `via.run(bot)`, объект `api` маршрутизирует вызов: бот текущего обновления → бот владельца `chat_id` → общий. Группы и каналы — только общий бот. Веб «Настройки → Telegram»: три шага. Тест `own-bot.test.ts` — два `MockTelegram` (`userApi` в опциях бота)
|
||||||
- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
|
- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
|
||||||
- **Видимость репозиториев (PEP-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility <KEY|--all> public|private` — админ, без проверки владельца
|
- **Видимость репозиториев (PEP-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility <KEY|--all> public|private` — админ, без проверки владельца
|
||||||
- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база — SQLite `/data/db.sqlite3` в томе `peppa-bugsink-data` (PEP-63; перенос из Postgres — `scripts/bugsink-migrate-to-sqlite.sh`: dumpdata → migrate → loaddata → сверка строк; `peppa-postgres` только под профилем `legacy` до недели после переноса, откат — `infra/bugsink-legacy-pg.yml`), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `<KEY>-web`/`<KEY>-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/<hook_secret>` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i:<id>:backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage`
|
- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база — SQLite `/data/db.sqlite3` в томе `peppa-bugsink-data` (PEP-63; перенос из Postgres — `scripts/bugsink-migrate-to-sqlite.sh`: dumpdata → migrate → loaddata → сверка строк; `peppa-postgres` только под профилем `legacy` до недели после переноса, откат — `infra/bugsink-legacy-pg.yml`), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `<KEY>-web`/`<KEY>-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/<hook_secret>` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i:<id>:backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage`
|
||||||
|
|||||||
@ -12,6 +12,7 @@ import {
|
|||||||
beat,
|
beat,
|
||||||
checkServices,
|
checkServices,
|
||||||
claimUpdate,
|
claimUpdate,
|
||||||
|
userBots,
|
||||||
dueOutbox,
|
dueOutbox,
|
||||||
enqueueTelegram,
|
enqueueTelegram,
|
||||||
finishUpdate,
|
finishUpdate,
|
||||||
@ -66,6 +67,7 @@ import {
|
|||||||
import { projects, tasks, type Db } from "@peppa/db";
|
import { projects, tasks, type Db } from "@peppa/db";
|
||||||
import { formatTaskKey } from "@peppa/shared";
|
import { formatTaskKey } from "@peppa/shared";
|
||||||
import { acceptTask, answerAndDeliver, decideIncident, moveTask, postToChat, resumeSession, stopSession } from "@peppa/runner";
|
import { acceptTask, answerAndDeliver, decideIncident, moveTask, postToChat, resumeSession, stopSession } from "@peppa/runner";
|
||||||
|
import { AsyncLocalStorage } from "node:async_hooks";
|
||||||
import { eq, sql } from "drizzle-orm";
|
import { eq, sql } from "drizzle-orm";
|
||||||
import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts";
|
import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts";
|
||||||
import { TelegramApi, TelegramError, type InlineButton, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts";
|
import { TelegramApi, TelegramError, type InlineButton, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts";
|
||||||
@ -88,6 +90,10 @@ export interface BotOptions {
|
|||||||
heartbeatIntervalMs?: number;
|
heartbeatIntervalMs?: number;
|
||||||
// How often to check PRAGMA data_version for writes the notify() poke missed.
|
// How often to check PRAGMA data_version for writes the notify() poke missed.
|
||||||
changesIntervalMs?: number;
|
changesIntervalMs?: number;
|
||||||
|
/** PEP-85: API client of a user's own bot (tests point it at a second mock). */
|
||||||
|
userApi?: (token: string) => TelegramApi;
|
||||||
|
/** How often the list of users' own bots is re-read. */
|
||||||
|
userBotsIntervalMs?: number;
|
||||||
log?: (msg: string) => void;
|
log?: (msg: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -120,9 +126,81 @@ function pushFor(q: Question, event: NotifyEvent, ctx: { taskKey: string | null;
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function createBot(o: BotOptions) {
|
export function createBot(o: BotOptions) {
|
||||||
const { db, api } = o;
|
const { db } = o;
|
||||||
const log = o.log ?? (() => {});
|
const log = o.log ?? (() => {});
|
||||||
const abort = new AbortController();
|
const abort = new AbortController();
|
||||||
|
|
||||||
|
// ── PEP-85: users' own bots ────────────────────────────────────────────────────
|
||||||
|
// Every bot is polled by its own loop; an update is handled inside `via.run(bot)`, so replies
|
||||||
|
// go out through the bot the message came to. Outside an update (outbox, digests) the bot is
|
||||||
|
// picked by the chat: the owner's private chat belongs to their bot, everything else — the
|
||||||
|
// platform's shared bot.
|
||||||
|
interface OwnBot {
|
||||||
|
userId: number;
|
||||||
|
token: string;
|
||||||
|
api: TelegramApi;
|
||||||
|
stop: AbortController;
|
||||||
|
}
|
||||||
|
const via = new AsyncLocalStorage<OwnBot>();
|
||||||
|
const ownBots = new Map<number, OwnBot>();
|
||||||
|
const ownByChat = new Map<number, OwnBot>();
|
||||||
|
const pick = (chatId?: unknown): TelegramApi => via.getStore()?.api ?? (typeof chatId === "number" ? ownByChat.get(chatId)?.api : undefined) ?? o.api;
|
||||||
|
/** The same surface as TelegramApi, routed to the right bot per call. */
|
||||||
|
const api = {
|
||||||
|
call: <T>(method: string, params: Record<string, unknown> = {}, timeoutMs?: number) => pick(params.chat_id).call<T>(method, params, timeoutMs),
|
||||||
|
sendMessage: (chatId: number, text: string, extra: Record<string, unknown> = {}) => pick(chatId).sendMessage(chatId, text, extra),
|
||||||
|
answerCallbackQuery: (id: string, text?: string) => pick().answerCallbackQuery(id, text),
|
||||||
|
getFile: (fileId: string) => pick().getFile(fileId),
|
||||||
|
downloadFile: (filePath: string) => pick().downloadFile(filePath),
|
||||||
|
getMe: () => o.api.getMe(),
|
||||||
|
getUpdates: (offset: number, timeoutSec: number, signal?: AbortSignal) => o.api.getUpdates(offset, timeoutSec, signal),
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Re-reads the connected bots: starts a poll loop for a new one, stops a removed or re-issued one. */
|
||||||
|
async function syncOwnBots(): Promise<void> {
|
||||||
|
const list = await userBots(db);
|
||||||
|
const seen = new Set<number>();
|
||||||
|
ownByChat.clear();
|
||||||
|
for (const b of list) {
|
||||||
|
seen.add(b.userId);
|
||||||
|
let bot = ownBots.get(b.userId);
|
||||||
|
if (bot && bot.token !== b.token) {
|
||||||
|
bot.stop.abort();
|
||||||
|
bot = undefined;
|
||||||
|
}
|
||||||
|
if (!bot) {
|
||||||
|
bot = { userId: b.userId, token: b.token, api: (o.userApi ?? ((t) => new TelegramApi(t, process.env.TELEGRAM_API_URL)))(b.token), stop: new AbortController() };
|
||||||
|
ownBots.set(b.userId, bot);
|
||||||
|
log(`own bot @${b.username} of user #${b.userId}: polling`);
|
||||||
|
void ownPollLoop(bot);
|
||||||
|
}
|
||||||
|
if (b.chatId != null) ownByChat.set(b.chatId, bot);
|
||||||
|
}
|
||||||
|
for (const [userId, bot] of ownBots) {
|
||||||
|
if (seen.has(userId)) continue;
|
||||||
|
bot.stop.abort();
|
||||||
|
ownBots.delete(userId);
|
||||||
|
log(`own bot of user #${userId}: stopped`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ownPollLoop(bot: OwnBot): Promise<void> {
|
||||||
|
while (!abort.signal.aborted && !bot.stop.signal.aborted) {
|
||||||
|
try {
|
||||||
|
let offset = await getOffset(db, bot.userId);
|
||||||
|
const updates = await bot.api.getUpdates(offset, o.pollTimeoutSec ?? 25, bot.stop.signal);
|
||||||
|
for (const u of updates) {
|
||||||
|
await via.run(bot, () => handleUpdate(u));
|
||||||
|
offset = u.update_id + 1;
|
||||||
|
await setOffset(db, offset, bot.userId);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// A revoked token (401) keeps failing: back off instead of hammering Telegram.
|
||||||
|
log(`own bot #${bot.userId} poll: ${(e as Error).message}`);
|
||||||
|
await sleep(e instanceof TelegramError && e.code === 401 ? 60_000 : 3000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
let reconcileQueued = false;
|
let reconcileQueued = false;
|
||||||
let wakeOutbox: (() => void) | null = null;
|
let wakeOutbox: (() => void) | null = null;
|
||||||
|
|
||||||
@ -495,8 +573,9 @@ export function createBot(o: BotOptions) {
|
|||||||
const text = m.text?.trim() ?? "";
|
const text = m.text?.trim() ?? "";
|
||||||
const start = /^\/start(?:@\w+)?(?:\s+(\S+))?$/.exec(text);
|
const start = /^\/start(?:@\w+)?(?:\s+(\S+))?$/.exec(text);
|
||||||
if (start?.[1] && m.from) {
|
if (start?.[1] && m.from) {
|
||||||
const b = await acceptPairing(db, o.secret, start[1], { chatId: m.chat.id, userId: m.from.id, username: m.from.username });
|
const b = await acceptPairing(db, o.secret, start[1], { chatId: m.chat.id, userId: m.from.id, username: m.from.username, botUserId: via.getStore()?.userId });
|
||||||
if (b) {
|
if (b) {
|
||||||
|
await syncOwnBots().catch(() => {}); // the chat now belongs to this bot
|
||||||
await reply(m.chat.id, `Привязано ✅\n\n${HELP}`);
|
await reply(m.chat.id, `Привязано ✅\n\n${HELP}`);
|
||||||
scheduleReconcile();
|
scheduleReconcile();
|
||||||
return "done";
|
return "done";
|
||||||
@ -506,6 +585,9 @@ export function createBot(o: BotOptions) {
|
|||||||
}
|
}
|
||||||
const user = m.from ? await telegramUser(db, m.chat.id, m.from.id) : null;
|
const user = m.from ? await telegramUser(db, m.chat.id, m.from.id) : null;
|
||||||
if (!user) return "ignored";
|
if (!user) return "ignored";
|
||||||
|
// PEP-85: a user's own bot serves its owner only.
|
||||||
|
const own = via.getStore();
|
||||||
|
if (own && own.userId !== user.id) return "ignored";
|
||||||
// PEP-48: what follows is done by this user through Telegram.
|
// PEP-48: what follows is done by this user through Telegram.
|
||||||
enterActor({ kind: "user", userId: user.id, channel: "telegram" });
|
enterActor({ kind: "user", userId: user.id, channel: "telegram" });
|
||||||
|
|
||||||
@ -612,13 +694,14 @@ export function createBot(o: BotOptions) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function handleUpdate(u: TgUpdate): Promise<void> {
|
async function handleUpdate(u: TgUpdate): Promise<void> {
|
||||||
if (!(await claimUpdate(db, u.update_id))) return;
|
const botUserId = via.getStore()?.userId;
|
||||||
|
if (!(await claimUpdate(db, u.update_id, botUserId))) return;
|
||||||
try {
|
try {
|
||||||
const r = u.message ? await onMessage(u.message) : u.callback_query ? await onCallback(u.callback_query) : "ignored";
|
const r = u.message ? await onMessage(u.message) : u.callback_query ? await onCallback(u.callback_query) : "ignored";
|
||||||
await finishUpdate(db, u.update_id, r);
|
await finishUpdate(db, u.update_id, r, botUserId);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log(`update ${u.update_id}: ${(e as Error).stack ?? e}`);
|
log(`update ${u.update_id}: ${(e as Error).stack ?? e}`);
|
||||||
await finishUpdate(db, u.update_id, "failed");
|
await finishUpdate(db, u.update_id, "failed", botUserId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -675,6 +758,13 @@ export function createBot(o: BotOptions) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function ownBotsLoop() {
|
||||||
|
while (!abort.signal.aborted) {
|
||||||
|
await syncOwnBots().catch((e) => log(`own bots: ${(e as Error).message}`));
|
||||||
|
await sleep(o.userBotsIntervalMs ?? 10_000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function monitorLoop() {
|
async function monitorLoop() {
|
||||||
while (!abort.signal.aborted) {
|
while (!abort.signal.aborted) {
|
||||||
try {
|
try {
|
||||||
@ -694,16 +784,19 @@ export function createBot(o: BotOptions) {
|
|||||||
reconcile,
|
reconcile,
|
||||||
flushOutbox,
|
flushOutbox,
|
||||||
handleUpdate,
|
handleUpdate,
|
||||||
|
syncOwnBots,
|
||||||
async start() {
|
async start() {
|
||||||
const me = await api.getMe();
|
const me = await api.getMe();
|
||||||
await setSetting(db, "telegram.bot", { id: me.id, username: me.username });
|
await setSetting(db, "telegram.bot", { id: me.id, username: me.username });
|
||||||
log(`bot @${me.username} started`);
|
log(`bot @${me.username} started`);
|
||||||
unlisten = await listenEvents("bot", () => scheduleReconcile());
|
unlisten = await listenEvents("bot", () => scheduleReconcile());
|
||||||
loops = Promise.all([pollLoop(), outboxLoop(), reconcileLoop(), changesLoop(), monitorLoop()]);
|
await syncOwnBots().catch((e) => log(`own bots: ${(e as Error).message}`));
|
||||||
|
loops = Promise.all([pollLoop(), outboxLoop(), reconcileLoop(), changesLoop(), monitorLoop(), ownBotsLoop()]);
|
||||||
return me;
|
return me;
|
||||||
},
|
},
|
||||||
async stop() {
|
async stop() {
|
||||||
abort.abort();
|
abort.abort();
|
||||||
|
for (const b of ownBots.values()) b.stop.abort();
|
||||||
wakeOutbox?.();
|
wakeOutbox?.();
|
||||||
await unlisten?.().catch(() => {});
|
await unlisten?.().catch(() => {});
|
||||||
await loops;
|
await loops;
|
||||||
|
|||||||
@ -21,6 +21,8 @@ import {
|
|||||||
updateIncidentSettings,
|
updateIncidentSettings,
|
||||||
setReviewSettings,
|
setReviewSettings,
|
||||||
setIntakeSettings,
|
setIntakeSettings,
|
||||||
|
setUserBot,
|
||||||
|
clearUserBot,
|
||||||
type IncidentPolicy,
|
type IncidentPolicy,
|
||||||
getUser,
|
getUser,
|
||||||
isSuperadmin,
|
isSuperadmin,
|
||||||
@ -419,9 +421,10 @@ export async function pairTelegram(f: FormData) {
|
|||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
||||||
const bot = await getSetting<{ username: string }>(db, "telegram.bot");
|
// PEP-85: the user's own bot if they connected one, else the platform's shared bot.
|
||||||
if (!token || !bot) throw new PeppaError("Telegram-бот Пеппы не запущен");
|
const username = user.telegramBotUsername ?? (await getSetting<{ username: string }>(db, "telegram.bot"))?.username;
|
||||||
return `https://t.me/${bot.username}?start=${await createPairingCode(db, token, user.id)}`;
|
if (!token || !username) throw new PeppaError("Telegram-бот Пеппы не запущен");
|
||||||
|
return `https://t.me/${username}?start=${await createPairingCode(db, token, user.id)}`;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -705,3 +708,20 @@ export async function saveIntakeSettingsAction(f: FormData) {
|
|||||||
await setIntakeSettings(db, p.id, { enabled: f.get("enabled") === "on", waitMin: Number(str(f, "waitMin") || 30) });
|
await setIntakeSettings(db, p.id, { enabled: f.get("enabled") === "on", waitMin: Number(str(f, "waitMin") || 30) });
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── PEP-85: the user's own Telegram bot ────────────────────────────────────────────
|
||||||
|
export async function connectOwnBotAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
await setUserBot(db, user.id, String(f.get("token") ?? ""));
|
||||||
|
return "/settings?bot=connected#telegram";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function disconnectOwnBotAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
await clearUserBot(db, user.id);
|
||||||
|
return "/settings#telegram";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
@ -72,6 +72,7 @@ export default async function Help() {
|
|||||||
<li><b>Участники</b> — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.</li>
|
<li><b>Участники</b> — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.</li>
|
||||||
<li><b>Подписка проекта</b> — на чём работают агенты. В проекте без подписки сверху появляется подсказка: нажмите «Подключить Claude» или «Подключить ChatGPT», откройте ссылку, войдите в свой аккаунт и (для Claude) вставьте код, который он покажет. Терминал не нужен. Готовый токен или ключ OpenAI API — в «⋯ Настройки проекта → Подписки».</li>
|
<li><b>Подписка проекта</b> — на чём работают агенты. В проекте без подписки сверху появляется подсказка: нажмите «Подключить Claude» или «Подключить ChatGPT», откройте ссылку, войдите в свой аккаунт и (для Claude) вставьте код, который он покажет. Терминал не нужен. Готовый токен или ключ OpenAI API — в «⋯ Настройки проекта → Подписки».</li>
|
||||||
<li><b>Стори берутся сами</b> — в новом проекте карточки перетаскивать не нужно: агент сам берёт стори из бэклога по порядку на доске, вам остаётся «Принять» результат. Уровень «Сам берёт» меняется в «⋯ Настройки проекта → Автономность».</li>
|
<li><b>Стори берутся сами</b> — в новом проекте карточки перетаскивать не нужно: агент сам берёт стори из бэклога по порядку на доске, вам остаётся «Принять» результат. Уровень «Сам берёт» меняется в «⋯ Настройки проекта → Автономность».</li>
|
||||||
|
<li><b>Telegram</b> — у каждого пользователя свой бот: в «Настройки → Telegram» три шага — создать бота у @BotFather (команда <span className="font-mono">/newbot</span>), вставить его токен, открыть бота и нажать Start. Из него приходят вопросы агентов и «готово к ревью», ему же можно написать новую задачу. Не хотите создавать — там же можно выбрать общего бота Пеппы.</li>
|
||||||
<li><b>Продакт и аналитик</b> — два агента, которые читают новую задачу раньше разработчика. Продакт решает, зачем это и что берём в первую версию (большое делит на несколько стори). Аналитик пишет критерии приёмки и задаёт до трёх вопросов — у каждого есть вариант по умолчанию; не ответите за 30 минут (ночью — до утра), он возьмёт его сам. Их реплики — во вкладке Comments стори и в чате проекта. Включается в «⋯ Настройки проекта → Продакт и аналитик», в новых проектах включено.</li>
|
<li><b>Продакт и аналитик</b> — два агента, которые читают новую задачу раньше разработчика. Продакт решает, зачем это и что берём в первую версию (большое делит на несколько стори). Аналитик пишет критерии приёмки и задаёт до трёх вопросов — у каждого есть вариант по умолчанию; не ответите за 30 минут (ночью — до утра), он возьмёт его сам. Их реплики — во вкладке Comments стори и в чате проекта. Включается в «⋯ Настройки проекта → Продакт и аналитик», в новых проектах включено.</li>
|
||||||
<li><b>Команда</b> — агенты Пеппы с именами (Айгерим, Нурлан…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его имя видно на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.</li>
|
<li><b>Команда</b> — агенты Пеппы с именами (Айгерим, Нурлан…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его имя видно на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.</li>
|
||||||
<li><b>Вход</b> — только через eGov QR (с телефона — кнопка «Открыть в eGov Mobile»). Первый вход сам создаёт учётку по ИИН: логин из имени в сертификате (например, <span className="font-mono">aigerim.ivanova</span>). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве <span className="font-mono">peppa-bot</span>.</li>
|
<li><b>Вход</b> — только через eGov QR (с телефона — кнопка «Открыть в eGov Mobile»). Первый вход сам создаёт учётку по ИИН: логин из имени в сертификате (например, <span className="font-mono">aigerim.ivanova</span>). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве <span className="font-mono">peppa-bot</span>.</li>
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
import { connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core";
|
import { connectedApps, getNotifyPrefs, isLocalUser, isSuperadmin, listUserProjects, maskIin, NOTIFY_EVENT_NAMES, NOTIFY_EVENTS, userPushSubscriptions, vapidPublicKey } from "@peppa/core";
|
||||||
import { Hidden } from "@/components/cards";
|
import { Hidden } from "@/components/cards";
|
||||||
import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
|
import { ago, Disclosure, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Card } from "@/components/ui/card";
|
import { Card } from "@/components/ui/card";
|
||||||
import { Input, Label } from "@/components/ui/input";
|
import { Input, Label } from "@/components/ui/input";
|
||||||
@ -8,12 +8,20 @@ import { EgovSign } from "@/components/EgovSign";
|
|||||||
import { Workspace } from "@/components/Workspace";
|
import { Workspace } from "@/components/Workspace";
|
||||||
import { publicOrigin, requireUser } from "@/lib/auth";
|
import { publicOrigin, requireUser } from "@/lib/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { pairTelegram, revokeConnectedApp, saveNotifyPrefsAction, unpairTelegramAction } from "../actions";
|
import { connectOwnBotAction, disconnectOwnBotAction, pairTelegram, revokeConnectedApp, saveNotifyPrefsAction, unpairTelegramAction } from "../actions";
|
||||||
import { PushNotifications } from "@/components/PushNotifications";
|
import { PushNotifications } from "@/components/PushNotifications";
|
||||||
import { TimezoneField } from "@/components/TimezoneField";
|
import { TimezoneField } from "@/components/TimezoneField";
|
||||||
|
|
||||||
const back = { back: "/settings" };
|
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. */
|
/** 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 }) {
|
function Row({ title, children, actions }: { title: React.ReactNode; children?: React.ReactNode; actions?: React.ReactNode }) {
|
||||||
return (
|
return (
|
||||||
@ -27,9 +35,10 @@ function Row({ title, children, actions }: { title: React.ReactNode; children?:
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; egov?: string; notify?: string }> }) {
|
export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; egov?: string; notify?: string; bot?: string }> }) {
|
||||||
const user = await requireUser();
|
const user = await requireUser();
|
||||||
const { error, egov, notify } = await searchParams;
|
const { error, egov, notify, bot } = await searchParams;
|
||||||
|
const hasBot = !!user.telegramBotUsername;
|
||||||
const local = isLocalUser(user);
|
const local = isLocalUser(user);
|
||||||
const superadmin = await isSuperadmin(db, user);
|
const superadmin = await isSuperadmin(db, user);
|
||||||
const apps = await connectedApps(db, user.id);
|
const apps = await connectedApps(db, user.id);
|
||||||
@ -38,6 +47,76 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
|||||||
const myProjects = await listUserProjects(db, user.id);
|
const myProjects = await listUserProjects(db, user.id);
|
||||||
const pushSubs = await userPushSubscriptions(db, user.id);
|
const pushSubs = await userPushSubscriptions(db, user.id);
|
||||||
const vapid = await vapidPublicKey(db);
|
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 (
|
return (
|
||||||
<Workspace>
|
<Workspace>
|
||||||
<div className="max-w-2xl">
|
<div className="max-w-2xl">
|
||||||
@ -111,6 +190,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
|||||||
{user.egovIin && egov === "linked" && <Notice>eGov привязан — теперь можно входить по QR</Notice>}
|
{user.egovIin && egov === "linked" && <Notice>eGov привязан — теперь можно входить по QR</Notice>}
|
||||||
|
|
||||||
<Section title="Telegram" id="telegram">
|
<Section title="Telegram" id="telegram">
|
||||||
|
{bot === "connected" && <Notice>Бот @{user.telegramBotUsername} подключён — остался последний шаг: откройте его и нажмите Start.</Notice>}
|
||||||
{user.telegramChatId ? (
|
{user.telegramChatId ? (
|
||||||
<Row
|
<Row
|
||||||
title={`Telegram привязан${user.telegramUsername ? ` (@${user.telegramUsername})` : ""}`}
|
title={`Telegram привязан${user.telegramUsername ? ` (@${user.telegramUsername})` : ""}`}
|
||||||
@ -121,20 +201,21 @@ export default async function Settings({ searchParams }: { searchParams: Promise
|
|||||||
</form>
|
</form>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
Вопросы агентов из ваших и общих проектов приходят в этот чат.
|
Вопросы агентов и «готово к ревью» приходят вам {user.telegramBotUsername ? <>от вашего бота <span className="font-mono">@{user.telegramBotUsername}</span></> : "от общего бота Пеппы"}. Новую задачу можно просто написать боту.
|
||||||
</Row>
|
</Row>
|
||||||
) : (
|
) : (
|
||||||
<Row
|
ownBotSteps
|
||||||
title="Telegram не привязан"
|
)}
|
||||||
actions={
|
{user.telegramChatId && !hasBot && (
|
||||||
<form action={pairTelegram}>
|
<Disclosure summary="Перейти на своего бота">
|
||||||
<Hidden fields={back} />
|
<div className="px-4 pb-4">{ownBotSteps}</div>
|
||||||
<Button variant="default" size="sm">Привязать Telegram</Button>
|
</Disclosure>
|
||||||
</form>
|
)}
|
||||||
}
|
{user.telegramChatId && hasBot && (
|
||||||
>
|
<form action={disconnectOwnBotAction}>
|
||||||
Бот присылает вопросы агентов и «готово к ревью» с кнопками. Нажмите кнопку — откроется бот, в нём нажмите Start.
|
<Hidden fields={back} />
|
||||||
</Row>
|
<Button size="xs" variant="ghost" className="text-muted-foreground">Отключить бота @{user.telegramBotUsername}</Button>
|
||||||
|
</form>
|
||||||
)}
|
)}
|
||||||
</Section>
|
</Section>
|
||||||
<Section title="Уведомления" id="notifications">
|
<Section title="Уведомления" id="notifications">
|
||||||
|
|||||||
@ -0,0 +1,18 @@
|
|||||||
|
# PEP-85: свой Telegram-бот у каждого пользователя
|
||||||
|
|
||||||
|
## Why
|
||||||
|
PM: у каждого пользователя должен быть свой Telegram-бот, через который он управляет своей фабрикой. Сейчас бот один на
|
||||||
|
всех (`TELEGRAM_BOT_TOKEN`), у пользователей с ним только личные чаты.
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
- `users.telegram_bot_token_enc` (шифруется, входит в ротацию `PEPPA_SECRET`) и `telegram_bot_username` — миграция 0016.
|
||||||
|
- core/telegram.ts: `verifyBotToken` (getMe у Telegram), `setUserBot` (проверка, один бот — один пользователь, сброс привязки чата),
|
||||||
|
`clearUserBot`, `userBots`. Код привязки, пришедший через свой бот, привязывает только его владельца; общий бот не привязывает
|
||||||
|
того, у кого есть свой. Offset и id обновлений — отдельные на каждого бота.
|
||||||
|
- Бот-процесс: `syncOwnBots` раз в 10 с запускает и останавливает опрос своих ботов; обновление обрабатывается «через» бота,
|
||||||
|
в который пришло (AsyncLocalStorage); исходящие (вопросы, «готово», дайджест) уходят через бота владельца чата, остальное —
|
||||||
|
через общий. Свой бот отвечает только владельцу. Отозванный токен (401) — пауза минуту между попытками.
|
||||||
|
- Веб «Настройки → Telegram»: три шага (BotFather → токен → Start в своём боте); общий бот — запасной вариант; у привязанных
|
||||||
|
к общему — «Перейти на своего бота». Шаг онбординга переименован.
|
||||||
|
|
||||||
|
Вне scope: группы и каналы через свой бот (остаются на общем), вебхуки вместо опроса. Открытых вопросов нет.
|
||||||
@ -0,0 +1,24 @@
|
|||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Свой бот пользователя
|
||||||
|
Пользователь SHALL подключать собственного Telegram-бота, вставив его токен в
|
||||||
|
«Настройки → Telegram»; токен проверяется у Telegram и хранится зашифрованным. Вопросы
|
||||||
|
агентов и сообщения его проектов SHALL приходить ему из его бота, а его ответы — приниматься
|
||||||
|
через него. Свой бот SHALL отвечать только владельцу.
|
||||||
|
|
||||||
|
#### Scenario: Подключение
|
||||||
|
- **WHEN** пользователь вставляет токен от BotFather и затем нажимает Start в своём боте по ссылке из Пеппы
|
||||||
|
- **THEN** чат привязан, следующий вопрос агента приходит из его бота, из общего бота — ничего
|
||||||
|
|
||||||
|
#### Scenario: Неверный токен
|
||||||
|
- **WHEN** пользователь вставляет строку, которую Telegram не принимает
|
||||||
|
- **THEN** бот не подключён, показано, что токен нужно скопировать целиком
|
||||||
|
|
||||||
|
#### Scenario: Чужой человек
|
||||||
|
- **WHEN** в бот пользователя пишет другой человек или приходит чужой код привязки
|
||||||
|
- **THEN** бот не привязывает его и на команды не отвечает
|
||||||
|
|
||||||
|
#### Scenario: Общий бот
|
||||||
|
- **GIVEN** пользователь без своего бота, привязанный к общему
|
||||||
|
- **WHEN** агент его проекта задаёт вопрос
|
||||||
|
- **THEN** вопрос приходит из общего бота, как раньше
|
||||||
@ -0,0 +1,5 @@
|
|||||||
|
- [x] 1 Схема и миграция 0016, шифрованная колонка в ревизии секретов
|
||||||
|
- [x] 2 core: проверка токена, подключение и отключение, привязка только владельца, offset и id по ботам
|
||||||
|
- [x] 3 Бот-процесс: опрос своих ботов, маршрутизация ответов и исходящих
|
||||||
|
- [x] 4 Веб: шаги подключения, действия, онбординг
|
||||||
|
- [x] 5 `own-bot.test.ts` на двух mock-telegram, регресс `bot.test.ts`, `openspec validate`
|
||||||
@ -81,3 +81,26 @@ Telegram-бот Пеппы: однократная обработка updates,
|
|||||||
- **GIVEN** у пользователя в проектах работают 2 сессии и открыт 1 вопрос
|
- **GIVEN** у пользователя в проектах работают 2 сессии и открыт 1 вопрос
|
||||||
- **WHEN** он пишет `/status`
|
- **WHEN** он пишет `/status`
|
||||||
- **THEN** бот отвечает «Активные сессии: 2» со списком и «Открытых вопросов: 1»
|
- **THEN** бот отвечает «Активные сессии: 2» со списком и «Открытых вопросов: 1»
|
||||||
|
|
||||||
|
### Requirement: Свой бот пользователя
|
||||||
|
Пользователь SHALL подключать собственного Telegram-бота, вставив его токен в
|
||||||
|
«Настройки → Telegram»; токен проверяется у Telegram и хранится зашифрованным. Вопросы
|
||||||
|
агентов и сообщения его проектов SHALL приходить ему из его бота, а его ответы — приниматься
|
||||||
|
через него. Свой бот SHALL отвечать только владельцу.
|
||||||
|
|
||||||
|
#### Scenario: Подключение
|
||||||
|
- **WHEN** пользователь вставляет токен от BotFather и затем нажимает Start в своём боте по ссылке из Пеппы
|
||||||
|
- **THEN** чат привязан, следующий вопрос агента приходит из его бота, из общего бота — ничего
|
||||||
|
|
||||||
|
#### Scenario: Неверный токен
|
||||||
|
- **WHEN** пользователь вставляет строку, которую Telegram не принимает
|
||||||
|
- **THEN** бот не подключён, показано, что токен нужно скопировать целиком
|
||||||
|
|
||||||
|
#### Scenario: Чужой человек
|
||||||
|
- **WHEN** в бот пользователя пишет другой человек или приходит чужой код привязки
|
||||||
|
- **THEN** бот не привязывает его и на команды не отвечает
|
||||||
|
|
||||||
|
#### Scenario: Общий бот
|
||||||
|
- **GIVEN** пользователь без своего бота, привязанный к общему
|
||||||
|
- **WHEN** агент его проекта задаёт вопрос
|
||||||
|
- **THEN** вопрос приходит из общего бота, как раньше
|
||||||
|
|||||||
@ -53,9 +53,9 @@ export async function onboardingChecklist(db: Db, user: Pick<User, "id" | "login
|
|||||||
// PEP-83: written for a product manager, not a programmer — what to do and why, in order.
|
// PEP-83: written for a product manager, not a programmer — what to do and why, in order.
|
||||||
const telegram: OnboardingStep = {
|
const telegram: OnboardingStep = {
|
||||||
id: "telegram",
|
id: "telegram",
|
||||||
title: "Привяжите Telegram",
|
title: "Подключите своего Telegram-бота",
|
||||||
hint: "Бот на телефоне позовёт вас, когда агенту нужен ответ или когда работа готова. Отвечать можно кнопками, не открывая ноутбук.",
|
hint: "Через него фабрика позовёт вас, когда агенту нужен ответ или когда работа готова. Отвечать можно кнопками с телефона. Бот создаётся за две минуты — в настройках есть шаги.",
|
||||||
action: "Привязать Telegram",
|
action: "Подключить Telegram",
|
||||||
href: "/settings#telegram",
|
href: "/settings#telegram",
|
||||||
done: me?.chat != null,
|
done: me?.chat != null,
|
||||||
optional: false,
|
optional: false,
|
||||||
|
|||||||
@ -185,6 +185,7 @@ function encryptedColumns(db: Db) {
|
|||||||
{ table: "users", column: "access_token_enc", rows: () => db.select({ id: users.id, enc: users.accessTokenEnc }).from(users).where(isNotNull(users.accessTokenEnc)), set: (id: number, enc: string) => db.update(users).set({ accessTokenEnc: enc }).where(eq(users.id, id)) },
|
{ table: "users", column: "access_token_enc", rows: () => db.select({ id: users.id, enc: users.accessTokenEnc }).from(users).where(isNotNull(users.accessTokenEnc)), set: (id: number, enc: string) => db.update(users).set({ accessTokenEnc: enc }).where(eq(users.id, id)) },
|
||||||
{ table: "users", column: "refresh_token_enc", rows: () => db.select({ id: users.id, enc: users.refreshTokenEnc }).from(users).where(isNotNull(users.refreshTokenEnc)), set: (id: number, enc: string) => db.update(users).set({ refreshTokenEnc: enc }).where(eq(users.id, id)) },
|
{ table: "users", column: "refresh_token_enc", rows: () => db.select({ id: users.id, enc: users.refreshTokenEnc }).from(users).where(isNotNull(users.refreshTokenEnc)), set: (id: number, enc: string) => db.update(users).set({ refreshTokenEnc: enc }).where(eq(users.id, id)) },
|
||||||
{ table: "users", column: "claude_token_enc", rows: () => db.select({ id: users.id, enc: users.claudeTokenEnc }).from(users).where(isNotNull(users.claudeTokenEnc)), set: (id: number, enc: string) => db.update(users).set({ claudeTokenEnc: enc }).where(eq(users.id, id)) },
|
{ table: "users", column: "claude_token_enc", rows: () => db.select({ id: users.id, enc: users.claudeTokenEnc }).from(users).where(isNotNull(users.claudeTokenEnc)), set: (id: number, enc: string) => db.update(users).set({ claudeTokenEnc: enc }).where(eq(users.id, id)) },
|
||||||
|
{ table: "users", column: "telegram_bot_token_enc", rows: () => db.select({ id: users.id, enc: users.telegramBotTokenEnc }).from(users).where(isNotNull(users.telegramBotTokenEnc)), set: (id: number, enc: string) => db.update(users).set({ telegramBotTokenEnc: enc }).where(eq(users.id, id)) },
|
||||||
{ table: "subscriptions", column: "secret_enc", rows: () => db.select({ id: subscriptions.id, enc: subscriptions.secretEnc }).from(subscriptions).where(isNotNull(subscriptions.secretEnc)), set: (id: number, enc: string) => db.update(subscriptions).set({ secretEnc: enc }).where(eq(subscriptions.id, id)) },
|
{ table: "subscriptions", column: "secret_enc", rows: () => db.select({ id: subscriptions.id, enc: subscriptions.secretEnc }).from(subscriptions).where(isNotNull(subscriptions.secretEnc)), set: (id: number, enc: string) => db.update(subscriptions).set({ secretEnc: enc }).where(eq(subscriptions.id, id)) },
|
||||||
{ table: "project_secrets", column: "value_enc", rows: () => db.select({ id: projectSecrets.id, enc: projectSecrets.valueEnc }).from(projectSecrets), set: (id: number, enc: string) => db.update(projectSecrets).set({ valueEnc: enc }).where(eq(projectSecrets.id, id)) },
|
{ table: "project_secrets", column: "value_enc", rows: () => db.select({ id: projectSecrets.id, enc: projectSecrets.valueEnc }).from(projectSecrets), set: (id: number, enc: string) => db.update(projectSecrets).set({ valueEnc: enc }).where(eq(projectSecrets.id, id)) },
|
||||||
];
|
];
|
||||||
|
|||||||
@ -2,6 +2,8 @@ import { createHmac, randomBytes } from "node:crypto";
|
|||||||
import { projectMembers, projects, questions, telegramOutbox, telegramUpdates, users, type Db } from "@peppa/db";
|
import { projectMembers, projects, questions, telegramOutbox, telegramUpdates, users, type Db } from "@peppa/db";
|
||||||
import { and, asc, eq, gt, inArray, isNotNull, lte, sql } from "drizzle-orm";
|
import { and, asc, eq, gt, inArray, isNotNull, lte, sql } from "drizzle-orm";
|
||||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||||
|
import { decrypt, encrypt } from "./crypto.ts";
|
||||||
|
import { PeppaError } from "./errors.ts";
|
||||||
import type { User } from "./users.ts";
|
import type { User } from "./users.ts";
|
||||||
|
|
||||||
export type OutboxRow = typeof telegramOutbox.$inferSelect;
|
export type OutboxRow = typeof telegramOutbox.$inferSelect;
|
||||||
@ -24,13 +26,19 @@ export async function acceptPairing(
|
|||||||
db: Db,
|
db: Db,
|
||||||
secret: string,
|
secret: string,
|
||||||
code: string,
|
code: string,
|
||||||
who: { chatId: number; userId: number; username?: string | null },
|
who: { chatId: number; userId: number; username?: string | null; /** PEP-85: the owner of the bot the code came through (absent = the shared bot). */ botUserId?: number },
|
||||||
): Promise<User | null> {
|
): Promise<User | null> {
|
||||||
const key = pairKey(code, secret);
|
const key = pairKey(code, secret);
|
||||||
const saved = await getSetting<{ userId: number; expiresAt: number }>(db, key);
|
const saved = await getSetting<{ userId: number; expiresAt: number }>(db, key);
|
||||||
if (!saved) return null;
|
if (!saved) return null;
|
||||||
await deleteSetting(db, key);
|
await deleteSetting(db, key);
|
||||||
if (Date.now() >= saved.expiresAt) return null;
|
if (Date.now() >= saved.expiresAt) return null;
|
||||||
|
// A user's own bot pairs only its owner; the shared bot never pairs someone who has their own.
|
||||||
|
if (who.botUserId != null && who.botUserId !== saved.userId) return null;
|
||||||
|
if (who.botUserId == null) {
|
||||||
|
const [owner] = await db.select({ own: users.telegramBotTokenEnc }).from(users).where(eq(users.id, saved.userId));
|
||||||
|
if (owner?.own) return null;
|
||||||
|
}
|
||||||
await db
|
await db
|
||||||
.update(users)
|
.update(users)
|
||||||
.set({ telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null })
|
.set({ telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null })
|
||||||
@ -65,21 +73,88 @@ export async function questionRecipients(db: Db, projectId: number): Promise<Use
|
|||||||
return db.select().from(users).where(and(inArray(users.id, ids), isNotNull(users.telegramChatId)));
|
return db.select().from(users).where(and(inArray(users.id, ids), isNotNull(users.telegramChatId)));
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getOffset = async (db: Db) => (await getSetting<number>(db, OFFSET)) ?? 0;
|
// PEP-85: every bot has its own update ids and offset. `botUserId` = the owner of a user's bot;
|
||||||
export const setOffset = (db: Db, offset: number) => setSetting(db, OFFSET, offset);
|
// absent = the platform's shared bot (ids and the offset key as before).
|
||||||
|
const offsetKey = (botUserId?: number) => (botUserId ? `${OFFSET}:u${botUserId}` : OFFSET);
|
||||||
|
export const getOffset = async (db: Db, botUserId?: number) => (await getSetting<number>(db, offsetKey(botUserId))) ?? 0;
|
||||||
|
export const setOffset = (db: Db, offset: number, botUserId?: number) => setSetting(db, offsetKey(botUserId), offset);
|
||||||
|
/** Update ids of different bots must not collide in `telegram_updates`. */
|
||||||
|
const updateKey = (updateId: number, botUserId?: number) => (botUserId ? botUserId * 2 ** 36 + updateId : updateId);
|
||||||
|
|
||||||
/** Claims an update before acting on it. False = already taken (don't replay). */
|
/** Claims an update before acting on it. False = already taken (don't replay). */
|
||||||
export async function claimUpdate(db: Db, updateId: number): Promise<boolean> {
|
export async function claimUpdate(db: Db, updateId: number, botUserId?: number): Promise<boolean> {
|
||||||
const rows = await db
|
const rows = await db
|
||||||
.insert(telegramUpdates)
|
.insert(telegramUpdates)
|
||||||
.values({ updateId, status: "dispatching" })
|
.values({ updateId: updateKey(updateId, botUserId), status: "dispatching" })
|
||||||
.onConflictDoNothing()
|
.onConflictDoNothing()
|
||||||
.returning();
|
.returning();
|
||||||
return rows.length > 0;
|
return rows.length > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function finishUpdate(db: Db, updateId: number, status: "done" | "ignored" | "failed"): Promise<void> {
|
export async function finishUpdate(db: Db, updateId: number, status: "done" | "ignored" | "failed", botUserId?: number): Promise<void> {
|
||||||
await db.update(telegramUpdates).set({ status }).where(eq(telegramUpdates.updateId, updateId));
|
await db.update(telegramUpdates).set({ status }).where(eq(telegramUpdates.updateId, updateKey(updateId, botUserId)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── PEP-85: the user's own bot ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export const BOT_TOKEN_RE = /^\d{5,15}:[A-Za-z0-9_-]{30,60}$/;
|
||||||
|
|
||||||
|
export interface UserBot {
|
||||||
|
userId: number;
|
||||||
|
token: string;
|
||||||
|
username: string;
|
||||||
|
/** The chat the owner started the bot in (null until they press Start). */
|
||||||
|
chatId: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Asks Telegram who the token belongs to (`TELEGRAM_API_URL` for the mock). */
|
||||||
|
export async function verifyBotToken(token: string): Promise<{ id: number; username: string }> {
|
||||||
|
const t = token.trim();
|
||||||
|
if (!BOT_TOKEN_RE.test(t)) throw new PeppaError("Это не похоже на токен бота. Он выглядит так: 1234567890:AAH… — скопируйте его целиком из сообщения BotFather");
|
||||||
|
let body: { ok?: boolean; result?: { id: number; username?: string; is_bot?: boolean }; description?: string };
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${process.env.TELEGRAM_API_URL ?? "https://api.telegram.org"}/bot${t}/getMe`, { signal: AbortSignal.timeout(15_000) });
|
||||||
|
body = (await res.json()) as typeof body;
|
||||||
|
} catch {
|
||||||
|
throw new PeppaError("Telegram не ответил — попробуйте ещё раз через минуту");
|
||||||
|
}
|
||||||
|
if (!body.ok || !body.result?.username) throw new PeppaError("Telegram не принял этот токен — проверьте, что скопировали его целиком, или получите новый в BotFather (/token)");
|
||||||
|
return { id: body.result.id, username: body.result.username };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Connects the user's own bot. The chat pairing is dropped: the owner presses Start in the new bot. */
|
||||||
|
export async function setUserBot(db: Db, userId: number, token: string): Promise<{ username: string }> {
|
||||||
|
const me = await verifyBotToken(token);
|
||||||
|
const taken = (await db.select({ id: users.id, username: users.telegramBotUsername }).from(users).where(isNotNull(users.telegramBotUsername))).find((u) => u.id !== userId && u.username?.toLowerCase() === me.username.toLowerCase());
|
||||||
|
if (taken) throw new PeppaError("Этот бот уже подключён другим пользователем — создайте своего в BotFather");
|
||||||
|
await db
|
||||||
|
.update(users)
|
||||||
|
.set({ telegramBotTokenEnc: encrypt(token.trim()), telegramBotUsername: me.username, telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null })
|
||||||
|
.where(eq(users.id, userId));
|
||||||
|
return { username: me.username };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Back to the platform's shared bot (the chat pairing is dropped too). */
|
||||||
|
export async function clearUserBot(db: Db, userId: number): Promise<void> {
|
||||||
|
await db
|
||||||
|
.update(users)
|
||||||
|
.set({ telegramBotTokenEnc: null, telegramBotUsername: null, telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null })
|
||||||
|
.where(eq(users.id, userId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every connected own bot (the bot process polls them and sends through them). */
|
||||||
|
export async function userBots(db: Db): Promise<UserBot[]> {
|
||||||
|
const rows = await db.select().from(users).where(isNotNull(users.telegramBotTokenEnc));
|
||||||
|
const out: UserBot[] = [];
|
||||||
|
for (const u of rows) {
|
||||||
|
if (u.disabledAt) continue;
|
||||||
|
try {
|
||||||
|
out.push({ userId: u.id, token: decrypt(u.telegramBotTokenEnc!), username: u.telegramBotUsername ?? "", chatId: u.telegramChatId });
|
||||||
|
} catch {
|
||||||
|
// Unreadable after a key rotation gone wrong: skipped, the secrets audit shows it.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Queues a Bot API call; a no-op if `dedupeKey` was queued before. */
|
/** Queues a Bot API call; a no-op if `dedupeKey` was queued before. */
|
||||||
|
|||||||
2
packages/db/migrations/0016_user_telegram_bot.sql
Normal file
2
packages/db/migrations/0016_user_telegram_bot.sql
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE `users` ADD `telegram_bot_token_enc` text;--> statement-breakpoint
|
||||||
|
ALTER TABLE `users` ADD `telegram_bot_username` text;
|
||||||
4120
packages/db/migrations/meta/0016_snapshot.json
Normal file
4120
packages/db/migrations/meta/0016_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@ -113,6 +113,13 @@
|
|||||||
"when": 1794665444878,
|
"when": 1794665444878,
|
||||||
"tag": "0015_chats",
|
"tag": "0015_chats",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 16,
|
||||||
|
"version": "6",
|
||||||
|
"when": 1794678698233,
|
||||||
|
"tag": "0016_user_telegram_bot",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@ -31,6 +31,10 @@ export const users = sqliteTable("users", {
|
|||||||
telegramUserId: integer("telegram_user_id"),
|
telegramUserId: integer("telegram_user_id"),
|
||||||
telegramUsername: text("telegram_username"),
|
telegramUsername: text("telegram_username"),
|
||||||
telegramPairedAt: integer("telegram_paired_at", { mode: "timestamp_ms" }),
|
telegramPairedAt: integer("telegram_paired_at", { mode: "timestamp_ms" }),
|
||||||
|
// PEP-85: the user's own bot (created in BotFather): its token, AES-256-GCM like every secret,
|
||||||
|
// and its @username. Null = the platform's shared bot.
|
||||||
|
telegramBotTokenEnc: text("telegram_bot_token_enc"),
|
||||||
|
telegramBotUsername: text("telegram_bot_username"),
|
||||||
// eGov login (PEP-65): the signer's IIN from the certificate, one account per IIN.
|
// eGov login (PEP-65): the signer's IIN from the certificate, one account per IIN.
|
||||||
egovIin: text("egov_iin").unique(),
|
egovIin: text("egov_iin").unique(),
|
||||||
egovLinkedAt: integer("egov_linked_at", { mode: "timestamp_ms" }),
|
egovLinkedAt: integer("egov_linked_at", { mode: "timestamp_ms" }),
|
||||||
|
|||||||
@ -23,7 +23,11 @@ const chatType = (chatId: number) => (chatId < 0 ? "group" : "private");
|
|||||||
|
|
||||||
export class MockTelegram {
|
export class MockTelegram {
|
||||||
readonly token = "mock-123:TOKEN";
|
readonly token = "mock-123:TOKEN";
|
||||||
readonly bot = { id: 999, username: "mock_peppa_bot", is_bot: true, first_name: "Mock Peppa" };
|
/** PEP-85: a second instance stands in for a user's own bot — give it its own identity. */
|
||||||
|
constructor(bot: { id?: number; username?: string } = {}) {
|
||||||
|
this.bot = { id: bot.id ?? 999, username: bot.username ?? "mock_peppa_bot", is_bot: true, first_name: "Mock Peppa" };
|
||||||
|
}
|
||||||
|
readonly bot: { id: number; username: string; is_bot: boolean; first_name: string };
|
||||||
readonly messages = new Map<number, MockTgMessage>();
|
readonly messages = new Map<number, MockTgMessage>();
|
||||||
readonly callbackAnswers: Array<{ id: string; text?: string }> = [];
|
readonly callbackAnswers: Array<{ id: string; text?: string }> = [];
|
||||||
readonly calls: Array<{ method: string; params: Record<string, unknown> }> = [];
|
readonly calls: Array<{ method: string; params: Record<string, unknown> }> = [];
|
||||||
|
|||||||
118
packages/testkit/test/own-bot.test.ts
Normal file
118
packages/testkit/test/own-bot.test.ts
Normal file
@ -0,0 +1,118 @@
|
|||||||
|
// PEP-85: a user's own Telegram bot — the token from BotFather, pairing by Start in that bot,
|
||||||
|
// questions arrive from it, the shared bot keeps serving everybody else. Two mock-telegram
|
||||||
|
// instances: the platform's bot and the user's.
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { after, before, describe, test } from "node:test";
|
||||||
|
import { core, db, teardown, waitFor } from "./helpers.ts";
|
||||||
|
import { MockTelegram } from "../src/mock-telegram.ts";
|
||||||
|
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 shared = await new MockTelegram().start();
|
||||||
|
const own = await new MockTelegram({ id: 4242, username: "mock_alice_factory_bot" }).start();
|
||||||
|
const OWN_TOKEN = "1234567890:" + "A".repeat(35);
|
||||||
|
const ALICE = { id: 601, chatId: 601, username: "alice" };
|
||||||
|
const BOB = { id: 602, chatId: 602, username: "bob" };
|
||||||
|
const EVE = { id: 666, chatId: 666, username: "eve" };
|
||||||
|
let bot: Bot;
|
||||||
|
let alice: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||||
|
let bob: typeof alice;
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
alice = await core.upsertUserFromGitea(db, { id: 8501, login: "mock-own-alice" }, { access_token: "x" });
|
||||||
|
bob = await core.upsertUserFromGitea(db, { id: 8502, login: "mock-own-bob" }, { access_token: "y" });
|
||||||
|
bot = createBot({
|
||||||
|
db,
|
||||||
|
api: new TelegramApi(shared.token, shared.url),
|
||||||
|
userApi: (token) => new TelegramApi(token, own.url),
|
||||||
|
secret: shared.token,
|
||||||
|
webUrl: "http://peppa.test",
|
||||||
|
pollTimeoutSec: 1,
|
||||||
|
outboxIntervalMs: 100,
|
||||||
|
reconcileIntervalMs: 400,
|
||||||
|
userBotsIntervalMs: 200,
|
||||||
|
});
|
||||||
|
await bot.start();
|
||||||
|
});
|
||||||
|
after(async () => {
|
||||||
|
await bot.stop();
|
||||||
|
await shared.stop();
|
||||||
|
await own.stop();
|
||||||
|
await teardown();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("свой Telegram-бот", () => {
|
||||||
|
test("Scenario: токен проверяется у Telegram; привязка — Start в своём боте; вопрос приходит из него", async () => {
|
||||||
|
await assert.rejects(core.setUserBot(db, alice.id, "не токен"), /не похоже на токен бота/);
|
||||||
|
process.env.TELEGRAM_API_URL = own.url;
|
||||||
|
try {
|
||||||
|
own.failNext("getMe", 401);
|
||||||
|
await assert.rejects(core.setUserBot(db, alice.id, OWN_TOKEN), /Telegram не принял этот токен/);
|
||||||
|
assert.deepEqual(await core.setUserBot(db, alice.id, OWN_TOKEN), { username: "mock_alice_factory_bot" });
|
||||||
|
await assert.rejects(core.setUserBot(db, bob.id, OWN_TOKEN), /уже подключён другим пользователем/);
|
||||||
|
} finally {
|
||||||
|
delete process.env.TELEGRAM_API_URL;
|
||||||
|
}
|
||||||
|
const saved = (await core.getUser(db, alice.id))!;
|
||||||
|
assert.equal(saved.telegramBotUsername, "mock_alice_factory_bot");
|
||||||
|
assert.ok(saved.telegramBotTokenEnc && !saved.telegramBotTokenEnc.includes(OWN_TOKEN), "stored encrypted");
|
||||||
|
assert.deepEqual((await core.userBots(db)).map((b) => [b.userId, b.token, b.chatId]), [[alice.id, OWN_TOKEN, null]]);
|
||||||
|
await bot.syncOwnBots();
|
||||||
|
|
||||||
|
// The owner's code works only in her own bot.
|
||||||
|
const code = await core.createPairingCode(db, shared.token, alice.id);
|
||||||
|
shared.userSends(ALICE, `/start ${code}`);
|
||||||
|
await waitFor("the shared bot refuses", async () => shared.botMessages(ALICE.chatId).some((m) => /неверный или истёк/.test(m.text)));
|
||||||
|
assert.equal((await core.getUser(db, alice.id))!.telegramChatId, null);
|
||||||
|
|
||||||
|
// Somebody else's code does not work in her bot either.
|
||||||
|
own.userSends(EVE, `/start ${await core.createPairingCode(db, shared.token, bob.id)}`);
|
||||||
|
await waitFor("her bot refuses a stranger", async () => own.botMessages(EVE.chatId).some((m) => /неверный или истёк/.test(m.text)));
|
||||||
|
assert.equal((await core.getUser(db, bob.id))!.telegramChatId, null);
|
||||||
|
|
||||||
|
own.userSends(ALICE, `/start ${await core.createPairingCode(db, shared.token, alice.id)}`);
|
||||||
|
await waitFor("paired in the own bot", async () => own.botMessages(ALICE.chatId).some((m) => /Привязано/.test(m.text)));
|
||||||
|
assert.equal((await core.getUser(db, alice.id))!.telegramChatId, ALICE.chatId);
|
||||||
|
|
||||||
|
// A question of her project comes from her bot, not from the shared one.
|
||||||
|
const p = await core.createProject(db, { slug: "mock-own-a", key: "MOWNA", name: "Own A", giteaOwner: "x", workspacePath: "/tmp/mock-own-a", ownerId: alice.id });
|
||||||
|
const ref = await core.createTask(db, { projectId: p.id, title: "Каталог" });
|
||||||
|
const sharedBefore = shared.botMessages(ALICE.chatId).length;
|
||||||
|
const q = await core.askPm(db, ref, { kind: "question", text: "Нужна ли мобильная версия?" });
|
||||||
|
await waitFor("question in the own bot", async () => own.botMessages(ALICE.chatId).some((m) => m.text.includes("Нужна ли мобильная версия?")));
|
||||||
|
assert.equal(shared.botMessages(ALICE.chatId).length, sharedBefore, "nothing through the shared bot");
|
||||||
|
|
||||||
|
// She answers by a reply in her bot.
|
||||||
|
const msg = own.botMessages(ALICE.chatId).find((m) => m.text.includes("Нужна ли мобильная версия?"))!;
|
||||||
|
own.userSends(ALICE, "Не нужна", msg.message_id);
|
||||||
|
await waitFor("answered", async () => !!(await core.getQuestion(db, q.id)).answeredAt);
|
||||||
|
assert.equal((await core.getQuestion(db, q.id)).answer, "Не нужна");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Scenario: общий бот продолжает работать для остальных; чужому свой бот не отвечает", async () => {
|
||||||
|
shared.userSends(BOB, `/start ${await core.createPairingCode(db, shared.token, bob.id)}`);
|
||||||
|
await waitFor("bob paired with the shared bot", async () => shared.botMessages(BOB.chatId).some((m) => /Привязано/.test(m.text)));
|
||||||
|
const p = await core.createProject(db, { slug: "mock-own-b", key: "MOWNB", name: "Own B", giteaOwner: "x", workspacePath: "/tmp/mock-own-b", ownerId: bob.id });
|
||||||
|
const ref = await core.createTask(db, { projectId: p.id, title: "Оплата" });
|
||||||
|
await core.askPm(db, ref, { kind: "question", text: "Какая валюта?" });
|
||||||
|
await waitFor("bob's question in the shared bot", async () => shared.botMessages(BOB.chatId).some((m) => m.text.includes("Какая валюта?")));
|
||||||
|
assert.equal(own.botMessages(BOB.chatId).length, 0);
|
||||||
|
|
||||||
|
// Bob writes to Alice's bot: it serves its owner only.
|
||||||
|
const n = own.botMessages(BOB.chatId).length;
|
||||||
|
own.userSends(BOB, "/status");
|
||||||
|
await new Promise((r) => setTimeout(r, 1500));
|
||||||
|
assert.equal(own.botMessages(BOB.chatId).length, n);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("отключение своего бота: опрос останавливается, привязка сбрасывается", async () => {
|
||||||
|
await core.clearUserBot(db, alice.id);
|
||||||
|
await bot.syncOwnBots();
|
||||||
|
const u = (await core.getUser(db, alice.id))!;
|
||||||
|
assert.deepEqual([u.telegramBotTokenEnc, u.telegramBotUsername, u.telegramChatId], [null, null, null]);
|
||||||
|
assert.deepEqual(await core.userBots(db), []);
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue
Block a user