PEP-117: chats a product manager understands — an overview of what waits and where to write, events in plain words
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
70eeaf2af5
commit
81eab53459
@ -39,6 +39,7 @@
|
||||
- **Группы чатов через свой бот (PEP-109)**: «Связать с Telegram» в чате — через собственного бота пользователя (PEP-85): `chats.tg_bot_user_id` (миграция 0018; null — общий бот, им связывает только суперадмин без своего бота: `createChatLinkCode(…, { sharedBot })`, остальным без бота — отказ с подсказкой). Код привязан к боту (`botUserId` в настройке кода): `acceptChatLink` принимает только от него и чужим ботом не сжигается; на `/link` без `@бота` с чужим кодом бот молчит (`chatLinkCodeBot`). Бот: `ownByChat` дополняется группами (`chatGroupBots` в `syncOwnBots`) — исходящие в группу идут через бота связки; входящие сообщения и кнопки группы обрабатывает только он (`linkedHere`). `clearUserBot` / `setUserBot` с другим ботом отвязывают его группы. Тест `chats-own-bot.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-110)**: сообщение человека в обсуждении проекта (PEP-106) → `analystChatTick` в тике вачдога (`runner/analyst-chat.ts`): `claudePrint` на подписке проекта (`PEPPA_INTAKE_BIN`, `PEPPA_ANALYST_CHAT_MODEL`), контекст `core/analyst-chat.ts` (`intakeContext` + `projectStatusBlock` со ссылками «где что смотреть»), ответ `{reply, create[]}` → сообщение `kind: user, authorKind: agent, authorLogin: «Аналитик»` в то же обсуждение + событие уведомлений `chat`; стори из `create` — только по явной просьбе, intake у них `done`. Курсор `chat.analyst:<chatId>`, `analystPending` («печатает…»), сообщения старше `PEPPA_ANALYST_CHAT_MAX_AGE_MIN` (60) пропускаются, сбой — одна заметка без повторов, `PEPPA_ANALYST_CHAT=off`. Мок — роль `chat` в `mock-intake`; тест `analyst-chat.test.ts`
|
||||
- **Чаты для продакта (PEP-117)**: `/chats` — обзор (`chatOverview` в core/chats.ts: карточка проекта — непрочитанное, открытые вопросы, последнее сообщение; сверху `inbox` «Ждут вашего ответа»); журнал — `/chats/master` («Все события»). В журналах (`master`, `?thread=feed`) поля ввода нет. `EVENT_TEXT`: смена статуса словами по `to` (и `from` для «на доработку»), сбои, которые Peppa чинит сама, не `important`. Подписи: `attention` — «Сообщение от фабрики»
|
||||
- **Прогресс на Главной (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 прежние)
|
||||
|
||||
@ -6,10 +6,10 @@ export const esc = (s: string) => s.replace(/&/g, "&").replace(/</g, "<")
|
||||
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s);
|
||||
|
||||
const KIND: Record<Question["kind"], string> = {
|
||||
approval: "📝 Нужно одобрение proposal",
|
||||
approval: "📝 Нужно одобрение плана",
|
||||
question: "❓ Вопрос",
|
||||
permission: "🔐 Нужно разрешение",
|
||||
attention: "👀 Сессия ждёт тебя",
|
||||
attention: "👀 Сообщение от фабрики",
|
||||
};
|
||||
|
||||
export interface Rendered {
|
||||
|
||||
@ -75,7 +75,7 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
: discussion
|
||||
? "Спросите аналитика, что с проектом, или опишите идею — он поможет сформулировать стори…"
|
||||
: taskThread
|
||||
? "Ответ агенту: на открытый вопрос, иначе комментарий, который он увидит сразу"
|
||||
? "Напишите агенту этой стори — ответ на его вопрос или замечание, он увидит сразу"
|
||||
: thread
|
||||
? "Заметка в тред или команда /help"
|
||||
: "Заметка в канал или команда: /status, /task KEY-N, /move KEY-N in_progress";
|
||||
@ -158,8 +158,12 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
</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>
|
||||
<p className="m-0">
|
||||
{master
|
||||
? "Журнал: готовые стори, вопросы, релизы и сбои по всем вашим проектам. Отвечать удобнее в «Обзоре» или в чате проекта."
|
||||
: "Слева: чат с аналитиком — для вопросов и новых задач; «События агентов» — журнал; ниже — переписка по каждой стори с её агентом."}
|
||||
</p>
|
||||
<p className="m-0">Журнал событий хранится {ttlDays} дн.; ваша переписка с аналитиком не удаляется.</p>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
@ -170,12 +174,16 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
<Flash error={error} />
|
||||
<PageHeader title="Чаты">
|
||||
{master
|
||||
? "Мастер-чат: всё важное по вашим проектам в одной ленте."
|
||||
? "Все события по вашим проектам — журнал, справочно. Чтобы ответить агенту или написать аналитику, откройте чат проекта."
|
||||
: "Чат с аналитиком — ИИ-агентом вашего проекта. Спросите, что сделано и где это посмотреть, или опишите идею: он уточнит, предложит стори и заведёт их в бэклог, когда вы скажете."}
|
||||
</PageHeader>
|
||||
|
||||
<nav className="mb-4 flex flex-wrap gap-1.5" aria-label="Чаты">
|
||||
{list.map((c) => (
|
||||
<Link href="/chats" className="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">
|
||||
← Обзор
|
||||
</Link>
|
||||
{/* PEP-117: projects first (by name), the journal of all events last. */}
|
||||
{[...list.filter((c) => c.kind === "project"), ...list.filter((c) => c.kind === "master")].map((c) => (
|
||||
<Link
|
||||
key={c.id}
|
||||
href={`/chats/${c.slug}`}
|
||||
@ -187,7 +195,7 @@ 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>
|
||||
<span>{c.kind === "master" ? "Все события" : c.title.includes(" · ") ? c.title.split(" · ").slice(1).join(" · ") : 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="новые сообщения в обсуждении">
|
||||
@ -203,12 +211,12 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
{!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" />}
|
||||
<ThreadLink href={url({ thread: FEED })} active={!discussion && thread === undefined} title="События агентов" meta="журнал: что делали агенты" />
|
||||
{threads.length > 0 && <p className="m-0 px-2 pt-2 text-[11px] tracking-wide text-muted-foreground uppercase">Переписка по стори</p>}
|
||||
{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>}
|
||||
{threads.length === 0 && <p className="m-0 px-2 py-1.5 text-xs text-muted-foreground">Переписки по стори пока нет.</p>}
|
||||
</nav>
|
||||
)}
|
||||
|
||||
@ -235,6 +243,12 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
<AgentBadge name="Аналитик" /> <span className="animate-pulse">печатает…</span>
|
||||
</p>
|
||||
)}
|
||||
{master || (!discussion && thread === undefined) ? (
|
||||
<p className="m-0 rounded-lg border border-dashed px-3 py-2 text-sm text-muted-foreground">
|
||||
Это журнал событий — писать сюда не нужно.{" "}
|
||||
{master ? <Link href="/chats">Выберите проект</Link> : <Link href={url({})}>Откройте чат с аналитиком</Link>}, чтобы задать вопрос или описать задачу.
|
||||
</p>
|
||||
) : (
|
||||
<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="Сообщение" />
|
||||
@ -246,6 +260,7 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
</Workspace>
|
||||
|
||||
@ -1,5 +1,80 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { ArrowRight, MessagesSquare } from "lucide-react";
|
||||
import { chatOverview, syncChats } from "@peppa/core";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { AgentBadge } from "@/components/AgentBadge";
|
||||
import { QuestionCard } from "@/components/cards";
|
||||
import { ago, Empty, Flash, PageHeader, Section } from "@/components/common";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { inbox } from "@/lib/queries";
|
||||
|
||||
export default function Chats() {
|
||||
redirect("/chats/master");
|
||||
export const metadata = { title: "Чаты — Peppa FACTORY" };
|
||||
|
||||
/**
|
||||
* «Чаты» (PEP-117): the overview a product manager lands on — what waits for their answer and
|
||||
* where to write to the analyst of each project. The raw feed of events lives at /chats/master.
|
||||
*/
|
||||
export default async function Chats({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const { error } = await searchParams;
|
||||
await syncChats(db).catch((e) => console.error("syncChats", e));
|
||||
const [cards, waiting] = await Promise.all([chatOverview(db, user), inbox(user.id)]);
|
||||
return (
|
||||
<Workspace>
|
||||
<LiveRefresh scope="chats" />
|
||||
<Flash error={error} />
|
||||
<PageHeader title="Чаты">Здесь вы разговариваете с фабрикой: отвечаете агентам и пишете аналитику своего проекта — что узнать или что сделать.</PageHeader>
|
||||
|
||||
<Section title="Ждут вашего ответа" count={waiting.length}>
|
||||
{waiting.length === 0 ? (
|
||||
<Empty>Сейчас от вас ничего не нужно — агенты работают сами.</Empty>
|
||||
) : (
|
||||
waiting.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/chats" />)
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<Section title="Ваши проекты" count={cards.length}>
|
||||
{cards.length === 0 ? (
|
||||
<Empty>
|
||||
Проектов пока нет. <Link href="/projects/new">Создайте проект</Link> — и у него появится чат с аналитиком.
|
||||
</Empty>
|
||||
) : (
|
||||
<ul className="m-0 grid list-none gap-3 p-0 md:grid-cols-2">
|
||||
{cards.map((c) => (
|
||||
<li key={c.chatId}>
|
||||
<Link href={`/chats/${c.key}`} className="flex h-full flex-col gap-2 rounded-xl border bg-card p-4 text-foreground hover:border-primary/60 hover:no-underline">
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="rounded bg-muted px-1.5 font-mono text-xs text-primary">{c.key}</span>
|
||||
<span className="min-w-0 flex-1 truncate font-medium">{c.name}</span>
|
||||
{c.unread > 0 && <span className="rounded-full bg-info px-2 text-xs font-semibold text-background" title="новые сообщения">{c.unread} нов.</span>}
|
||||
{c.open > 0 && <span className="rounded-full bg-primary px-2 text-xs font-semibold text-primary-foreground" title="агенты ждут вашего ответа">ждут ответа: {c.open}</span>}
|
||||
</span>
|
||||
{c.last ? (
|
||||
<span className="flex min-w-0 flex-col gap-0.5 text-sm">
|
||||
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
{c.last.who === "Аналитик" ? <AgentBadge name="Аналитик" /> : <span>{c.last.mine ? "вы" : c.last.who}</span>}
|
||||
<span>· {ago(c.last.at)}</span>
|
||||
</span>
|
||||
<span className="line-clamp-2 text-muted-foreground">{c.last.text}</span>
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground">Здесь пока тихо. Спросите аналитика, что с проектом, или опишите новую задачу.</span>
|
||||
)}
|
||||
<span className="mt-auto inline-flex items-center gap-1.5 text-sm font-medium text-primary">
|
||||
<MessagesSquare className="size-4" /> Написать аналитику <ArrowRight className="size-3.5" />
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<p className="mt-6 text-sm text-muted-foreground">
|
||||
Нужна история? <Link href="/chats/master">Все события по вашим проектам</Link> — что делали агенты, релизы и сбои, справочно.
|
||||
</p>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
|
||||
@ -16,7 +16,7 @@ const KIND = {
|
||||
approval: { label: "Одобрение плана", icon: FileCheck, border: "border-l-primary" },
|
||||
question: { label: "Вопрос", icon: CircleHelp, border: "border-l-info" },
|
||||
permission: { label: "Разрешение", icon: ShieldQuestion, border: "border-l-warn" },
|
||||
attention: { label: "Сессия ждёт тебя", icon: BellRing, border: "border-l-ok" },
|
||||
attention: { label: "Сообщение от фабрики", icon: BellRing, border: "border-l-ok" },
|
||||
} as const;
|
||||
|
||||
/** Hidden inputs of a server-action form. */
|
||||
|
||||
18
openspec/changes/pep-117-chats-for-product/proposal.md
Normal file
18
openspec/changes/pep-117-chats-for-product/proposal.md
Normal file
@ -0,0 +1,18 @@
|
||||
# Proposal: PEP-117 — чаты понятны продакту
|
||||
|
||||
## Why
|
||||
PM: «чат непонятный для продакта». «Чаты» открывались на мастер-чате — ленте технических событий
|
||||
(«Статус: готово → ревью», «Сессия ждёт тебя», напоминания по чужим проектам) с полем ввода для
|
||||
команд `/status`. Непонятно, что ждёт ответа и где писать.
|
||||
|
||||
## What Changes
|
||||
- `/chats` — обзор: «Ждут вашего ответа» (вопросы агентов с кнопками) и «Ваши проекты» —
|
||||
карточка на проект (`chatOverview`: новые сообщения, сколько ждёт ответа, последнее сообщение,
|
||||
«Написать аналитику»). Журнал всех событий — по ссылке (`/chats/master`, «Все события»).
|
||||
- Страница чата: «← Обзор», проекты по названиям, «Все события» последним; в журналах (все
|
||||
события, «События агентов») поля ввода нет — подсказка, куда писать; поле в треде стори —
|
||||
«Напишите агенту этой стори…».
|
||||
- События словами: «Агент взял стори в работу», «Стори готова — посмотрите результат и примите»,
|
||||
«Стори вернулась агенту на доработку», «Стори принята и закрыта»; сбои, которые Peppa чинит
|
||||
сама (молчит, споткнулся, перезапущен), — спокойным текстом и не «важное»; без «PR», «процесс».
|
||||
- Подписи: «Сообщение от фабрики» вместо «Сессия ждёт тебя», «Одобрение плана» в напоминаниях и боте.
|
||||
@ -0,0 +1,12 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Обзор чатов
|
||||
«Чаты» SHALL открываться на обзоре: что ждёт ответа пользователя и чат с аналитиком каждого его проекта.
|
||||
|
||||
#### Scenario: Пользователь открывает «Чаты»
|
||||
- **WHEN** у пользователя два проекта и один открытый вопрос агента
|
||||
- **THEN** он видит вопрос с кнопками ответа и карточки проектов с последним сообщением и «Написать аналитику»
|
||||
|
||||
#### Scenario: Журнал событий
|
||||
- **WHEN** пользователь открывает «Все события» или «События агентов»
|
||||
- **THEN** поля ввода нет, есть подсказка, где писать; события сказаны словами, без «статус X → Y»
|
||||
4
openspec/changes/pep-117-chats-for-product/tasks.md
Normal file
4
openspec/changes/pep-117-chats-for-product/tasks.md
Normal file
@ -0,0 +1,4 @@
|
||||
- [x] 1.1 core: chatOverview, тексты событий
|
||||
- [x] 1.2 веб: обзор /chats, страница чата без поля в журналах
|
||||
- [x] 1.3 подписи карточек, бота и напоминаний
|
||||
- [x] 1.4 тесты (discussion.test.ts, chats.test.ts), проверка в браузере на копии базы
|
||||
@ -234,6 +234,38 @@ export async function discussionUnread(db: Db, userId: number): Promise<Map<numb
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface ProjectChatCard {
|
||||
chatId: number;
|
||||
key: string;
|
||||
name: string;
|
||||
/** Messages of other people and the analyst the user has not read. */
|
||||
unread: number;
|
||||
/** Agent questions of the project waiting for a person. */
|
||||
open: number;
|
||||
/** The last message of the chat with the analyst. */
|
||||
last: { who: string; mine: boolean; text: string; at: Date } | null;
|
||||
}
|
||||
|
||||
/** PEP-117: the user's project chats at a glance — what is new and what was said last. */
|
||||
export async function chatOverview(db: Db, user: Pick<User, "id">): Promise<ProjectChatCard[]> {
|
||||
const list = (await listChats(db, user)).filter((c) => c.kind === "project");
|
||||
const unread = await discussionUnread(db, user.id);
|
||||
const out: ProjectChatCard[] = [];
|
||||
for (const c of list) {
|
||||
const [m] = await db.select().from(chatMessages).where(and(eq(chatMessages.chatId, c.id), DISCUSSION)).orderBy(desc(chatMessages.id)).limit(1);
|
||||
out.push({
|
||||
chatId: c.id,
|
||||
key: c.slug,
|
||||
name: c.title.includes(" · ") ? c.title.split(" · ").slice(1).join(" · ") : c.title,
|
||||
unread: unread.get(c.id) ?? 0,
|
||||
open: c.open,
|
||||
last: m ? { who: m.authorKind === "agent" ? (m.authorLogin ?? "Аналитик") : (m.authorLogin ?? "Пеппа"), mine: m.authorUserId === user.id, text: m.text, at: m.createdAt } : null,
|
||||
});
|
||||
}
|
||||
// What needs the person first: open questions, then unread, then the most recent talk.
|
||||
return out.sort((a, b) => b.open - a.open || b.unread - a.unread || (b.last?.at.getTime() ?? 0) - (a.last?.at.getTime() ?? 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
@ -306,29 +338,38 @@ const EVENT_TEXT: Record<string, (p: P) => { text: string; important?: boolean;
|
||||
const from = (p.from as P | undefined)?.status;
|
||||
const to = (p.to as P | undefined)?.status;
|
||||
if (!to || from === to) return null;
|
||||
const icon = to === "review" ? "👀" : to === "done" ? "✅" : to === "in_progress" ? "▶️" : to === "blocked" ? "⛔" : "•";
|
||||
const tail = to === "review" ? " — готово к ревью" : "";
|
||||
return { text: `${icon} Статус: ${from ? `${statusRu(String(from))} → ` : ""}${statusRu(String(to))}${tail}`, important: ["review", "done", "blocked", "awaiting_approval"].includes(String(to)) };
|
||||
// PEP-117: what happened to the story, in words — not «статус X → Y».
|
||||
const said: Record<string, string> = {
|
||||
proposing: "📝 Агент составляет план стори",
|
||||
awaiting_approval: "⏸ План готов и ждёт вашего одобрения",
|
||||
in_progress: from === "review" ? "🔧 Стори вернулась агенту на доработку" : "▶️ Агент взял стори в работу",
|
||||
review: "👀 Стори готова — посмотрите результат и примите",
|
||||
done: "✅ Стори принята и закрыта",
|
||||
blocked: "⛔ Стори заблокирована — агент не может продолжать",
|
||||
backlog: "↩️ Стори вернулась в бэклог",
|
||||
};
|
||||
return { text: said[String(to)] ?? `• Статус: ${statusRu(String(to))}`, important: ["review", "done", "blocked", "awaiting_approval"].includes(String(to)) };
|
||||
},
|
||||
progress: (p) => ({ text: `📈 ${cut(s(p.text), 1500)}`, author: "agent" }),
|
||||
pm_comment: () => null, // handled separately: a person's message
|
||||
// PEP-4: the project's repo moved to another Gitea namespace.
|
||||
repo_transferred: (p) => ({ text: `📦 Репозиторий перенесён: ${s(p.from)} → ${s(p.to)}`, important: true }),
|
||||
repo_transferred: (p) => ({ text: `📦 Код проекта переехал: ${s(p.from)} → ${s(p.to)}` }),
|
||||
// PEP-84: «продакт» and «аналитик» talk to the PM in the story's thread.
|
||||
intake_note: (p) => ({ text: `${p.role === "product" ? "🧭 Продакт" : "🔎 Аналитик"}: ${cut(s(p.text), 3000)}`, important: true, author: "agent" }),
|
||||
pr_merged_in_gitea: (p) => ({ text: `🔀 PR #${s(p.pr)} смержен${p.by ? ` (${s(p.by)})` : ""}`, important: true }),
|
||||
started: () => ({ text: "▶️ Агент запущен" }),
|
||||
pr_merged_in_gitea: (p) => ({ text: `🔀 Изменения стори приняты в код проекта${p.by ? ` (${s(p.by)})` : ""}` }),
|
||||
started: () => ({ text: "▶️ Агент начал работу" }),
|
||||
resumed: () => ({ text: "🔁 Агент продолжает работу" }),
|
||||
stopped: () => ({ text: "⏹ Агент остановлен" }),
|
||||
stalled: (p) => ({ text: `⚠️ Агент молчит${p.idleMinutes ? ` ${s(p.idleMinutes)} мин` : ""}`, important: true }),
|
||||
stop_failure: (p) => ({ text: `❌ Ход агента прерван: ${s(p.error) || "ошибка"}`, important: true }),
|
||||
exited: (p) => ({ text: `💀 Процесс агента завершился${p.exitStatus != null ? ` (код ${s(p.exitStatus)})` : ""}`, important: true }),
|
||||
usage_limit: (p) => ({ text: `⏳ Лимит подписки${p.line ? `: ${cut(s(p.line), 200)}` : ""}`, important: true }),
|
||||
auto_restarted: (p) => ({ text: `🔁 Перезапуск после сбоя${p.attempt ? ` (${s(p.attempt)} из ${s(p.of)})` : ""}`, important: true }),
|
||||
restart_failed: (p) => ({ text: `❌ Перезапуск не удался${p.error ? `: ${cut(s(p.error), 200)}` : ""}`, important: true }),
|
||||
budget_paused: () => ({ text: "💸 Бюджет стори исчерпан — агент на паузе", important: true }),
|
||||
subscription_switched: (p) => ({ text: `🔀 Подписка переключена${p.to ? ` на ${s(p.to)}` : ""}`, important: true }),
|
||||
model_escalated: (p) => ({ text: `⬆️ Модель усилена${p.model ? `: ${s(p.model)}` : ""}` }),
|
||||
// Hiccups Peppa handles by itself are told calmly and are not «важное» for a product manager.
|
||||
stalled: (p) => ({ text: `⚠️ Агент давно молчит${p.idleMinutes ? ` (${s(p.idleMinutes)} мин)` : ""} — Peppa перезапустит его сама` }),
|
||||
stop_failure: (p) => ({ text: `⚠️ Агент споткнулся (${s(p.error) || "ошибка"}) — Peppa продолжит сама` }),
|
||||
exited: () => ({ text: "⚠️ Агент остановился раньше времени — Peppa перезапустит его сама" }),
|
||||
usage_limit: () => ({ text: "⏳ Подписка упёрлась в лимит — агент продолжит после сброса или на другой подписке", important: true }),
|
||||
auto_restarted: (p) => ({ text: `🔁 Агент перезапущен после сбоя${p.attempt ? ` (попытка ${s(p.attempt)} из ${s(p.of)})` : ""}` }),
|
||||
restart_failed: () => ({ text: "❌ Агента не удалось перезапустить — нужна ваша помощь: откройте стори", important: true }),
|
||||
budget_paused: () => ({ text: "💸 Бюджет стори исчерпан — агент на паузе, нужен ваш ответ", important: true }),
|
||||
subscription_switched: (p) => ({ text: `🔀 Агент перешёл на другую подписку${p.to ? ` (${s(p.to)})` : ""} и продолжает` }),
|
||||
model_escalated: () => ({ text: "⬆️ Задача оказалась сложнее — агент взял модель посильнее" }),
|
||||
};
|
||||
|
||||
const RELEASE_ICON: Record<string, string> = { deploying: "⏳", healthy: "🚀", rolled_back: "↩️", failed: "❌", removed: "🧹" };
|
||||
|
||||
@ -209,7 +209,7 @@ export async function restartStalled(db: Db, s: SessionView, o: { now: Date; cfg
|
||||
// ── reminders and escalation ──────────────────────────────────────────────────────
|
||||
|
||||
const REMIND_KINDS = ["question", "permission", "approval"] as const;
|
||||
const KIND_RU: Record<string, string> = { question: "Вопрос", permission: "Разрешение", approval: "Одобрение proposal" };
|
||||
const KIND_RU: Record<string, string> = { question: "Вопрос", permission: "Разрешение", approval: "Одобрение плана" };
|
||||
|
||||
/**
|
||||
* Unanswered questions: reminders to the project's people after `remindMin` and 2×, then the
|
||||
|
||||
@ -131,10 +131,13 @@ describe("master chat", () => {
|
||||
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: "restart_failed", payload: { error: "tmux" } });
|
||||
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));
|
||||
// PEP-117: only what needs the person is «важное»; hiccups Peppa handles itself stay in the project feed.
|
||||
assert.ok(feed.some((m) => /Агента не удалось перезапустить — нужна ваша помощь/.test(m.text) && m.threadKey === threadOf(ref.task.id) && m.projectKey === p.key));
|
||||
assert.ok(!feed.some((m) => /Агент давно молчит/.test(m.text)), "a stall Peppa restarts by itself is not important");
|
||||
assert.ok(!feed.some((m) => /половина готова/.test(m.text)), "progress is not important");
|
||||
|
||||
const master = await core.ensureMasterChat(db, pm.id);
|
||||
|
||||
@ -69,6 +69,29 @@ describe("PEP-106: project discussion", () => {
|
||||
assert.equal((await core.discussionUnread(db, member.id)).get(chat.id), 1);
|
||||
});
|
||||
|
||||
test("PEP-117: the overview card of a project chat — unread, open questions, the last message", async () => {
|
||||
const story = await core.createTask(db, { projectId: project.id, title: "Вопросная" });
|
||||
await core.askPm(db, story, { kind: "question", text: "Какой цвет кнопки?" });
|
||||
const forMember = (await core.chatOverview(db, member)).find((c) => c.key === "MTLK")!;
|
||||
assert.equal(forMember.name, "Talk");
|
||||
assert.equal(forMember.open, 1, "agents wait for an answer");
|
||||
assert.equal(forMember.unread, 1);
|
||||
assert.deepEqual([forMember.last?.who, forMember.last?.mine, forMember.last?.text], ["mock-owner", false, "ещё одно"]);
|
||||
const forOwner = (await core.chatOverview(db, owner)).find((c) => c.key === "MTLK")!;
|
||||
assert.equal(forOwner.last?.mine, true);
|
||||
assert.equal((await core.chatOverview(db, stranger)).length, 0, "only the user's own projects");
|
||||
});
|
||||
|
||||
test("PEP-117: status changes are said in words, not «статус X → Y»", async () => {
|
||||
const story = await core.createTask(db, { projectId: project.id, title: "Словами" });
|
||||
for (const [from, to] of [["backlog", "in_progress"], ["in_progress", "review"], ["review", "in_progress"], ["review", "done"]]) {
|
||||
await core.logEvent(db, { projectId: project.id, taskId: story.task.id, type: "task_updated", payload: { from: { status: from }, to: { status: to } } });
|
||||
}
|
||||
await core.syncChats(db);
|
||||
const texts = (await core.chatMessagesView(db, chat.id, { threadKey: `task:${story.task.id}` })).map((m) => m.text);
|
||||
assert.deepEqual(texts, ["▶️ Агент взял стори в работу", "👀 Стори готова — посмотрите результат и примите", "🔧 Стори вернулась агенту на доработку", "✅ Стори принята и закрыта"]);
|
||||
});
|
||||
|
||||
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 });
|
||||
|
||||
Loading…
Reference in New Issue
Block a user