PEP-62: web «Чаты» (master + project chats, threads, composer, Telegram link), live scope, watchdog sync/TTL, e2e

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-14 19:09:32 +05:00
parent 46840ffef5
commit a0d1097e37
8 changed files with 611 additions and 8 deletions

View File

@ -0,0 +1,248 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { Bot, Hash, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react";
import { chatMessagesView, chatThreads, chatTtlMs, getSetting, listChats, masterFeed, syncChats, threadTitle, THREAD_KEY, type ChatMessageView, type Question } from "@peppa/core";
import { projects, questions, tasks } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { eq, inArray } from "drizzle-orm";
import { LiveRefresh } from "@/components/LiveRefresh";
import { ago, Empty, Flash, PageHeader } from "@/components/common";
import { Hidden, QuestionCard } from "@/components/cards";
import { Workspace } from "@/components/Workspace";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/input";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { cn } from "@/lib/utils";
import { linkChatAction, postChatAction, unlinkChatAction } from "../actions";
type Params = { error?: string; thread?: string; link?: string };
const CHANNEL = "channel";
/** «Чаты» (PEP-62): the master chat and project chats with threads; a linked Telegram group mirrors them. */
export default async function ChatPage({ params, searchParams }: { params: Promise<{ chat: string }>; searchParams: Promise<Params> }) {
const user = await requireUser();
const { chat: slug } = await params;
const { error, thread: rawThread, link } = await searchParams;
// Whoever renders first moves fresh events into the chats (the bot and the watchdog do it too).
await syncChats(db).catch((e) => console.error("syncChats", e));
const list = await listChats(db, user);
const chat = list.find((c) => c.slug.toLowerCase() === slug.toLowerCase());
if (!chat) notFound();
const master = chat.kind === "master";
const thread = rawThread === CHANNEL ? null : rawThread && THREAD_KEY.test(rawThread) ? rawThread : undefined;
const threads = master ? [] : await chatThreads(db, chat.id);
const messages = master ? await masterFeed(db, user, { limit: 150 }) : await chatMessagesView(db, chat.id, { threadKey: thread, limit: 150 });
const current = thread ? (threads.find((t) => t.key === thread)?.title ?? (await threadTitle(db, thread)) ?? thread) : null;
// Live state of the questions in view (answer buttons, «отвечено» marks).
const qIds = messages.map((m) => m.question?.id).filter((x): x is number => x != null);
const qs = qIds.length
? await db.select({ q: questions, status: tasks.status, key: projects.key, number: tasks.number }).from(questions).innerJoin(projects, eq(questions.projectId, projects.id)).leftJoin(tasks, eq(questions.taskId, tasks.id)).where(inArray(questions.id, qIds))
: [];
const qById = new Map(qs.map((r) => [r.q.id, { q: r.q as Question, taskStatus: r.status, taskKey: r.number != null ? formatTaskKey(r.key, r.number) : null }]));
const url = (p: { thread?: string | null }) => {
const base = `/chats/${chat.slug}`;
return p.thread ? `${base}?thread=${encodeURIComponent(p.thread)}` : base;
};
const here = url({ thread: thread === null ? CHANNEL : thread });
const bot = (await getSetting<{ username: string }>(db, "telegram.bot"))?.username ?? null;
const ttlDays = Math.round(chatTtlMs() / 86_400_000);
const taskThread = thread?.startsWith("task:");
const placeholder = master
? "/status, /task KEY-N, /move KEY-N in_progress, /help"
: taskThread
? "Ответ агенту: на открытый вопрос, иначе комментарий, который он увидит сразу"
: thread
? "Заметка в тред или команда /help"
: "Заметка в канал или команда: /status, /task KEY-N, /move KEY-N in_progress";
const aside = (
<div className="flex flex-col gap-5 text-sm">
<section className="flex flex-col gap-2">
<h2 className="m-0 text-[15px] font-semibold">Telegram</h2>
{chat.tgTitle ? (
<>
<p className="m-0 text-muted-foreground">
Связан с группой <b className="text-foreground">{chat.tgTitle}</b>. Сообщения чата приходят туда, треды — цепочками ответов; ответ реплаем уходит в тред{master ? "" : " (в треде стори — агенту)"}.
</p>
<form action={unlinkChatAction}>
<Hidden fields={{ chatId: chat.id, back: here }} />
<Button size="sm" variant="outline">
<Unlink />
Отвязать группу
</Button>
</form>
</>
) : link ? (
<div className="flex flex-col gap-2 rounded-lg border bg-card p-3">
<p className="m-0">Код действует 10 минут.</p>
{bot && (
<a href={`https://t.me/${bot}?startgroup=${encodeURIComponent(link)}`} target="_blank" rel="noreferrer" className="font-medium">
Добавить @{bot} в группу →
</a>
)}
<p className="m-0 text-muted-foreground">Или добавь бота в группу сам и отправь там:</p>
<code className="rounded bg-muted px-2 py-1 font-mono text-xs break-all select-all">/link {link}</code>
</div>
) : (
<>
<p className="m-0 text-muted-foreground">{master ? "Свяжи мастер-чат с группой — туда пойдёт всё важное по твоим проектам." : "Свяжи чат проекта с группой команды — по ней сразу видно, к какому проекту сообщение."}</p>
<form action={linkChatAction}>
<Hidden fields={{ chatId: chat.id, back: here }} />
<Button size="sm" variant="outline">
<Link2 />
Связать с Telegram
</Button>
</form>
</>
)}
<p className="m-0 text-xs text-muted-foreground">Отвечать из группы могут те, кто привязал Telegram в «Настройках» и имеет доступ к {master ? "мастер-чату (только ты)" : "проекту"}.</p>
</section>
<section className="flex flex-col gap-1.5 text-xs text-muted-foreground">
<h2 className="m-0 text-[15px] font-semibold text-foreground">Как это устроено</h2>
<p className="m-0">{master ? "Мастер-чат — вопросы, ревью, сбои, лимиты, релизы и ошибки всех твоих проектов, мониторинг и сводка. Команды — без LLM." : "Тред на каждую стори, инцидент и релиз. Вопросы агентов видны и здесь, и на Главной."}</p>
<p className="m-0">Переписка хранится {ttlDays} дн.; стори, вопросы и события остаются на своих страницах.</p>
</section>
</div>
);
return (
<Workspace aside={aside}>
<LiveRefresh scope="chats" />
<Flash error={error} />
<PageHeader title="Чаты">Мастер-чат и чаты проектов: события и вопросы агентов по тредам. Ответ в треде стори уходит агенту.</PageHeader>
<nav className="mb-4 flex flex-wrap gap-1.5" aria-label="Чаты">
{list.map((c) => (
<Link
key={c.id}
href={`/chats/${c.slug}`}
aria-current={c.id === chat.id ? "page" : undefined}
title={c.title}
className={cn(
"flex items-center gap-1.5 rounded-md border bg-card px-2.5 py-1 text-sm text-muted-foreground hover:border-muted-foreground hover:text-foreground hover:no-underline",
c.id === chat.id && "border-primary/60 bg-primary/10 text-foreground",
)}
>
{c.kind === "master" ? <MessagesSquare className="size-3.5" /> : <Hash className="size-3.5" />}
<span className={c.kind === "project" ? "font-mono" : undefined}>{c.kind === "master" ? "Мастер-чат" : c.slug}</span>
{c.tgTitle && <Send className="size-3 text-info" aria-label="связан с Telegram" />}
{c.open > 0 && <span className="rounded-full bg-primary px-1.5 font-mono text-[11px] leading-4 font-semibold text-primary-foreground tabular-nums">{c.open}</span>}
</Link>
))}
</nav>
<div className={cn("grid gap-4", !master && "lg:grid-cols-[230px_minmax(0,1fr)]")}>
{!master && (
<nav aria-label="Треды" className="flex flex-col gap-0.5 self-start rounded-lg border bg-card/50 p-1.5 text-sm max-lg:max-h-48 max-lg:overflow-y-auto">
<ThreadLink href={url({})} active={thread === undefined} title="Вся лента" />
<ThreadLink href={url({ thread: CHANNEL })} active={thread === null} title="# Канал" />
{threads.length > 0 && <div className="mx-2 my-1 border-t" />}
{threads.map((t) => (
<ThreadLink key={t.key} href={url({ thread: t.key })} active={thread === t.key} title={t.title} meta={`${t.count} · ${ago(t.lastAt)}`} open={t.open} />
))}
{threads.length === 0 && <p className="m-0 px-2 py-1.5 text-xs text-muted-foreground">Тредов пока нет.</p>}
</nav>
)}
<section className="flex min-w-0 flex-col gap-3" aria-label="Сообщения">
{current && (
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-medium">🧵 {current}</span>
{taskThread && <TaskLink messages={messages} />}
</div>
)}
{messages.length === 0 ? (
<Empty>{master ? "Пока тихо: здесь появятся вопросы агентов, сбои, релизы и ошибки твоих проектов." : thread === undefined ? "Сообщений пока нет: они появятся, когда агенты возьмутся за стори." : "В этом треде пока пусто."}</Empty>
) : (
<ol className="m-0 flex list-none flex-col gap-2 p-0">
{messages.map((m) => (
<li key={m.id}>
<MessageItem m={m} q={m.question ? qById.get(m.question.id) : undefined} back={here} showThread={thread === undefined} masterView={master} />
</li>
))}
</ol>
)}
<form action={postChatAction} className="sticky bottom-16 flex flex-col gap-2 rounded-lg border bg-card p-3 md:bottom-3">
<Hidden fields={{ chatId: chat.id, thread: thread ?? "", back: here }} />
<Textarea name="text" rows={2} required maxLength={8000} placeholder={placeholder} aria-label="Сообщение" />
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">{thread ? "в тред" : master ? "в мастер-чат" : "в канал"}{chat.tgTitle ? ` · и в Telegram «${chat.tgTitle}»` : ""}</span>
<Button size="sm" className="ml-auto">
<Send />
Отправить
</Button>
</div>
</form>
</section>
</div>
</Workspace>
);
}
function ThreadLink({ href, active, title, meta, open = 0 }: { href: string; active: boolean; title: string; meta?: string; open?: number }) {
return (
<Link
href={href}
aria-current={active ? "page" : undefined}
className={cn("flex flex-col rounded-md px-2 py-1.5 text-foreground hover:bg-accent hover:no-underline", active && "bg-accent font-medium")}
>
<span className="flex items-center gap-1.5">
<span className="min-w-0 flex-1 truncate" title={title}>{title}</span>
{open > 0 && <span className="rounded-full bg-primary px-1.5 font-mono text-[11px] leading-4 font-semibold text-primary-foreground tabular-nums" title="ждут ответа">{open}</span>}
</span>
{meta && <span className="text-[11px] text-muted-foreground">{meta}</span>}
</Link>
);
}
function TaskLink({ messages }: { messages: ChatMessageView[] }) {
const key = messages.find((m) => m.threadTitle)?.threadTitle?.split(" · ")[0];
return key ? <Link href={`/t/${key}`} className="text-xs">открыть стори →</Link> : null;
}
function threadHref(m: ChatMessageView) {
return m.projectKey && m.threadKey ? `/chats/${m.projectKey}?thread=${encodeURIComponent(m.threadKey)}` : m.projectKey ? `/chats/${m.projectKey}` : null;
}
function MessageItem({ m, q, back, showThread, masterView }: { m: ChatMessageView; q?: { q: Question; taskStatus: string | null; taskKey: string | null }; back: string; showThread: boolean; masterView: boolean }) {
const where = (showThread || masterView) && (m.threadTitle || (masterView && m.projectKey));
const href = threadHref(m);
const label = [masterView && m.projectKey ? m.projectKey : null, m.threadTitle].filter(Boolean).join(" · ");
const head = (
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
{m.authorKind === "user" ? <UserIcon className="size-3.5" /> : m.authorKind === "agent" ? <Bot className="size-3.5" /> : <MessagesSquare className="size-3.5" />}
<span className="font-medium text-foreground">{m.authorKind === "user" ? (m.authorLogin ?? "?") : m.authorKind === "agent" ? "агент" : "Пеппа"}</span>
{m.via === "telegram" && <span title="из Telegram">· Telegram</span>}
{where && href && (
<Link href={href} className="max-w-full truncate">
🧵 {label}
</Link>
)}
<span className="ml-auto font-mono">{ago(m.createdAt)}</span>
</div>
);
if (q) {
return (
<div className="flex flex-col gap-1">
{head}
<QuestionCard q={q.q} taskKey={q.taskKey} taskStatus={q.taskStatus} back={back} compact />
</div>
);
}
return (
<article className={cn("flex flex-col gap-1 rounded-lg border bg-card px-3 py-2", m.kind === "user" && "border-primary/30 bg-primary/5", m.kind === "system" && "border-dashed bg-transparent")}>
{head}
<p className="m-0 text-sm break-words whitespace-pre-wrap">{m.text}</p>
{m.url && (
<a href={m.url} target="_blank" rel="noreferrer" className="truncate text-xs">
{m.url}
</a>
)}
</article>
);
}

View File

@ -0,0 +1,54 @@
"use server";
// «Чаты» (PEP-62): a message into a chat/thread, Telegram group link/unlink. Access — chatForUser.
import { chatForUser, createChatLinkCode, PeppaError, unlinkChat } from "@peppa/core";
import { postToChat } from "@peppa/runner";
import { loadEnv } from "@peppa/shared";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { asWebActor, requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
/** Runs an action; errors come back as ?error=… (redirect stays outside try). */
async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<never> {
let target = str(f, "back") || "/chats";
try {
target = (await fn()) || target;
} catch (e) {
const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
const [path, query] = target.split("?");
const params = new URLSearchParams(query);
params.set("error", msg.slice(0, 300));
target = `${path}?${params}`;
}
revalidatePath("/chats", "layout");
redirect(target);
}
export async function postChatAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const thread = str(f, "thread");
await postToChat(db, user, { chatId: Number(str(f, "chatId")), threadKey: thread || null, text: String(f.get("text") ?? ""), via: "web" });
});
}
/** A one-time code (10 min) for `/link <код>` in a group, or the startgroup link that sends it. */
export async function linkChatAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
const token = loadEnv().TELEGRAM_BOT_TOKEN;
if (!token) throw new PeppaError("Telegram-бот Пеппы не настроен");
const chat = await chatForUser(db, user, Number(str(f, "chatId")));
const code = await createChatLinkCode(db, token, user, chat.id);
const back = str(f, "back") || "/chats";
return `${back}${back.includes("?") ? "&" : "?"}link=${encodeURIComponent(code)}`;
});
}
export async function unlinkChatAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, () => unlinkChat(db, user, Number(str(f, "chatId"))));
}

