diff --git a/AGENTS.md b/AGENTS.md index 562a3095..5fafc5bd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,7 +7,7 @@ ## Структура - `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; входящие, проект (цели → задачи), задача (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. После правок: `next build` + `launchctl kickstart -k gui/$(id -u)/quest.telecom.peppa.web` -- `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка только через `/start <код>` (`peppa telegram pair`), чужие чаты игнорируются. Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта +- `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка у каждого пользователя своя: веб «Настройки → Telegram» (или `peppa telegram pair `), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (PEP-2). Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта - `packages/db` — Drizzle-схема и клиент (Postgres на 127.0.0.1:5433) - `packages/shared` — env, ключи задач (`PEP-42`) - `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM, pg NOTIFY `peppa_events`); всё ходит через неё diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 886d19e3..7ea93c67 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -9,9 +9,13 @@ import { enqueueTelegram, EVENTS_CHANNEL, finishUpdate, - getBinding, + answeredQuestionMessages, + projectForUser, + questionRecipients, + telegramUser, + userProjectIds, + type User, getOffset, - getOutbox, getQuestion, getSession, listSessions, @@ -25,10 +29,10 @@ import { type Question, type SessionView, } from "@peppa/core"; -import { questions, tasks, projects, type Db } from "@peppa/db"; +import { projects, tasks, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { acceptTask, answerAndDeliver, resumeSession, stopSession } from "@peppa/runner"; -import { and, eq, gt, isNotNull } from "drizzle-orm"; +import { eq } from "drizzle-orm"; import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts"; import { TelegramApi, TelegramError, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts"; @@ -76,35 +80,29 @@ export function createBot(o: BotOptions) { } /** Makes sure every open question has a message and every closed one an edit. */ + /** Makes sure every open question has a message for each recipient, and every closed one an edit. */ async function reconcile(): Promise { - const binding = await getBinding(db); - if (!binding) return; for (const q of await pendingQuestions(db)) { - if (await getOutbox(db, `q:${q.id}`)) continue; + const recipients = await questionRecipients(db, q.projectId); + if (!recipients.length) continue; const r = renderQuestion(q, await context(q)); - await enqueueTelegram(db, { - dedupeKey: `q:${q.id}`, - method: "sendMessage", - questionId: q.id, - params: { chat_id: binding.chatId, text: r.text, parse_mode: "HTML", reply_markup: { inline_keyboard: r.buttons } }, - }); + for (const u of recipients) { + await enqueueTelegram(db, { + dedupeKey: `q:${q.id}:${u.telegramChatId}`, + method: "sendMessage", + questionId: q.id, + params: { chat_id: u.telegramChatId, text: r.text, parse_mode: "HTML", reply_markup: { inline_keyboard: r.buttons } }, + }); + } } - const since = new Date(Date.now() - 24 * 3600_000); - const answered = await db - .select() - .from(questions) - .where(and(isNotNull(questions.answeredAt), isNotNull(questions.telegramMessageId), gt(questions.answeredAt, since))); - for (const q of answered) { - if (await getOutbox(db, `qa:${q.id}`)) continue; - const sent = await getOutbox(db, `q:${q.id}`); - if (!sent) continue; + for (const { sent, q } of await answeredQuestionMessages(db, new Date(Date.now() - 24 * 3600_000))) { await enqueueTelegram(db, { - dedupeKey: `qa:${q.id}`, + dedupeKey: `qa:${q.id}:${sent.params.chat_id}`, method: "editMessageText", questionId: q.id, params: { chat_id: sent.params.chat_id, - message_id: q.telegramMessageId, + message_id: sent.telegramMessageId, text: renderAnswered(String(sent.params.text), q), parse_mode: "HTML", reply_markup: { inline_keyboard: [] }, @@ -160,9 +158,16 @@ export function createBot(o: BotOptions) { return delivered ? "Отправлено в сессию ✅" : "Ответ сохранён, но сессия сейчас не запущена — агент увидит его в истории задачи."; } - async function status(): Promise { - const sessions = await listSessions(db, { active: true }); - const open = await pendingQuestions(db); + const canAccess = (user: User, projectId: number) => + projectForUser(db, user.id, projectId).then( + () => true, + () => false, + ); + + async function status(user: User): Promise { + const ids = new Set(await userProjectIds(db, user.id)); + const sessions = (await listSessions(db, { active: true })).filter((s) => ids.has(s.projectId)); + const open = (await pendingQuestions(db)).filter((q) => ids.has(q.projectId)); const lines = [`Активные сессии: ${sessions.length}`]; for (const s of sessions) lines.push(`• ${esc(s.taskKey ?? `#${s.id}`)} — ${s.status} (${s.provider})`); lines.push("", `Открытых вопросов: ${open.length}`); @@ -171,7 +176,6 @@ export function createBot(o: BotOptions) { async function onMessage(m: TgMessage): Promise<"done" | "ignored"> { const text = m.text?.trim() ?? ""; - const binding = await getBinding(db); const start = /^\/start(?:@\w+)?(?:\s+(\S+))?$/.exec(text); 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 }); @@ -180,17 +184,18 @@ export function createBot(o: BotOptions) { scheduleReconcile(); return "done"; } - await reply(m.chat.id, "Код привязки неверный или истёк. Получи новый: peppa telegram pair"); + await reply(m.chat.id, `Код привязки неверный или истёк. Получи новый: ${esc(o.webUrl)}/settings → Telegram`); return "done"; } - if (!binding || m.chat.id !== binding.chatId || m.from?.id !== binding.userId) return "ignored"; + const user = m.from ? await telegramUser(db, m.chat.id, m.from.id) : null; + if (!user) return "ignored"; if (/^\/(start|help)\b/.test(text)) return reply(m.chat.id, HELP).then(() => "done"); - if (/^\/status\b/.test(text)) return reply(m.chat.id, await status()).then(() => "done"); + if (/^\/status\b/.test(text)) return reply(m.chat.id, await status(user)).then(() => "done"); if (m.reply_to_message) { - const q = await questionByTelegramMessage(db, m.reply_to_message.message_id); - if (!q) { + const q = await questionByTelegramMessage(db, m.chat.id, m.reply_to_message.message_id); + if (!q || !(await canAccess(user, q.projectId))) { await reply(m.chat.id, "Не нашёл вопрос для этого сообщения.", m.message_id); return "done"; } @@ -202,14 +207,22 @@ export function createBot(o: BotOptions) { } async function onCallback(c: TgCallbackQuery): Promise<"done" | "ignored"> { - const binding = await getBinding(db); - if (!binding || c.from.id !== binding.userId || c.message?.chat.id !== binding.chatId) { + const user = c.message ? await telegramUser(db, c.message.chat.id, c.from.id) : null; + if (!user) { await api.answerCallbackQuery(c.id, "Нет доступа").catch(() => {}); return "ignored"; } const [kind, idStr, choice] = (c.data ?? "").split(":"); const id = Number(idStr); let toast = "Неизвестная кнопка"; + const q0 = kind === "q" ? await getQuestion(db, id).catch(() => null) : null; + const s0 = kind === "s" ? await getSession(db, id).catch(() => null) : null; + const projectId = q0?.projectId ?? s0?.projectId; + if (projectId == null || !(await canAccess(user, projectId))) { + // Unknown or someone else's question/session: don't reveal which. + await api.answerCallbackQuery(c.id, kind === "s" ? "Сессия не найдена" : "Вопрос не найден").catch(() => {}); + return "done"; + } if (kind === "q" && choice === "accept") { try { const ref = await acceptTask(db, id, "telegram"); diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 908b4570..cd72651e 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -11,7 +11,11 @@ import { resolveTask, revokeApp, setClaudeToken, + createPairingCode, + getSetting, + unpairTelegram, } from "@peppa/core"; +import { loadEnv } from "@peppa/shared"; import { acceptTask, answerAndDeliver, cancelClaudeSetup, finishClaudeSetup, moveTask, provisionProject, shareProject, startClaudeSetup, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; @@ -195,3 +199,20 @@ export async function removeProjectMember(f: FormData) { if (login.toLowerCase() === user.login.toLowerCase()) return "/"; }); } + +export async function pairTelegram(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + const token = loadEnv().TELEGRAM_BOT_TOKEN; + const bot = await getSetting<{ username: string }>(db, "telegram.bot"); + if (!token || !bot) throw new PeppaError("Telegram-бот Пеппы не запущен"); + return `https://t.me/${bot.username}?start=${await createPairingCode(db, token, user.id)}`; + }); +} + +export async function unpairTelegramAction(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + await unpairTelegram(db, user.id); + }); +} diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index 6f75bfbd..d05208af 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -77,7 +77,8 @@ export default async function Help() {

