PEP-155: project chat list — groups, status, agent, unread, search

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-16 13:20:32 +05:00
parent bfe722d941
commit ea3515d31c
8 changed files with 538 additions and 42 deletions

View File

@ -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
))}
</nav>
<div className={cn("grid gap-4", !master && "lg:grid-cols-[230px_minmax(0,1fr)]")}>
{!master && (
<nav aria-label={t("Треды")} 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={t("💬 Чат с аналитиком")} meta={t("вопросы и новые задачи")} />
<ThreadLink href={url({ thread: FEED })} active={!discussion && thread === undefined} title={t("События агентов")} meta={t("журнал: что делали агенты")} />
{threads.length > 0 && <p className="m-0 px-2 pt-2 text-[11px] tracking-wide text-muted-foreground uppercase">{t("Переписка по {tasks}", { tasks: w.task("datPl") })}</p>}
{threads.map((th) => (
<ThreadLink key={th.key} href={url({ thread: th.key })} active={thread === th.key} title={t.text(th.title)} meta={`${th.count} · ${ago(th.lastAt, t)}`} open={th.open} />
))}
{threads.length === 0 && <p className="m-0 px-2 py-1.5 text-xs text-muted-foreground">{t("Переписки по {tasks} пока нет.", { tasks: w.task("datPl") })}</p>}
</nav>
<div className={cn("grid gap-4", !master && "lg:grid-cols-[320px_minmax(0,1fr)]")}>
{threads && (
<div className={cn(!showList && "max-lg:hidden")}>
<ChatThreadList base={base} list={threads} active={thread ?? null} discussion={discussion} feed={!discussion && thread === undefined} raw={rawThread ?? null} />
</div>
)}
<section className="flex min-w-0 flex-col gap-3" aria-label={t("Сообщения")}>
<section className={cn("flex min-w-0 flex-col gap-3", showList && "max-lg:hidden")} aria-label={t("Сообщения")}>
{!master && (
<Link href={url({ thread: rawThread, list: true })} className="self-start rounded-md border bg-card px-2.5 py-1 text-sm text-muted-foreground hover:text-foreground hover:no-underline lg:hidden">
{t("← К списку")}
</Link>
)}
{current && (
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-medium">🧵 {t.text(current)}</span>
{openRow?.status && <StatusBadge status={openRow.status} />}
{openRow?.agentName && <AgentBadge name={openRow.agentName} />}
{taskThread && <TaskLink messages={messages} label={t("открыть {task} →", { task: w.task("acc") })} />}
</div>
)}
@ -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 (
<Link
href={href}
aria-current={active ? "page" : undefined}
className={cn("flex flex-col rounded-md px-2 py-1.5 text-foreground hover:bg-accent hover:no-underline", active && "bg-accent font-medium")}
>
<span className="flex items-center gap-1.5">
<span className="min-w-0 flex-1 truncate" title={title}>{title}</span>
{open > 0 && <span className="rounded-full bg-primary px-1.5 font-mono text-[11px] leading-4 font-semibold text-primary-foreground tabular-nums" title={t("ждут ответа")}>{open}</span>}
</span>
{meta && <span className="text-[11px] text-muted-foreground">{meta}</span>}
</Link>
);
}
function TaskLink({ messages, label }: { messages: ChatMessageView[]; label: string }) {
const key = messages.find((m) => m.threadTitle)?.threadTitle?.split(" · ")[0];
return key ? <Link href={`/t/${key}`} className="text-xs">{label}</Link> : null;

View File

@ -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/<KEY>` */
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) => <Row key={r.key} r={r} href={href(r.key)} active={active === r.key} />);
return (
<nav aria-label={t("Треды")} className="flex flex-col gap-0.5 self-start rounded-lg border bg-card/50 p-1.5 text-sm">
<form action={base} method="get" role="search" className="mb-1 flex items-center gap-1">
{/* On a phone the answer to a search is the list, not the open conversation. */}
<Hidden fields={{ list: 1, ...(raw ? { thread: raw } : {}) }} />
<Input type="search" name="q" defaultValue={q ?? ""} maxLength={100} placeholder={t("Найти в переписке…")} aria-label={t("Поиск по переписке")} className="h-8 min-w-0 flex-1 text-sm" />
<Button size="sm" variant="outline" aria-label={t("Найти")} title={t("Найти")} className="px-2">
<Search />
</Button>
{q && (
<Link href={raw ? `${base}?thread=${encodeURIComponent(raw)}&list=1` : `${base}?list=1`} aria-label={t("Сбросить поиск")} title={t("Сбросить поиск")} className="grid size-8 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground">
<X className="size-4" />
</Link>
)}
</form>
<Plain href={href(null)} active={discussion} title={t("💬 Чат с аналитиком")} meta={t("вопросы и новые задачи")} />
<Plain href={href("feed")} active={feed} title={t("События агентов")} meta={t("журнал: что делали агенты")} />
{q && total === 0 ? (
<p className="m-0 px-2 py-3 text-muted-foreground">{t("Ничего не нашлось. Попробуйте другое слово.")}</p>
) : total === 0 ? (
<p className="m-0 px-2 py-1.5 text-xs text-muted-foreground">{t("Переписки по {tasks} пока нет.", { tasks: w.task("datPl") })}</p>
) : (
<>
{(!q || list.waiting.length > 0) && (
<section aria-label={t("Ждут вас")} data-group="waiting" className="flex flex-col gap-0.5">
<GroupTitle count={list.waiting.length} tone={list.waiting.length ? "bg-primary text-primary-foreground" : undefined}>
{t("Ждут вас")}
</GroupTitle>
{list.waiting.length ? rows(list.waiting) : <p className="m-0 px-2 py-1 text-xs text-muted-foreground">{t("Сейчас от вас ничего не нужно.")}</p>}
</section>
)}
{list.working.length > 0 && (
<section aria-label={t("В работе")} data-group="working" className="flex flex-col gap-0.5">
<GroupTitle count={list.working.length}>{t("В работе")}</GroupTitle>
{rows(list.working)}
</section>
)}
{list.done.length > 0 && (
<details data-group="done" open={!!q || list.done.some((r) => r.key === active)} className="group/done flex flex-col">
<summary className="flex cursor-pointer list-none items-center gap-1.5 rounded-md px-2 pt-2 pb-1 text-[11px] tracking-wide text-muted-foreground uppercase hover:text-foreground [&::-webkit-details-marker]:hidden">
<span aria-hidden className="transition-transform group-open/done:rotate-90">▸</span>
{t("Готово")}
<span className={cn(COUNT, "bg-muted text-muted-foreground")}>{list.done.length}</span>
</summary>
<div className="flex flex-col gap-0.5">{rows(list.done)}</div>
</details>
)}
</>
)}
</nav>
);
}
function GroupTitle({ children, count, tone = "bg-muted text-muted-foreground" }: { children: React.ReactNode; count: number; tone?: string }) {
return (
<h2 className="m-0 flex items-center gap-1.5 px-2 pt-2 pb-1 text-[11px] font-normal tracking-wide text-muted-foreground uppercase">
{children}
{count > 0 && <span className={cn(COUNT, tone)}>{count}</span>}
</h2>
);
}
function Plain({ href, active, title, meta }: { href: string; active: boolean; title: string; meta: string }) {
return (
<Link href={href} aria-current={active ? "page" : undefined} className={cn("flex flex-col rounded-md px-2 py-1.5 text-foreground hover:bg-accent hover:no-underline", active && "bg-accent font-medium")}>
<span className="truncate">{title}</span>
<span className="text-[11px] font-normal text-muted-foreground">{meta}</span>
</Link>
);
}
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 (
<Link
href={href}
data-thread={r.key}
aria-current={active ? "page" : undefined}
className={cn("flex flex-col gap-1 rounded-md px-2 py-2 text-foreground hover:bg-accent hover:no-underline", active && "bg-accent")}
>
<span className="flex items-baseline gap-1.5">
{r.taskKey && <span className="shrink-0 font-mono text-xs text-muted-foreground">{r.taskKey}</span>}
<span className={cn("min-w-0 flex-1 truncate", (active || r.unread > 0) && "font-medium")} title={title}>
{title}
</span>
{r.open > 0 && (
<span className={cn(COUNT, "self-center bg-primary text-primary-foreground")} title={t("ждут ответа")}>
?
</span>
)}
{r.unread > 0 && (
<span className={cn(COUNT, "self-center bg-info text-background")} title={t("Новых сообщений: {n}", { n: r.unread })}>
{r.unread > 99 ? "99+" : r.unread}
</span>
)}
</span>
{(r.status || r.agentName || r.lastAt) && (
<span className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
{r.status && <StatusBadge status={r.status} />}
{r.agentName && <AgentBadge name={r.agentName} />}
{r.lastAt && <span className="ml-auto shrink-0 font-mono text-[11px] text-muted-foreground">{ago(r.lastAt, t)}</span>}
</span>
)}
{r.last && (
<span className="truncate text-xs text-muted-foreground">
{r.last.mine && t("вы") + ": "}
{r.last.system ? t.text(r.last.text) : r.last.text}
</span>
)}
</Link>
);
}

View File

@ -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:<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")) {
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<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, 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)) {
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<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;
}

View File

@ -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";

View File

@ -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;
}

View File

@ -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}",
};

View File

@ -381,4 +381,14 @@ export const story: Dict = {
"ждёт сброса лимита": "лимит тасталуын күтуде",
"закончил": "аяқтады",
"остановился с ошибкой": "қатемен тоқтады",
// PEP-155: the list of a project chat's conversations
"Ждут вас": "Сізді күтуде",
"Сейчас от вас ничего не нужно.": "Қазір сізден ештеңе қажет емес.",
"Найти в переписке…": "Хат алмасудан іздеу…",
"Поиск по переписке": "Хат алмасудан іздеу",
"Найти": "Іздеу",
"Сбросить поиск": "Іздеуді тазарту",
"Ничего не нашлось. Попробуйте другое слово.": "Ештеңе табылмады. Басқа сөзді қолданып көріңіз.",
"← К списку": "← Тізімге",
"Новых сообщений: {n}": "Жаңа хабарлар: {n}",
};

View File

@ -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<typeof core.setPendingAccept>[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();