peppa/apps/web/app/(app)/chats/[chat]/page.tsx
Асель fca28b8fec PEP-106: the platform's Telegram bot is never shown to users — group linking is superadmin-only
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-15 15:16:05 +05:00

288 lines
17 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import Link from "next/link";
import { notFound } from "next/navigation";
import { Bot, Hash, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react";
import { isSuperadmin, chatMessagesView, chatThreads, chatTtlMs, discussionMessages, discussionUnread, getSetting, listChats, markDiscussionRead, 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-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<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;
// 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);
if (discussion) await markDiscussionRead(db, user.id, chat.id);
const threads = master ? [] : await chatThreads(db, chat.id);
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 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 = discussion ? url({}) : url({ thread: thread === null ? CHANNEL : (thread ?? FEED) });
// The platform's bot (groups) is the superadmin's: users never see it — their own bot notifies them.
const superadmin = await isSuperadmin(db, user);
const bot = superadmin ? ((await getSetting<{ username: string }>(db, "telegram.bot"))?.username ?? null) : 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"
: discussion
? "Напишите сообщение участникам проекта…"
: taskThread
? "Ответ агенту: на открытый вопрос, иначе комментарий, который он увидит сразу"
: thread
? "Заметка в тред или команда /help"
: "Заметка в канал или команда: /status, /task KEY-N, /move KEY-N in_progress";
const aside = (
<div className="flex flex-col gap-5 text-sm">
{!superadmin && (
<section className="flex flex-col gap-2">
<h2 className="m-0 text-[15px] font-semibold">Telegram</h2>
<p className="m-0 text-muted-foreground">
{user.telegramBotUsername ? (
<>
Новые сообщения обсуждения и вопросы агентов приходят в ваш бот <span className="font-mono text-foreground">@{user.telegramBotUsername}</span>.
</>
) : (
<>
Чтобы новые сообщения приходили в Telegram, подключите своего бота: <Link href="/settings#telegram">Настройки → Telegram</Link>.
</>
)}
</p>
</section>
)}
<section className={cn("flex flex-col gap-2", !superadmin && "hidden")}>
<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="Чаты">
{master
? "Мастер-чат: всё важное по вашим проектам в одной ленте."
: "Обсуждение — обычный чат участников проекта: статусы, вопросы, договорённости. Агенты его не читают; чтобы написать агенту, откройте стори."}
</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" />}
{(unread.get(c.id) ?? 0) > 0 && c.id !== chat.id && (
<span className="rounded-full bg-info px-1.5 font-mono text-[11px] leading-4 font-semibold text-background tabular-nums" title="новые сообщения в обсуждении">
{unread.get(c.id)}
</span>
)}
{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" title="вопросы агентов">{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={discussion} title="💬 Обсуждение" meta="чат участников проекта" />
<ThreadLink href={url({ thread: FEED })} active={!discussion && thread === undefined} title="События агентов" meta="вопросы, ревью, релизы" />
{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>{discussion ? "Здесь пока тихо. Напишите первое сообщение — его увидят участники проекта." : 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={!discussion && thread === undefined} masterView={master} mine={discussion && m.authorUserId === user.id} />
</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">{discussion ? "видят участники проекта · агенты не читают" : 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, mine = false }: { m: ChatMessageView; q?: { q: Question; taskStatus: string | null; taskKey: string | null }; back: string; showThread: boolean; masterView: boolean; mine?: 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" ? (mine ? "вы" : (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>
);
}