// 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 { delayedTaskIds } from "./platform-delay.ts"; import { awaitingRollout } from "./rollout.ts"; import { threadTitle, type Chat } from "./chats.ts"; import { questionType } from "./questions.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; } 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.status === "rollout" || 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")) { // Markup and the leading icon of an event («📈 …») are not the point. const line = raw.replace(/\*\*|__/g, "").replace(/^[^\p{L}\p{N}«"(]+/u, "").replace(/\s+/g, " ").trim(); if (!/\p{L}{2}/u.test(line)) 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(); const inside = start > 0 && text[start - 1] !== "\n"; return inside ? `…${cut(s)}` : cut(s.replace(/^[^\p{L}\p{N}«"(]+/u, "") || 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))]), ); // PEP-149: only a question waits for an answer; «готово» is the `review` status, the rest are notices. const openRows = (await db.select({ taskId: questions.taskId, id: questions.id, kind: questions.kind, msgType: questions.msgType, options: questions.options }).from(questions).where(and(eq(questions.projectId, project.id), isNull(questions.answeredAt)))).filter((r) => questionType(r) === "question"); 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); // PEP-278: accepted, the version with the changes is not running yet — the badge says so. const rollout = await awaitingRollout(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, kind: chatMessages.kind, 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!; // PEP-207: an event a person's press caused is the factory's line, not «вы: …». const mine = m.authorUserId === user.id && m.kind === "user"; const said = (text: string) => ({ text, system: m.authorKind === "system", mine }); // PEP-207: «N нов.» counts what asks for attention — questions and messages written to the person — // not the factory's events. const counts = m.kind === "question" || (m.kind === "user" && m.authorKind !== "user"); if (counts && !mine && m.id > Math.max(read.base, read.seen[key] ?? 0)) unread.set(key, (unread.get(key) ?? 0) + 1); if (!lastLine.has(key)) { // A question is projected as « \n»: the point is the question. const line = plainLine(m.kind === "question" && m.text.includes("\n") ? m.text.slice(m.text.indexOf("\n") + 1) : 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 === "done" && rollout.has(t.id) ? "rollout" : 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; } export interface ChatStatusLine { /** Stories with an agent at work now. */ working: Array<{ key: string; title: string }>; /** Stories held up on the factory's side (PEP-150 delays). */ delayed: Array<{ key: string; title: string }>; } /** * PEP-207: what the chat with the analyst shows in one folding line on top instead of service * messages («задерживается на нашей стороне», «агент взял задачу»): «Сейчас: делается N, * задерживаются на нашей стороне M» with links to the stories. */ export async function chatStatusLine(db: Db, projectId: number): Promise { const [project] = await db.select({ key: projects.key }).from(projects).where(eq(projects.id, projectId)); if (!project) return { working: [], delayed: [] }; const inWork = await db .select({ id: tasks.id, number: tasks.number, title: tasks.title }) .from(tasks) .where(and(eq(tasks.projectId, projectId), eq(tasks.status, "in_progress"), isNull(tasks.archivedAt))) .orderBy(asc(tasks.position)); const delayedIds = await delayedTaskIds(db); const row = (t: { number: number; title: string }) => ({ key: formatTaskKey(project.key, t.number), title: t.title }); return { working: inWork.filter((t) => !delayedIds.has(t.id)).map(row), delayed: inWork.filter((t) => delayedIds.has(t.id)).map(row), }; }