Merge pull request 'PEP-106: обсуждение проекта — простой чат для людей' (#95) from task/pep-106 into main
This commit is contained in:
commit
91eca5ce23
@ -36,6 +36,7 @@
|
||||
- **Команда агентов (PEP-75)**: таблица `agents` (имя, `character`, `disabled_at`) + `sessions.agent_id` (миграция 0014), одна команда на платформу. `core/team.ts`: `ensureSessionAgent` (в `launch`, sync-транзакция: персонаж прошлых раннеров стори → свободный, отдыхавший дольше → новый из `AGENT_NAMES`), `agentPrompt` дописывается к правилам запуска вместе с памятью, `taskAgentNames` — имена на доске, `SessionView.agentName`. Имена сравнивать в JS: `lower()` SQLite не трогает кириллицу. Веб `/team` (видят все, меняет суперадмин — `team/actions.ts`), `components/AgentBadge.tsx`
|
||||
- **Выбор подписки проекта (PEP-76)**: общий пул платформы — `platform.shared_pool` (`sharedPool`/`setSharedPool`, CLI `peppa platform shared-pool [id|-]`); владелец проекта (или суперадмин) в «⋯ Настройки проекта → Подписки» жмёт «Общая подписка Пеппы» (`chooseSharedSubscription`) или вставляет токен `claude setup-token` — «Своя подписка Claude» (`connectOwnSubscription`, runner/project-subscription.ts: подписка + личный пул `ownPool`); `projectAgentWarning` для проекта без пула и без права на вход машины — «подписка не выбрана»
|
||||
- **Чаты (PEP-62)**: таблицы `chats` (master на пользователя / project на проект, связанная Telegram-группа `tg_chat_id`) и `chat_messages` (тред = `thread_key` `task:|incident:|release:<id>`, null — канал; `important` → мастер-лента; `dedupe_key`), `telegram_outbox.chat_message_id` (миграция 0015). `core/chats.ts`: `syncChats` — идемпотентная проекция `events` (курсор `chat.cursor.events`, список `EVENT_TEXT`), `questions`, `releases`/`incidents` (по `updated_at`, ключ `<вид>:<id>:<статус>`) в чаты; зовут бот (`reconcile`), вачдог (`tick`) и страница `/chats`; `masterFeed` = свои сообщения мастер-чата ∪ `important` проектов; `pruneChats` — TTL `PEPPA_CHAT_TTL_DAYS` (14) в вачдоге раз в час; мониторинг и дайджест из `deliverToUser` пишутся в мастер-чат. `runner/chats.ts` `postToChat`: тред стори → `answerAndDeliver` открытого вопроса, иначе `addStoryComment` (`chatMessageId` в payload, проекция не дублирует) + `sendToSession`; `/status|/task|/move|/help` без LLM. Telegram (бот): связка кодом (`createChatLinkCode`, `c…`, 10 мин; `t.me/<bot>?startgroup=<код>` или `/link <код>`), зеркало по курсору `chat.mirror.cursor` (тред — реплаем на первое сообщение: `threadAnchor` при отправке), в группу принимаются только реплаи и команды от пользователя с личной привязкой (`telegramAccountUser`) и доступом; кнопки вопросов работают в группе. Веб `/chats/[master|KEY]?thread=`, live-область `chats`. Тест `chats.test.ts`
|
||||
- **Обсуждение проекта (PEP-106)**: чат проекта открывается на «Обсуждении» — только сообщения людей в канале (`discussionMessages`: `thread_key` null, `kind` user, не команда); события агентов — `/chats/KEY?thread=feed`. `markDiscussionRead`/`discussionUnread` (`chat.read:<user>:<chat>`) → счётчик `navCounts.chats`, плашки чатов, ссылка «Обсуждение» после «Доски» на странице проекта. `postToChat` в канал проекта уведомляет остальных (`projectAudience`) событием уведомлений `chat`. `pruneChats` обсуждение не удаляет. Агентам обсуждение не уходит. Тест `discussion.test.ts`
|
||||
- **Прогресс на Главной (PEP-77)**: `progressOverview` (core/progress.ts: стори по колонкам доски без архивных, стори в работе с агентом и прогрессом tasks.md, ждущие «Принять»; итог — только свои проекты, суперадмину отдельно `others`), раздел «Прогресс» — `components/ProgressOverview.tsx`
|
||||
- **Стори берутся сами (PEP-79)**: уровень автономности `self` «Сам берёт» (pick=auto, приёмка за PM); `provisionProject` ставит новому проекту `NEW_PROJECT_AUTONOMY`; диспетчер (`autonomyTick`) не запускает и не пингует, пока есть `projectAgentWarning`
|
||||
- **Продакту — без технических вопросов (PEP-94)**: правила `template/RULES.md` — технику агент решает сам (`design.md`, `remember`), `ask_pm` — только продуктовое, простыми словами, рекомендация первой, ответа не ждёт; MCP `request_approval` отклоняется, если `proposal !== "pm"`; аналитик не спрашивает (вопросы → «Допущения» сразу); `NEW_PROJECT_AUTONOMY` = `auto`; в вебе Proposal → «План», вкладки стори по-русски (id прежние)
|
||||
|
||||
@ -114,6 +114,7 @@ const PUSH_TITLE: Record<NotifyEvent, string> = {
|
||||
failures: "Раннер остановился",
|
||||
releases: "Релиз",
|
||||
incidents: "Ошибка в проде",
|
||||
chat: "Сообщение в обсуждении",
|
||||
monitoring: "Мониторинг",
|
||||
digest: "Сводка",
|
||||
platform: "Обновления Пеппы",
|
||||
|
||||
@ -433,9 +433,10 @@ export async function pairTelegram(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
||||
// PEP-85: the user's own bot if they connected one, else the platform's shared bot.
|
||||
const username = user.telegramBotUsername ?? (await getSetting<{ username: string }>(db, "telegram.bot"))?.username;
|
||||
if (!token || !username) throw new PeppaError("Telegram-бот Пеппы не запущен");
|
||||
// Every user has their own bot (PEP-85/100): the platform's bot is never offered to users.
|
||||
const username = user.telegramBotUsername;
|
||||
if (!username) throw new PeppaError("Сначала подключите своего Telegram-бота");
|
||||
if (!token) throw new PeppaError("Telegram-сервис Пеппы не запущен");
|
||||
return `https://t.me/${username}?start=${await createPairingCode(db, token, user.id)}`;
|
||||
});
|
||||
}
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
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 { 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";
|
||||
@ -19,6 +19,8 @@ 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> }) {
|
||||
@ -32,9 +34,17 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
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 }) : await chatMessagesView(db, chat.id, { threadKey: thread, limit: 150 });
|
||||
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).
|
||||
@ -48,22 +58,42 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
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 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"
|
||||
: taskThread
|
||||
? "Ответ агенту: на открытый вопрос, иначе комментарий, который он увидит сразу"
|
||||
: thread
|
||||
? "Заметка в тред или команда /help"
|
||||
: "Заметка в канал или команда: /status, /task KEY-N, /move KEY-N in_progress";
|
||||
: discussion
|
||||
? "Напишите сообщение участникам проекта…"
|
||||
: 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>
|
||||
{!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">
|
||||
@ -114,7 +144,11 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
<Workspace aside={aside}>
|
||||
<LiveRefresh scope="chats" />
|
||||
<Flash error={error} />
|
||||
<PageHeader title="Чаты">Мастер-чат и чаты проектов: события и вопросы агентов по тредам. Ответ в треде стори уходит агенту.</PageHeader>
|
||||
<PageHeader title="Чаты">
|
||||
{master
|
||||
? "Мастер-чат: всё важное по вашим проектам в одной ленте."
|
||||
: "Обсуждение — обычный чат участников проекта: статусы, вопросы, договорённости. Агенты его не читают; чтобы написать агенту, откройте стори."}
|
||||
</PageHeader>
|
||||
|
||||
<nav className="mb-4 flex flex-wrap gap-1.5" aria-label="Чаты">
|
||||
{list.map((c) => (
|
||||
@ -131,7 +165,12 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
{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>}
|
||||
{(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>
|
||||
@ -139,8 +178,8 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
<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="# Канал" />
|
||||
<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} />
|
||||
@ -157,12 +196,12 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
</div>
|
||||
)}
|
||||
{messages.length === 0 ? (
|
||||
<Empty>{master ? "Пока тихо: здесь появятся вопросы агентов, сбои, релизы и ошибки твоих проектов." : thread === undefined ? "Сообщений пока нет: они появятся, когда агенты возьмутся за стори." : "В этом треде пока пусто."}</Empty>
|
||||
<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={thread === undefined} masterView={master} />
|
||||
<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>
|
||||
@ -171,7 +210,7 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
<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>
|
||||
<span className="text-xs text-muted-foreground">{discussion ? "видят участники проекта · агенты не читают" : thread ? "в тред" : master ? "в мастер-чат" : "в канал"}{chat.tgTitle ? ` · и в Telegram «${chat.tgTitle}»` : ""}</span>
|
||||
<Button size="sm" className="ml-auto">
|
||||
<Send />
|
||||
Отправить
|
||||
@ -209,14 +248,14 @@ 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 }) {
|
||||
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" ? (m.authorLogin ?? "?") : m.authorKind === "agent" ? "агент" : "Пеппа"}</span>
|
||||
<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">
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
"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 { chatForUser, createChatLinkCode, isSuperadmin, PeppaError, unlinkChat } from "@peppa/core";
|
||||
import { postToChat } from "@peppa/runner";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { revalidatePath } from "next/cache";
|
||||
@ -41,6 +41,8 @@ export async function linkChatAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const token = loadEnv().TELEGRAM_BOT_TOKEN;
|
||||
if (!token) throw new PeppaError("Telegram-бот Пеппы не настроен");
|
||||
// PEP-106: groups work through the platform's bot only — that bot is the superadmin's, not the users'.
|
||||
if (!(await isSuperadmin(db, user))) 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";
|
||||
|
||||
@ -74,7 +74,7 @@ export default async function Help() {
|
||||
<li><b>Стори берутся сами</b> — в новом проекте карточки перетаскивать не нужно: агент сам берёт стори из бэклога по порядку на доске, вам остаётся «Принять» результат. Уровень «Сам берёт» меняется в «⋯ Настройки проекта → Автономность».</li>
|
||||
<li><b>Telegram</b> — у каждого пользователя свой бот: в «Настройки → Telegram» три шага — создать бота у @BotFather (команда <span className="font-mono">/newbot</span>), вставить его токен, открыть бота и нажать Start. Из него приходят вопросы агентов и «готово к ревью», ему же можно написать новую задачу. Не хотите создавать — там же можно выбрать общего бота Пеппы.</li>
|
||||
<li><b>Продакт и аналитик</b> — два агента, которые читают новую задачу раньше разработчика. Продакт решает, зачем это и что берём в первую версию (большое делит на несколько стори). Аналитик пишет критерии приёмки и задаёт до трёх вопросов — у каждого есть вариант по умолчанию; не ответите за 30 минут (ночью — до утра), он возьмёт его сам. Их реплики — во вкладке Comments стори и в чате проекта. Включается в «⋯ Настройки проекта → Продакт и аналитик», в новых проектах включено.</li>
|
||||
<li><b>Команда</b> — агенты Пеппы с именами (Айгерим, Нурлан…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его имя видно на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.</li>
|
||||
<li><b>Команда</b> — ИИ-агенты с кличками (Шустрик, Беркут…), одна команда на все проекты: свободный агент берёт стори и ведёт её до конца, его кличка видна на карточке. В разделе «Команда» суперадмин задаёт агенту характер и специализацию — они добавляются к его промпту.</li>
|
||||
<li><b>Вход</b> — через eGov QR (с телефона — кнопка «Открыть в eGov Mobile») или через Google (кнопка есть, когда суперадмин задал <span className="font-mono">GOOGLE_CLIENT_ID/SECRET</span>); в «Настройках» их можно связать в одну учётку. Первый вход сам создаёт учётку по ИИН или Google-почте: логин из имени в сертификате (например, <span className="font-mono">aigerim.ivanova</span>). Новый пользователь видит только проекты, куда его пригласили, и свои; агенты его проектов работают только на пуле подписок, который назначает суперадмин. У такой учётки нет аккаунта Gitea — код только через Пеппу, а новые проекты создаются в пространстве <span className="font-mono">peppa-bot</span>.</li>
|
||||
<li><b>Раннер</b> — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе <Link href="/runners">Раннеры</Link>: статус, стори, команда <code>tmux attach</code>, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и <b>живой терминал</b>: экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта.</li>
|
||||
<li><b>Новый терминал</b> — раннер без стори: в «Раннерах» или на вкладке «Сессии» проекта выбери проект, имя, агента и напиши промпт (можно голосом — кнопка «Голосом» в браузерах с распознаванием речи). После ходов такой раннер не пингует — им управляешь ты в терминале. Получилась работа — «Оформить стори» в карточке раннера: стори создаётся в работе, раннер ведёт её дальше. Раннер можно переименовать.</li>
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
import { Fragment } from "react";
|
||||
import { notFound } from "next/navigation";
|
||||
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
|
||||
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release } from "@peppa/runner";
|
||||
import { listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
||||
import { discussionUnread, ensureProjectChat, listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { PanelSection } from "@/components/ActivityAside";
|
||||
import { Board, type Card } from "@/components/Board";
|
||||
@ -141,6 +142,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
const [code, pulls] = await Promise.all([tab === "code" ? repoOverview(db, p) : null, tab === "pulls" ? openPulls(db, p) : null]);
|
||||
const specs = tab === "specs" ? listSpecs(p) : [];
|
||||
const agentsMd = tab === "agents" ? await readAgentsMd(db, p) : null;
|
||||
const discussionNew = (await discussionUnread(db, user.id)).get((await ensureProjectChat(db, p.id)).id) ?? 0;
|
||||
const memory = tab === "specs" ? readMemory(p.workspacePath) : "";
|
||||
// PEP-47 metrics, PEP-48 journal, PEP-43 default budget.
|
||||
const metrics = tab === "metrics" ? await projectMetrics(db, p.id, { weeks: Number(weeks) || 8 }) : null;
|
||||
@ -429,8 +431,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
|
||||
<nav aria-label="Разделы проекта" className="-mt-2 mb-4 flex gap-1 overflow-x-auto border-b">
|
||||
{TABS.map((t) => (
|
||||
<Fragment key={t.id}>
|
||||
<a
|
||||
key={t.id}
|
||||
href={t.id === "board" ? `/p/${p.key}` : `/p/${p.key}?tab=${t.id}`}
|
||||
aria-current={tab === t.id ? "page" : undefined}
|
||||
className={cn(
|
||||
@ -441,6 +443,14 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
{t.label}
|
||||
{!!tabCount[t.id] && <span className="rounded-full bg-muted px-1.5 font-mono text-[11px] tabular-nums">{tabCount[t.id]}</span>}
|
||||
</a>
|
||||
{/* PEP-106: the people's chat of the project lives in «Чаты»; the link sits right after the board. */}
|
||||
{t.id === "board" && (
|
||||
<a href={`/chats/${p.key}`} className="-mb-px flex items-center gap-1.5 border-b-2 border-transparent px-3 py-2 text-sm whitespace-nowrap text-muted-foreground hover:text-foreground hover:no-underline">
|
||||
Обсуждение
|
||||
{discussionNew > 0 && <span className="rounded-full bg-info px-1.5 font-mono text-[11px] text-background tabular-nums">{discussionNew}</span>}
|
||||
</a>
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
|
||||
@ -13,7 +13,7 @@ interface Item {
|
||||
label: string;
|
||||
icon: LucideIcon;
|
||||
match: (p: string) => boolean;
|
||||
count?: "questions" | "waitingRunners";
|
||||
count?: "questions" | "waitingRunners" | "chats";
|
||||
/** 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 «Чаты»). */
|
||||
@ -22,7 +22,7 @@ interface Item {
|
||||
|
||||
const ITEMS: Item[] = [
|
||||
{ href: "/", label: "Главная", icon: House, match: (p) => p === "/", count: "questions" },
|
||||
{ href: "/chats", label: "Чаты", icon: MessagesSquare, match: (p) => p.startsWith("/chats") },
|
||||
{ href: "/chats", label: "Чаты", icon: MessagesSquare, match: (p) => p.startsWith("/chats"), count: "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"), desktopOnly: true },
|
||||
@ -36,10 +36,10 @@ const ITEMS: Item[] = [
|
||||
{ href: "/users", label: "Пользователи", icon: Users, match: (p) => p.startsWith("/users"), admin: true },
|
||||
{ href: "/settings", label: "Настройки", icon: Settings, match: (p) => p.startsWith("/settings") },
|
||||
];
|
||||
const COUNT_TITLE = { questions: "вопросов ждут тебя", waitingRunners: "раннеров ждут тебя" };
|
||||
const COUNT_TITLE = { questions: "вопросов ждут вас", waitingRunners: "агентов ждут вас", chats: "новых сообщений в обсуждениях" };
|
||||
|
||||
/** Left panel on desktop; on phones a top bar plus a bottom tab bar (PEP-38): sections with «ждут тебя» counters, theme, user. */
|
||||
export function Sidebar({ login, avatarUrl, counts, superadmin = false }: { login: string; avatarUrl: string | null; counts: Record<"questions" | "waitingRunners", number>; superadmin?: boolean }) {
|
||||
export function Sidebar({ login, avatarUrl, counts, superadmin = false }: { login: string; avatarUrl: string | null; counts: Record<"questions" | "waitingRunners" | "chats", number>; superadmin?: boolean }) {
|
||||
const path = usePathname();
|
||||
return (
|
||||
<header className="sticky top-0 z-30 flex h-14 items-center gap-2 border-b bg-sidebar px-3 md:h-dvh md:flex-col md:items-stretch md:gap-1 md:border-r md:border-b-0 md:px-3 md:py-4">
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { listSessions, PeppaError, STEP_EVENT, projectForUser, resolveTask, userProjectIds, type Project, type TaskRef } from "@peppa/core";
|
||||
import { listSessions, PeppaError, STEP_EVENT, projectForUser, resolveTask, userProjectIds, type Project, type TaskRef, discussionUnread } from "@peppa/core";
|
||||
import { events, projects, questions, sessions, tasks } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { and, asc, count, desc, eq, inArray, isNull, ne } from "drizzle-orm";
|
||||
@ -61,12 +61,14 @@ export const isActiveSession = (status: string) => !["done", "failed"].includes(
|
||||
|
||||
/** OpenSpec artifacts of a change from the working copy (active or archived). */
|
||||
/** Counters of the side navigation (PEP-38): open PM questions and runners waiting for the PM. */
|
||||
export async function navCounts(userId: number): Promise<{ questions: number; waitingRunners: number }> {
|
||||
export async function navCounts(userId: number): Promise<{ questions: number; waitingRunners: number; chats: number }> {
|
||||
const ids = await userProjectIds(db, userId);
|
||||
if (!ids.length) return { questions: 0, waitingRunners: 0 };
|
||||
if (!ids.length) return { questions: 0, waitingRunners: 0, chats: 0 };
|
||||
const [q] = await db.select({ n: count() }).from(questions).where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt)));
|
||||
const [r] = await db.select({ n: count() }).from(sessions).where(and(inArray(sessions.projectId, ids), eq(sessions.status, "waiting_input")));
|
||||
return { questions: q?.n ?? 0, waitingRunners: r?.n ?? 0 };
|
||||
// PEP-106: messages of other people in the projects' discussions the user has not read.
|
||||
const chats = [...(await discussionUnread(db, userId)).values()].reduce((a, b) => a + b, 0);
|
||||
return { questions: q?.n ?? 0, waitingRunners: r?.n ?? 0, chats };
|
||||
}
|
||||
|
||||
/** Latest events of one runner, newest first (runner details panel, PEP-38). */
|
||||
|
||||
22
openspec/changes/pep-106-project-discussion/proposal.md
Normal file
22
openspec/changes/pep-106-project-discussion/proposal.md
Normal file
@ -0,0 +1,22 @@
|
||||
# Proposal: PEP-106 — обсуждение проекта: простой чат для людей
|
||||
|
||||
## Why
|
||||
Пользователям нужен обычный чат проекта — обсудить статусы и вопросы между собой, без кода и
|
||||
агентов. «Чаты» (PEP-62) — лента событий агентов с командами; писать людям можно было только
|
||||
в «# Канал» с подписью «Заметка в канал или команда».
|
||||
|
||||
## What Changes
|
||||
- Чат проекта открывается на «Обсуждении»: только сообщения людей проекта в канале
|
||||
(`discussionMessages`: без тредов, событий и команд). События агентов — `?thread=feed`.
|
||||
- Поле «Напишите сообщение участникам проекта…», подпись «видят участники проекта · агенты не
|
||||
читают»; своё сообщение подписано «вы».
|
||||
- Непрочитанное: `markDiscussionRead` / `discussionUnread` (`chat.read:<user>:<chat>`), счётчик в
|
||||
меню «Чаты», на плашке чата и у ссылки «Обсуждение» на странице проекта (после «Доски»).
|
||||
- Уведомление остальным участникам (владелец + участники): новое событие уведомлений `chat`
|
||||
«Сообщения в обсуждении проекта» (Telegram + браузер, отключаемо в «Настройках»).
|
||||
- Сообщения обсуждения не удаляются по TTL чатов (`pruneChats` чистит только проекцию).
|
||||
|
||||
- Общий бот платформы пользователям не показывается: блок «Telegram-группа» в чатах и `linkChatAction` — только суперадмину; пользователю — «сообщения приходят в ваш бот»; `pairTelegram` без запасного общего бота.
|
||||
|
||||
## Вне scope
|
||||
Личные сообщения, вложения, реакции, упоминания.
|
||||
@ -0,0 +1,20 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Обсуждение проекта
|
||||
Чат проекта SHALL давать его людям обычную переписку между собой, отдельно от событий и вопросов агентов; агенты её не получают.
|
||||
|
||||
#### Scenario: Участник пишет в обсуждение
|
||||
- **WHEN** владелец пишет «Когда покажем заказчику?» в обсуждении проекта
|
||||
- **THEN** сообщение видят участники проекта, остальным приходит уведомление по их настройкам, агентам оно не отправляется
|
||||
|
||||
#### Scenario: Посторонний
|
||||
- **WHEN** пользователь без доступа к проекту пытается написать в его обсуждение
|
||||
- **THEN** сообщение отклоняется
|
||||
|
||||
#### Scenario: Непрочитанное
|
||||
- **WHEN** в обсуждении есть сообщения других людей, которых пользователь не открывал
|
||||
- **THEN** он видит их число в меню «Чаты» и у ссылки «Обсуждение», после открытия счётчик сбрасывается
|
||||
|
||||
#### Scenario: Срок хранения
|
||||
- **WHEN** проходит срок хранения проекции чатов
|
||||
- **THEN** события и треды удаляются, сообщения обсуждения остаются
|
||||
4
openspec/changes/pep-106-project-discussion/tasks.md
Normal file
4
openspec/changes/pep-106-project-discussion/tasks.md
Normal file
@ -0,0 +1,4 @@
|
||||
- [x] 1.1 core: discussionMessages, read/unread, prune, событие `chat`
|
||||
- [x] 1.2 runner: уведомление участникам из postToChat
|
||||
- [x] 1.3 веб: «Обсуждение» по умолчанию, «События агентов», счётчики, ссылка в проекте
|
||||
- [x] 1.4 тест discussion.test.ts; проверка в браузере на копии базы
|
||||
@ -151,6 +151,7 @@ export interface ChatMessageView {
|
||||
kind: ChatMessage["kind"];
|
||||
important: boolean;
|
||||
authorKind: ChatMessage["authorKind"];
|
||||
authorUserId: number | null;
|
||||
authorLogin: string | null;
|
||||
via: ChatMessage["via"];
|
||||
text: string;
|
||||
@ -179,6 +180,7 @@ async function views(db: Db, where: SQL, limit: number, before?: number): Promis
|
||||
kind: m.kind,
|
||||
important: m.important,
|
||||
authorKind: m.authorKind,
|
||||
authorUserId: m.authorUserId,
|
||||
authorLogin: m.authorLogin,
|
||||
via: m.via,
|
||||
text: m.text,
|
||||
@ -196,6 +198,42 @@ export async function chatMessagesView(db: Db, chatId: number, o: { threadKey?:
|
||||
return views(db, and(...w)!, o.limit ?? 100, o.before);
|
||||
}
|
||||
|
||||
// ── discussion (PEP-106) ────────────────────────────────────────────────────
|
||||
|
||||
/** People's messages in a project chat's channel: no agents, no events, no commands. */
|
||||
const DISCUSSION = and(isNull(chatMessages.threadKey), eq(chatMessages.kind, "user"), sql`${chatMessages.text} NOT LIKE '/%'`)!;
|
||||
|
||||
/** PEP-106: the project's discussion — a plain chat of its people, oldest first. */
|
||||
export async function discussionMessages(db: Db, chatId: number, o: { limit?: number } = {}): Promise<ChatMessageView[]> {
|
||||
return views(db, and(eq(chatMessages.chatId, chatId), DISCUSSION)!, o.limit ?? 200);
|
||||
}
|
||||
|
||||
const readKey = (userId: number, chatId: number) => `chat.read:${userId}:${chatId}`;
|
||||
|
||||
/** The user has seen the discussion up to its last message. */
|
||||
export async function markDiscussionRead(db: Db, userId: number, chatId: number): Promise<void> {
|
||||
const [last] = await db.select({ id: sql<number | null>`max(${chatMessages.id})` }).from(chatMessages).where(and(eq(chatMessages.chatId, chatId), DISCUSSION));
|
||||
const id = Number(last?.id ?? 0);
|
||||
if (id > ((await getSetting<number>(db, readKey(userId, chatId))) ?? 0)) await setSetting(db, readKey(userId, chatId), id);
|
||||
}
|
||||
|
||||
/** Messages of other people the user has not seen yet, per project chat (chatId → count). */
|
||||
export async function discussionUnread(db: Db, userId: number): Promise<Map<number, number>> {
|
||||
const ids = await userProjectIds(db, userId);
|
||||
const out = new Map<number, number>();
|
||||
if (!ids.length) return out;
|
||||
const cs = await db.select({ id: chats.id }).from(chats).where(inArray(chats.projectId, ids));
|
||||
for (const c of cs) {
|
||||
const seen = (await getSetting<number>(db, readKey(userId, c.id))) ?? 0;
|
||||
const [r] = await db
|
||||
.select({ n: sql<number>`count(*)` })
|
||||
.from(chatMessages)
|
||||
.where(and(eq(chatMessages.chatId, c.id), DISCUSSION, gt(chatMessages.id, seen), or(isNull(chatMessages.authorUserId), sql`${chatMessages.authorUserId} <> ${userId}`)));
|
||||
if (Number(r?.n)) out.set(c.id, Number(r!.n));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The master feed: the user's own master messages and the important messages of the chats
|
||||
* of their projects (muted projects left out). `threadKey` narrows it to one project thread.
|
||||
@ -424,9 +462,11 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise<number>
|
||||
/** Deletes chat messages older than the TTL (the stories, questions and events stay). */
|
||||
export async function pruneChats(db: Db, o: { now?: Date } = {}): Promise<number> {
|
||||
const before = new Date((o.now ?? new Date()).getTime() - chatTtlMs());
|
||||
const old = db.select({ id: chatMessages.id }).from(chatMessages).where(lt(chatMessages.createdAt, before));
|
||||
// PEP-106: what people wrote to each other in the discussion is kept; the projection is not.
|
||||
const stale = and(lt(chatMessages.createdAt, before), sql`NOT (${DISCUSSION})`)!;
|
||||
const old = db.select({ id: chatMessages.id }).from(chatMessages).where(stale);
|
||||
await db.update(telegramOutbox).set({ chatMessageId: null }).where(inArray(telegramOutbox.chatMessageId, old));
|
||||
const rows = await db.delete(chatMessages).where(lt(chatMessages.createdAt, before)).returning({ id: chatMessages.id });
|
||||
const rows = await db.delete(chatMessages).where(stale).returning({ id: chatMessages.id });
|
||||
return rows.length;
|
||||
}
|
||||
|
||||
|
||||
@ -22,7 +22,7 @@ export function htmlToText(html: string): string {
|
||||
.replace(/&/g, "&");
|
||||
}
|
||||
|
||||
export const NOTIFY_EVENTS = ["questions", "review", "failures", "releases", "incidents", "monitoring", "digest", "platform"] as const;
|
||||
export const NOTIFY_EVENTS = ["questions", "review", "failures", "releases", "incidents", "chat", "monitoring", "digest", "platform"] as const;
|
||||
export type NotifyEvent = (typeof NOTIFY_EVENTS)[number];
|
||||
|
||||
export const NOTIFY_EVENT_NAMES: Record<NotifyEvent, string> = {
|
||||
@ -31,6 +31,7 @@ export const NOTIFY_EVENT_NAMES: Record<NotifyEvent, string> = {
|
||||
failures: "Сбои, зависания и лимиты раннеров",
|
||||
releases: "Релизы и выкаты",
|
||||
incidents: "Ошибки из прода",
|
||||
chat: "Сообщения в обсуждении проекта",
|
||||
monitoring: "Мониторинг Пеппы (админам)",
|
||||
digest: "Ежедневный дайджест",
|
||||
platform: "Дайджест обновлений Пеппы",
|
||||
@ -62,7 +63,7 @@ export const serverTimezone = () => process.env.PEPPA_TZ || Intl.DateTimeFormat(
|
||||
export function defaultPrefs(): NotifyPrefs {
|
||||
const on = { telegram: true, push: true };
|
||||
return {
|
||||
events: { questions: on, review: on, failures: on, releases: on, incidents: on, monitoring: on, digest: { telegram: true, push: false }, platform: { telegram: true, push: false } },
|
||||
events: { questions: on, review: on, failures: on, releases: on, incidents: on, chat: on, monitoring: on, digest: { telegram: true, push: false }, platform: { telegram: true, push: false } },
|
||||
quiet: null,
|
||||
timezone: serverTimezone(),
|
||||
digestTime: "09:00",
|
||||
|
||||
@ -5,6 +5,8 @@ import {
|
||||
addChatMessage,
|
||||
addStoryComment,
|
||||
chatForUser,
|
||||
deliverToUser,
|
||||
projectAudience,
|
||||
listSessions,
|
||||
notify,
|
||||
pendingQuestions,
|
||||
@ -105,10 +107,35 @@ export async function postToChat(db: Db, user: User, p: ChatPost): Promise<ChatP
|
||||
replyText = `⚠️ ${(e as Error).message}`;
|
||||
}
|
||||
const reply = replyText ? await say(replyText) : null;
|
||||
// PEP-106: a message in the project's discussion reaches its other people (by their preferences).
|
||||
if (chat.kind === "project" && chat.projectId && !p.threadKey && !text.startsWith("/")) {
|
||||
await notifyDiscussion(db, user, chat.projectId, message).catch(() => {});
|
||||
}
|
||||
await notify(db, { type: "chat_message", messageId: message.id });
|
||||
return { message, reply };
|
||||
}
|
||||
|
||||
const esc = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
|
||||
/** Tells the project's other people about a new message in its discussion. */
|
||||
async function notifyDiscussion(db: Db, author: User, projectId: number, m: ChatMessage): Promise<void> {
|
||||
const [project] = await db.select({ key: projects.key, name: projects.name }).from(projects).where(eq(projects.id, projectId));
|
||||
if (!project) return;
|
||||
const url = `/chats/${project.key}`;
|
||||
const short = m.text.length > 500 ? `${m.text.slice(0, 500)}…` : m.text;
|
||||
for (const u of await projectAudience(db, projectId)) {
|
||||
if (u.id === author.id) continue;
|
||||
await deliverToUser(db, u, {
|
||||
event: "chat",
|
||||
projectId,
|
||||
dedupeKey: `chat:m${m.id}:${u.telegramChatId}`,
|
||||
pushKey: `chat:m${m.id}:u${u.id}`,
|
||||
telegram: { params: { text: `💬 <b>${esc(project.name)}</b> · ${esc(author.login)}:\n${esc(short)}\n\nОтветить: ${process.env.PEPPA_WEB_URL ?? ""}${url}`, parse_mode: "HTML", link_preview_options: { is_disabled: true } } },
|
||||
push: { title: `${project.name}: ${author.login}`, body: short.slice(0, 200), url, tag: `chat:${projectId}` },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function assertTaskInChat(db: Db, chat: Chat, taskId: number) {
|
||||
const ref = await resolveTaskById(db, taskId);
|
||||
if (chat.kind !== "project" || ref.project.id !== chat.projectId) throw new PeppaError("Тред не из этого чата");
|
||||
|
||||
79
packages/testkit/test/discussion.test.ts
Normal file
79
packages/testkit/test/discussion.test.ts
Normal file
@ -0,0 +1,79 @@
|
||||
// PEP-106: the project's discussion — a plain chat of its people: no agents, no events, no
|
||||
// commands; the others are notified, unread is counted, and it is not pruned with the projection.
|
||||
import assert from "node:assert/strict";
|
||||
import { after, before, describe, test } from "node:test";
|
||||
import { sql } from "drizzle-orm";
|
||||
import { core, db, runner, teardown } from "./helpers.ts";
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
process.env.PEPPA_WEB_URL = "http://peppa.test";
|
||||
after(teardown);
|
||||
|
||||
let owner: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||
let member: typeof owner;
|
||||
let stranger: typeof owner;
|
||||
let project: Awaited<ReturnType<typeof core.createProject>>;
|
||||
let chat: Awaited<ReturnType<typeof core.ensureProjectChat>>;
|
||||
|
||||
before(async () => {
|
||||
owner = await core.upsertUserFromGitea(db, { id: 1061, login: "mock-owner" }, { access_token: "a" });
|
||||
member = await core.upsertUserFromGitea(db, { id: 1062, login: "mock-member" }, { access_token: "b" });
|
||||
stranger = await core.upsertUserFromGitea(db, { id: 1063, login: "mock-stranger" }, { access_token: "c" });
|
||||
project = await core.createProject(db, { slug: "mock-talk", key: "MTLK", name: "Talk", giteaOwner: "x", workspacePath: "/tmp/mock-talk", ownerId: owner.id });
|
||||
db.run(sql`insert into project_members (project_id, user_id, created_at) values (${project.id}, ${member.id}, 0)`);
|
||||
db.run(sql`update users set telegram_chat_id = 9001 where id = ${member.id}`);
|
||||
member = (await core.getUser(db, member.id))!;
|
||||
chat = await core.ensureProjectChat(db, project.id);
|
||||
});
|
||||
|
||||
describe("PEP-106: project discussion", () => {
|
||||
test("people's messages only: events, agent threads and commands stay out", async () => {
|
||||
const story = await core.createTask(db, { projectId: project.id, title: "Каталог" });
|
||||
await core.addChatMessage(db, { chatId: chat.id, kind: "event", text: "стори создана" });
|
||||
await core.addChatMessage(db, { chatId: chat.id, kind: "user", authorKind: "user", authorUserId: owner.id, authorLogin: owner.login, threadKey: `task:${story.task.id}`, text: "ответ агенту в треде" });
|
||||
await runner.postToChat(db, owner, { chatId: chat.id, threadKey: null, text: "/status", via: "web" });
|
||||
await runner.postToChat(db, owner, { chatId: chat.id, threadKey: null, text: "Когда покажем заказчику?", via: "web" });
|
||||
await runner.postToChat(db, member, { chatId: chat.id, threadKey: null, text: "В пятницу, после ревью", via: "web" });
|
||||
const talk = await core.discussionMessages(db, chat.id);
|
||||
assert.deepEqual(talk.map((m) => [m.authorLogin, m.text]), [["mock-owner", "Когда покажем заказчику?"], ["mock-member", "В пятницу, после ревью"]]);
|
||||
});
|
||||
|
||||
test("the other people are notified; the author and outsiders are not", async () => {
|
||||
const out = await db.all<{ dedupe_key: string; params: string }>(sql`select dedupe_key, params from telegram_outbox where dedupe_key like 'chat:m%'`);
|
||||
// Only the member has Telegram: the owner's message reached them, their own did not.
|
||||
assert.equal(out.length, 1);
|
||||
const text = JSON.parse(out[0]!.params).text as string;
|
||||
assert.match(text, /Talk/);
|
||||
assert.match(text, /mock-owner/);
|
||||
assert.match(text, /Когда покажем заказчику\?/);
|
||||
assert.match(text, /http:\/\/peppa\.test\/chats\/MTLK/);
|
||||
await assert.rejects(runner.postToChat(db, stranger, { chatId: chat.id, threadKey: null, text: "пустите", via: "web" }), "an outsider can't write");
|
||||
});
|
||||
|
||||
test("notifications can be switched off (event «chat»)", async () => {
|
||||
const prefs = await core.getNotifyPrefs(db, member.id);
|
||||
assert.deepEqual(prefs.events.chat, { telegram: true, push: true }, "on by default");
|
||||
await core.setNotifyPrefs(db, member.id, { ...prefs, events: { ...prefs.events, chat: { telegram: false, push: false } } });
|
||||
await runner.postToChat(db, owner, { chatId: chat.id, threadKey: null, text: "без уведомления", via: "web" });
|
||||
const out = await db.all(sql`select 1 from telegram_outbox where dedupe_key like 'chat:m%'`);
|
||||
assert.equal(out.length, 1, "nothing new went out");
|
||||
});
|
||||
|
||||
test("unread: other people's messages until the discussion is opened", async () => {
|
||||
assert.equal((await core.discussionUnread(db, member.id)).get(chat.id), 2, "the owner's two messages");
|
||||
assert.equal((await core.discussionUnread(db, owner.id)).get(chat.id), 1, "the member's one");
|
||||
assert.equal((await core.discussionUnread(db, stranger.id)).size, 0);
|
||||
await core.markDiscussionRead(db, member.id, chat.id);
|
||||
assert.equal((await core.discussionUnread(db, member.id)).size, 0);
|
||||
await runner.postToChat(db, owner, { chatId: chat.id, threadKey: null, text: "ещё одно", via: "web" });
|
||||
assert.equal((await core.discussionUnread(db, member.id)).get(chat.id), 1);
|
||||
});
|
||||
|
||||
test("the discussion outlives the chat TTL; the projection of events does not", async () => {
|
||||
const later = new Date(Date.now() + core.chatTtlMs() + 86_400_000);
|
||||
await core.pruneChats(db, { now: later });
|
||||
assert.equal((await core.discussionMessages(db, chat.id)).length, 4, "people's words are kept");
|
||||
const rest = await core.chatMessagesView(db, chat.id, {});
|
||||
assert.ok(rest.every((m) => m.kind === "user" && m.threadKey === null && !m.text.startsWith("/")), "events, threads and commands are pruned");
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user