From ea3515d31c0e57e77fb6a9e1dfb5e1b1339b9d2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 13:20:32 +0500 Subject: [PATCH] =?UTF-8?q?PEP-155:=20project=20chat=20list=20=E2=80=94=20?= =?UTF-8?q?groups,=20status,=20agent,=20unread,=20search?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- apps/web/app/(app)/chats/[chat]/page.tsx | 72 ++++---- apps/web/components/ChatThreadList.tsx | 162 ++++++++++++++++++ packages/core/src/chat-threads.ts | 203 +++++++++++++++++++++++ packages/core/src/index.ts | 1 + packages/core/src/story-product.ts | 5 +- packages/shared/src/i18n/en/story.ts | 10 ++ packages/shared/src/i18n/kk/story.ts | 10 ++ packages/testkit/test/chats.test.ts | 117 ++++++++++++- 8 files changed, 538 insertions(+), 42 deletions(-) create mode 100644 apps/web/components/ChatThreadList.tsx create mode 100644 packages/core/src/chat-threads.ts diff --git a/apps/web/app/(app)/chats/[chat]/page.tsx b/apps/web/app/(app)/chats/[chat]/page.tsx index 3250b222..718db789 100644 --- a/apps/web/app/(app)/chats/[chat]/page.tsx +++ b/apps/web/app/(app)/chats/[chat]/page.tsx @@ -1,14 +1,15 @@ import Link from "next/link"; import { notFound } from "next/navigation"; import { Bot, Hash, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react"; -import { analystPending, isSuperadmin, chatGroupBotName, chatMessagesView, chatThreads, chatTtlMs, discussionMessages, discussionUnread, getSetting, listChats, markDiscussionRead, masterFeed, syncChats, threadTitle, THREAD_KEY, type ChatMessageView, type Question } from "@peppa/core"; +import { analystPending, isSuperadmin, chatGroupBotName, chatMessagesView, chatTtlMs, discussionMessages, discussionUnread, getSetting, listChats, markDiscussionRead, markThreadRead, masterFeed, projectThreadList, syncChats, threadTitle, THREAD_KEY, type ChatMessageView, type Question } from "@peppa/core"; import { projects, questions, tasks } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { PRODUCT_NAME } from "@peppa/shared/i18n"; import { eq, inArray } from "drizzle-orm"; import { LiveRefresh } from "@/components/LiveRefresh"; import { AgentBadge } from "@/components/AgentBadge"; -import { ago, Empty, Flash, PageHeader } from "@/components/common"; +import { ChatThreadList } from "@/components/ChatThreadList"; +import { ago, Empty, Flash, PageHeader, StatusBadge } from "@/components/common"; import { Hidden, QuestionCard } from "@/components/cards"; import { Dictate } from "@/components/Dictate"; import { Workspace } from "@/components/Workspace"; @@ -20,7 +21,7 @@ import { getT } from "@/lib/i18n"; import { cn } from "@/lib/utils"; import { linkChatAction, postChatAction, unlinkChatAction } from "../actions"; -type Params = { error?: string; thread?: string; link?: string }; +type Params = { error?: string; thread?: string; link?: string; q?: string; list?: string }; const CHANNEL = "channel"; /** PEP-106: `?thread=feed` — the agents' events; no `thread` — the people's discussion. */ @@ -32,7 +33,7 @@ export default async function ChatPage({ params, searchParams }: { params: Promi const t = await getT(); const w = await words(); const { chat: slug } = await params; - const { error, thread: rawThread, link } = await searchParams; + const { error, thread: rawThread, link, q, list: rawList } = await searchParams; // Whoever renders first moves fresh events into the chats (the bot and the watchdog do it too). await syncChats(db).catch((e) => console.error("syncChats", e)); const list = await listChats(db, user); @@ -43,17 +44,21 @@ export default async function ChatPage({ params, searchParams }: { params: Promi // 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); + // PEP-155: on a phone it is either the list (`?list=1`) or the open conversation, full screen. + const showList = !master && rawList === "1"; + if (discussion && !showList) await markDiscussionRead(db, user.id, chat.id); + if (thread && !master && !showList) await markThreadRead(db, user.id, chat.id, thread); // PEP-110: a person's message the analyst has not answered yet — «печатает…». const typing = discussion && (await analystPending(db, chat.id)); - const threads = master ? [] : await chatThreads(db, chat.id); + const threads = master ? null : await projectThreadList(db, user, chat, { q }); + const rows = threads ? [...threads.waiting, ...threads.working, ...threads.done] : []; const messages = master ? await masterFeed(db, user, { limit: 150 }) : discussion ? await discussionMessages(db, chat.id) : await chatMessagesView(db, chat.id, { threadKey: thread, limit: 150 }); - const current = thread ? (threads.find((t) => t.key === thread)?.title ?? (await threadTitle(db, thread)) ?? thread) : null; + const current = thread ? ((await threadTitle(db, thread)) ?? thread) : null; // Live state of the questions in view (answer buttons, «отвечено» marks). const qIds = messages.map((m) => m.question?.id).filter((x): x is number => x != null); @@ -62,10 +67,15 @@ export default async function ChatPage({ params, searchParams }: { params: Promi : []; 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 base = `/chats/${chat.slug}`; + const url = (p: { thread?: string | null; list?: boolean }) => { + const params = new URLSearchParams(); + if (p.thread) params.set("thread", p.thread); + if (threads?.q) params.set("q", threads.q); + if (p.list) params.set("list", "1"); + return params.size ? `${base}?${params}` : base; }; + const openRow = thread ? rows.find((r) => r.key === thread) : undefined; const here = discussion ? url({}) : url({ thread: thread === null ? CHANNEL : (thread ?? FEED) }); // PEP-109: a group is linked through the user's own bot. The platform's bot is the superadmin's // (users never see it) and links groups only for a superadmin without a bot of their own. @@ -215,23 +225,24 @@ export default async function ChatPage({ params, searchParams }: { params: Promi ))} -
- {!master && ( - +
+ {threads && ( +
+ +
)} -
+
+ {!master && ( + + {t("← К списку")} + + )} {current && (
🧵 {t.text(current)} + {openRow?.status && } + {openRow?.agentName && } {taskThread && }
)} @@ -276,23 +287,6 @@ export default async function ChatPage({ params, searchParams }: { params: Promi ); } -async function ThreadLink({ href, active, title, meta, open = 0 }: { href: string; active: boolean; title: string; meta?: string; open?: number }) { - const t = await getT(); - return ( - - - {title} - {open > 0 && {open}} - - {meta && {meta}} - - ); -} - function TaskLink({ messages, label }: { messages: ChatMessageView[]; label: string }) { const key = messages.find((m) => m.threadTitle)?.threadTitle?.split(" · ")[0]; return key ? {label} : null; diff --git a/apps/web/components/ChatThreadList.tsx b/apps/web/components/ChatThreadList.tsx new file mode 100644 index 00000000..9ff610c4 --- /dev/null +++ b/apps/web/components/ChatThreadList.tsx @@ -0,0 +1,162 @@ +import Link from "next/link"; +import { Search, X } from "lucide-react"; +import type { ThreadList, ThreadRow } from "@peppa/core"; +import { AgentBadge } from "@/components/AgentBadge"; +import { ago, StatusBadge } from "@/components/common"; +import { Hidden } from "@/components/cards"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { getT } from "@/lib/i18n"; +import { words } from "@/lib/auth"; +import { cn } from "@/lib/utils"; + +const COUNT = "rounded-full px-1.5 font-mono text-[11px] leading-4 font-semibold tabular-nums"; + +/** + * PEP-155: the conversations of a project chat — the chat with the analyst and the agents' events + * on top, then story threads in groups «Ждут вас», «В работе», «Готово» (folded), with a search. + */ +export async function ChatThreadList({ + base, + list, + active, + discussion, + feed, + raw, +}: { + /** `/chats/` */ + base: string; + list: ThreadList; + /** The open thread's key, if a thread is open. */ + active: string | null; + discussion: boolean; + feed: boolean; + /** The `thread` parameter as it is in the URL: the search keeps the open conversation. */ + raw: string | null; +}) { + const t = await getT(); + const w = await words(); + const q = list.q; + const href = (thread: string | null) => { + const p = new URLSearchParams(); + if (thread) p.set("thread", thread); + if (q) p.set("q", q); + return p.size ? `${base}?${p}` : base; + }; + const total = list.waiting.length + list.working.length + list.done.length; + const rows = (items: ThreadRow[]) => items.map((r) => ); + return ( + + ); +} + +function GroupTitle({ children, count, tone = "bg-muted text-muted-foreground" }: { children: React.ReactNode; count: number; tone?: string }) { + return ( +

+ {children} + {count > 0 && {count}} +

+ ); +} + +function Plain({ href, active, title, meta }: { href: string; active: boolean; title: string; meta: string }) { + return ( + + {title} + {meta} + + ); +} + +async function Row({ r, href, active }: { r: ThreadRow; href: string; active: boolean }) { + const t = await getT(); + const title = r.taskKey ? r.title : t.text(r.title); + return ( + + + {r.taskKey && {r.taskKey}} + 0) && "font-medium")} title={title}> + {title} + + {r.open > 0 && ( + + ? + + )} + {r.unread > 0 && ( + + {r.unread > 99 ? "99+" : r.unread} + + )} + + {(r.status || r.agentName || r.lastAt) && ( + + {r.status && } + {r.agentName && } + {r.lastAt && {ago(r.lastAt, t)}} + + )} + {r.last && ( + + {r.last.mine && t("вы") + ": "} + {r.last.system ? t.text(r.last.text) : r.last.text} + + )} + + ); +} diff --git a/packages/core/src/chat-threads.ts b/packages/core/src/chat-threads.ts new file mode 100644 index 00000000..c5acfc71 --- /dev/null +++ b/packages/core/src/chat-threads.ts @@ -0,0 +1,203 @@ +// PEP-155: the list of a project chat's conversations for a product manager — story threads in +// three groups («Ждут вас», «В работе», «Готово»), each with the story's status, its agent, the +// last message in one plain line, the unread count; and a search over keys, titles and texts. +// Data only: group names and status labels are the web's (lib/status.ts). +import { agents, chatMessages, projects, questions, sessions, tasks, type Db } from "@peppa/db"; +import { formatTaskKey } from "@peppa/shared"; +import { and, asc, desc, eq, inArray, isNotNull, isNull, sql } from "drizzle-orm"; +import { listPendingAccepts } from "./accept-pending.ts"; +import { threadTitle, type Chat } from "./chats.ts"; +import { getSetting, setSetting } from "./settings.ts"; +import { TECHNICAL_TEXT } from "./story-product.ts"; +import type { User } from "./users.ts"; + +export type ThreadGroup = "waiting" | "working" | "done"; + +export interface ThreadRow { + /** Thread key: `task:` (or `release:` / `incident:` with an open question). */ + key: string; + /** "PAY-7"; null — not a story thread. */ + taskKey: string | null; + title: string; + /** Story status; null — not a story thread. */ + status: string | null; + archived: boolean; + /** PEP-127: «Принять» is pressed already, the factory finishes by itself. */ + accepted: boolean; + agentName: string | null; + /** The last message in one plain line (or the found one, when searching); null — nothing readable. */ + last: { text: string; /** Written by the factory itself: a translatable text. */ system: boolean; mine: boolean } | null; + lastAt: Date | null; + unread: number; + /** Open questions that need the person's answer. */ + open: number; + group: ThreadGroup; +} + +export interface ThreadList { + waiting: ThreadRow[]; + working: ThreadRow[]; + done: ThreadRow[]; + /** The search the list is narrowed by; null — the whole list. */ + q: string | null; +} + +/** Question kinds a person has to answer; `attention` is a notice («готово» is the `review` status). */ +const ASKS = ["question", "approval", "permission"] as const; +const ACTIVE = new Set(["proposing", "awaiting_approval", "in_progress", "review", "blocked"]); +const SCAN = 3000; +const SCAN_SEARCH = 20_000; +const LINE = 140; + +/** Which group a story thread belongs to. */ +export function threadGroup(t: { status: string | null; archived?: boolean; accepted?: boolean; open: number }): ThreadGroup { + if (t.open > 0) return "waiting"; + if (t.status === "done" || t.archived) return "done"; + if (t.status === "awaiting_approval" || (t.status === "review" && !t.accepted)) return "waiting"; + return "working"; +} + +const cut = (s: string, n = LINE) => (s.length > n ? `${s.slice(0, n - 1).trimEnd()}…` : s); + +/** + * A message as one line a product manager can read: its first meaningful line without markup; + * null when that line is technical (code, paths, identifiers). + */ +export function plainLine(text: string | null | undefined): string | null { + for (const raw of (text ?? "").split("\n")) { + const line = raw.replace(/^[\s>#*\-•]+/, "").replace(/\*\*|__/g, "").replace(/\s+/g, " ").trim(); + if (line.length < 2) continue; + if (line.includes("`") || TECHNICAL_TEXT.test(line)) return null; + return cut(line); + } + return null; +} + +/** The piece of a message around the found word, in one line. */ +function snippet(text: string, at: number, len: number): string { + const start = Math.max(0, text.lastIndexOf("\n", at) + 1, at - 60); + const s = text.slice(start, Math.max(at + len, start + LINE)).split("\n")[0]!.replace(/\s+/g, " ").trim(); + return `${start > 0 && text[start - 1] !== "\n" ? "…" : ""}${cut(s)}`; +} + +interface ThreadRead { + /** Messages up to this id were there before the user first saw the list — never «new». */ + base: number; + seen: Record; +} +const readKey = (userId: number, chatId: number) => `chat.threads.read:${userId}:${chatId}`; + +/** The user has opened the thread: its messages so far are read. */ +export async function markThreadRead(db: Db, userId: number, chatId: number, threadKey: string): Promise { + const [last] = await db.select({ id: sql`max(${chatMessages.id})` }).from(chatMessages).where(and(eq(chatMessages.chatId, chatId), eq(chatMessages.threadKey, threadKey))); + const id = Number(last?.id ?? 0); + const st = (await getSetting(db, readKey(userId, chatId))) ?? { base: 0, seen: {} }; + if (!id || id <= Math.max(st.base, st.seen[threadKey] ?? 0)) return; + await setSetting(db, readKey(userId, chatId), { ...st, seen: { ...st.seen, [threadKey]: id } } satisfies ThreadRead); +} + +/** + * The conversations of a project chat in groups, most recent first. With `q` — only the threads + * whose story key, title or message text has it (case-insensitive; in JS: SQLite does not fold + * Cyrillic), archived stories included. + */ +export async function projectThreadList(db: Db, user: Pick, chat: Pick, o: { q?: string | null } = {}): Promise { + const q = (o.q ?? "").trim().toLocaleLowerCase().slice(0, 100) || null; + const empty: ThreadList = { waiting: [], working: [], done: [], q }; + if (!chat.projectId) return empty; + const [project] = await db.select({ id: projects.id, key: projects.key }).from(projects).where(eq(projects.id, chat.projectId)); + if (!project) return empty; + + const [last] = await db.select({ id: sql`max(${chatMessages.id})` }).from(chatMessages).where(eq(chatMessages.chatId, chat.id)); + let read = await getSetting(db, readKey(user.id, chat.id)); + if (!read) { + // First look at the list: what is already there does not become «unread» all at once. + read = { base: Number(last?.id ?? 0), seen: {} }; + await setSetting(db, readKey(user.id, chat.id), read); + } + + const taskRows = await db.select({ id: tasks.id, number: tasks.number, title: tasks.title, status: tasks.status, archivedAt: tasks.archivedAt, updatedAt: tasks.updatedAt }).from(tasks).where(eq(tasks.projectId, project.id)); + const stats = new Map( + ( + await db + .select({ key: chatMessages.threadKey, lastAt: sql`max(${chatMessages.createdAt})` }) + .from(chatMessages) + .where(and(eq(chatMessages.chatId, chat.id), isNotNull(chatMessages.threadKey))) + .groupBy(chatMessages.threadKey) + ).map((r) => [r.key!, new Date(Number(r.lastAt))]), + ); + const openRows = await db.select({ taskId: questions.taskId, id: questions.id }).from(questions).where(and(eq(questions.projectId, project.id), isNull(questions.answeredAt), inArray(questions.kind, [...ASKS]))); + const openByTask = new Map(); + for (const r of openRows) if (r.taskId != null) openByTask.set(r.taskId, (openByTask.get(r.taskId) ?? 0) + 1); + // Questions without a story (a version, a product error) live in their own threads. + const loose = openRows.filter((r) => r.taskId == null).map((r) => r.id); + const looseThreads = new Map(); + if (loose.length) { + const rows = await db.select({ key: chatMessages.threadKey }).from(chatMessages).where(and(eq(chatMessages.chatId, chat.id), isNotNull(chatMessages.threadKey), inArray(chatMessages.questionId, loose))); + for (const r of rows) if (!r.key!.startsWith("task:")) looseThreads.set(r.key!, (looseThreads.get(r.key!) ?? 0) + 1); + } + + // The agent of a story: the one working now, else the one of its last run. + const agentByTask = new Map(); + const runs = await db.select({ taskId: sessions.taskId, status: sessions.status, name: agents.name }).from(sessions).innerJoin(agents, eq(sessions.agentId, agents.id)).where(and(eq(sessions.projectId, project.id), isNotNull(sessions.taskId))).orderBy(asc(sessions.id)); + for (const r of runs) { + const live = r.status !== "done" && r.status !== "failed"; + if (live || !agentByTask.get(r.taskId!)?.live) agentByTask.set(r.taskId!, { name: r.name, live }); + } + const accepted = await listPendingAccepts(db); + + // The newest messages of the threads: the last readable line, the unread count, the search. + const msgs = await db + .select({ id: chatMessages.id, key: chatMessages.threadKey, text: chatMessages.text, authorKind: chatMessages.authorKind, authorUserId: chatMessages.authorUserId }) + .from(chatMessages) + .where(and(eq(chatMessages.chatId, chat.id), isNotNull(chatMessages.threadKey))) + .orderBy(desc(chatMessages.id)) + .limit(q ? SCAN_SEARCH : SCAN); + const lastLine = new Map(); + const found = new Map(); + const unread = new Map(); + for (const m of msgs) { + const key = m.key!; + const mine = m.authorUserId === user.id; + const said = (text: string) => ({ text, system: m.authorKind === "system", mine }); + if (!mine && m.id > Math.max(read.base, read.seen[key] ?? 0)) unread.set(key, (unread.get(key) ?? 0) + 1); + if (!lastLine.has(key)) { + const line = plainLine(m.text); + if (line) lastLine.set(key, said(line)); + } + if (q && !found.has(key)) { + const at = m.text.toLocaleLowerCase().indexOf(q); + if (at >= 0) found.set(key, said(snippet(m.text, at, q.length))); + } + } + + const out: ThreadList = { ...empty }; + const sortAt = new Map(); + const add = (row: Omit, at: number) => { + const full = { ...row, group: threadGroup(row) }; + out[full.group].push(full); + sortAt.set(full, at); + }; + for (const t of taskRows) { + const key = `task:${t.id}`; + const taskKey = formatTaskKey(project.key, t.number); + const open = openByTask.get(t.id) ?? 0; + const archived = t.archivedAt != null; + const lastAt = stats.get(key) ?? null; + if (q) { + if (!found.has(key) && !taskKey.toLocaleLowerCase().includes(q) && !t.title.toLocaleLowerCase().includes(q)) continue; + } else if (open === 0 && (archived || (!lastAt && !ACTIVE.has(t.status)))) continue; + add( + { key, taskKey, title: t.title, status: t.status, archived, accepted: accepted.has(t.id), agentName: agentByTask.get(t.id)?.name ?? null, last: found.get(key) ?? lastLine.get(key) ?? null, lastAt, unread: unread.get(key) ?? 0, open }, + (lastAt ?? t.updatedAt).getTime(), + ); + } + for (const [key, open] of looseThreads) { + const title = (await threadTitle(db, key)) ?? key; + if (q && !found.has(key) && !title.toLocaleLowerCase().includes(q)) continue; + const lastAt = stats.get(key) ?? null; + add({ key, taskKey: null, title, status: null, archived: false, accepted: false, agentName: null, last: found.get(key) ?? lastLine.get(key) ?? null, lastAt, unread: unread.get(key) ?? 0, open }, lastAt?.getTime() ?? 0); + } + for (const g of ["waiting", "working", "done"] as const) out[g].sort((a, b) => sortAt.get(b)! - sortAt.get(a)!); + return out; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index d32cfffe..b0ead52a 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -65,6 +65,7 @@ export * from "./memory.ts"; export * from "./agent-model.ts"; export * from "./onboarding.ts"; export * from "./chats.ts"; +export * from "./chat-threads.ts"; export * from "./subscription-care.ts"; export * from "./subscription-names.ts"; export * from "./transcribe.ts"; diff --git a/packages/core/src/story-product.ts b/packages/core/src/story-product.ts index 40a51c92..13e9424a 100644 --- a/packages/core/src/story-product.ts +++ b/packages/core/src/story-product.ts @@ -57,7 +57,8 @@ export const STORY_PRODUCT_TEXT = { }; /** File names, paths, identifiers and commands — not for a product manager's screen. */ -const TECHNICAL = /[/\\_$<>{}=]|\w\.\w|\w\(|[a-z][A-Z]|--\w|\b(?:tmux|git|npm|pnpm|sql|api|json|mcp|ci|pr|cli|env)\b/i; +/** Code, paths, identifiers — text a product manager cannot read. */ +export const TECHNICAL_TEXT = /[/\\_$<>{}=]|\w\.\w|\w\(|[a-z][A-Z]|--\w|\b(?:tmux|git|npm|pnpm|sql|api|json|mcp|ci|pr|cli|env)\b/i; /** * The current tasks.md item for the product view: the leading «1.2», code in backticks and @@ -67,7 +68,7 @@ export function plainStep(text: string | null | undefined): string | null { if (!text) return null; if (text.includes("`")) return null; const s = text.replace(/^\s*\d+(?:\.\d+)*\.?\s+/, "").replace(/\s+/g, " ").trim(); - if (s.length < 3 || s.length > 140 || TECHNICAL.test(s)) return null; + if (s.length < 3 || s.length > 140 || TECHNICAL_TEXT.test(s)) return null; return s; } diff --git a/packages/shared/src/i18n/en/story.ts b/packages/shared/src/i18n/en/story.ts index 8a984261..de599143 100644 --- a/packages/shared/src/i18n/en/story.ts +++ b/packages/shared/src/i18n/en/story.ts @@ -416,4 +416,14 @@ export const story: Dict = { "ждёт сброса лимита": "waiting for the limit reset", закончил: "finished", "остановился с ошибкой": "stopped with an error", + // PEP-155: the list of a project chat's conversations + "Ждут вас": "Waiting for you", + "Сейчас от вас ничего не нужно.": "Nothing is needed from you right now.", + "Найти в переписке…": "Search the conversations…", + "Поиск по переписке": "Search the conversations", + "Найти": "Search", + "Сбросить поиск": "Clear the search", + "Ничего не нашлось. Попробуйте другое слово.": "Nothing found. Try another word.", + "← К списку": "← Back to the list", + "Новых сообщений: {n}": "New messages: {n}", }; diff --git a/packages/shared/src/i18n/kk/story.ts b/packages/shared/src/i18n/kk/story.ts index 6735bea4..0cd45266 100644 --- a/packages/shared/src/i18n/kk/story.ts +++ b/packages/shared/src/i18n/kk/story.ts @@ -381,4 +381,14 @@ export const story: Dict = { "ждёт сброса лимита": "лимит тасталуын күтуде", "закончил": "аяқтады", "остановился с ошибкой": "қатемен тоқтады", + // PEP-155: the list of a project chat's conversations + "Ждут вас": "Сізді күтуде", + "Сейчас от вас ничего не нужно.": "Қазір сізден ештеңе қажет емес.", + "Найти в переписке…": "Хат алмасудан іздеу…", + "Поиск по переписке": "Хат алмасудан іздеу", + "Найти": "Іздеу", + "Сбросить поиск": "Іздеуді тазарту", + "Ничего не нашлось. Попробуйте другое слово.": "Ештеңе табылмады. Басқа сөзді қолданып көріңіз.", + "← К списку": "← Тізімге", + "Новых сообщений: {n}": "Жаңа хабарлар: {n}", }; diff --git a/packages/testkit/test/chats.test.ts b/packages/testkit/test/chats.test.ts index 38f8562b..f45ff3e4 100644 --- a/packages/testkit/test/chats.test.ts +++ b/packages/testkit/test/chats.test.ts @@ -6,7 +6,7 @@ import { after, before, describe, test } from "node:test"; // helpers must load first: it sets the isolated test env that runner modules read on load. import { core, db, runner, teardown, waitFor } from "./helpers.ts"; import { MockTelegram } from "../src/mock-telegram.ts"; -import { chatMessages, users } from "@peppa/db"; +import { chatMessages, tasks, users } from "@peppa/db"; import { eq } from "drizzle-orm"; import type { Bot } from "@peppa/bot"; @@ -126,6 +126,121 @@ describe("project chat", () => { }); }); +// PEP-155: the list of a project chat's conversations. +describe("Список переписки проекта", () => { + const setStatus = (taskId: number, status: "in_progress" | "review" | "done" | "backlog") => db.update(tasks).set({ status }).where(eq(tasks.id, taskId)); + const say = (chatId: number, taskId: number, text: string, authorKind: "agent" | "system" = "agent") => core.addChatMessage(db, { chatId, threadKey: threadOf(taskId), kind: "event", authorKind, text }); + const keys = (rows: Array<{ taskKey: string | null }>) => rows.map((r) => r.taskKey); + + test("Три группы", async () => { + const p = await newProject(); + const chat = await core.ensureProjectChat(db, p.id); + const asked = await newTask(p, "Формат даты"); + const working = await newTask(p, "Экспорт в CSV"); + const review = await newTask(p, "Отчёт"); + const done = await newTask(p, "Вход"); + const idle = await newTask(p, "Ещё не начата"); + await core.askPm(db, asked, { kind: "question", text: "Какой формат даты?" }); + await setStatus(working.task.id, "in_progress"); + await setStatus(review.task.id, "review"); + await setStatus(done.task.id, "done"); + await core.syncChats(db); + await say(chat.id, done.task.id, "Вход работает"); + const list = await core.projectThreadList(db, pm, chat); + assert.deepEqual(keys(list.waiting).sort(), [asked.key, review.key].sort()); + assert.deepEqual(keys(list.working), [working.key]); + assert.deepEqual(keys(list.done), [done.key]); + assert.ok(![...list.waiting, ...list.working, ...list.done].some((r) => r.taskKey === idle.key), "a backlog story nobody wrote about is not in the list"); + assert.equal(list.waiting.find((r) => r.taskKey === asked.key)!.open, 1); + }); + + test("Уведомление не делает тред ждущим", async () => { + const p = await newProject(); + const chat = await core.ensureProjectChat(db, p.id); + const ref = await newTask(p); + await setStatus(ref.task.id, "in_progress"); + await core.askPm(db, ref, { kind: "attention", text: "Агент перезапущен после сбоя" }); + await core.syncChats(db); + const list = await core.projectThreadList(db, pm, chat); + assert.deepEqual(keys(list.working), [ref.key]); + assert.equal(list.waiting.length, 0); + // PEP-127: «Принять» is pressed already — nothing is waited from the person. + await setStatus(ref.task.id, "review"); + assert.deepEqual(keys((await core.projectThreadList(db, pm, chat)).waiting), [ref.key]); + await core.setPendingAccept(db, ref.task.id, { at: Date.now(), via: "web", rebases: 0 } as Parameters[2]); + assert.deepEqual(keys((await core.projectThreadList(db, pm, chat)).working), [ref.key]); + await core.clearPendingAccept(db, ref.task.id); + }); + + test("Статус и агент; техническое сообщение не показывается", async () => { + const p = await newProject(); + const chat = await core.ensureProjectChat(db, p.id); + const ref = await newTask(p); + await setStatus(ref.task.id, "in_progress"); + const session = await core.createSession(db, { projectId: p.id, taskId: ref.task.id }); + const agent = await core.ensureSessionAgent(db, session.id); + await say(chat.id, ref.task.id, "Экспорт готов наполовину"); + await say(chat.id, ref.task.id, "Поправил `src/export.ts`, запустил pnpm test"); + const [row] = (await core.projectThreadList(db, pm, chat)).working; + assert.equal(row!.taskKey, ref.key); + assert.equal(row!.title, "Экспорт в CSV"); + assert.equal(row!.status, "in_progress"); + assert.equal(row!.agentName, agent!.name); + assert.equal(row!.last!.text, "Экспорт готов наполовину"); + assert.equal(core.plainLine("**Готово:** проверил вход\nвторая строка"), "Готово: проверил вход"); + assert.equal(core.plainLine("update_task(status: review)"), null); + }); + + test("Непрочитанное", async () => { + const p = await newProject(); + const chat = await core.ensureProjectChat(db, p.id); + const ref = await newTask(p); + await setStatus(ref.task.id, "in_progress"); + await say(chat.id, ref.task.id, "Старое сообщение"); + // The first look: what was there before is not «new». + assert.equal((await core.projectThreadList(db, pm, chat)).working[0]!.unread, 0); + await say(chat.id, ref.task.id, "Первое новое"); + await say(chat.id, ref.task.id, "Второе новое"); + await core.addChatMessage(db, { chatId: chat.id, threadKey: threadOf(ref.task.id), kind: "user", authorKind: "user", authorUserId: pm.id, authorLogin: pm.login, text: "моё сообщение" }); + const mine = (await core.projectThreadList(db, pm, chat)).working[0]!; + assert.equal(mine.unread, 2, "own messages are not «new»"); + assert.equal(mine.last!.mine, true); + await core.markThreadRead(db, pm.id, chat.id, threadOf(ref.task.id)); + assert.equal((await core.projectThreadList(db, pm, chat)).working[0]!.unread, 0); + // Bob has his own marks. + await core.projectThreadList(db, bob, chat); + await say(chat.id, ref.task.id, "Третье новое"); + assert.equal((await core.projectThreadList(db, bob, chat)).working[0]!.unread, 1); + assert.equal((await core.projectThreadList(db, pm, chat)).working[0]!.unread, 1); + assert.equal((await core.projectThreadList(db, eve, chat)).working[0]!.unread, 0); + }); + + test("Поиск: слово из сообщения, ключ, название; чужой проект", async () => { + const p = await newProject(); + const other = await newProject(); + const chat = await core.ensureProjectChat(db, p.id); + const otherChat = await core.ensureProjectChat(db, other.id); + const done = await newTask(p, "Отчёты"); + const working = await newTask(p, "Оплата картой"); + const foreign = await newTask(other, "Склад"); + await setStatus(done.task.id, "done"); + await setStatus(working.task.id, "in_progress"); + await say(chat.id, done.task.id, "Проверил вход\nДобавил выгрузку в Эксель"); + await say(chat.id, working.task.id, "Подключаю оплату"); + await say(otherChat.id, foreign.task.id, "Самолёт и Эксель"); + + const byText = await core.projectThreadList(db, pm, chat, { q: "эксель" }); + assert.equal(byText.q, "эксель"); + assert.deepEqual(keys(byText.done), [done.key]); + assert.equal(byText.done[0]!.last!.text, "Добавил выгрузку в Эксель"); + assert.equal(byText.working.length + byText.waiting.length, 0); + assert.deepEqual(keys((await core.projectThreadList(db, pm, chat, { q: "ОПЛАТА" })).working), [working.key]); + assert.deepEqual(keys((await core.projectThreadList(db, pm, chat, { q: done.key.toLowerCase() })).done), [done.key]); + const none = await core.projectThreadList(db, pm, chat, { q: "самолёт" }); + assert.equal(none.waiting.length + none.working.length + none.done.length, 0); + }); +}); + describe("master chat", () => { test("Сбой раннера в мастер-чате; команды /task и неизвестная", async () => { const p = await newProject();