PEP-228: тест области chat:<id> и отбора сообщений; отбор — в lib/chat-live-types

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-21 14:57:00 +00:00
parent 0dceba0ff2
commit 496db3999a
3 changed files with 175 additions and 25 deletions

View File

@ -13,33 +13,9 @@ 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 { chatParts, type ChatView, 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 File

@ -30,3 +30,27 @@ export interface LiveChatMessage {
/** The thread's title for the «События агентов» view (🧵 …). */
thread: { label: string; href: string } | null;
}
/** 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: list.filter((m) => inView(m, view) && !m.render) };
}

View File

@ -0,0 +1,150 @@
// PEP-228: a chat page's own scope `chat:<id>` — access like the page's, new messages of the chat
// come in the event (and only to this chat's watchers); the page draws messages of its
// conversation in place and leaves questions, offers and other threads to a server re-render.
import assert from "node:assert/strict";
import { after, describe, test } from "node:test";
import { LiveConnection } from "@peppa/runner/live-ws";
import { core, db, project, runner, teardown } from "./helpers.ts";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
after(teardown);
const { chatParts, inView } = (await import(new URL("../../../apps/web/lib/chat-live-types.ts", import.meta.url).href)) as typeof import("../../../apps/web/lib/chat-live-types.ts");
let seq = 0;
const user = (login: string) => core.upsertUserFromGitea(db, { id: 9300 + seq++, login }, { access_token: "x" });
type Msg = Record<string, unknown> & { t: string };
function conn(u: import("@peppa/core").User) {
const out: Msg[] = [];
const c = new LiveConnection(db, u, (m) => out.push(m as Msg), () => {});
return { c, out, send: (m: object) => c.receive(JSON.stringify(m)), events: () => out.filter((m) => m.t === "ev") as Array<Msg & { parts: string[]; messages?: Array<Record<string, unknown>> }> };
}
async function ownedChat(login: string) {
const owner = await user(login);
const p = await project({ turns: [] });
const ref = await core.resolveTask(db, p.taskKey);
await core.setProjectOwner(db, ref.project.id, owner.id);
const chat = await core.ensureProjectChat(db, ref.project.id);
return { owner, ref, chat };
}
const say = (chatId: number, text: string, o: Partial<Parameters<typeof core.addChatMessage>[1]> = {}) =>
core.addChatMessage(db, { chatId, kind: "user", authorKind: "agent", authorLogin: "Аналитик", text, ...o });
describe("chat messages in place (PEP-228)", () => {
test("Чужой чат: 404, мастер-чат — только владельцу", async () => {
const a = await ownedChat("cl-owner-1");
const bob = await user("cl-bob-1");
const x = conn(bob);
await x.send({ t: "sub", scope: `chat:${a.chat.id}` });
assert.equal(x.out.at(-1)!.status, 404);
const master = await core.ensureMasterChat(db, a.owner.id);
await x.send({ t: "sub", scope: `chat:${master.id}` });
assert.equal(x.out.at(-1)!.status, 404, "somebody else's master chat");
await x.send({ t: "sub", scope: "chat:999999" });
assert.equal(x.out.at(-1)!.status, 404);
assert.deepEqual(x.c.scopes, []);
const own = conn(a.owner);
await own.send({ t: "sub", scope: `chat:${master.id}` });
assert.equal(own.out.at(-1)!.t, "ok");
x.c.close();
own.c.close();
});
test("Ответ аналитика приходит в событии своего чата и не приходит в чужой", async () => {
const a = await ownedChat("cl-owner-2");
const b = await ownedChat("cl-owner-3");
const x = conn(a.owner);
await x.send({ t: "sub", scope: `chat:${a.chat.id}` });
assert.equal(x.out.at(-1)!.t, "ok");
try {
await say(b.chat.id, "Ответ в другом проекте");
await runner.liveHub(db).check();
assert.equal(x.events().length, 0, "another chat is not this scope");
const m = await say(a.chat.id, "В работе PAY-3");
await runner.liveHub(db).check();
const ev = x.events().at(-1)!;
assert.ok(ev, "the change arrives");
assert.ok(ev.parts.includes("m"));
assert.deepEqual(ev.messages?.map((r) => [r.id, r.text, r.authorKind]), [[m!.id, "В работе PAY-3", "agent"]]);
assert.deepEqual(ev.messages?.[0]!.files, []);
} finally {
x.c.close();
}
});
test("Вид для зрителя: поставщик веба получает зрителя и сообщения", async () => {
const a = await ownedChat("cl-owner-4");
const seen: Array<[number, number[]]> = [];
runner.setLiveChatView((_db, userId, messages) => {
seen.push([userId, messages.map((m) => m.id)]);
return messages.map((m) => ({ id: m.id, main: `для ${userId}` }));
});
const x = conn(a.owner);
await x.send({ t: "sub", scope: `chat:${a.chat.id}` });
try {
const m = await say(a.chat.id, "Готово");
await runner.liveHub(db).check();
assert.deepEqual(seen.at(-1), [a.owner.id, [m!.id]]);
assert.deepEqual(x.events().at(-1)!.messages, [{ id: m!.id, main: `для ${a.owner.id}` }]);
} finally {
x.c.close();
runner.setLiveChatView(undefined as never);
}
});
test("Вопрос агента: в событии с пометкой вопроса, на месте не рисуется", async () => {
const a = await ownedChat("cl-owner-5");
const x = conn(a.owner);
await x.send({ t: "sub", scope: `chat:${a.chat.id}` });
try {
await core.askPm(db, a.ref, { kind: "question", text: "Какой разделитель?", options: [";", ","] });
await core.syncChats(db);
await runner.liveHub(db).check();
const evs = x.events();
assert.ok(evs.some((e) => e.parts.includes("q")), "questions changed — the page re-renders");
const withMsg = evs.find((e) => e.messages?.length);
assert.ok(withMsg?.messages?.some((r) => r.question), "the question message is in the event");
} finally {
x.c.close();
}
});
});
describe("what the chat page draws in place (PEP-228)", () => {
const msg = (o: Record<string, unknown>) => ({ id: 1, threadKey: null, kind: "user", command: false, notice: false, render: false, ...o }) as never;
test("Сообщение своей переписки — на месте, без перерисовки", () => {
const r = chatParts({ parts: ["m"], messages: [msg({ id: 5 })] }, { kind: "discussion" });
assert.deepEqual(r.applied, ["x", "m"]);
assert.deepEqual(r.add.map((m) => m.id), [5]);
});
test("Вопрос или кнопки — перерисовка", () => {
const r = chatParts({ parts: ["m", "q"], messages: [msg({ id: 6, threadKey: "task:3", kind: "question", render: true })] }, { kind: "thread", key: "task:3" });
assert.deepEqual(r.applied, ["x"]);
assert.deepEqual(r.add, []);
});
test("Сообщение другого треда — не в ленту, перерисовка списка", () => {
const r = chatParts({ parts: ["m"], messages: [msg({ id: 7, threadKey: "task:4", kind: "event" })] }, { kind: "thread", key: "task:3" });
assert.deepEqual(r.applied, ["x"]);
assert.deepEqual(r.add, []);
});
test("Без сообщений (их слишком много) — перерисовка", () => {
assert.deepEqual(chatParts({ parts: ["m", "x"] }, { kind: "feed" }).applied, []);
});
test("Обсуждение: без событий, команд и служебных строк; «События агентов» — всё", () => {
assert.equal(inView(msg({ threadKey: "task:3" }), { kind: "discussion" }), false);
assert.equal(inView(msg({ kind: "event" }), { kind: "discussion" }), false);
assert.equal(inView(msg({ command: true }), { kind: "discussion" }), false);
assert.equal(inView(msg({ notice: true }), { kind: "discussion" }), false);
assert.equal(inView(msg({ threadKey: "task:3", kind: "event" }), { kind: "feed" }), true);
assert.equal(inView(msg({ kind: "event" }), { kind: "channel" }), true);
});
});