import Link from "next/link"; import { notFound } from "next/navigation"; import { ArrowLeft, Bot, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react"; import { ANALYST_NAME, analystPending, attachmentsByMessage, chatStatusLine, isSuperadmin, chatGroupBotName, chatMessagesView, chatTtlMs, discussionMessages, discussionUnread, getSetting, listChats, markDiscussionRead, markThreadRead, masterFeed, projectThreadList, splitForDisplay, syncChats, threadTitle, THREAD_KEY, type AttachmentView, type ChatMessageView, type Question } from "@peppa/core"; import { projects, questions, tasks } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { PRODUCT_NAME, stripAsIs } from "@peppa/shared/i18n"; import { eq, inArray } from "drizzle-orm"; import { LiveRefresh } from "@/components/LiveRefresh"; import { AgentBadge } from "@/components/AgentBadge"; import { ChatThreadList } from "@/components/ChatThreadList"; import { ChatScroll } from "@/components/ChatScroll"; import { ChatLiveFeed } from "@/components/ChatLiveFeed"; import { ChatSwitch } from "@/components/ChatSwitch"; import { ago, Empty, Flash, linkify, StatusBadge } from "@/components/common"; import { Hidden, QuestionCard } from "@/components/cards"; import { ProposalList } from "@/components/ProposalList"; import { Dictate } from "@/components/Dictate"; import { Attachments } from "@/components/Attachments"; import { AttachField } from "@/components/AttachField"; import { Workspace } from "@/components/Workspace"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/input"; import { requireUser, words } from "@/lib/auth"; import { db } from "@/lib/db"; import { getT } from "@/lib/i18n"; import { cn } from "@/lib/utils"; import { cleanText, messageLink, STUCK_NOTICE } from "@/lib/chat-text"; import { chatOfferAction, linkChatAction, postChatAction, unlinkChatAction } from "../actions"; type Params = { error?: string; thread?: string; link?: string; q?: string; list?: string }; const CHANNEL = "channel"; /** PEP-106: `?thread=feed` — the agents' events; no `thread` — the people's discussion. */ const FEED = "feed"; /** «Чаты» (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 t = await getT(); const w = await words(); const { chat: slug } = await params; const { error, thread: rawThread, link, q, list: rawList } = 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; // A project chat opens on the discussion: people talking to each other, no agents or events. const discussion = !master && rawThread === undefined; const unread = await discussionUnread(db, user.id); // PEP-155: on a phone it is either the list (`?list=1`) or the open conversation, full screen. const showList = rawList === "1"; // PEP-207: what was unread before this look — the conversation opens there. const unreadBefore = discussion ? (unread.get(chat.id) ?? 0) : null; const threads = master ? null : await projectThreadList(db, user, chat, { q }); if (discussion && !showList) await markDiscussionRead(db, user.id, chat.id); if (thread && !master && !showList) await markThreadRead(db, user.id, chat.id, thread); // PEP-110: a person's message the analyst has not answered yet — «печатает…». const typing = discussion && (await analystPending(db, chat.id)); const rows = threads ? [...threads.waiting, ...threads.working, ...threads.done] : []; const messages = master ? await masterFeed(db, user, { limit: 150 }) : discussion ? await discussionMessages(db, chat.id) : await chatMessagesView(db, chat.id, { threadKey: thread, limit: 150 }); const files = await attachmentsByMessage(db, messages.map((m) => m.id)); const current = thread ? ((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 base = `/chats/${chat.slug}`; const url = (p: { thread?: string | null; list?: boolean }) => { const params = new URLSearchParams(); if (p.thread) params.set("thread", p.thread); if (threads?.q) params.set("q", threads.q); if (p.list) params.set("list", "1"); return params.size ? `${base}?${params}` : base; }; const openRow = thread ? rows.find((r) => r.key === thread) : undefined; const here = discussion ? url({}) : url({ thread: thread === null ? CHANNEL : (thread ?? FEED) }); // PEP-109: a group is linked through the user's own bot. The platform's bot is the superadmin's // (users never see it) and links groups only for a superadmin without a bot of their own. const superadmin = await isSuperadmin(db, user); const bot = user.telegramBotUsername ?? (superadmin ? ((await getSetting<{ username: string }>(db, "telegram.bot"))?.username ?? null) : null); const mayLink = !!user.telegramBotUsername || superadmin; const groupBot = chat.tgTitle ? await chatGroupBotName(db, chat.id) : null; const ttlDays = Math.round(chatTtlMs() / 86_400_000); const taskThread = thread?.startsWith("task:"); const placeholder = master ? w.engineer ? "/status, /task KEY-N, /move KEY-N in_progress, /help" : t("Заметка для себя") : discussion ? t("Спросите аналитика, что с проектом, или опишите идею — он поможет сформулировать {task}…", { task: w.task("acc") }) : taskThread ? t("Напишите агенту этой {task} — ответ на его вопрос или замечание, он увидит сразу", { task: w.task("gen") }) : thread ? w.engineer ? t("Заметка в тред или команда /help") : t("Заметка к этой переписке") : w.engineer ? t("Заметка в канал или команда: /status, /task KEY-N, /move KEY-N in_progress") : t("Заметка для себя и участников проекта"); const aside = (

Telegram

{user.telegramBotUsername ? ( <> {t("Новые сообщения обсуждения и вопросы агентов приходят в ваш бот")} @{user.telegramBotUsername}. ) : ( <> {t("Чтобы новые сообщения приходили в Telegram, подключите своего бота:")} {t("Настройки → Telegram")}. )}

{t("Telegram-группа")}

{chat.tgTitle ? ( <>

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

) : !mayLink ? (

{master ? t("Мастер-чат можно связать с группой Telegram — туда пойдёт всё важное по вашим проектам.") : t("Чат проекта можно связать с группой команды в Telegram.")}{" "} {t("Группа подключается через вашего собственного бота — сначала подключите его:")} {t("Настройки → Telegram")}.

) : link ? (

{t("Код действует 10 минут.")}

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

{t("Или добавьте {bot} в группу сами и отправьте там:", { bot: bot ? `@${bot}` : t("бота") })}

/link{bot ? `@${bot}` : ""} {link}
) : ( <>

{master ? t("Свяжите мастер-чат с группой — туда пойдёт всё важное по вашим проектам.") : t("Свяжите чат проекта с группой команды — по ней сразу видно, к какому проекту сообщение.")} {bot && ( <> {" "} {t("В группу добавится ваш бот")} @{bot}. )}

)}

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

{t("Как это устроено")}

{master ? t("Журнал: готовые {tasks}, вопросы, обновления продукта и сбои по всем вашим проектам. Отвечать удобнее в «Обзоре» или в чате проекта.", { tasks: w.task("pl") }) : t("Слева: чат с аналитиком — для вопросов и новых задач; «События агентов» — журнал; ниже — переписка по каждой {task} с её агентом.", { task: w.task("dat") })}

{t("Журнал событий хранится {n} дн.; ваша переписка с аналитиком не удаляется.", { n: ttlDays })}

); // PEP-207: the chat with the analyst holds people and the analyst; the factory's service notices // («задерживается на нашей стороне») are the status line on top, not messages — old ones included. const shownMessages = discussion ? messages.filter((m) => !(m.authorKind !== "user" && STUCK_NOTICE.test(stripAsIs(m.text)))) : messages; const status = discussion && chat.projectId ? await chatStatusLine(db, chat.projectId) : null; // PEP-207: oldest first, newest at the bottom — the first unread message is where the reader lands. const ordered = [...shownMessages]; const unreadCount = discussion ? (unreadBefore ?? 0) : (openRow?.unread ?? 0); const counted = (m: ChatMessageView) => (discussion ? m.authorUserId !== user.id : m.kind === "question" || (m.kind === "user" && m.authorKind !== "user")); let firstUnreadId: number | null = null; if (unreadCount > 0) { let left = unreadCount; for (let i = ordered.length - 1; i >= 0 && left > 0; i--) { if (!counted(ordered[i]!)) continue; firstUnreadId = ordered[i]!.id; left--; } } const groups = groupMessages(ordered, !discussion && !master); const taskStatus = openRow?.status ?? null; const writable = !(master || (!discussion && thread === undefined)); // PEP-207: superadmins see the raw journal on its own page; this view is cleaned for everybody. const gitea = (process.env.GITEA_URL ?? "").replace(/\/+$/, ""); const options = [...list.filter((c) => c.kind === "project"), ...list.filter((c) => c.kind === "master")].map((c) => { const name = c.kind === "master" ? t("Все события") : c.title.includes(" · ") ? c.title.split(" · ").slice(1).join(" · ") : c.slug; const marks = [(unread.get(c.id) ?? 0) > 0 && c.id !== chat.id ? t("{n} нов.", { n: unread.get(c.id) ?? 0 }) : null, c.open > 0 ? `${c.open} ?` : null].filter(Boolean).join(" · "); return { slug: c.slug, label: marks ? `${c.kind === "master" ? name : `${c.slug} · ${name}`} (${marks})` : c.kind === "master" ? name : `${c.slug} · ${name}` }; }); const feed = ordered.length === 0 ? ( {discussion ? t("Напишите, что хотите узнать или сделать, — аналитик ответит здесь же. Например: «Что сейчас в работе?» или «Хочу страницу с отзывами клиентов».") : master ? t("Пока тихо: здесь появятся вопросы агентов, сбои и обновления ваших проектов.") : thread === undefined ? t("Сообщений пока нет: они появятся, когда агенты возьмутся за {tasks}.", { tasks: w.task("accPl") }) : t("В этом треде пока пусто.")} ) : (
    {groups.map((g) => g.kind === "events" ? (
  1. ) : (
  2. ), )}
); return ( {/* PEP-228: a project chat draws its new messages in place (ChatLiveFeed) and re-renders only for what it can't draw; the master feed gathers every project and re-renders. */}