View File

@ -0,0 +1,5 @@
import { redirect } from "next/navigation";
export default function Chats() {
redirect("/chats/master");
}

View File

@ -2,7 +2,7 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Bot, Contact, FolderKanban, House, KeyRound, ScrollText, LifeBuoy, LogOut, Search, Server, Settings, ShieldCheck, Users, type LucideIcon } from "lucide-react";
import { Bot, Contact, FolderKanban, House, KeyRound, MessagesSquare, ScrollText, LifeBuoy, LogOut, Search, Server, Settings, ShieldCheck, Users, type LucideIcon } from "lucide-react";
import { Brand } from "@/components/Brand";
import { ThemeToggle } from "@/components/ThemeToggle";
import { Button } from "@/components/ui/button";
@ -16,13 +16,16 @@ interface Item {
count?: "questions" | "waitingRunners";
/** Superadmin only (PEP-68, PEP-67; others get 404 on the URL too); desktop panel only — on phones it is linked from Settings. */
admin?: boolean;
/** Not in the phone tab bar (six tabs fit; PEP-62 added «Чаты»). */
desktopOnly?: boolean;
}
const ITEMS: Item[] = [
{ href: "/", label: "Главная", icon: House, match: (p) => p === "/", count: "questions" },
{ href: "/chats", label: "Чаты", icon: MessagesSquare, match: (p) => p.startsWith("/chats") },
{ href: "/projects", label: "Проекты", icon: FolderKanban, match: (p) => p.startsWith("/projects") || p.startsWith("/p/") || p.startsWith("/t/") },
{ href: "/runners", label: "Раннеры", icon: Bot, match: (p) => p.startsWith("/runners"), count: "waitingRunners" },
{ href: "/team", label: "Команда", icon: Contact, match: (p) => p.startsWith("/team") },
{ href: "/team", label: "Команда", icon: Contact, match: (p) => p.startsWith("/team"), desktopOnly: true },
{ href: "/help", label: "Помощь", icon: LifeBuoy, match: (p) => p.startsWith("/help") },
{ href: "/subscriptions", label: "Подписки", icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true },
{ href: "/secrets", label: "Секреты", icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true },
@ -55,7 +58,7 @@ export function Sidebar({ login, avatarUrl, counts, superadmin = false }: { logi
</button>
<nav
aria-label="Разделы"
className="fixed inset-x-0 bottom-0 z-30 grid grid-cols-5 border-t bg-sidebar/95 pb-[env(safe-area-inset-bottom)] backdrop-blur md:static md:flex md:flex-col md:gap-0.5 md:border-0 md:bg-transparent md:pb-0 md:backdrop-blur-none"
className="fixed inset-x-0 bottom-0 z-30 grid grid-cols-6 border-t bg-sidebar/95 pb-[env(safe-area-inset-bottom)] backdrop-blur md:static md:flex md:flex-col md:gap-0.5 md:border-0 md:bg-transparent md:pb-0 md:backdrop-blur-none"
>
{ITEMS.filter((i) => !i.admin || superadmin).map((i) => {
const active = i.match(path);
@ -66,7 +69,7 @@ export function Sidebar({ login, avatarUrl, counts, superadmin = false }: { logi
href={i.href}
aria-current={active ? "page" : undefined}
className={cn(
i.admin && "max-md:hidden",
(i.admin || i.desktopOnly) && "max-md:hidden",
"relative flex flex-col items-center gap-0.5 px-1 pt-2 pb-1.5 text-[10px] text-muted-foreground transition-colors hover:text-foreground hover:no-underline md:flex-row md:gap-2 md:rounded-md md:px-2.5 md:py-1.5 md:text-sm md:hover:bg-accent",
active && "font-medium text-foreground md:bg-accent md:before:absolute md:before:inset-y-1.5 md:before:-left-3 md:before:w-0.5 md:before:rounded-full md:before:bg-primary",
)}

View File

@ -9,7 +9,7 @@ import { findChangeDir, listenEvents, projectForUser, STEP_EVENT, stepView, type
import { events, sessions, tasks, type Db } from "@peppa/db";
import { and, eq, gt } from "drizzle-orm";
export type LiveScope = "home" | "runners" | `project:${number}` | `task:${number}` | `steps:${number}`;
export type LiveScope = "home" | "runners" | "chats" | `project:${number}` | `task:${number}` | `steps:${number}`;
export type LiveEvent = { type: "change"; scope: LiveScope } | { type: "step"; scope: LiveScope; step: StepView };
type Listener = (e: LiveEvent) => void;
@ -29,7 +29,7 @@ const WAKE_DEBOUNCE_MS = 250;
export function parseScopes(raw: string | null): LiveScope[] {
const out = new Set<LiveScope>();
for (const part of (raw ?? "").split(",").map((s) => s.trim()).filter(Boolean)) {
if (part === "home" || part === "runners") out.add(part);
if (part === "home" || part === "runners" || part === "chats") out.add(part);
else if (/^(project|task|steps):[1-9]\d{0,9}$/.test(part)) out.add(part as LiveScope);
else throw new LiveError(`Неизвестная область: ${part}`, 400);
}
@ -99,6 +99,19 @@ function fingerprint(db: Db, scope: LiveScope): string {
.get(id) as Record<string, unknown>;
return Object.values(row).join("|");
}
if (kind === "chats") {
// PEP-62: a new chat message (projected or written) or a question answered anywhere.
const row = c
.prepare(
`SELECT
(SELECT coalesce(max(id),0) FROM chat_messages) AS m,
(SELECT count(*) || ':' || count(answered_at) FROM questions) AS q,
(SELECT coalesce(max(id),0) FROM events WHERE type <> 'step') AS e,
(SELECT coalesce(group_concat(id || ':' || coalesce(tg_chat_id,'')),'') FROM chats WHERE tg_chat_id IS NOT NULL) AS tg`,
)
.get() as Record<string, unknown>;
return Object.values(row).join("|");
}
// home / runners: across projects (only wakes the page — data stays behind access checks).
const row = c
.prepare(

View File

@ -5,6 +5,8 @@ import { createHash } from "node:crypto";
import {
backupDb,
digestTick,
pruneChats,
syncChats,
getBudgetState,
runAsActor,
expireSessionQuestions,
@ -83,7 +85,15 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise<void> {
await incidentTick(db, { now: opts.now, log }).catch((e) => log(`incidents: ${(e as Error).message}`));
// Daily digest at each user's time (PEP-29); a no-op outside their window.
await digestTick(db, { now: opts.now, log }).catch((e) => log(`digest: ${(e as Error).message}`));
// PEP-62: events → chats (the bot does it too; idempotent) and the chats' TTL, once an hour.
await syncChats(db, { now: opts.now }).catch((e) => log(`chats: ${(e as Error).message}`));
const nowMs = (opts.now ?? new Date()).getTime();
if (nowMs - lastChatPrune >= 3600_000) {
lastChatPrune = nowMs;
await pruneChats(db, { now: opts.now }).then((n) => n && log(`chats: pruned ${n}`)).catch((e) => log(`chats prune: ${(e as Error).message}`));
}
}
let lastChatPrune = 0;
async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg: WatchdogSettings, log: (m: string) => void) {
if (s.tmuxName.startsWith("pending-")) return;

View File

@ -18,6 +18,9 @@ export interface MockTgUser {
username?: string;
}
/** Groups have negative ids in Telegram. */
const chatType = (chatId: number) => (chatId < 0 ? "group" : "private");
export class MockTelegram {
readonly token = "mock-123:TOKEN";
readonly bot = { id: 999, username: "mock_peppa_bot", is_bot: true, first_name: "Mock Peppa" };
@ -104,7 +107,7 @@ export class MockTelegram {
reply_to: (p.reply_parameters as { message_id?: number } | undefined)?.message_id,
};
this.messages.set(m.message_id, m);
return { ok: true, result: { message_id: m.message_id, chat: { id: m.chat_id, type: "private" }, text: m.text } };
return { ok: true, result: { message_id: m.message_id, chat: { id: m.chat_id, type: chatType(m.chat_id) }, text: m.text } };
}
case "editMessageText": {
const m = this.messages.get(Number(p.message_id));
@ -148,6 +151,20 @@ export class MockTelegram {
});
}
/** PEP-62: a user writes in a group (negative chat id, as in Telegram), optionally as a reply. */
userSendsInGroup(user: MockTgUser, group: { id: number; title: string }, text: string, replyTo?: number) {
const chat = { id: group.id, type: "group", title: group.title };
return this.push({
message: {
message_id: this.nextMessageId++,
chat,
from: { id: user.id, username: user.username, first_name: user.username ?? "user" },
text,
...(replyTo ? { reply_to_message: { message_id: replyTo, chat } } : {}),
},
});
}
/** User sends a voice note (OGG/Opus in real Telegram; any bytes here). */
userSendsVoice(user: MockTgUser, audio: Buffer, duration = 3) {
const fileId = `mock-voice-${this.nextMessageId}`;
@ -170,7 +187,7 @@ export class MockTelegram {
callback_query: {
id,
from: { id: user.id, username: user.username },
message: { message_id: messageId, chat: { id: m?.chat_id ?? user.chatId, type: "private" }, text: m?.text },
message: { message_id: messageId, chat: { id: m?.chat_id ?? user.chatId, type: chatType(m?.chat_id ?? user.chatId) }, text: m?.text },
data,
},
});

View File

@ -0,0 +1,253 @@
// PEP-62: chats — events projected into project chats with threads, a reply in a story thread
// goes to the agent, the master feed and its commands, a linked Telegram group (the real bot
// against mock-telegram), and the short TTL.
import assert from "node:assert/strict";
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, runner, teardown, waitFor } from "./helpers.ts";
import { MockTelegram } from "../src/mock-telegram.ts";
import { chatMessages, users } from "@peppa/db";
import { eq } from "drizzle-orm";
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 tg = await new MockTelegram().start();
const PM = { id: 701, chatId: 701, username: "pm" };
const BOB = { id: 702, chatId: 702, username: "bob" };
const STRANGER = { id: 709, chatId: 709, username: "stranger" };
const GROUP = { id: -100500, title: "PAY team" };
let bot: Bot;
let pm: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let bob: typeof pm;
let eve: typeof pm;
let seq = 0;
async function newProject() {
const key = `C${String.fromCharCode(65 + seq++)}`;
const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: `Проект ${key}`, giteaOwner: "test", workspacePath: "/tmp/none", ownerId: pm.id });
await core.addMember(db, p, bob.login, pm.id);
return p;
}
async function newTask(p: { id: number }, title = "Экспорт в CSV") {
const ref = await core.createTask(db, { projectId: p.id, title });
return core.resolveTask(db, ref.key);
}
const threadOf = (taskId: number) => `task:${taskId}`;
const groupMessages = () => tg.botMessages(GROUP.id);
before(async () => {
pm = await core.upsertUserFromGitea(db, { id: 81, login: "mock-pm" }, { access_token: "x" });
bob = await core.upsertUserFromGitea(db, { id: 82, login: "mock-bob" }, { access_token: "y" });
eve = await core.upsertUserFromGitea(db, { id: 83, login: "mock-eve" }, { access_token: "z" });
await db.update(users).set({ telegramChatId: PM.chatId, telegramUserId: PM.id }).where(eq(users.id, pm.id));
await db.update(users).set({ telegramChatId: BOB.chatId, telegramUserId: BOB.id }).where(eq(users.id, bob.id));
pm = (await core.getUser(db, pm.id))!;
bob = (await core.getUser(db, bob.id))!;
});
after(async () => {
await bot?.stop();
await tg.stop();
await teardown();
});
describe("project chat", () => {
test("Вопрос агента в треде стори; повторный перенос без дублей", async () => {
const p = await newProject();
const chat = await core.ensureProjectChat(db, p.id);
const ref = await newTask(p);
const q = await core.askPm(db, ref, { kind: "question", text: "Какой разделитель?", options: [";", ","] });
await core.syncChats(db);
await core.syncChats(db);
const msgs = await core.chatMessagesView(db, chat.id, { threadKey: threadOf(ref.task.id) });
const qs = msgs.filter((m) => m.question?.id === q.id);
assert.equal(qs.length, 1);
assert.equal(qs[0]!.threadTitle, `${ref.key} · Экспорт в CSV`);
const threads = await core.chatThreads(db, chat.id);
assert.equal(threads[0]!.key, threadOf(ref.task.id));
assert.equal(threads[0]!.open, 1);
// The question is still on the home page (pending questions).
assert.ok((await core.pendingQuestions(db)).some((x) => x.id === q.id));
});
test("Ответ на вопрос из треда уходит агенту", async () => {
const p = await newProject();
const chat = await core.ensureProjectChat(db, p.id);
const ref = await newTask(p);
const q = await core.askPm(db, ref, { kind: "question", text: "Какой разделитель?" });
const r = await runner.postToChat(db, bob, { chatId: chat.id, threadKey: threadOf(ref.task.id), text: "точка с запятой", via: "web" });
const fresh = await core.getQuestion(db, q.id);
assert.equal(fresh.answer, "точка с запятой");
assert.equal(fresh.answeredVia, "web");
assert.match(r.reply!.text, /сохранён|ушёл агенту/);
const thread = await core.chatMessagesView(db, chat.id, { threadKey: threadOf(ref.task.id) });
assert.ok(thread.some((m) => m.kind === "user" && m.authorLogin === bob.login && m.text === "точка с запятой"));
});
test("Комментарий без вопроса: у стори комментарий, в треде одно сообщение", async () => {
const p = await newProject();
const chat = await core.ensureProjectChat(db, p.id);
const ref = await newTask(p);
const r = await runner.postToChat(db, pm, { chatId: chat.id, threadKey: threadOf(ref.task.id), text: "не забудь заголовки", via: "web" });
assert.match(r.reply!.text, /Комментарий сохранён/);
const comments = await core.storyComments(db, ref.task.id);
assert.deepEqual(comments.map((c) => c.text), ["не забудь заголовки"]);
await core.syncChats(db);
const thread = await core.chatMessagesView(db, chat.id, { threadKey: threadOf(ref.task.id) });
assert.equal(thread.filter((m) => m.text === "не забудь заголовки").length, 1);
});
test("Чужой проект: запрос отклонён, сообщения нет", async () => {
const p = await newProject();
const chat = await core.ensureProjectChat(db, p.id);
await assert.rejects(runner.postToChat(db, eve, { chatId: chat.id, threadKey: null, text: "привет", via: "web" }), /не найден/);
assert.equal((await core.chatMessagesView(db, chat.id)).length, 0);
assert.equal((await core.listChats(db, eve)).filter((c) => c.kind === "project").length, 0);
});
test("Тред чужого проекта нельзя подставить", async () => {
const a = await newProject();
const b = await newProject();
const ref = await newTask(b);
const chat = await core.ensureProjectChat(db, a.id);
await assert.rejects(runner.postToChat(db, pm, { chatId: chat.id, threadKey: threadOf(ref.task.id), text: "x", via: "web" }), /не из этого чата/);
});
test("Релиз и инцидент — свои треды", async () => {
const p = await newProject();
const chat = await core.ensureProjectChat(db, p.id);
const { releases } = await import("@peppa/db");
const [rel] = await db.insert(releases).values({ projectId: p.id, env: "staging", sha: "abcdef1234567", status: "healthy", tasks: ["CX-1"] }).returning();
await core.syncChats(db);
const threads = await core.chatThreads(db, chat.id);
assert.ok(threads.some((t) => t.key === `release:${rel!.id}` && t.title === "Релиз staging abcdef1"));
});
});
describe("master chat", () => {
test("Сбой раннера в мастер-чате; команды /task и неизвестная", async () => {
const p = await newProject();
const ref = await newTask(p, "Платежи");
await core.logEvent(db, { projectId: p.id, taskId: ref.task.id, type: "stalled", payload: { idleMinutes: 15 } });
await core.logEvent(db, { projectId: p.id, taskId: ref.task.id, type: "progress", payload: { text: "половина готова" } });
await core.syncChats(db);
const feed = await core.masterFeed(db, pm);
assert.ok(feed.some((m) => /Агент молчит 15 мин/.test(m.text) && m.threadKey === threadOf(ref.task.id) && m.projectKey === p.key));
assert.ok(!feed.some((m) => /половина готова/.test(m.text)), "progress is not important");
const master = await core.ensureMasterChat(db, pm.id);
const r = await runner.postToChat(db, pm, { chatId: master.id, threadKey: null, text: `/task ${ref.key}`, via: "web" });
assert.match(r.reply!.text, new RegExp(`${ref.key}: Платежи[\\s\\S]*бэклог`));
const bad = await runner.postToChat(db, pm, { chatId: master.id, threadKey: null, text: "/deploy всё", via: "web" });
assert.match(bad.reply!.text, /Не знаю такую команду[\s\S]*\/move/);
// Bob's master chat is his own.
await assert.rejects(runner.postToChat(db, bob, { chatId: master.id, threadKey: null, text: "/status", via: "web" }), /не найден/);
});
test("Команда перемещения", async () => {
const p = await newProject();
const ref = await newTask(p);
const master = await core.ensureMasterChat(db, pm.id);
const r = await runner.postToChat(db, pm, { chatId: master.id, threadKey: null, text: `/move ${ref.key} done`, via: "web" });
assert.match(r.reply!.text, new RegExp(`${ref.key} → Готово`));
assert.equal((await core.resolveTask(db, ref.key)).task.status, "done");
});
});
describe("Telegram group", () => {
let p: Awaited<ReturnType<typeof newProject>>;
let chat: Awaited<ReturnType<typeof core.ensureProjectChat>>;
before(async () => {
p = await newProject();
chat = await core.ensureProjectChat(db, p.id);
bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 300, changesIntervalMs: 200, log: (m) => process.env.MOCK_DEBUG && console.log(m) });
await bot.start();
await bot.reconcile(); // first start: mirroring begins from here
});
test("Просроченный код и связка группы", async () => {
const code = await core.createChatLinkCode(db, tg.token, pm, chat.id);
// A stale code: accepted 11 minutes later.
const stale = await core.createChatLinkCode(db, tg.token, pm, chat.id);
assert.equal(await core.acceptChatLink(db, tg.token, stale, { tgChatId: -1, title: "x" }, Date.now() + 11 * 60_000), null);
tg.userSendsInGroup(PM, GROUP, `/link ${stale}`);
await waitFor("stale code reply", async () => groupMessages().some((m) => /неверный или истёк/.test(m.text)));
tg.userSendsInGroup(PM, GROUP, `/link@mock_peppa_bot ${code}`);
await waitFor("linked", async () => groupMessages().some((m) => /Группа связана с чатом проекта/.test(m.text)));
const linked = await core.getChat(db, chat.id);
assert.equal(linked.tgChatId, GROUP.id);
assert.equal(linked.tgTitle, GROUP.title);
});
test("Вопрос в группе, ответ реплаем, тред — цепочка ответов", async () => {
const ref = await newTask(p, "Экспорт отчёта");
const q = await core.askPm(db, ref, { kind: "question", text: "Какой формат даты?", options: ["ISO", "ДД.ММ.ГГГГ"] });
const qMsg = await waitFor("question in the group", async () => groupMessages().find((m) => m.text.includes("Какой формат даты?")));
assert.ok(qMsg.reply_markup?.inline_keyboard.flat().some((b) => b.callback_data === `q:${q.id}:o0`));
// Somebody without a Peppa account replies: ignored with a hint.
tg.userSendsInGroup(STRANGER, GROUP, "ISO конечно", qMsg.message_id);
await waitFor("stranger hint", async () => groupMessages().some((m) => /Не знаю тебя в Пеппе/.test(m.text)));
assert.equal((await core.getQuestion(db, q.id)).answeredAt, null);
tg.userSendsInGroup(BOB, GROUP, "ДД.ММ.ГГГГ", qMsg.message_id);
const answered = await waitFor("answered from the group", async () => {
const x = await core.getQuestion(db, q.id);
return x.answeredAt ? x : null;
});
assert.equal(answered.answer, "ДД.ММ.ГГГГ");
assert.equal(answered.answeredVia, "telegram");
const thread = await core.chatMessagesView(db, chat.id, { threadKey: threadOf(ref.task.id) });
assert.ok(thread.some((m) => m.kind === "user" && m.via === "telegram" && m.authorLogin === bob.login));
// Peppa's note about it hangs on the thread's first message; Bob's own message isn't echoed.
const note = await waitFor("reply note in the thread", async () => groupMessages().find((m) => /Ответ (ушёл агенту|сохранён)/.test(m.text)));
assert.equal(note.reply_to, qMsg.message_id);
assert.ok(!groupMessages().some((m) => m.text.includes("mock-bob") && m.text.includes("ДД.ММ.ГГГГ") && !m.text.includes("Какой формат")));
// A web message in the same thread reaches the group as a reply too.
await runner.postToChat(db, pm, { chatId: chat.id, threadKey: threadOf(ref.task.id), text: "и время в UTC", via: "web" });
const web = await waitFor("web message in the group", async () => groupMessages().find((m) => m.text.includes("и время в UTC")));
assert.equal(web.reply_to, qMsg.message_id);
assert.match(web.text, /mock-pm.*\(веб\)/);
});
test("Кнопка вопроса в группе", async () => {
const ref = await newTask(p, "Кнопки");
const q = await core.askPm(db, ref, { kind: "question", text: "Кнопкой?", options: ["да", "нет"] });
const qMsg = await waitFor("question in the group", async () => groupMessages().find((m) => m.text.includes("Кнопкой?")));
tg.userClicks(STRANGER, qMsg.message_id, `q:${q.id}:o0`);
await waitFor("stranger refused", async () => tg.callbackAnswers.some((c) => /Нет доступа/.test(c.text ?? "")));
tg.userClicks(BOB, qMsg.message_id, `q:${q.id}:o1`);
const x = await waitFor("answered by button", async () => {
const r = await core.getQuestion(db, q.id);
return r.answeredAt ? r : null;
});
assert.equal(x.answer, "нет");
});
test("Супергруппа сохраняет связку", async () => {
// Telegram sends migrate_to_chat_id when a group is upgraded.
await core.migrateChatGroup(db, GROUP.id, -1009999);
assert.equal((await core.getChat(db, chat.id)).tgChatId, -1009999);
await core.migrateChatGroup(db, -1009999, GROUP.id);
});
});
describe("TTL", () => {
test("Старые сообщения удалены, вопрос остаётся", async () => {
const p = await newProject();
const chat = await core.ensureProjectChat(db, p.id);
const ref = await newTask(p);
const q = await core.askPm(db, ref, { kind: "question", text: "Старый вопрос" });
await core.syncChats(db);
const old = new Date(Date.now() - 15 * 86_400_000);
await db.update(chatMessages).set({ createdAt: old }).where(eq(chatMessages.chatId, chat.id));
const n = await core.pruneChats(db);
assert.ok(n >= 1);
assert.equal((await core.chatMessagesView(db, chat.id)).length, 0);
assert.equal((await core.getQuestion(db, q.id)).text, "Старый вопрос");
});
});