PEP-228: область chat:<id> несёт сообщения для зрителя, лента чата дорисовывает их на месте

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-21 14:54:13 +00:00
parent 2acfb8af27
commit 0dceba0ff2
20 changed files with 468 additions and 99 deletions

View File

@ -10,6 +10,7 @@ import { LiveRefresh } from "@/components/LiveRefresh";
import { AgentBadge } from "@/components/AgentBadge";
import { ChatThreadList } from "@/components/ChatThreadList";
import { ChatScroll } from "@/components/ChatScroll";
import { ChatLiveFeed } from "@/components/ChatLiveFeed";
import { ChatSwitch } from "@/components/ChatSwitch";
import { ago, Empty, Flash, linkify, StatusBadge } from "@/components/common";
import { Hidden, QuestionCard } from "@/components/cards";
@ -24,7 +25,7 @@ import { requireUser, words } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
import { cn } from "@/lib/utils";
import { cleanText } from "@/lib/chat-text";
import { cleanText, messageLink, STUCK_NOTICE } from "@/lib/chat-text";
import { chatOfferAction, linkChatAction, postChatAction, unlinkChatAction } from "../actions";
type Params = { error?: string; thread?: string; link?: string; q?: string; list?: string };
@ -223,10 +224,31 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
return { slug: c.slug, label: marks ? `${c.kind === "master" ? name : `${c.slug} · ${name}`} (${marks})` : c.kind === "master" ? name : `${c.slug} · ${name}` };
});
const feed = ordered.length === 0 ? (
<Empty>{discussion ? t("Напишите, что хотите узнать или сделать, — аналитик ответит здесь же. Например: «Что сейчас в работе?» или «Хочу страницу с отзывами клиентов».") : master ? t("Пока тихо: здесь появятся вопросы агентов, сбои и обновления ваших проектов.") : thread === undefined ? t("Сообщений пока нет: они появятся, когда агенты возьмутся за {tasks}.", { tasks: w.task("accPl") }) : t("В этом треде пока пусто.")}</Empty>
) : (
<ol data-chat-messages className="m-0 flex list-none flex-col gap-2 p-0 pr-12 md:pr-14">
{groups.map((g) =>
g.kind === "events" ? (
<li key={`e${g.items[0]!.id}`}>
<EventLines items={g.items} firstUnreadId={firstUnreadId} taskStatus={taskStatus} agentName={openRow?.agentName ?? null} masterView={master} showThread={!discussion && thread === undefined} superadmin={superadmin} gitea={gitea} />
</li>
) : (
<li key={g.m.id} data-first-unread={g.m.id === firstUnreadId ? "" : undefined} className={cn("flex", discussion && g.m.authorUserId === user.id && g.m.kind === "user" ? "justify-end" : "justify-start")}>
<div className={cn("min-w-0", g.m.question ? "w-full" : "max-w-[85%]")}>
<MessageItem files={files.get(g.m.id)} m={g.m} q={g.m.question ? qById.get(g.m.question.id) : undefined} back={here} showThread={!discussion && thread === undefined} masterView={master} mine={discussion && g.m.authorUserId === user.id} agentName={openRow?.agentName ?? null} superadmin={superadmin} gitea={gitea} />
</div>
</li>
),
)}
</ol>
);
return (
<Workspace aside={null} wide>
{/* PEP-225: a project chat re-renders only for its own new messages; the master feed gathers every project. */}
<LiveRefresh scope="chats" indicator={false} chatId={master ? undefined : chat.id} />
{/* PEP-228: a project chat draws its new messages in place (ChatLiveFeed) and re-renders only for
what it can't draw; the master feed gathers every project and re-renders. */}
<LiveRefresh scope={master ? "chats" : `chat:${chat.id}`} indicator={false} />
<Flash error={error} />
<h1 className="sr-only">{t("Чаты")}</h1>
@ -285,32 +307,33 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
</p>
)}
{ordered.length === 0 ? (
<Empty>{discussion ? t("Напишите, что хотите узнать или сделать, — аналитик ответит здесь же. Например: «Что сейчас в работе?» или «Хочу страницу с отзывами клиентов».") : master ? t("Пока тихо: здесь появятся вопросы агентов, сбои и обновления ваших проектов.") : thread === undefined ? t("Сообщений пока нет: они появятся, когда агенты возьмутся за {tasks}.", { tasks: w.task("accPl") }) : t("В этом треде пока пусто.")}</Empty>
{master ? (
<>
{feed}
<div data-chat-end />
<ChatScroll lastId={ordered.at(-1)?.id ?? 0} />
</>
) : (
<ol data-chat-messages className="m-0 flex list-none flex-col gap-2 p-0 pr-12 md:pr-14">
{groups.map((g) =>
g.kind === "events" ? (
<li key={`e${g.items[0]!.id}`}>
<EventLines items={g.items} firstUnreadId={firstUnreadId} taskStatus={taskStatus} agentName={openRow?.agentName ?? null} masterView={master} showThread={!discussion && thread === undefined} superadmin={superadmin} gitea={gitea} />
</li>
) : (
<li key={g.m.id} data-first-unread={g.m.id === firstUnreadId ? "" : undefined} className={cn("flex", discussion && g.m.authorUserId === user.id && g.m.kind === "user" ? "justify-end" : "justify-start")}>
<div className={cn("min-w-0", g.m.question ? "w-full" : "max-w-[85%]")}>
<MessageItem files={files.get(g.m.id)} m={g.m} q={g.m.question ? qById.get(g.m.question.id) : undefined} back={here} showThread={!discussion && thread === undefined} masterView={master} mine={discussion && g.m.authorUserId === user.id} agentName={openRow?.agentName ?? null} superadmin={superadmin} gitea={gitea} />
</div>
</li>
),
)}
</ol>
<ChatLiveFeed
chatId={chat.id}
lastId={messages.at(-1)?.id ?? 0}
view={discussion ? { kind: "discussion" } : thread === undefined ? { kind: "feed" } : thread === null ? { kind: "channel" } : { kind: "thread", key: thread }}
userId={user.id}
compact={!discussion}
showThread={!discussion && thread === undefined}
agentName={openRow?.agentName ?? null}
empty={ordered.length === 0}
typing={
typing ? (
<p className="m-0 flex items-center gap-2 text-sm text-muted-foreground" aria-live="polite">
<AgentBadge name={ANALYST_NAME} role /> <span className="animate-pulse">{t("печатает…")}</span>
</p>
) : null
}
>
{feed}
</ChatLiveFeed>
)}
{typing && (
<p className="m-0 flex items-center gap-2 text-sm text-muted-foreground" aria-live="polite">
<AgentBadge name={ANALYST_NAME} role /> <span className="animate-pulse">{t("печатает…")}</span>
</p>
)}
<div data-chat-end />
<ChatScroll lastId={ordered.at(-1)?.id ?? 0} />
{writable && (
<form action={postChatAction} data-chat-composer className="sticky bottom-[calc(4rem+env(safe-area-inset-bottom))] z-20 -mx-1 flex flex-col gap-1 rounded-lg border bg-card p-2 shadow-md md:bottom-3">
@ -335,7 +358,6 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
);
}
const STUCK_NOTICE = /задерживается на нашей стороне/i;
type Group = { kind: "events"; items: ChatMessageView[] } | { kind: "message"; m: ChatMessageView };
@ -387,13 +409,6 @@ async function EventLines({ items, firstUnreadId, taskStatus, agentName, masterV
);
}
/** A link under a message: never the bare «/», never Gitea for a product manager. */
function messageLink(url: string | null, superadmin: boolean, gitea: string): string | null {
if (!url || url === "/" || url === "#") return null;
if (!superadmin && gitea && url.startsWith(gitea)) return null;
return url;
}
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

@ -1,7 +1,7 @@
"use server";
// «Чаты» (PEP-62): a message into a chat/thread, Telegram group link/unlink. Access — chatForUser.
import { parseAttachmentIds, chatForUser, createChatLinkCode, isSuperadmin, PeppaError, unlinkChat } from "@peppa/core";
import { parseAttachmentIds, chatForUser, createChatLinkCode, isSuperadmin, markDiscussionRead, markThreadRead, PeppaError, THREAD_KEY, unlinkChat } from "@peppa/core";
import { postToChat, resolveChatOffer, type ChatOfferChoice } from "@peppa/runner";
import { loadEnv } from "@peppa/shared";
import { m } from "@peppa/shared/i18n";
@ -36,6 +36,18 @@ export async function postChatAction(f: FormData) {
});
}
/**
* PEP-228: messages drawn in place on an open chat page are read — the discussion (thread null)
* or one thread. No redirect: the page stays as it is.
*/
export async function markChatReadAction(chatId: number, thread: string | null): Promise<void> {
const user = await requireUser();
const chat = await chatForUser(db, user, Number(chatId)).catch(() => null);
if (!chat || chat.kind !== "project") return;
if (thread == null) await markDiscussionRead(db, user.id, chat.id);
else if (typeof thread === "string" && THREAD_KEY.test(thread)) await markThreadRead(db, user.id, chat.id, thread);
}
/** PEP-153: a button under a chat message — «Завести как задачу», «Ответить», «Создать», «Отмена». */
export async function chatOfferAction(f: FormData) {
const user = asWebActor(await requireUser());

View File

@ -1,5 +1,6 @@
import { FileSpreadsheet, FileText, Presentation } from "lucide-react";
import { humanSize, type AttachmentView } from "@peppa/core";
import type { AttachmentView } from "@peppa/core";
import { humanSize } from "@peppa/shared/format";
/**
* PEP-159: files of a message, a comment or a story — pictures as thumbnails that open large,

View File

@ -0,0 +1,200 @@
"use client";
// PEP-228: new messages of the open conversation drawn in place. The page's chat scope
// (`chat:<id>`) brings them ready for this viewer (lib/chat-live.ts); what belongs to this
// conversation and needs no buttons is added to the end of the feed at once — no server
// re-render. Questions, offers, other threads go to LiveRefresh (the island leaves `m` to it).
import { useEffect, useRef, useState, type ReactNode } from "react";
import { Bot, MessagesSquare, User as UserIcon } from "lucide-react";
import { PRODUCT_NAME } from "@peppa/shared/i18n";
import { AgentBadge } from "@/components/AgentBadge";
import { Attachments } from "@/components/Attachments";
import { ChatScroll } from "@/components/ChatScroll";
import { useT } from "@/components/I18n";
import { ago, linkify } from "@/lib/format";
import { useLiveIsland } from "@/lib/live";
import { cn } from "@/lib/utils";
import type { LiveChatMessage } from "@/lib/chat-live-types";
import { markChatReadAction } from "@/app/(app)/chats/actions";
/** Which conversation the page shows — the same rules as its server query. */
export type ChatView = { kind: "discussion" } | { kind: "channel" } | { kind: "feed" } | { kind: "thread"; key: string };
export function inView(m: Pick<LiveChatMessage, "threadKey" | "kind" | "command" | "notice">, view: ChatView): boolean {
if (view.kind === "feed") return true;
if (view.kind === "thread") return m.threadKey === view.key;
if (view.kind === "channel") return m.threadKey === null;
return m.threadKey === null && m.kind === "user" && !m.command && !m.notice;
}
/**
* What of a `change` of the chat scope the feed applies in place: `m` when every new message is
* of this conversation and none needs buttons; `x` (offers, files) when it came with messages —
* they carry their own. Pure: the test and the island share it.
*/
export function chatParts(e: { parts: string[]; messages?: unknown[] }, view: ChatView): { applied: string[]; add: LiveChatMessage[] } {
const list = (e.messages ?? []) as LiveChatMessage[];
if (!e.messages) return { applied: [], add: [] };
const plain = list.every((m) => inView(m, view) && !m.render);
const applied = ["x"];
if (plain) applied.push("m");
return { applied, add: plain ? list : list.filter((m) => inView(m, view) && !m.render) };
}
export function ChatLiveFeed({
chatId,
lastId,
view,
userId,
compact,
showThread,
agentName,
typing,
empty,
children,
}: {
chatId: number;
/** The last message the server drew: anything newer is ours to draw. */
lastId: number;
view: ChatView;
userId: number;
/** Events as compact lines (threads and «События агентов»). */
compact: boolean;
showThread: boolean;
agentName: string | null;
/** «Аналитик печатает…» while the analyst has not answered yet (PEP-110); hidden once an answer is drawn. */
typing: ReactNode;
/** The server drew no messages (its children are the empty state). */
empty: boolean;
children: ReactNode;
}) {
const t = useT();
const [added, setAdded] = useState<LiveChatMessage[]>([]);
const [answered, setAnswered] = useState(false);
const read = useRef<ReturnType<typeof setTimeout> | null>(null);
const scope = `chat:${chatId}`;
const thread = view.kind === "thread" ? view.key : view.kind === "discussion" ? null : undefined;
// A server re-render drew them itself.
const shown = added.filter((m) => m.id > lastId);
useEffect(() => setAnswered(false), [lastId]);
const markRead = () => {
if (thread === undefined || read.current) return;
read.current = setTimeout(() => {
read.current = null;
if (document.visibilityState === "visible") void markChatReadAction(chatId, thread).catch(() => {});
}, 1000);
};
useEffect(() => () => {
if (read.current) clearTimeout(read.current);
}, []);
useLiveIsland((e) => {
if (e.scope !== scope) return [];
const { applied, add } = chatParts(e, view);
const fresh = add.filter((m) => m.id > lastId);
if (fresh.length) {
setAdded((was) => {
const have = new Set(was.map((m) => m.id));
return [...was, ...fresh.filter((m) => !have.has(m.id))].sort((a, b) => a.id - b.id);
});
if (view.kind === "discussion" && fresh.some((m) => m.authorKind !== "user")) setAnswered(true);
markRead();
}
return applied;
});
const groups: Array<{ events: LiveChatMessage[] } | { m: LiveChatMessage }> = [];
for (const m of shown) {
const event = compact && (m.kind === "event" || m.kind === "system");
const last = groups.at(-1);
if (event && last && "events" in last) last.events.push(m);
else groups.push(event ? { events: [m] } : { m });
}
return (
<>
{!(empty && shown.length) && children}
{shown.length > 0 && (
<ol data-chat-live className="m-0 flex list-none flex-col gap-2 p-0 pr-12 md:pr-14">
{groups.map((g) =>
"events" in g ? (
<li key={`e${g.events[0]!.id}`} className="flex flex-col gap-1 border-y border-dashed py-1">
{g.events.map((m) => (
<div key={m.id} data-event-line className="flex items-baseline gap-2 px-1 text-xs text-muted-foreground">
<span className="min-w-0 flex-1 break-words">
{m.authorKind === "agent" && (m.agent ?? agentName) && <span className="mr-1.5 text-foreground/80">{m.agent ?? agentName}:</span>}
{m.main.split("\n")[0]}
{m.link && (
<a href={m.link} className="ml-1.5">
{t("открыть")}
</a>
)}
</span>
{m.repeats > 0 && <span className="shrink-0 font-mono">×{m.repeats + 1}</span>}
<span className="shrink-0 font-mono">{ago(new Date(m.at), t)}</span>
</div>
))}
</li>
) : (
<li key={g.m.id} className={cn("flex", view.kind === "discussion" && g.m.authorUserId === userId && g.m.kind === "user" ? "justify-end" : "justify-start")}>
<div className="min-w-0 max-w-[85%]">
<LiveMessage m={g.m} mine={view.kind === "discussion" && g.m.authorUserId === userId} showThread={showThread} agentName={agentName} />
</div>
</li>
),
)}
</ol>
)}
{!answered && typing}
<div data-chat-end />
<ChatScroll lastId={Math.max(lastId, shown.at(-1)?.id ?? 0)} />
</>
);
}
/** The client twin of the page's MessageItem for a message without buttons. */
function LiveMessage({ m, mine, showThread, agentName }: { m: LiveChatMessage; mine: boolean; showThread: boolean; agentName: string | null }) {
const t = useT();
const person = m.authorKind === "user" && m.kind === "user";
const agentLabel = m.authorKind === "agent" ? (m.agent ?? agentName) : null;
return (
<article data-live-message={m.id} className={cn("flex flex-col gap-1 rounded-lg border bg-card px-3 py-2", mine && "border-primary/30 bg-primary/10", m.kind === "system" && "border-dashed bg-transparent")}>
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
{person ? <UserIcon className="size-3.5" /> : agentLabel ? null : m.authorKind === "agent" ? <Bot className="size-3.5" /> : <MessagesSquare className="size-3.5" />}
{agentLabel ? (
<AgentBadge name={agentLabel} className="text-foreground" />
) : (
<span className="font-medium text-foreground">{person ? (mine ? t("вы") : (m.login ?? "?")) : m.authorKind === "agent" ? t("агент") : PRODUCT_NAME}</span>
)}
{m.via === "telegram" && <span title={t("из Telegram")}>· Telegram</span>}
{showThread && m.thread && (
<a href={m.thread.href} className="max-w-full truncate">
🧵 {m.thread.label}
</a>
)}
{m.repeats > 0 && (
<span className="rounded-full border px-1.5 font-mono tabular-nums" title={t("Повторов: {n}", { n: m.repeats })}>
×{m.repeats + 1}
</span>
)}
<span className="ml-auto font-mono">{ago(new Date(m.at), t)}</span>
</div>
<p data-message-main className="m-0 text-sm break-words whitespace-pre-wrap">
{linkify(m.main)}
</p>
{m.more && (
<details data-message-details className="text-xs text-muted-foreground">
<summary className="cursor-pointer">{t("Подробнее")}</summary>
<p className="m-0 mt-1 max-h-72 overflow-auto break-words whitespace-pre-wrap">{linkify(m.more)}</p>
</details>
)}
<Attachments files={m.files} />
{m.link && (
<a href={m.link} target={m.link.startsWith("/") ? undefined : "_blank"} rel="noreferrer" className="truncate text-xs">
{m.link.startsWith("/") ? t("Открыть") : m.link}
</a>
)}
</article>
);
}

View File

@ -31,9 +31,6 @@ function busy(): boolean {
/** PEP-215: at most one re-render per tab in this many ms, however many changes the channel reports. */
export const MIN_REFRESH_GAP_MS = 4000;
/** PEP-225: parts of the `chats` scope a chat page cares about besides messages of its own chat. */
const CHAT_PAGE_PARTS = new Set(["q", "tg", "*"]);
/**
* Live page (PEP-37, PEP-225): watches its scope over the tab's channel. A change the page's
* islands apply in place (board cards, the attention counter…) needs nothing more; anything else
@ -44,15 +41,12 @@ export function LiveRefresh({
scope,
pauseHidden = false,
indicator = true,
chatId,
}: {
scope: string;
/** PEP-179: a hidden tab drops the scope (battery) and catches up when back in view. */
pauseHidden?: boolean;
/** PEP-207: the chat hides the corner pill — it sits over the message field. */
indicator?: boolean;
/** PEP-225: a chat page re-renders only for new messages of this chat (and answered questions). */
chatId?: number;
}) {
const router = useRouter();
const mode = useLiveMode();
@ -95,15 +89,8 @@ export function LiveRefresh({
scope,
(e: LiveEvent) => {
if (e.type !== "change") return;
let parts = e.parts;
if (chatId != null) {
// Messages of other chats and events not yet projected into this chat don't concern it.
const mine = e.chats?.includes(chatId) ?? false;
parts = parts.filter((p) => (p === "m" ? mine : CHAT_PAGE_PARTS.has(p)));
if (!parts.length) return;
}
const applied = applyIslands(e);
if (parts.every((p) => applied.has(p))) return;
if (e.parts.every((p) => applied.has(p))) return;
request();
},
{ heavy: pauseHidden },

View File

@ -6,7 +6,6 @@ import { Badge } from "@/components/ui/badge";
import { SESSION_STATUS, TASK_STATUS, TONE_BG } from "@/lib/status";
import { cn } from "@/lib/utils";
import { getT } from "@/lib/i18n";
import { intlLocale, type Translator } from "@peppa/shared/i18n";
export function PageHeader({ title, crumbs, actions, children }: { title: ReactNode; crumbs?: ReactNode; actions?: ReactNode; children?: ReactNode }) {
return (
@ -97,25 +96,4 @@ export function Disclosure({ summary, children, open, className }: { summary: Re
}
/** «5 мин назад» in the page's language. */
export function ago(d: Date | null | undefined, t: Translator): string {
if (!d) return "—";
const s = Math.round((Date.now() - d.getTime()) / 1000);
if (s < 60) return t("{n} с назад", { n: s });
if (s < 3600) return t("{n} мин назад", { n: Math.round(s / 60) });
if (s < 86400) return t("{n} ч назад", { n: Math.round(s / 3600) });
return d.toLocaleDateString(intlLocale(t.locale));
}
/** Text with its http(s) addresses as links. */
export function linkify(text: string) {
return text.split(/(https?:\/\/[^\s<>«»"]+[^\s<>«»".,;:!?)])/g).map((part, i) =>
i % 2 ? (
<a key={i} href={part} target={part.startsWith(process.env.PEPPA_WEB_URL ?? "\0") ? undefined : "_blank"} rel="noreferrer">
{part}
</a>
) : (
part
),
);
}
export { ago, linkify } from "@/lib/format";

View File

@ -0,0 +1,32 @@
// PEP-228: a chat message as the live channel brings it to a chat page — already translated and
// cleaned for its viewer on the server (lib/chat-live.ts); the browser only draws it.
import type { AttachmentView } from "@peppa/core";
export interface LiveChatMessage {
id: number;
threadKey: string | null;
kind: "event" | "question" | "user" | "system";
authorKind: "system" | "agent" | "user";
authorUserId: number | null;
/** A person's login (people's messages). */
login: string | null;
/** An agent's or a role's name, translated; null — the thread's agent. */
agent: string | null;
via: "web" | "telegram" | null;
/** ISO time of the message (of its last repeat). */
at: string;
repeats: number;
/** A command («/status») — not a part of the discussion. */
command: boolean;
/** The factory's service notice — the chat with the analyst doesn't show it (PEP-207). */
notice: boolean;
/** What the screen shows at once and what opens under «Подробнее». */
main: string;
more: string | null;
link: string | null;
files: AttachmentView[];
/** A question or a message with buttons: the page re-renders it from the server. */
render: boolean;
/** The thread's title for the «События агентов» view (🧵 …). */
thread: { label: string; href: string } | null;
}

43
apps/web/lib/chat-live.ts Normal file
View File

@ -0,0 +1,43 @@
// PEP-228: new messages of a chat for the live channel — the same text a chat page renders on
// the server (translation, cleaning, «Подробнее», links), built for one viewer.
import { getUserLocale, isSuperadmin, splitForDisplay, type AttachmentView, type ChatMessageView } from "@peppa/core";
import { users, type Db } from "@peppa/db";
import { stripAsIs, translator } from "@peppa/shared/i18n";
import { eq } from "drizzle-orm";
import { cleanText, messageLink, STUCK_NOTICE } from "./chat-text";
import type { LiveChatMessage } from "./chat-live-types";
export async function liveChatView(db: Db, userId: number, messages: ChatMessageView[], files: Map<number, AttachmentView[]>): Promise<LiveChatMessage[]> {
const user = (await db.select({ login: users.login }).from(users).where(eq(users.id, userId)))[0];
const superadmin = await isSuperadmin(db, user ?? null);
const t = translator(await getUserLocale(db, userId));
const gitea = (process.env.GITEA_URL ?? "").replace(/\/+$/, "");
return messages.map((m) => {
// Same as MessageItem / EventLines of the chat page.
const shown =
m.kind === "user"
? { main: m.authorKind === "agent" ? cleanText(t.role(m.text), superadmin, gitea) : m.text, more: null }
: splitForDisplay(cleanText(t.text(m.text), superadmin, gitea), m.details ? t.text(m.details) : null);
const label = m.threadTitle ? t.text(m.threadTitle) : null;
return {
id: m.id,
threadKey: m.threadKey,
kind: m.kind,
authorKind: m.authorKind,
authorUserId: m.authorUserId,
login: m.authorLogin,
agent: m.authorKind === "agent" && m.authorLogin ? t.role(m.authorLogin) : null,
via: m.via,
at: (m.updatedAt ?? m.createdAt).toISOString(),
repeats: m.repeats,
command: m.text.startsWith("/"),
notice: m.authorKind !== "user" && STUCK_NOTICE.test(stripAsIs(m.text)),
main: shown.main,
more: shown.more,
link: messageLink(m.url, superadmin, gitea),
files: files.get(m.id) ?? [],
render: !!m.question || !!m.offer,
thread: label && m.projectKey && m.threadKey ? { label, href: `/chats/${m.projectKey}?thread=${encodeURIComponent(m.threadKey)}` } : null,
};
});
}

View File

@ -12,3 +12,13 @@ export function cleanText(text: string, superadmin: boolean, gitea = ""): string
}
const TERMINAL_LINE = /^\s*(?:[⏺⎿●│└├╭╰─━]|\$ |> |✻|Calling\b|Running\b)/;
/** A link under a message: never the bare «/», never Gitea for a product manager. */
export function messageLink(url: string | null, superadmin: boolean, gitea: string): string | null {
if (!url || url === "/" || url === "#") return null;
if (!superadmin && gitea && url.startsWith(gitea)) return null;
return url;
}
/** PEP-207: the factory's «задерживается на нашей стороне» — the status line of the chat with the analyst, not a message. */
export const STUCK_NOTICE = /задерживается на нашей стороне/i;

25
apps/web/lib/format.tsx Normal file
View File

@ -0,0 +1,25 @@
// Formatters of the console shared by server and client components (no server imports).
import { intlLocale, type Translator } from "@peppa/shared/i18n";
/** «5 мин назад» in the page's language. */
export function ago(d: Date | null | undefined, t: Translator): string {
if (!d) return "—";
const s = Math.round((Date.now() - d.getTime()) / 1000);
if (s < 60) return t("{n} с назад", { n: s });
if (s < 3600) return t("{n} мин назад", { n: Math.round(s / 60) });
if (s < 86400) return t("{n} ч назад", { n: Math.round(s / 3600) });
return d.toLocaleDateString(intlLocale(t.locale));
}
/** Text with its http(s) addresses as links. */
export function linkify(text: string) {
return text.split(/(https?:\/\/[^\s<>«»"]+[^\s<>«»".,;:!?)])/g).map((part, i) =>
i % 2 ? (
<a key={i} href={part} target={part.startsWith(process.env.PEPPA_WEB_URL ?? "\0") ? undefined : "_blank"} rel="noreferrer">
{part}
</a>
) : (
part
),
);
}

View File

@ -3,9 +3,10 @@
// `upgrade` requests of /api/ws to what is registered here (globalThis: the custom server and
// the Next bundle are different module graphs of one process).
import { getNotifyPrefs } from "@peppa/core";
import { setLiveProvider } from "@peppa/runner";
import { setLiveChatView, setLiveProvider } from "@peppa/runner";
import { createLiveWs, readCookie, type LiveWs } from "@peppa/runner/live-ws";
import { bootId } from "./boot";
import { liveChatView } from "./chat-live";
import { db } from "./db";
import { navCounts } from "./queries";
import { SESSION_COOKIE, userFromSessionToken } from "./session-user";
@ -18,6 +19,7 @@ export function registerLiveWs(): void {
return { count: c.questions + c.waitingRunners, questions: c.questions, waitingRunners: c.waitingRunners, chats: c.chats, sound };
});
setLiveProvider("version", () => ({ boot: bootId() }));
setLiveChatView(liveChatView);
g.__peppaLiveWs?.close();
g.__peppaLiveWs = createLiveWs({
db,

View File

@ -20,7 +20,8 @@ export interface LiveTaskRow {
other?: boolean;
}
export type LiveEvent =
| { type: "change"; scope: string; v: string; parts: string[]; tasks?: LiveTaskRow[]; chats?: number[] }
/** `messages` — new messages of a `chat:` scope, ready for this viewer (PEP-228, lib/chat-live-types.ts). */
| { type: "change"; scope: string; v: string; parts: string[]; tasks?: LiveTaskRow[]; messages?: unknown[] }
| { type: "step"; scope: string; step: { id: number } & Record<string, unknown> }
| { type: "data"; scope: string; v: string; data: unknown }
| { type: "frame"; scope: string; cols: number; rows: number; data: string }

View File

@ -10,7 +10,7 @@ PEP-225 дал вкладке один канал и «острова» (`useLiv
Отпечаток — один SQL по чату: `m` — последнее сообщение, `q` — вопросы проекта, `tg` — связь с
группой, `x` — предложения и вложения 50 последних сообщений (они пишутся отдельной записью
после сообщения). Доступ: чат проекта — `projectForUser`, мастер-чат — только его владелец.
2. **Сообщение готовит сервер, рисует клиент.** Хаб берёт новые сообщения (`chatMessagesAfter`,
2. **Сообщение готовит сервер, рисует клиент.** Хаб берёт новые сообщения (`newChatMessagesView`,
не больше 30 за раз; больше — без сообщений, страница перерисуется) и вложения, а вид для
зрителя строит поставщик веба `setLiveChatView` (как `attention`): перевод `t.text`/`t.role`,
`cleanText`, `splitForDisplay`, `messageLink` — тот же код, что у серверной страницы (вынесен

View File

@ -21,7 +21,7 @@
## Impact
- `packages/runner/src/live.ts` (область, отпечаток, сообщения в событии, поставщик вида),
`packages/core/src/chats.ts` (`chatMessagesAfter`), `packages/shared` (`humanSize` без ядра).
`packages/core/src/chats.ts` (`newChatMessagesView`), `packages/shared` (`humanSize` без ядра).
- `apps/web`: `lib/live-server.ts` (поставщик вида сообщения), `lib/chat-text.ts`,
`components/ChatLiveFeed.tsx` (новый), страница `/chats/[chat]`, `LiveRefresh`.
- Основа — PEP-225 (ветка ещё не в main: эта ветка начата от неё).

View File

@ -1,5 +1,5 @@
## 1. Сервер
- [ ] 1.1 `chatMessagesAfter` в core, `humanSize` в `@peppa/shared/format`
- [ ] 1.1 `newChatMessagesView` в core, `humanSize` в `@peppa/shared/format`
- [ ] 1.2 Хаб: область `chat:<id>` на зрителя, доступ, отпечаток, сообщения в `change`, поставщик `setLiveChatView`; убрать `chatsAfter`
- [ ] 1.3 Веб: поставщик вида сообщения (`lib/chat-live.ts`), `messageLink` в `lib/chat-text.ts`, `markChatReadAction`

View File

@ -5,6 +5,7 @@
import { guardUntrusted } from "./untrusted.ts";
import { attachments, events, chatMessages, type Db } from "@peppa/db";
import { peppaHome } from "@peppa/shared";
import { humanSize } from "@peppa/shared/format";
import { m as tr } from "@peppa/shared/i18n";
import { and, asc, eq, inArray, isNull, lt } from "drizzle-orm";
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
@ -129,7 +130,7 @@ export interface AttachmentView {
const kindOf = (mime: string): AttachmentKind => (mime.startsWith("image/") ? "image" : mime === "application/pdf" ? "pdf" : mime.startsWith("application/vnd.") ? "office" : "text");
export const attachmentView = (a: Attachment): AttachmentView => ({ id: a.id, name: a.name, mime: a.mime, size: a.size, kind: kindOf(a.mime) });
export const humanSize = (n: number) => (n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${Math.round(n / 1024)} KB` : `${(n / 1024 / 1024).toFixed(1).replace(/\.0$/, "")} MB`);
export { humanSize };
/** Stores an uploaded file for a project's person; it stays unlinked until a form takes it. */
export async function saveAttachment(db: Db, user: Pick<User, "id">, o: { projectId: number; name: string; data: Uint8Array; now?: Date }): Promise<AttachmentView> {

View File

@ -246,6 +246,12 @@ export async function chatMessagesView(db: Db, chatId: number, o: { threadKey?:
return views(db, and(...w)!, o.limit ?? 100, o.before);
}
/** PEP-228: messages of a chat newer than `after`, oldest first; `more` — there were more than `limit` (the page re-renders). */
export async function newChatMessagesView(db: Db, chatId: number, after: number, limit = 30): Promise<{ messages: ChatMessageView[]; more: boolean }> {
const rows = await views(db, and(eq(chatMessages.chatId, chatId), gt(chatMessages.id, after))!, limit + 1);
return rows.length > limit ? { messages: [], more: true } : { messages: rows, more: false };
}
// ── discussion (PEP-106) ────────────────────────────────────────────────────
/** People's messages in a project chat's channel: no agents, no events, no commands. */

View File

@ -9,8 +9,8 @@ import { m } from "@peppa/shared/i18n";
import { createHash } from "node:crypto";
import { existsSync, statSync } from "node:fs";
import { join } from "node:path";
import { findChangeDir, isSuperadmin, listenEvents, observeDb, observeDbPath, projectForUser, STEP_EVENT, stepView, type StepView, type User } from "@peppa/core";
import { events, sessions, subscriptions, tasks, type Db } from "@peppa/db";
import { attachmentsByMessage, findChangeDir, newChatMessagesView, isSuperadmin, listenEvents, observeDb, observeDbPath, projectForUser, STEP_EVENT, stepView, type AttachmentView, type ChatMessageView, type StepView, type User } from "@peppa/core";
import { chats, events, sessions, subscriptions, tasks, type Db } from "@peppa/db";
import { and, eq, gt } from "drizzle-orm";
import { columnOf, type BoardColumn } from "./flow.ts";
import { pollCodexLogin } from "./subscription-login.ts";
@ -18,7 +18,7 @@ import { terminalSession } from "./terminal.ts";
/** Scopes without an id. `attention` and `me` are per user (the hub keys them by the viewer). */
export const LIVE_PLAIN_SCOPES = ["home", "runners", "chats", "team", "attention", "version", "observe", "subs", "me"] as const;
const ID_KINDS = ["project", "task", "steps", "login", "terminal"] as const;
const ID_KINDS = ["project", "task", "steps", "login", "terminal", "chat"] as const;
type PlainScope = (typeof LIVE_PLAIN_SCOPES)[number];
type IdKind = (typeof ID_KINDS)[number];
export type LiveScope = PlainScope | `${IdKind}:${number}`;
@ -35,8 +35,11 @@ export interface LiveTaskRow {
type Row = LiveTaskRow & { sig: string };
export type LiveEvent =
/** The scope changed: `v` — its new version, `parts` — which parts of it, `tasks` — changed task rows, `chats` — chats with new messages. */
| { type: "change"; scope: LiveScope; v: string; parts: string[]; tasks?: LiveTaskRow[]; chats?: number[] }
/**
* The scope changed: `v` — its new version, `parts` — which parts of it, `tasks` — changed task
* rows, `messages` — new messages of a `chat:` scope as its viewer sees them (PEP-228).
*/
| { type: "change"; scope: LiveScope; v: string; parts: string[]; tasks?: LiveTaskRow[]; messages?: unknown[] }
| { type: "step"; scope: LiveScope; step: StepView }
/** The current value of a value scope (`attention`, `version`). */
| { type: "data"; scope: LiveScope; v: string; data: unknown };
@ -63,7 +66,7 @@ export const LOGIN_POLL_MS = 3000;
/** Checks one scope name; unknown ones are refused. */
export function parseScope(part: string): LiveScope {
if ((LIVE_PLAIN_SCOPES as readonly string[]).includes(part)) return part as LiveScope;
if (/^(project|task|steps|login|terminal):[1-9]\d{0,9}$/.test(part)) return part as LiveScope;
if (/^(project|task|steps|login|terminal|chat):[1-9]\d{0,9}$/.test(part)) return part as LiveScope;
throw new LiveError(m("Неизвестная область: {scope}", { scope: part }), 400);
}
@ -83,7 +86,8 @@ const notFound = () => new LiveError(m("Не найдено"), 404);
/**
* Access, the same as the page's: project / story / steps / terminal need the project,
* `observe` and `subs` a superadmin, `login:<id>` the author of that sign-in or a superadmin.
* `observe` and `subs` a superadmin, `login:<id>` the author of that sign-in or a superadmin,
* `chat:<id>` the project's people (a master chat — its owner only).
*/
export async function checkScopeAccess(db: Db, user: User, scope: LiveScope): Promise<void> {
const [kind, raw] = scope.split(":") as [string, string?];
@ -103,6 +107,18 @@ export async function checkScopeAccess(db: Db, user: User, scope: LiveScope): Pr
});
return;
}
if (kind === "chat") {
const chat = (await db.select({ userId: chats.userId, projectId: chats.projectId }).from(chats).where(eq(chats.id, id)))[0];
if (!chat) throw notFound();
if (chat.projectId == null) {
if (chat.userId !== user.id) throw notFound();
return;
}
await projectForUser(db, user.id, chat.projectId).catch(() => {
throw notFound();
});
return;
}
let projectId: number | undefined;
if (kind === "project") projectId = id;
else if (kind === "task") projectId = (await db.select({ p: tasks.projectId }).from(tasks).where(eq(tasks.id, id)))[0]?.p;
@ -184,6 +200,21 @@ function fingerprint(db: Db, scope: LiveScope, userId: number): Parts {
.get(id) as Record<string, unknown>;
return str(row);
}
if (kind === "chat") {
// PEP-228: one chat — `m` new messages (sent along), `q` questions of its project, `tg` the
// linked group, `x` offers and files of its latest messages (written right after a message).
const row = c
.prepare(
`SELECT
(SELECT coalesce(max(id),0) FROM chat_messages WHERE chat_id = ?1) AS m,
(SELECT count(*) || ':' || count(answered_at) FROM questions WHERE project_id = (SELECT project_id FROM chats WHERE id = ?1)) AS q,
(SELECT coalesce(tg_chat_id,'') FROM chats WHERE id = ?1) AS tg,
(SELECT count(*) FROM settings WHERE key IN (SELECT 'chat.offer:' || id FROM chat_messages WHERE chat_id = ?1 ORDER BY id DESC LIMIT 50)) || ':' ||
(SELECT count(*) FROM attachments WHERE chat_message_id IN (SELECT id FROM chat_messages WHERE chat_id = ?1 ORDER BY id DESC LIMIT 50)) AS x`,
)
.get(id) as Record<string, unknown>;
return str(row);
}
if (kind === "chats") {
// PEP-62: a new chat message (projected or written) or a question answered anywhere.
const row = c
@ -261,12 +292,6 @@ function taskRows(db: Db, scope: LiveScope): Map<number, Row> {
return new Map(rows.map((r) => [r.id, { id: r.id, status: r.status, title: r.title, column: columnOf(r.status), sig: String(r.sig) }]));
}
/** Chats with a message newer than `after` (PEP-225: a chat page re-renders only for its own chat). */
function chatsAfter(db: Db, after: number): number[] {
const rows = db.$client.prepare(`SELECT DISTINCT chat_id AS id FROM chat_messages WHERE id > ? LIMIT 50`).all(after) as Array<{ id: number }>;
return rows.map((r) => r.id);
}
/** A value scope's provider: the web registers `attention` (it owns navCounts). */
export type LiveProvider = (db: Db, userId: number) => Promise<unknown> | unknown;
const g = globalThis as { __peppaLiveHub?: LiveHub; __peppaLiveProviders?: Map<string, LiveProvider>; __peppaBoot?: string };
@ -279,10 +304,19 @@ export function setLiveProvider(scope: "attention" | "version", fn: LiveProvider
providers.set(scope, fn);
}
/** PEP-228: new messages of a chat as the viewer `userId` sees them (the web registers its view). */
export type LiveChatView = (db: Db, userId: number, messages: ChatMessageView[], files: Map<number, AttachmentView[]>) => Promise<unknown[]> | unknown[];
const gv = globalThis as { __peppaLiveChatView?: LiveChatView };
export function setLiveChatView(fn: LiveChatView): void {
gv.__peppaLiveChatView = fn;
}
/** Most new messages one event carries; more — the page re-renders. */
export const LIVE_CHAT_MAX = 30;
const VALUE_SCOPES = new Set(["attention", "version"]);
const PER_USER = new Set(["attention", "me"]);
/** Hub key of a scope: per-user scopes are watched per viewer. */
const keyOf = (scope: LiveScope, userId: number) => (PER_USER.has(scope) ? `${scope}@${userId}` : scope);
/** Hub key of a scope: per-user scopes (and a chat — its messages are shown per viewer) are watched per viewer. */
const keyOf = (scope: LiveScope, userId: number) => (PER_USER.has(scope) || scope.startsWith("chat:") ? `${scope}@${userId}` : scope);
interface Watch {
scope: LiveScope;
@ -354,7 +388,7 @@ class LiveHub {
w.parts = fingerprint(this.db, s, w.userId);
w.v = liveVersion(JSON.stringify(w.parts));
if (s.startsWith("project:") || s.startsWith("task:")) w.rows = taskRows(this.db, s);
if (s === "chats") w.chatMax = Number(w.parts.m) || 0;
if (s.startsWith("chat:")) w.chatMax = Number(w.parts.m) || 0;
}
} catch (e) {
console.error("live: prime failed", e);
@ -538,9 +572,12 @@ class LiveHub {
w.rows = rows;
if (diff.length) e.tasks = diff.slice(0, 100);
}
if (scope === "chats") {
if (scope.startsWith("chat:")) {
const max = Number(parts.m) || 0;
if (max > (w.chatMax ?? 0)) e.chats = chatsAfter(this.db, w.chatMax ?? 0);
if (max > (w.chatMax ?? 0)) {
const messages = await this.chatMessages(w, w.chatMax ?? 0);
if (messages) e.messages = messages;
}
w.chatMax = max;
}
this.send(w, e);
@ -549,6 +586,20 @@ class LiveHub {
}
}
/** New messages of a watched chat for its viewer; undefined — too many or failed (the page re-renders). */
private async chatMessages(w: Watch, after: number): Promise<unknown[] | undefined> {
try {
const { messages, more } = await newChatMessagesView(this.db, Number(w.scope.slice(5)), after, LIVE_CHAT_MAX);
if (more) return undefined;
const files = await attachmentsByMessage(this.db, messages.map((m) => m.id));
const view = gv.__peppaLiveChatView;
return view ? await view(this.db, w.userId, messages, files) : messages.map((m) => ({ ...m, files: files.get(m.id) ?? [] }));
} catch (err) {
console.error(`live: ${w.scope} messages failed`, err);
return undefined;
}
}
get watched(): LiveScope[] {
return [...new Set([...this.watches.values()].map((w) => w.scope))];
}

View File

@ -8,7 +8,8 @@
"./palette": "./src/palette.ts",
"./i18n": "./src/i18n/index.ts",
"./wording": "./src/wording.ts",
"./glossary": "./src/glossary.ts"
"./glossary": "./src/glossary.ts",
"./format": "./src/format.ts"
},
"scripts": {
"typecheck": "tsc -p ."

View File

@ -0,0 +1,4 @@
// Small formatters safe for the browser bundle (no Node modules).
/** «12 KB» — the size of a file for a person. */
export const humanSize = (n: number) => (n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${Math.round(n / 1024)} KB` : `${(n / 1024 / 1024).toFixed(1).replace(/\.0$/, "")} MB`);