Telegram

- Бот присылает вопросы агентов и «готово к ревью» с кнопками; ответ реплаем уходит прямо в сессию агента. + Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с + кнопками; ответ реплаем уходит прямо в сессию агента.

); diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index 1221d0e4..901efd6f 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -3,7 +3,7 @@ import { ago, Flash } from "@/components/ui"; import { publicOrigin, requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; import { pendingClaudeSetup } from "@peppa/runner"; -import { cancelClaude, connectClaude, disconnectClaude, revokeConnectedApp, submitClaudeCode } from "../actions"; +import { cancelClaude, connectClaude, disconnectClaude, pairTelegram, revokeConnectedApp, submitClaudeCode, unpairTelegramAction } from "../actions"; export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; claude?: string }> }) { const user = await requireUser(); @@ -63,6 +63,29 @@ export default async function Settings({ searchParams }: { searchParams: Promise )} +

Telegram

+ {user.telegramChatId ? ( +
+
+ Telegram привязан{user.telegramUsername ? ` (@${user.telegramUsername})` : ""} +
Вопросы агентов из ваших и общих проектов приходят в этот чат.
+
+
+ + +
+
+ ) : ( +
+

+ Бот присылает вопросы агентов и «готово к ревью» с кнопками. Нажмите кнопку — откроется бот, в нём нажмите Start. +

+
+ + +
+
+ )}

MCP для ChatGPT и других клиентов

Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент diff --git a/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/.openspec.yaml b/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/.openspec.yaml new file mode 100644 index 00000000..55ab199b --- /dev/null +++ b/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-12 diff --git a/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/proposal.md b/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/proposal.md new file mode 100644 index 00000000..7cf95c5f --- /dev/null +++ b/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/proposal.md @@ -0,0 +1,30 @@ +# Proposal: PEP-2 — Telegram по пользователям + +Задача Пеппы: **PEP-2** · Цель #2. + +## Why + +У бота одна глобальная привязка: вопросы агентов из всех проектов всех пользователей +уходят в один чат. Это утечка чужих данных и мешает работать нескольким людям. + +## What Changes + +- Привязка Telegram — у каждого пользователя своя, из «Настроек» веба: кнопка ведёт в + бота с одноразовым кодом. Отвязка там же. **BREAKING**: прежняя глобальная привязка + удаляется, пользователям нужно привязаться заново. +- Вопрос агента получают владелец и участники проекта, у кого привязан Telegram. + Ответить (кнопкой или реплаем) может только тот, у кого есть доступ к проекту; + после ответа сообщение закрывается у всех получателей. +- `/status` показывает только проекты пользователя. + +## Capabilities + +### New Capabilities +- `telegram-notifications`: привязка Telegram пользователя и доставка вопросов агентов участникам проекта. + +### Modified Capabilities + +## Impact + +`packages/db` (поля Telegram у users), `packages/core/telegram.ts`, `apps/bot`, +`apps/web` (Настройки), CLI, dev-стенд, тесты бота. diff --git a/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/specs/telegram-notifications/spec.md b/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/specs/telegram-notifications/spec.md new file mode 100644 index 00000000..19c3f3de --- /dev/null +++ b/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/specs/telegram-notifications/spec.md @@ -0,0 +1,40 @@ +# Spec Delta: telegram-notifications + +## Purpose + +Определяет, как пользователь Пеппы привязывает свой Telegram и кто получает вопросы агентов и может на них отвечать. + +## ADDED Requirements + +### Requirement: Привязка из веба +Каждый пользователь SHALL привязывать свой Telegram из настроек веба по одноразовой +ссылке на бота (действует 10 минут) и отвязывать его там же. Один чат привязан не более +чем к одному пользователю. + +#### Scenario: Привязка +- **WHEN** пользователь открывает ссылку привязки и нажимает Start в боте +- **THEN** бот подтверждает привязку, в настройках виден привязанный аккаунт Telegram + +#### Scenario: Чужой или использованный код +- **WHEN** код привязки предъявлен повторно, после истечения или неверный +- **THEN** привязка не создаётся + +### Requirement: Доставка по доступу к проекту +Вопрос агента SHALL доставляться владельцу и участникам проекта, у которых привязан +Telegram, и никому больше. + +#### Scenario: Два пользователя +- **WHEN** агент проекта пользователя А задаёт вопрос, а у пользователя Б нет доступа к проекту +- **THEN** сообщение получает только А + +#### Scenario: Участник проекта +- **WHEN** у проекта есть участник с привязанным Telegram +- **THEN** вопрос получают и владелец, и участник; после ответа любого из них сообщение закрыто у обоих + +### Requirement: Ответ только с доступом +Бот SHALL принимать ответ (кнопку или реплай) только от пользователя, имеющего доступ к +проекту вопроса; сообщения из непривязанных чатов игнорируются. + +#### Scenario: Нет доступа +- **WHEN** пользователь без доступа к проекту присылает нажатие кнопки чужого вопроса +- **THEN** вопрос остаётся без ответа diff --git a/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/tasks.md b/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/tasks.md new file mode 100644 index 00000000..92074db0 --- /dev/null +++ b/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/tasks.md @@ -0,0 +1,12 @@ +# Tasks: PEP-2 + +## 1. Привязка и маршрутизация + +- [x] 1.1 Поля Telegram у `users`; core: код привязки на пользователя, приём, отвязка, получатели вопроса, поиск вопроса по (чат, сообщение) +- [x] 1.2 Бот: рассылка получателям, проверка доступа на ответы и кнопки, `/status` по своим проектам, закрытие сообщений у всех +- [x] 1.3 Веб «Настройки → Telegram»; CLI `telegram pair ` / `status` / `unpair `; dev-стенд + +## 2. Проверка + +- [x] 2.1 Тесты бота: привязка, два пользователя, участник, чужая кнопка; весь набор зелёный +- [x] 2.2 Выкатка (миграция, бот, веб), удаление глобальной привязки; `openspec validate` diff --git a/openspec/specs/telegram-notifications/spec.md b/openspec/specs/telegram-notifications/spec.md new file mode 100644 index 00000000..0d25f8fe --- /dev/null +++ b/openspec/specs/telegram-notifications/spec.md @@ -0,0 +1,39 @@ +# telegram-notifications Specification + +## Purpose +Определяет, как пользователь Пеппы привязывает свой Telegram и кто получает вопросы агентов и может на них отвечать. + +## Requirements + +### Requirement: Привязка из веба +Каждый пользователь SHALL привязывать свой Telegram из настроек веба по одноразовой +ссылке на бота (действует 10 минут) и отвязывать его там же. Один чат привязан не более +чем к одному пользователю. + +#### Scenario: Привязка +- **WHEN** пользователь открывает ссылку привязки и нажимает Start в боте +- **THEN** бот подтверждает привязку, в настройках виден привязанный аккаунт Telegram + +#### Scenario: Чужой или использованный код +- **WHEN** код привязки предъявлен повторно, после истечения или неверный +- **THEN** привязка не создаётся + +### Requirement: Доставка по доступу к проекту +Вопрос агента SHALL доставляться владельцу и участникам проекта, у которых привязан +Telegram, и никому больше. + +#### Scenario: Два пользователя +- **WHEN** агент проекта пользователя А задаёт вопрос, а у пользователя Б нет доступа к проекту +- **THEN** сообщение получает только А + +#### Scenario: Участник проекта +- **WHEN** у проекта есть участник с привязанным Telegram +- **THEN** вопрос получают и владелец, и участник; после ответа любого из них сообщение закрыто у обоих + +### Requirement: Ответ только с доступом +Бот SHALL принимать ответ (кнопку или реплай) только от пользователя, имеющего доступ к +проекту вопроса; сообщения из непривязанных чатов игнорируются. + +#### Scenario: Нет доступа +- **WHEN** пользователь без доступа к проекту присылает нажатие кнопки чужого вопроса +- **THEN** вопрос остаётся без ответа diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 582cc639..df7a99e6 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -9,7 +9,9 @@ import { getProject, createLoginLink, createPairingCode, - getBinding, + listUsers, + unpairTelegram, + upsertUserFromGitea, getSession, allowedLogins, getSetting, @@ -18,7 +20,6 @@ import { giteaForBot, setProjectOwner, getTaskDetails, - unpair, listSessions, listGoals, listProjects, @@ -56,7 +57,8 @@ const USAGE = `peppa — Peppa software factory CLI peppa session stop peppa session resume [-p ] (new generation, claude --resume) peppa platform allowlist | allow | deny (who may log into Peppa) - peppa telegram pair | status | unpair + peppa telegram pair | status | unpair (users normally pair in web Settings) + peppa user ensure mock- (local test user) peppa web login-link (one-time admin login, 10 minutes) peppa watchdog [--once] [--interval ] [--stall ] @@ -261,23 +263,35 @@ async function main(): Promise { } case "telegram pair": { if (!env.TELEGRAM_BOT_TOKEN) throw new PeppaError("TELEGRAM_BOT_TOKEN is not set in .env"); + const u = await getUserByLogin(db, args[0] ?? ""); + if (!u) throw new PeppaError("usage: peppa telegram pair (the user must exist; users normally pair in web Settings)"); const bot = await getSetting<{ username: string }>(db, "telegram.bot"); - const code = await createPairingCode(db, env.TELEGRAM_BOT_TOKEN); + const code = await createPairingCode(db, env.TELEGRAM_BOT_TOKEN, u.id); console.log(`Открой в Telegram (ссылка живёт 10 минут):\n https://t.me/${bot?.username ?? ""}?start=${code}`); - if (!bot) console.log("(бот ещё ни разу не запускался — имя подставится после первого старта peppa-bot)"); break; } case "telegram status": { - const b = await getBinding(db); const bot = await getSetting<{ username: string }>(db, "telegram.bot"); console.log(`bot: ${bot ? `@${bot.username}` : "не запускался"}`); - console.log(b ? `привязан: chat ${b.chatId}, user ${b.userId}${b.username ? ` (@${b.username})` : ""}, с ${b.pairedAt}` : "не привязан — peppa telegram pair"); + const paired = (await listUsers(db)).filter((u) => u.telegramChatId); + for (const u of paired) console.log(`${u.login}: chat ${u.telegramChatId}${u.telegramUsername ? ` (@${u.telegramUsername})` : ""}`); + if (!paired.length) console.log("никто не привязан — веб → Настройки → Telegram"); break; } - case "telegram unpair": - await unpair(db); + case "telegram unpair": { + const u = await getUserByLogin(db, args[0] ?? ""); + if (!u) throw new PeppaError("usage: peppa telegram unpair "); + await unpairTelegram(db, u.id); console.log("отвязано"); break; + } + case "user ensure": { + // Local user without a Gitea account — for the dev stand and manual checks. + if (!args[0]?.startsWith("mock-")) throw new PeppaError("usage: peppa user ensure mock-"); + const u = (await getUserByLogin(db, args[0])) ?? (await upsertUserFromGitea(db, { id: -Math.floor(Math.random() * 1e9) - 1, login: args[0] }, { access_token: "mock-no-gitea-access" })); + console.log(`${u.login} (#${u.id})`); + break; + } case "watchdog": { const wopts = { intervalMs: Number(opts.interval) * 1000, diff --git a/packages/core/src/telegram.ts b/packages/core/src/telegram.ts index 33bb80f1..60b7c251 100644 --- a/packages/core/src/telegram.ts +++ b/packages/core/src/telegram.ts @@ -1,60 +1,68 @@ -import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; -import { questions, telegramOutbox, telegramUpdates, type Db } from "@peppa/db"; -import { and, asc, eq, lte } from "drizzle-orm"; +import { createHmac, randomBytes } from "node:crypto"; +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 { deleteSetting, getSetting, setSetting } from "./settings.ts"; +import type { User } from "./users.ts"; export type OutboxRow = typeof telegramOutbox.$inferSelect; -const PAIRING = "telegram.pairing"; -const BINDING = "telegram.binding"; const OFFSET = "telegram.offset"; const PAIRING_TTL_MS = 10 * 60_000; -export interface TelegramBinding { - chatId: number; - userId: number; - username: string | null; - pairedAt: string; -} - // Only a keyed hash of the pairing code is stored. -const hashCode = (code: string, secret: string) => createHmac("sha256", secret).update(code).digest("hex"); +const pairKey = (code: string, secret: string) => `telegram.pair:${createHmac("sha256", secret).update(code).digest("hex")}`; -/** One-time /start code for binding the PM's Telegram chat (valid 10 minutes). */ -export async function createPairingCode(db: Db, secret: string): Promise { +/** One-time /start code that binds a Telegram chat to this Peppa user (valid 10 minutes). */ +export async function createPairingCode(db: Db, secret: string, userId: number): Promise { const code = randomBytes(18).toString("base64url"); - await setSetting(db, PAIRING, { hash: hashCode(code, secret), expiresAt: Date.now() + PAIRING_TTL_MS }); + await setSetting(db, pairKey(code, secret), { userId, expiresAt: Date.now() + PAIRING_TTL_MS }); return code; } -/** Binds the chat if `code` matches the pending pairing code. One binding at a time. */ +/** Binds the chat to the user the code was issued for. A chat belongs to one user at a time. */ export async function acceptPairing( db: Db, secret: string, code: string, who: { chatId: number; userId: number; username?: string | null }, -): Promise { - const saved = await getSetting<{ hash: string; expiresAt: number }>(db, PAIRING); - if (!saved || Date.now() >= saved.expiresAt) return null; - const a = Buffer.from(hashCode(code, secret)); - const b = Buffer.from(saved.hash); - if (a.length !== b.length || !timingSafeEqual(a, b)) return null; - const binding: TelegramBinding = { - chatId: who.chatId, - userId: who.userId, - username: who.username ?? null, - pairedAt: new Date().toISOString(), - }; - await setSetting(db, BINDING, binding); - await deleteSetting(db, PAIRING); - return binding; +): Promise { + const key = pairKey(code, secret); + const saved = await getSetting<{ userId: number; expiresAt: number }>(db, key); + if (!saved) return null; + await deleteSetting(db, key); + if (Date.now() >= saved.expiresAt) return null; + await db + .update(users) + .set({ telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null }) + .where(eq(users.telegramChatId, who.chatId)); + const [u] = await db + .update(users) + .set({ telegramChatId: who.chatId, telegramUserId: who.userId, telegramUsername: who.username ?? null, telegramPairedAt: new Date() }) + .where(eq(users.id, saved.userId)) + .returning(); + return u ?? null; } -export const getBinding = (db: Db) => getSetting(db, BINDING); +export async function unpairTelegram(db: Db, userId: number): Promise { + await db + .update(users) + .set({ telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null }) + .where(eq(users.id, userId)); +} -export async function unpair(db: Db): Promise { - await deleteSetting(db, BINDING); - await db.delete(telegramOutbox).where(eq(telegramOutbox.status, "pending")); +/** The Peppa user paired with this chat (and Telegram account), if any. */ +export async function telegramUser(db: Db, chatId: number, fromId: number): Promise { + const [u] = await db.select().from(users).where(and(eq(users.telegramChatId, chatId), eq(users.telegramUserId, fromId))); + return u ?? null; +} + +/** Owner and members of a project who paired Telegram: they get its agents' questions. */ +export async function questionRecipients(db: Db, projectId: number): Promise { + const [p] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, projectId)); + const members = await db.select({ id: projectMembers.userId }).from(projectMembers).where(eq(projectMembers.projectId, projectId)); + const ids = [...new Set([p?.ownerId, ...members.map((m) => m.id)].filter((x): x is number => x != null))]; + if (!ids.length) return []; + return db.select().from(users).where(and(inArray(users.id, ids), isNotNull(users.telegramChatId))); } export const getOffset = async (db: Db) => (await getSetting(db, OFFSET)) ?? 0; @@ -124,7 +132,27 @@ export async function markOutboxRetry(db: Db, row: OutboxRow, error: string, ret .where(eq(telegramOutbox.id, row.id)); } -export async function questionByTelegramMessage(db: Db, messageId: number) { - const [row] = await db.select().from(questions).where(eq(questions.telegramMessageId, messageId)); - return row ?? null; +/** The question a bot message in this chat is about (message ids are per chat). */ +export async function questionByTelegramMessage(db: Db, chatId: number, messageId: number) { + const [row] = await db + .select({ q: questions }) + .from(telegramOutbox) + .innerJoin(questions, eq(telegramOutbox.questionId, questions.id)) + .where( + and( + eq(telegramOutbox.method, "sendMessage"), + eq(telegramOutbox.telegramMessageId, messageId), + sql`${telegramOutbox.params}->>'chat_id' = ${String(chatId)}`, + ), + ); + return row?.q ?? null; +} + +/** Delivered question messages whose question got answered since `since` (to close them). */ +export async function answeredQuestionMessages(db: Db, since: Date) { + return db + .select({ sent: telegramOutbox, q: questions }) + .from(telegramOutbox) + .innerJoin(questions, eq(telegramOutbox.questionId, questions.id)) + .where(and(eq(telegramOutbox.method, "sendMessage"), eq(telegramOutbox.status, "sent"), isNotNull(telegramOutbox.telegramMessageId), gt(questions.answeredAt, since))); } diff --git a/packages/core/src/users.ts b/packages/core/src/users.ts index b765e1d4..3eb7cb18 100644 --- a/packages/core/src/users.ts +++ b/packages/core/src/users.ts @@ -192,3 +192,7 @@ export async function claudeTokenForProject(db: Db, project: Pick { + return db.select().from(users).orderBy(asc(users.login)); +} diff --git a/packages/db/migrations/0009_steady_preak.sql b/packages/db/migrations/0009_steady_preak.sql new file mode 100644 index 00000000..e4c004c8 --- /dev/null +++ b/packages/db/migrations/0009_steady_preak.sql @@ -0,0 +1,5 @@ +ALTER TABLE "users" ADD COLUMN "telegram_chat_id" bigint;--> statement-breakpoint +ALTER TABLE "users" ADD COLUMN "telegram_user_id" bigint;--> statement-breakpoint +ALTER TABLE "users" ADD COLUMN "telegram_username" text;--> statement-breakpoint +ALTER TABLE "users" ADD COLUMN "telegram_paired_at" timestamp with time zone;--> statement-breakpoint +ALTER TABLE "users" ADD CONSTRAINT "users_telegram_chat_id_unique" UNIQUE("telegram_chat_id"); \ No newline at end of file diff --git a/packages/db/migrations/meta/0009_snapshot.json b/packages/db/migrations/meta/0009_snapshot.json new file mode 100644 index 00000000..c55b0666 --- /dev/null +++ b/packages/db/migrations/meta/0009_snapshot.json @@ -0,0 +1,1433 @@ +{ + "id": "89dc4030-a75f-4f23-a8dd-cf52b5c2d9c4", + "prevId": "69625371-6b59-41c2-8555-4582c3e311fa", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.goals": { + "name": "goals", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "goal_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_clients": { + "name": "oauth_clients", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_codes": { + "name": "oauth_codes", + "schema": "", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "used_at": { + "name": "used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_tokens": { + "name": "oauth_tokens", + "schema": "", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project_invites": { + "name": "project_invites", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "invited_by": { + "name": "invited_by", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "project_invites_project_id_projects_id_fk": { + "name": "project_invites_project_id_projects_id_fk", + "tableFrom": "project_invites", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_invites_invited_by_users_id_fk": { + "name": "project_invites_invited_by_users_id_fk", + "tableFrom": "project_invites", + "tableTo": "users", + "columnsFrom": [ + "invited_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_invites_project_id_login_pk": { + "name": "project_invites_project_id_login_pk", + "columns": [ + "project_id", + "login" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project_members": { + "name": "project_members", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "added_by": { + "name": "added_by", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "project_members_project_id_projects_id_fk": { + "name": "project_members_project_id_projects_id_fk", + "tableFrom": "project_members", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_user_id_users_id_fk": { + "name": "project_members_user_id_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_added_by_users_id_fk": { + "name": "project_members_added_by_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "added_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_members_project_id_user_id_pk": { + "name": "project_members_project_id_user_id_pk", + "columns": [ + "project_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.projects": { + "name": "projects", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "projects_owner_id_users_id_fk": { + "name": "projects_owner_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + }, + "projects_key_unique": { + "name": "projects_key_unique", + "nullsNotDistinct": false, + "columns": [ + "key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.questions": { + "name": "questions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "options": { + "name": "options", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "answered_at": { + "name": "answered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sessions": { + "name": "sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'claude'" + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "session_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "nullsNotDistinct": false, + "columns": [ + "tmux_name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.settings": { + "name": "settings", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tasks": { + "name": "tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "task_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_outbox": { + "name": "telegram_outbox", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "params": { + "name": "params", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "telegram_outbox_question_id_questions_id_fk": { + "name": "telegram_outbox_question_id_questions_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "nullsNotDistinct": false, + "columns": [ + "dedupe_key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_updates": { + "name": "telegram_updates", + "schema": "", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claude_token_enc": { + "name": "claude_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claude_token_set_at": { + "name": "claude_token_set_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "telegram_chat_id": { + "name": "telegram_chat_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "telegram_user_id": { + "name": "telegram_user_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "telegram_username": { + "name": "telegram_username", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram_paired_at": { + "name": "telegram_paired_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_login_at": { + "name": "last_login_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "nullsNotDistinct": false, + "columns": [ + "gitea_id" + ] + }, + "users_login_unique": { + "name": "users_login_unique", + "nullsNotDistinct": false, + "columns": [ + "login" + ] + }, + "users_telegram_chat_id_unique": { + "name": "users_telegram_chat_id_unique", + "nullsNotDistinct": false, + "columns": [ + "telegram_chat_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.goal_status": { + "name": "goal_status", + "schema": "public", + "values": [ + "open", + "done", + "archived" + ] + }, + "public.session_status": { + "name": "session_status", + "schema": "public", + "values": [ + "starting", + "running", + "waiting_input", + "idle", + "stalled", + "rate_limited", + "done", + "failed" + ] + }, + "public.task_status": { + "name": "task_status", + "schema": "public", + "values": [ + "backlog", + "proposing", + "awaiting_approval", + "in_progress", + "review", + "done", + "blocked" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 2f3c2115..2b32be02 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -64,6 +64,13 @@ "when": 1794504595170, "tag": "0008_wandering_jetstream", "breakpoints": true + }, + { + "idx": 9, + "version": "7", + "when": 1794505063021, + "tag": "0009_steady_preak", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index d6f38cc7..c28e7875 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -1,5 +1,5 @@ import { relations } from "drizzle-orm"; -import { boolean, integer, jsonb, pgEnum, pgTable, primaryKey, serial, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core"; +import { bigint, boolean, integer, jsonb, pgEnum, pgTable, primaryKey, serial, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core"; const createdAt = () => timestamp("created_at", { withTimezone: true }).notNull().defaultNow(); const updatedAt = () => @@ -21,6 +21,11 @@ export const users = pgTable("users", { // Claude sessions of this user's projects. claudeTokenEnc: text("claude_token_enc"), claudeTokenSetAt: timestamp("claude_token_set_at", { withTimezone: true }), + // Telegram chat paired from Settings; agent questions of this user's projects go there. + telegramChatId: bigint("telegram_chat_id", { mode: "number" }).unique(), + telegramUserId: bigint("telegram_user_id", { mode: "number" }), + telegramUsername: text("telegram_username"), + telegramPairedAt: timestamp("telegram_paired_at", { withTimezone: true }), createdAt: createdAt(), lastLoginAt: timestamp("last_login_at", { withTimezone: true }), }); diff --git a/packages/testkit/bin/peppa-dev b/packages/testkit/bin/peppa-dev index 241bdcf2..5cd5c5b4 100755 --- a/packages/testkit/bin/peppa-dev +++ b/packages/testkit/bin/peppa-dev @@ -4,7 +4,8 @@ # Lets an agent play the PM in Telegram without a human and without touching prod. # # peppa-dev up | down | status -# peppa-dev peppa Peppa CLI against the stand +# peppa-dev peppa Peppa CLI against the stand (give projects to the test PM: +# peppa-dev peppa project owner mock-pm) # peppa-dev tg messages|click|reply|send|callbacks ... set -euo pipefail ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" @@ -33,10 +34,11 @@ up() { for _ in $(seq 1 40); do curl -sf "$TELEGRAM_API_URL/_mock/messages" >/dev/null && break; sleep 0.25; done "${TM[@]}" has-session -t dev-bot 2>/dev/null || "${TM[@]}" new-session -d -s dev-bot "$ROOT/apps/bot/bin/peppa-bot" for _ in $(seq 1 40); do "$PEPPA" telegram status 2>/dev/null | grep -q '^bot: @' && break; sleep 0.25; done - if ! "$PEPPA" telegram status | grep -q 'привязан:'; then - code=$("$PEPPA" telegram pair | grep -o 'start=[A-Za-z0-9_-]*' | cut -d= -f2) + "$PEPPA" user ensure mock-pm >/dev/null + if ! "$PEPPA" telegram status | grep -q '^mock-pm: chat'; then + code=$("$PEPPA" telegram pair mock-pm | grep -o 'start=[A-Za-z0-9_-]*' | cut -d= -f2) curl -sf -X POST "$TELEGRAM_API_URL/_mock/send" -H 'Content-Type: application/json' -d "{\"text\":\"/start $code\"}" >/dev/null - for _ in $(seq 1 40); do "$PEPPA" telegram status | grep -q 'привязан:' && break; sleep 0.25; done + for _ in $(seq 1 40); do "$PEPPA" telegram status | grep -q '^mock-pm: chat' && break; sleep 0.25; done fi status } diff --git a/packages/testkit/test/bot.test.ts b/packages/testkit/test/bot.test.ts index 8799a27f..41081929 100644 --- a/packages/testkit/test/bot.test.ts +++ b/packages/testkit/test/bot.test.ts @@ -3,7 +3,7 @@ import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import { after, before, describe, test } from "node:test"; // helpers must load first: it sets the isolated test env that runner modules read on load. -import { core, db, project, runner, teardown, tick, waitFor } from "./helpers.ts"; +import { core, db, project, runner, setDefaultOwner, teardown, tick, waitFor } from "./helpers.ts"; import { MockTelegram, type MockTgMessage } from "../src/mock-telegram.ts"; import type { Bot } from "@peppa/bot"; @@ -13,9 +13,16 @@ const { TelegramApi } = await import("@peppa/bot/telegram"); const tg = await new MockTelegram().start(); const PM = { id: 501, chatId: 501, username: "pm" }; const STRANGER = { id: 777, chatId: 777, username: "stranger" }; +const BOB = { id: 888, chatId: 888, username: "bob" }; let bot: Bot; +let pmUser: Awaited>; +let bobUser: typeof pmUser; +process.env.PEPPA_SECRET = "mock-secret-for-tests"; before(async () => { + pmUser = await core.upsertUserFromGitea(db, { id: 61, login: "mock-pm" }, { access_token: "x" }); + bobUser = await core.upsertUserFromGitea(db, { id: 62, login: "mock-bob" }, { access_token: "y" }); + setDefaultOwner(pmUser.id); // every project below belongs to the PM bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), @@ -53,16 +60,16 @@ describe("pairing", () => { await waitFor("wrong code reply", async () => tg.botMessages(PM.chatId).some((m) => /неверный или истёк/.test(m.text))); assert.equal(tg.botMessages(STRANGER.chatId).length, 0); - const code = await core.createPairingCode(db, tg.token); + const code = await core.createPairingCode(db, tg.token, pmUser.id); tg.userSends(PM, `/start ${code}`); await waitFor("paired", async () => tg.botMessages(PM.chatId).some((m) => /Привязано/.test(m.text))); - const b = await core.getBinding(db); - assert.equal(b?.chatId, PM.chatId); + assert.equal((await core.getUser(db, pmUser.id))?.telegramChatId, PM.chatId); // The code is single-use; a stranger can't take over with it. tg.userSends(STRANGER, `/start ${code}`); await waitFor("stranger refused", async () => tg.botMessages(STRANGER.chatId).some((m) => /неверный/.test(m.text))); - assert.equal((await core.getBinding(db))?.userId, PM.id); + assert.equal((await core.getUser(db, pmUser.id))?.telegramUserId, PM.id); + assert.equal((await core.telegramUser(db, STRANGER.chatId, STRANGER.id)), null); tg.userSends(PM, "/status"); await waitFor("status", async () => tg.botMessages(PM.chatId).some((m) => /Активные сессии/.test(m.text))); @@ -136,6 +143,37 @@ describe("answering from Telegram", () => { }); }); +describe("several users", () => { + test("questions go only to people with access; a member gets them too; foreign buttons do nothing", async () => { + tg.userSends(BOB, `/start ${await core.createPairingCode(db, tg.token, bobUser.id)}`); + await waitFor("bob paired", async () => (await core.getUser(db, bobUser.id))?.telegramChatId === BOB.chatId); + + // PM's project: Bob has no access. + const mine = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Секрет проекта PM?", options: ["Да", "Нет"] } }], [{ say: "Ок." }]] }); + const sid = await mine.start(); + const q = await mine.waitQuestion(sid, "question"); + const m = await messageFor(q.id); + assert.equal(m.chat_id, PM.chatId); + await new Promise((r) => setTimeout(r, 1200)); + assert.ok(!tg.botMessages(BOB.chatId).some((x) => /Секрет проекта PM/.test(x.text)), "Bob must not see it"); + const cb = tg.userClicks(BOB, m.message_id, `q:${q.id}:o0`); + await waitFor("refused", async () => tg.callbackAnswers.find((a) => a.id === cb && /не найден|Нет доступа/.test(a.text ?? ""))); + assert.equal((await core.getQuestion(db, q.id)).answeredAt, null); + + // Bob becomes a member: the open question reaches him too, and his answer closes both messages. + await core.addMember(db, await core.getProject(db, mine.key), "mock-bob", pmUser.id); + const bobMsg = await waitFor("bob gets the question", async () => tg.botMessages(BOB.chatId).find((x) => /Секрет проекта PM/.test(x.text))); + tg.userClicks(BOB, bobMsg.message_id, `q:${q.id}:o1`); + await mine.waitLog("member's answer delivered", isPrompt(`Ответ PM на вопрос #${q.id}: Нет`)); + await waitFor("closed for both", async () => /Ответ в Telegram/.test(m.text) && /Ответ в Telegram/.test(bobMsg.text)); + await runner.stopSession(db, sid); + + // /status is scoped to the user's projects. + tg.userSends(BOB, "/status"); + await waitFor("bob status", async () => tg.botMessages(BOB.chatId).some((x) => /Активные сессии: 0/.test(x.text))); + }); +}); + describe("review", () => { test("ready-for-review message: Accept closes the task", async () => { const p = await project({ turns: [[{ mcp: "update_task", args: { task: "1", status: "review", pr_url: "https://git.example/pr/9" } }, { say: "PR открыт." }]] }); @@ -189,7 +227,7 @@ describe("staleness and reliability", () => { const q = await p.waitQuestion(sid, "question"); const m = await messageFor(q.id); assert.match(m.text, /Проверка ретраев/); - const row = await core.getOutbox(db, `q:${q.id}`); + const row = await core.getOutbox(db, `q:${q.id}:${PM.chatId}`); assert.ok(row && row.attempts >= 2, `expected retries, got ${row?.attempts}`); await runner.stopSession(db, sid); }); diff --git a/packages/testkit/test/helpers.ts b/packages/testkit/test/helpers.ts index 26939366..e74b541d 100644 --- a/packages/testkit/test/helpers.ts +++ b/packages/testkit/test/helpers.ts @@ -67,6 +67,11 @@ export async function waitFor(label: string, fn: () => Promise { writeFileSync(join(dir, ".peppa/project.json"), JSON.stringify({ slug: key.toLowerCase(), key, name: key, peppaUrl: "http://test" })); writeFileSync(join(dir, ".mcp.json"), JSON.stringify({ mcpServers: { peppa: { command: process.env.PEPPA_MOCK_MCP_BIN } } })); writeFileSync(join(dir, ".peppa/mock-scenario.json"), JSON.stringify(scenario)); - const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: key, giteaOwner: "test", workspacePath: dir }); + const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: key, giteaOwner: "test", workspacePath: dir, ownerId: defaultOwnerId }); const ref = await core.createTask(db, { projectId: p.id, title: `CJM ${key}`, description: "test task" }); const logPath = join(dir, ".peppa/mock-log.jsonl"); const log = () =>