From a0d1097e376b4ace82221513f7186d8216834f25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 19:09:32 +0500 Subject: [PATCH] =?UTF-8?q?PEP-62:=20web=20=C2=AB=D0=A7=D0=B0=D1=82=D1=8B?= =?UTF-8?q?=C2=BB=20(master=20+=20project=20chats,=20threads,=20composer,?= =?UTF-8?q?=20Telegram=20link),=20live=20scope,=20watchdog=20sync/TTL,=20e?= =?UTF-8?q?2e?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/web/app/(app)/chats/[chat]/page.tsx | 248 ++++++++++++++++++++++ apps/web/app/(app)/chats/actions.ts | 54 +++++ apps/web/app/(app)/chats/page.tsx | 5 + apps/web/components/Sidebar.tsx | 11 +- packages/runner/src/live.ts | 17 +- packages/runner/src/watchdog.ts | 10 + packages/testkit/src/mock-telegram.ts | 21 +- packages/testkit/test/chats.test.ts | 253 +++++++++++++++++++++++ 8 files changed, 611 insertions(+), 8 deletions(-) create mode 100644 apps/web/app/(app)/chats/[chat]/page.tsx create mode 100644 apps/web/app/(app)/chats/actions.ts create mode 100644 apps/web/app/(app)/chats/page.tsx create mode 100644 packages/testkit/test/chats.test.ts diff --git a/apps/web/app/(app)/chats/[chat]/page.tsx b/apps/web/app/(app)/chats/[chat]/page.tsx new file mode 100644 index 00000000..8b915adf --- /dev/null +++ b/apps/web/app/(app)/chats/[chat]/page.tsx @@ -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 }) { + 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 = ( +
+
+

Telegram

+ {chat.tgTitle ? ( + <> +

+ Связан с группой {chat.tgTitle}. Сообщения чата приходят туда, треды — цепочками ответов; ответ реплаем уходит в тред{master ? "" : " (в треде стори — агенту)"}. +

+
+ + + + + ) : link ? ( +
+

Код действует 10 минут.

+ {bot && ( + + Добавить @{bot} в группу → + + )} +

Или добавь бота в группу сам и отправь там:

+ /link {link} +
+ ) : ( + <> +

{master ? "Свяжи мастер-чат с группой — туда пойдёт всё важное по твоим проектам." : "Свяжи чат проекта с группой команды — по ней сразу видно, к какому проекту сообщение."}

+
+ + + + + )} +

Отвечать из группы могут те, кто привязал Telegram в «Настройках» и имеет доступ к {master ? "мастер-чату (только ты)" : "проекту"}.

+
+
+

Как это устроено

+

{master ? "Мастер-чат — вопросы, ревью, сбои, лимиты, релизы и ошибки всех твоих проектов, мониторинг и сводка. Команды — без LLM." : "Тред на каждую стори, инцидент и релиз. Вопросы агентов видны и здесь, и на Главной."}

+

Переписка хранится {ttlDays} дн.; стори, вопросы и события остаются на своих страницах.

+
+
+ ); + + return ( + + + + Мастер-чат и чаты проектов: события и вопросы агентов по тредам. Ответ в треде стори уходит агенту. + + + +
+ {!master && ( + + )} + +
+ {current && ( +
+ 🧵 {current} + {taskThread && } +
+ )} + {messages.length === 0 ? ( + {master ? "Пока тихо: здесь появятся вопросы агентов, сбои, релизы и ошибки твоих проектов." : thread === undefined ? "Сообщений пока нет: они появятся, когда агенты возьмутся за стори." : "В этом треде пока пусто."} + ) : ( +
    + {messages.map((m) => ( +
  1. + +
  2. + ))} +
+ )} +
+ +