{t("Чаты")}

{t("Все чаты")} {threads ? ( ) : (

{t("Все события по вашим проектам — справочно. Чтобы ответить или написать, выберите проект.")}

)} {master && superadmin && ( {t("Полный журнал платформы →")} )}
Telegram
{aside}
{current ? t.text(current) : master ? t("Все события") : discussion ? t("Чат с аналитиком") : t("События агентов")} {openRow?.status && } {openRow?.agentName && } {taskThread && }
{status && status.working.length + status.delayed.length > 0 && (
{status.delayed.length ? t("Сейчас: делается {n}, задерживаются на нашей стороне {m}", { n: status.working.length, m: status.delayed.length }) : t("Сейчас: делается {n}", { n: status.working.length })}
    {[...status.delayed.map((r) => ({ ...r, delayed: true })), ...status.working.map((r) => ({ ...r, delayed: false }))].map((r) => (
  • {r.key} {r.title} {r.delayed && {t("небольшая задержка на нашей стороне")}}
  • ))}
)} {!writable && (

{t("Это журнал событий — писать сюда не нужно.")}{" "} {master ? {t("Выберите проект")} : {t("Откройте чат с аналитиком")}}{t(", чтобы задать вопрос или описать задачу.")}

)} {master ? ( <> {feed}
) : ( {t("печатает…")}

) : null } > {feed}
)} {writable && (