diff --git a/apps/web/app/(app)/chats/[chat]/page.tsx b/apps/web/app/(app)/chats/[chat]/page.tsx index c7a3848b..c867f609 100644 --- a/apps/web/app/(app)/chats/[chat]/page.tsx +++ b/apps/web/app/(app)/chats/[chat]/page.tsx @@ -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 ? ( + {discussion ? t("Напишите, что хотите узнать или сделать, — аналитик ответит здесь же. Например: «Что сейчас в работе?» или «Хочу страницу с отзывами клиентов».") : master ? t("Пока тихо: здесь появятся вопросы агентов, сбои и обновления ваших проектов.") : thread === undefined ? t("Сообщений пока нет: они появятся, когда агенты возьмутся за {tasks}.", { tasks: w.task("accPl") }) : t("В этом треде пока пусто.")} + ) : ( +
    + {groups.map((g) => + g.kind === "events" ? ( +
  1. + +
  2. + ) : ( +
  3. +
    + +
    +
  4. + ), + )} +
+ ); + return ( - {/* PEP-225: a project chat re-renders only for its own new messages; the master feed gathers every project. */} - + {/* 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. */} +

{t("Чаты")}

@@ -285,32 +307,33 @@ export default async function ChatPage({ params, searchParams }: { params: Promi

)} - {ordered.length === 0 ? ( - {discussion ? t("Напишите, что хотите узнать или сделать, — аналитик ответит здесь же. Например: «Что сейчас в работе?» или «Хочу страницу с отзывами клиентов».") : master ? t("Пока тихо: здесь появятся вопросы агентов, сбои и обновления ваших проектов.") : thread === undefined ? t("Сообщений пока нет: они появятся, когда агенты возьмутся за {tasks}.", { tasks: w.task("accPl") }) : t("В этом треде пока пусто.")} + {master ? ( + <> + {feed} +
+ + ) : ( -
    - {groups.map((g) => - g.kind === "events" ? ( -
  1. - -
  2. - ) : ( -
  3. -
    - -
    -
  4. - ), - )} -
+ + {t("печатает…")} +

+ ) : null + } + > + {feed} +
)} - {typing && ( -

- {t("печатает…")} -

- )} -
- {writable && (
@@ -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 ? {label} : null; diff --git a/apps/web/app/(app)/chats/actions.ts b/apps/web/app/(app)/chats/actions.ts index ba2f5d06..328995cb 100644 --- a/apps/web/app/(app)/chats/actions.ts +++ b/apps/web/app/(app)/chats/actions.ts @@ -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 { + 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()); diff --git a/apps/web/components/Attachments.tsx b/apps/web/components/Attachments.tsx index 3da6d05c..904333e5 100644 --- a/apps/web/components/Attachments.tsx +++ b/apps/web/components/Attachments.tsx @@ -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, diff --git a/apps/web/components/ChatLiveFeed.tsx b/apps/web/components/ChatLiveFeed.tsx new file mode 100644 index 00000000..51e14b30 --- /dev/null +++ b/apps/web/components/ChatLiveFeed.tsx @@ -0,0 +1,200 @@ +"use client"; +// PEP-228: new messages of the open conversation drawn in place. The page's chat scope +// (`chat:`) 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, 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([]); + const [answered, setAnswered] = useState(false); + const read = useRef | 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 && ( +
    + {groups.map((g) => + "events" in g ? ( +
  1. + {g.events.map((m) => ( +
    + + {m.authorKind === "agent" && (m.agent ?? agentName) && {m.agent ?? agentName}:} + {m.main.split("\n")[0]} + {m.link && ( + + {t("открыть")} + + )} + + {m.repeats > 0 && ×{m.repeats + 1}} + {ago(new Date(m.at), t)} +
    + ))} +
  2. + ) : ( +
  3. +
    + +
    +
  4. + ), + )} +
+ )} + {!answered && typing} +
+ + + ); +} + +/** 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 ( +
+
+ {person ? : agentLabel ? null : m.authorKind === "agent" ? : } + {agentLabel ? ( + + ) : ( + {person ? (mine ? t("вы") : (m.login ?? "?")) : m.authorKind === "agent" ? t("агент") : PRODUCT_NAME} + )} + {m.via === "telegram" && · Telegram} + {showThread && m.thread && ( + + 🧵 {m.thread.label} + + )} + {m.repeats > 0 && ( + + ×{m.repeats + 1} + + )} + {ago(new Date(m.at), t)} +
+

+ {linkify(m.main)} +

+ {m.more && ( +
+ {t("Подробнее")} +

{linkify(m.more)}

+
+ )} + + {m.link && ( + + {m.link.startsWith("/") ? t("Открыть") : m.link} + + )} +
+ ); +} diff --git a/apps/web/components/LiveRefresh.tsx b/apps/web/components/LiveRefresh.tsx index b88f2ce2..3326f297 100644 --- a/apps/web/components/LiveRefresh.tsx +++ b/apps/web/components/LiveRefresh.tsx @@ -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 }, diff --git a/apps/web/components/common.tsx b/apps/web/components/common.tsx index f7d98adc..163aae8c 100644 --- a/apps/web/components/common.tsx +++ b/apps/web/components/common.tsx @@ -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 ? ( - - {part} - - ) : ( - part - ), - ); -} +export { ago, linkify } from "@/lib/format"; diff --git a/apps/web/lib/chat-live-types.ts b/apps/web/lib/chat-live-types.ts new file mode 100644 index 00000000..0feb7ebf --- /dev/null +++ b/apps/web/lib/chat-live-types.ts @@ -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; +} diff --git a/apps/web/lib/chat-live.ts b/apps/web/lib/chat-live.ts new file mode 100644 index 00000000..15d96039 --- /dev/null +++ b/apps/web/lib/chat-live.ts @@ -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): Promise { + 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, + }; + }); +} diff --git a/apps/web/lib/chat-text.ts b/apps/web/lib/chat-text.ts index fddf3767..6e86bea3 100644 --- a/apps/web/lib/chat-text.ts +++ b/apps/web/lib/chat-text.ts @@ -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; diff --git a/apps/web/lib/format.tsx b/apps/web/lib/format.tsx new file mode 100644 index 00000000..f3a21dc9 --- /dev/null +++ b/apps/web/lib/format.tsx @@ -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 ? ( + + {part} + + ) : ( + part + ), + ); +} diff --git a/apps/web/lib/live-server.ts b/apps/web/lib/live-server.ts index 9b2c7f30..a5e922f1 100644 --- a/apps/web/lib/live-server.ts +++ b/apps/web/lib/live-server.ts @@ -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, diff --git a/apps/web/lib/live.ts b/apps/web/lib/live.ts index eb48e8d3..46e97e10 100644 --- a/apps/web/lib/live.ts +++ b/apps/web/lib/live.ts @@ -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 } | { type: "data"; scope: string; v: string; data: unknown } | { type: "frame"; scope: string; cols: number; rows: number; data: string } diff --git a/openspec/changes/pep-228-chat-messages-in-place/design.md b/openspec/changes/pep-228-chat-messages-in-place/design.md index e61921bc..0fad7029 100644 --- a/openspec/changes/pep-228-chat-messages-in-place/design.md +++ b/openspec/changes/pep-228-chat-messages-in-place/design.md @@ -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` — тот же код, что у серверной страницы (вынесен diff --git a/openspec/changes/pep-228-chat-messages-in-place/proposal.md b/openspec/changes/pep-228-chat-messages-in-place/proposal.md index e047f180..fec75ff7 100644 --- a/openspec/changes/pep-228-chat-messages-in-place/proposal.md +++ b/openspec/changes/pep-228-chat-messages-in-place/proposal.md @@ -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: эта ветка начата от неё). diff --git a/openspec/changes/pep-228-chat-messages-in-place/tasks.md b/openspec/changes/pep-228-chat-messages-in-place/tasks.md index 34e840e9..7785ce33 100644 --- a/openspec/changes/pep-228-chat-messages-in-place/tasks.md +++ b/openspec/changes/pep-228-chat-messages-in-place/tasks.md @@ -1,5 +1,5 @@ ## 1. Сервер -- [ ] 1.1 `chatMessagesAfter` в core, `humanSize` в `@peppa/shared/format` +- [ ] 1.1 `newChatMessagesView` в core, `humanSize` в `@peppa/shared/format` - [ ] 1.2 Хаб: область `chat:` на зрителя, доступ, отпечаток, сообщения в `change`, поставщик `setLiveChatView`; убрать `chatsAfter` - [ ] 1.3 Веб: поставщик вида сообщения (`lib/chat-live.ts`), `messageLink` в `lib/chat-text.ts`, `markChatReadAction` diff --git a/packages/core/src/attachments.ts b/packages/core/src/attachments.ts index af2b4524..89285513 100644 --- a/packages/core/src/attachments.ts +++ b/packages/core/src/attachments.ts @@ -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, o: { projectId: number; name: string; data: Uint8Array; now?: Date }): Promise { diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts index 97fd131c..f65e458c 100644 --- a/packages/core/src/chats.ts +++ b/packages/core/src/chats.ts @@ -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. */ diff --git a/packages/runner/src/live.ts b/packages/runner/src/live.ts index c52158a7..eb13ecfb 100644 --- a/packages/runner/src/live.ts +++ b/packages/runner/src/live.ts @@ -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:` the author of that sign-in or a superadmin. + * `observe` and `subs` a superadmin, `login:` the author of that sign-in or a superadmin, + * `chat:` the project's people (a master chat — its owner only). */ export async function checkScopeAccess(db: Db, user: User, scope: LiveScope): Promise { 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; 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; + 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 { 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; const g = globalThis as { __peppaLiveHub?: LiveHub; __peppaLiveProviders?: Map; __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) => Promise | 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 { + 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))]; } diff --git a/packages/shared/package.json b/packages/shared/package.json index 985b0eea..f4182b0d 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -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 ." diff --git a/packages/shared/src/format.ts b/packages/shared/src/format.ts new file mode 100644 index 00000000..a85fb615 --- /dev/null +++ b/packages/shared/src/format.ts @@ -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`);