peppa/packages/testkit/test/discussion.test.ts
Асель 43e1319c5f PEP-156: кто говорит — события от имени Peppa FACTORY, агент под кличкой, роли на «вы»
Проекция событий в чаты подписывает то, что сделала фабрика или агент, «Peppa FACTORY»;
логин — только под словами человека. Слова агента — с кличкой (чат, карточка вопроса,
Telegram «🤖 Шустрик: …»), роли — «Аналитик» и «Продакт-агент». «Агент <кличка> взял
задачу в работу» ждёт запуска агента. Промпты ролей требуют «вы» (ADDRESS_RULE),
informalAddress проверяет ответы моков. Change pep-156-who-speaks в архиве, спека
project-chats, тест who-speaks.test.ts.

Rebased on main (one commit on top of 1074d276).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 18:30:48 +05:00

124 lines
8.6 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.

// 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("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);
// PEP-156: «агент взял задачу» is said when an agent starts — here nobody did.
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 });
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");
});
// PEP-161, spec project-chats: «Чат с аналитиком из раздела „Проекты“».
test("PEP-161: Ссылка на аналитика у своего проекта · Непрочитанный ответ аналитика виден на карточке", async () => {
await core.markDiscussionRead(db, owner.id, chat.id);
const before = (await core.analystLinks(db, owner)).get(project.id);
assert.deepEqual(before, { href: "/chats/MTLK", unread: 0 });
await core.addChatMessage(db, { chatId: chat.id, kind: "user", authorKind: "agent", authorLogin: "Аналитик", text: "Готово: каталог открыт." });
assert.deepEqual((await core.analystLinks(db, owner)).get(project.id), { href: "/chats/MTLK", unread: 1 });
assert.equal((await core.analystLinks(db, member)).get(project.id)?.href, "/chats/MTLK", "a member writes to the analyst too");
});
test("PEP-161: У чужого проекта ссылки нет", async () => {
await core.setPlatformAdmins(db, [stranger.login]);
try {
assert.ok((await core.listOtherProjects(db, stranger.id)).some((p) => p.key === "MTLK"), "the superadmin sees the project among other people's");
assert.equal((await core.analystLinks(db, stranger)).size, 0);
} finally {
await core.setPlatformAdmins(db, null);
}
});
});