peppa/packages/core/src/chat-threads.ts
Асель dc6eb424a9 PEP-155: plain last line, phone layout, AGENTS.md
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 13:24:37 +05:00

207 lines
11 KiB
TypeScript

// 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:<id>` (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")) {
// 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<string, number>;
}
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<void> {
const [last] = await db.select({ id: sql<number | null>`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<ThreadRead>(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<User, "id">, chat: Pick<Chat, "id" | "projectId">, o: { q?: string | null } = {}): Promise<ThreadList> {
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<number | null>`max(${chatMessages.id})` }).from(chatMessages).where(eq(chatMessages.chatId, chat.id));
let read = await getSetting<ThreadRead>(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<number>`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<number, number>();
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<string, number>();
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<number, { name: string; live: boolean }>();
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, 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<string, ThreadRow["last"]>();
const found = new Map<string, ThreadRow["last"]>();
const unread = new Map<string, number>();
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)) {
// A question is projected as «<icon> <what it is>\n<the question>»: 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<ThreadRow, number>();
const add = (row: Omit<ThreadRow, "group">, 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;
}