From d513cf22ebf7f38391bf85281b0e585a2dd2aded Mon Sep 17 00:00:00 2001 From: Guilherme Cruz <100307080+https-shini@users.noreply.github.com> Date: Sat, 14 Nov 2026 04:25:18 +0000 Subject: [PATCH 1/4] =?UTF-8?q?feat(servidor):=20responder,=20editar,=20ap?= =?UTF-8?q?agar,=20reagir,=20fixar,=20descri=C3=A7=C3=A3o=20e=20sil=C3=AAn?= =?UTF-8?q?cio=20com=20prazo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Decisões F1 a F7, com o modelo de dados do Fluxer adaptado ao produto (tudo em memória, autoria por @ e número de autor da conversa, nenhum id interno nos quadros). Núcleo comum a salas e privadas em messageOps.js. - Responder: chat_message aceita replyTo; a mensagem leva reference com cópia de quem escreveu e um trecho (lida mesmo que a original saia). Id de outra conversa é ignorado. - Editar (message_edit → message_updated): só a mesma identidade que escreveu, só texto digitado; o histórico de quem entra já vem editado. - Apagar (message_delete → message_deleted): quem escreveu, sempre; na sala, quem modera também (registrado como moderação). Na privada, cada um só as suas. - Reagir (reaction_toggle → message_reactions): lista fixa de 12 emojis, até 8 diferentes por mensagem; autores como @#número. - Fixar (message_pin → pins_updated): na sala, quem modera; na privada, as duas pessoas; até 25; quem entra recebe a lista; apagar ou limpar o histórico tira das fixadas. - Descrição da sala (room_update → room_updated): quem modera, até 200 caracteres. - Silêncio: a recusa traz until (quando há prazo) e texto neutro; editar e reagir também ficam bloqueados. - 15 testes novos; contrato do cliente espelhado e conferido (eventos, erros, limites e emojis). --- backend/src/errors.js | 30 ++- backend/src/metrics.js | 2 + backend/src/protocol.js | 74 +++++- backend/src/room/direct.js | 61 ++++- backend/src/room/hub.js | 14 ++ backend/src/room/messageOps.js | 271 ++++++++++++++++++++++ backend/src/room/room.js | 115 ++++++++- backend/src/room/transcript.js | 29 ++- backend/src/transport/connection.js | 37 ++- backend/test/unit/contract.test.js | 3 + backend/test/unit/messageFeatures.test.js | 271 ++++++++++++++++++++++ backend/test/unit/roomPhase4.test.js | 5 +- frontend/src/protocol.js | 35 +++ 13 files changed, 933 insertions(+), 14 deletions(-) create mode 100644 backend/src/room/messageOps.js create mode 100644 backend/test/unit/messageFeatures.test.js diff --git a/backend/src/errors.js b/backend/src/errors.js index 2a443e5..5c9e5d4 100644 --- a/backend/src/errors.js +++ b/backend/src/errors.js @@ -52,6 +52,13 @@ export const ERROR_CODES = Object.freeze({ LOOKUP_LIMITED: "lookup_limited", DM_OPEN_LIMITED: "dm_open_limited", BLOCK_LIMIT: "block_limit", + // Recursos de mensagem (responder, editar, apagar, reagir, fixar) + MESSAGE_NOT_FOUND: "message_not_found", + NOT_ALLOWED: "not_allowed", + INVALID_REACTION: "invalid_reaction", + REACTION_LIMIT: "reaction_limit", + PIN_LIMIT: "pin_limit", + INVALID_DESCRIPTION: "invalid_description", }); const { PROTOCOL, VALIDATION, AUTHORIZATION, RATE_LIMIT, INTERNAL } = ERROR_CATEGORIES; @@ -88,7 +95,7 @@ const CATALOG = Object.freeze({ }, [ERROR_CODES.MUTED]: { category: AUTHORIZATION, - message: "Você foi silenciado por um administrador e não pode enviar mensagens agora.", + message: "Quem modera a sala silenciou você por enquanto. Você pode continuar lendo.", }, [ERROR_CODES.INTERNAL_ERROR]: { category: INTERNAL, message: "Erro interno do servidor" }, [ERROR_CODES.INVALID_ROOM_CODE]: { @@ -163,6 +170,27 @@ const CATALOG = Object.freeze({ category: AUTHORIZATION, message: "Você já bloqueou o número máximo de pessoas nesta sessão.", }, + [ERROR_CODES.MESSAGE_NOT_FOUND]: { + category: VALIDATION, + message: "Esta mensagem não está mais disponível.", + }, + [ERROR_CODES.NOT_ALLOWED]: { + category: AUTHORIZATION, + message: "Você não pode fazer isso nesta conversa.", + }, + [ERROR_CODES.INVALID_REACTION]: { category: VALIDATION, message: "Reação inválida." }, + [ERROR_CODES.REACTION_LIMIT]: { + category: VALIDATION, + message: "Esta mensagem já tem o número máximo de reações diferentes.", + }, + [ERROR_CODES.PIN_LIMIT]: { + category: VALIDATION, + message: "Esta conversa já tem o número máximo de mensagens fixadas. Desafixe uma antes.", + }, + [ERROR_CODES.INVALID_DESCRIPTION]: { + category: VALIDATION, + message: "Descrição inválida. Use até 200 caracteres.", + }, }); /** diff --git a/backend/src/metrics.js b/backend/src/metrics.js index 17d5ce3..7ac3b0c 100644 --- a/backend/src/metrics.js +++ b/backend/src/metrics.js @@ -48,6 +48,8 @@ export const createMetrics = ({ now = () => Date.now(), startedAt = Date.now() } dmsOpened: 0, dmsClosed: 0, blocks: 0, + // Recursos de mensagem (editar, apagar, reagir, fixar, descrição) + messageActions: {}, }; const buckets = new Array(PROCESSING_BUCKETS_MS.length + 1).fill(0); diff --git a/backend/src/protocol.js b/backend/src/protocol.js index 4792dad..11e5349 100644 --- a/backend/src/protocol.js +++ b/backend/src/protocol.js @@ -50,6 +50,8 @@ export const LIMITS = Object.freeze({ awayTextMaxLength: 60, /** Nome opcional de uma sala. */ roomNameMaxLength: 40, + /** Descrição de uma sala (definida por quem modera). */ + roomDescriptionMaxLength: 200, /** Código de convite como digitado (com espaços, hífens ou o link inteiro). */ roomCodeInputMaxLength: 200, /** `conversationId` recebido do cliente. */ @@ -83,6 +85,16 @@ export const CLIENT_EVENTS = Object.freeze({ USER_BLOCK: "user_block", /** Desfazer um bloqueio. */ USER_UNBLOCK: "user_unblock", + /** Editar a própria mensagem (`{conversationId, id, content}`). */ + MESSAGE_EDIT: "message_edit", + /** Apagar uma mensagem (sua; ou qualquer uma, para quem modera a sala). */ + MESSAGE_DELETE: "message_delete", + /** Ligar ou desligar a sua reação (`{conversationId, id, emoji}`). */ + REACTION_TOGGLE: "reaction_toggle", + /** Fixar ou desafixar uma mensagem (`{conversationId, id, pinned}`). */ + MESSAGE_PIN: "message_pin", + /** Mudar a descrição da sala (`{conversationId, description}`). */ + ROOM_UPDATE: "room_update", }); /** Eventos que o servidor envia. */ @@ -117,6 +129,14 @@ export const SERVER_EVENTS = Object.freeze({ DM_CLOSED: "dm_closed", /** Quem você bloqueou nesta sessão (resposta a bloquear/desbloquear). */ BLOCK_LIST: "block_list", + /** Uma mensagem foi editada por quem a escreveu. */ + MESSAGE_UPDATED: "message_updated", + /** Uma mensagem foi apagada (por quem escreveu ou pela moderação). */ + MESSAGE_DELETED: "message_deleted", + /** As reações de uma mensagem mudaram. */ + MESSAGE_REACTIONS: "message_reactions", + /** As mensagens fixadas da conversa mudaram (ou o estado ao entrar). */ + PINS_UPDATED: "pins_updated", }); /** @@ -263,6 +283,7 @@ const authorOf = (user) => (typeof user.author === "number" ? { author: user.aut * @property {number | null} author o SEU número de autor nesta sala * @property {number} memberCount * @property {number} historyVersion + * @property {string} [description] descrição da sala, quando houver */ /** @@ -391,6 +412,7 @@ export const serverMessage = Object.freeze({ kind = MESSAGE_KINDS.TEXT, format = null, clientMsgId = null, + reference = null, }) => ({ id, type: SERVER_EVENTS.CHAT_MESSAGE, @@ -403,9 +425,52 @@ export const serverMessage = Object.freeze({ ...(kind !== MESSAGE_KINDS.TEXT ? { kind } : {}), ...(format ? { format } : {}), ...(clientMsgId ? { clientMsgId } : {}), + ...(reference ? { reference } : {}), }, }), + /** + * Mensagem editada por quem a escreveu. + * @param {string} id + * @param {string} content + * @param {string} editedAt + */ + messageUpdated: (id, content, editedAt) => ({ + type: SERVER_EVENTS.MESSAGE_UPDATED, + payload: { id, content, editedAt }, + }), + + /** + * Mensagem apagada. `by` diz se foi quem escreveu ou a moderação (sem + * dizer quem moderou). + * @param {string} id + * @param {"author" | "moderation"} by + */ + messageDeleted: (id, by) => ({ + type: SERVER_EVENTS.MESSAGE_DELETED, + payload: { id, by }, + }), + + /** + * Reações de uma mensagem. `authors` são chaves `@username#número` desta + * conversa (já públicas nela); nenhum id interno. + * @param {string} id + * @param {{emoji: string, count: number, authors: string[]}[]} reactions + */ + messageReactions: (id, reactions) => ({ + type: SERVER_EVENTS.MESSAGE_REACTIONS, + payload: { id, reactions }, + }), + + /** + * Mensagens fixadas da conversa (cópias de trecho e autoria). + * @param {unknown[]} pins + */ + pinsUpdated: (pins) => ({ + type: SERVER_EVENTS.PINS_UPDATED, + payload: { pins }, + }), + /** @param {{name: string, username?: string}} user @param {string} timestamp */ joined: (user, timestamp) => ({ type: SERVER_EVENTS.USER_JOINED, @@ -467,10 +532,15 @@ export const serverMessage = Object.freeze({ * @param {string | null} [ref] `clientMsgId` ou `requestId` recusado, quando houver * @param {string | null} [conversationId] conversa a que o erro se refere */ - error: (code, ref = null, conversationId = null) => ({ + error: (code, ref = null, conversationId = null, detail = null) => ({ type: SERVER_EVENTS.ERROR, ...(conversationId ? { conversationId } : {}), - payload: { code, message: describeError(code).message, ...(ref ? { ref } : {}) }, + payload: { + code, + message: describeError(code).message, + ...(ref ? { ref } : {}), + ...(detail ?? {}), + }, }), /** @param {unknown[]} commands metadados do registro (ver commands/registry.js) */ diff --git a/backend/src/room/direct.js b/backend/src/room/direct.js index 05c1d21..a1efaf2 100644 --- a/backend/src/room/direct.js +++ b/backend/src/room/direct.js @@ -18,9 +18,10 @@ import crypto from "node:crypto"; import { ERROR_CODES } from "../errors.js"; -import { DM_CLOSED_REASONS, MESSAGE_KINDS, scoped, serverMessage } from "../protocol.js"; +import { DM_CLOSED_REASONS, MESSAGE_KINDS, TONES, scoped, serverMessage } from "../protocol.js"; import { readClientId, readContent } from "../validation.js"; import { createTranscript } from "./transcript.js"; +import { createMessageOps } from "./messageOps.js"; /** Limites padrão; configuráveis por variável de ambiente. */ export const DM_DEFAULTS = Object.freeze({ @@ -91,6 +92,34 @@ export const createDirectConversation = ({ deliver(identity.holder, JSON.stringify(message)); }; + /** Para as duas (só quem já sabe da conversa). @param {Record} message */ + const broadcast = (message) => { + const data = scoped(id, message); + for (const identity of participants) if (announced.has(identity)) sendTo(identity, data); + }; + + /** Responder, editar, apagar, reagir e fixar (comum com as salas). */ + const ops = createMessageOps({ + transcript, + broadcast, + notice: (text) => + broadcast( + serverMessage.notice({ + id: newMessageId(), + tone: TONES.INFO, + text, + timestamp: now().toISOString(), + }), + ), + timestamp: () => now().toISOString(), + log, + conversationId: id, + }); + + /** @param {Identity} identity */ + const allowed = (identity) => + closed || !has(identity) ? { ok: false, code: ERROR_CODES.CONVERSATION_NOT_FOUND } : null; + /** * Resumo do ponto de vista de quem recebe: a outra pessoa e a presença dela. * @param {Identity} identity @@ -122,6 +151,7 @@ export const createDirectConversation = ({ sendTo(identity, serverMessage.dmOpened(summaryFor(identity), how)); const recent = transcript.recent(historyOnJoin); if (recent.length > 0) sendTo(identity, scoped(id, serverMessage.history(recent))); + if (ops.pinCount > 0) sendTo(identity, scoped(id, ops.pinsUpdated())); }; /** A outra pessoa (se já sabe da conversa) recebe o resumo atualizado. @param {Identity} identity */ @@ -187,11 +217,40 @@ export const createDirectConversation = ({ return publish(identity, { content: content.content, clientMsgId: readClientId(payload.clientMsgId), + reference: ops.reference(payload.replyTo), }); }, publish, + /** @param {Identity} identity @param {Record} payload */ + edit(identity, payload) { + return allowed(identity) ?? ops.edit(persona(identity), payload); + }, + + /** Numa privada, cada pessoa apaga só as próprias mensagens. @param {Identity} identity @param {Record} payload */ + removeMessage(identity, payload) { + return ( + allowed(identity) ?? + ops.remove(persona(identity), payload, { moderator: false, actorId: identity.id }) + ); + }, + + /** @param {Identity} identity @param {Record} payload */ + react(identity, payload) { + return allowed(identity) ?? ops.react(persona(identity), payload); + }, + + /** Numa privada, as duas pessoas fixam. @param {Identity} identity @param {Record} payload */ + pin(identity, payload) { + return allowed(identity) ?? ops.pin(persona(identity), payload, true); + }, + + /** Privada não tem descrição. */ + describe() { + return { ok: false, code: ERROR_CODES.NOT_ALLOWED }; + }, + /** * Digitação, só para a outra pessoa — e só se ela já sabe da conversa. * @param {Identity} identity diff --git a/backend/src/room/hub.js b/backend/src/room/hub.js index 76fdae8..690ad07 100644 --- a/backend/src/room/hub.js +++ b/backend/src/room/hub.js @@ -415,6 +415,20 @@ export const createHub = ({ return found.conversation.post(found.identity, payload); }, + /** + * Editar, apagar, reagir, fixar ou mudar a descrição, numa conversa + * de que a conexão participa. Permissão decidida pela conversa. + * @param {unknown} member + * @param {Record} payload + * @param {"edit" | "removeMessage" | "react" | "pin" | "describe"} action + * @returns {{ok: true} | {ok: false, code: string, until?: string}} + */ + conversationAction(member, payload, action) { + const found = resolveConversation(member, payload.conversationId); + if (!found.ok) return found; + return found.conversation[action](found.identity, payload); + }, + /** * Procura alguém conectado pelo @ EXATO. Nunca lista, completa ou * sugere: sem o @ certo, nada aparece. Quem bloqueou você também não diff --git a/backend/src/room/messageOps.js b/backend/src/room/messageOps.js new file mode 100644 index 0000000..24c5877 --- /dev/null +++ b/backend/src/room/messageOps.js @@ -0,0 +1,271 @@ +/** + * Operações sobre mensagens já publicadas, comuns a salas e conversas + * privadas (decisões F1 a F5): responder, editar, apagar, reagir e fixar. + * + * O modelo de dados segue o do Fluxer (referência da mensagem respondida, + * carimbo de edição, reações com contagem, mensagens fixadas), adaptado ao + * produto: tudo em memória, some com a conversa, e ninguém é identificado + * pelo id interno — a autoria é o `@username` mais o número de autor DESTA + * conversa, que já é público nela. + * + * Regras puras: quem chama (sala ou privada) diz quem é a pessoa, se ela + * modera e por onde os quadros saem. + */ + +import { ERROR_CODES } from "../errors.js"; +import { LIMITS, MESSAGE_KINDS, serverMessage } from "../protocol.js"; +import { normalizeText, readClientId, readContent } from "../validation.js"; + +/** + * Emojis de reação: lista fixa, sem texto livre (nada de conteúdo arbitrário + * entrando por reação). + */ +export const REACTION_EMOJIS = Object.freeze([ + "👍", + "❤️", + "😂", + "🎉", + "😮", + "😢", + "🙏", + "🔥", + "👀", + "✅", + "❓", + "💯", +]); + +/** Emojis diferentes numa mesma mensagem. */ +export const MAX_REACTIONS_PER_MESSAGE = 8; +/** Mensagens fixadas por conversa. */ +export const MAX_PINS = 25; +/** Tamanho do trecho copiado na resposta e na lista de fixadas. */ +export const EXCERPT_LENGTH = 100; + +/** + * Trecho de uma mensagem numa linha só. + * @param {string} content + */ +export const excerptOf = (content) => { + const line = normalizeText(content.replace(/\s+/g, " "), EXCERPT_LENGTH + 1); + return line.length > EXCERPT_LENGTH ? `${line.slice(0, EXCERPT_LENGTH - 1)}…` : line; +}; + +/** + * @typedef {{name: string, username: string, author: number}} Persona + * @typedef {{ok: true} | {ok: false, code: string}} Result + * @typedef {ReturnType} Transcript + * @typedef {{id: string, userName: string, username: string, author: number | null, excerpt: string, at: string, by: string}} Pin + */ + +/** + * @param {{ + * transcript: Transcript, + * broadcast: (message: Record) => void, + * notice: (text: string) => void, + * timestamp: () => string, + * log: (level: "info" | "warn" | "error", event: string, fields?: Record) => void, + * conversationId: string, + * }} deps + */ +export const createMessageOps = ({ + transcript, + broadcast, + notice, + timestamp, + log, + conversationId, +}) => { + /** @type {Pin[]} */ + const pins = []; + + /** A mensagem foi escrita por esta pessoa (mesmo @ E mesmo número)? */ + const isAuthor = (/** @type {any} */ message, /** @type {Persona} */ persona) => + message.payload.username === persona.username && message.payload.author === persona.author; + + /** @param {unknown} raw */ + const find = (raw) => { + const id = readClientId(raw); + return id ? transcript.find(id) : null; + }; + + const pinsUpdated = () => serverMessage.pinsUpdated(pins); + + /** Tira a mensagem das fixadas (apagada, ou desafixada). @param {string} id */ + const unpinQuietly = (id) => { + const index = pins.findIndex((pin) => pin.id === id); + if (index === -1) return false; + pins.splice(index, 1); + return true; + }; + + return { + /** + * Referência da mensagem respondida (F1): cópia de quem escreveu e de + * um trecho, feita na hora — continua legível mesmo que a original + * saia do histórico ou seja apagada. Id que não é desta conversa é + * ignorado (a resposta vira uma mensagem comum). + * @param {unknown} replyTo + */ + reference(replyTo) { + const message = /** @type {any} */ (find(replyTo)); + if (!message) return null; + return { + id: message.id, + userName: message.payload.userName, + username: message.payload.username, + ...(typeof message.payload.author === "number" + ? { author: message.payload.author } + : {}), + excerpt: excerptOf(message.payload.content), + }; + }, + + /** + * Editar a própria mensagem (F2): só quem escreveu (mesma identidade + * na conversa), só texto digitado, enquanto estiver no histórico. + * @param {Persona} persona + * @param {Record} payload `{ id, content }` + * @returns {Result} + */ + edit(persona, payload) { + const message = /** @type {any} */ (find(payload.id)); + if (!message) return { ok: false, code: ERROR_CODES.MESSAGE_NOT_FOUND }; + if ( + !isAuthor(message, persona) || + (message.payload.kind ?? MESSAGE_KINDS.TEXT) !== MESSAGE_KINDS.TEXT || + message.payload.format + ) { + return { ok: false, code: ERROR_CODES.NOT_ALLOWED }; + } + const content = readContent(payload.content); + if (!content.ok) return content; + if (content.content === message.payload.content) return { ok: true }; + const editedAt = timestamp(); + message.payload.content = content.content; + message.payload.editedAt = editedAt; + const pin = pins.find((item) => item.id === message.id); + if (pin) { + pin.excerpt = excerptOf(content.content); + broadcast(pinsUpdated()); + } + broadcast(serverMessage.messageUpdated(message.id, content.content, editedAt)); + return { ok: true }; + }, + + /** + * Apagar (F3): quem escreveu, sempre; quem modera a sala, qualquer + * mensagem dela. Some do histórico de todos. + * @param {Persona} persona + * @param {Record} payload `{ id }` + * @param {{moderator: boolean, actorId: string}} who + * @returns {Result} + */ + remove(persona, payload, { moderator, actorId }) { + const message = /** @type {any} */ (find(payload.id)); + if (!message) return { ok: false, code: ERROR_CODES.MESSAGE_NOT_FOUND }; + const own = isAuthor(message, persona); + if (!own && !moderator) return { ok: false, code: ERROR_CODES.NOT_ALLOWED }; + transcript.remove(message.id); + const wasPinned = unpinQuietly(message.id); + broadcast(serverMessage.messageDeleted(message.id, own ? "author" : "moderation")); + if (wasPinned) broadcast(pinsUpdated()); + if (!own) { + log("warn", "moderation_action", { + action: "delete_message", + conversation: conversationId, + actor: actorId, + }); + } + return { ok: true }; + }, + + /** + * Reagir (F4): liga ou desliga a sua reação com um dos emojis da + * lista. Até `MAX_REACTIONS_PER_MESSAGE` emojis diferentes. + * @param {Persona} persona + * @param {Record} payload `{ id, emoji }` + * @returns {Result} + */ + react(persona, payload) { + const message = /** @type {any} */ (find(payload.id)); + if (!message) return { ok: false, code: ERROR_CODES.MESSAGE_NOT_FOUND }; + const emoji = typeof payload.emoji === "string" ? payload.emoji : ""; + if (!REACTION_EMOJIS.includes(emoji)) + return { ok: false, code: ERROR_CODES.INVALID_REACTION }; + const key = `${persona.username}#${persona.author}`; + /** @type {{emoji: string, count: number, authors: string[]}[]} */ + const reactions = message.payload.reactions ?? []; + const existing = reactions.find((item) => item.emoji === emoji); + if (existing) { + const at = existing.authors.indexOf(key); + if (at === -1) existing.authors.push(key); + else existing.authors.splice(at, 1); + existing.count = existing.authors.length; + } else { + if (reactions.length >= MAX_REACTIONS_PER_MESSAGE) { + return { ok: false, code: ERROR_CODES.REACTION_LIMIT }; + } + reactions.push({ emoji, count: 1, authors: [key] }); + } + const kept = reactions.filter((item) => item.count > 0); + if (kept.length) message.payload.reactions = kept; + else delete message.payload.reactions; + broadcast(serverMessage.messageReactions(message.id, kept)); + return { ok: true }; + }, + + /** + * Fixar ou desafixar (F5). Quem pode é decidido por quem chama. + * @param {Persona} persona + * @param {Record} payload `{ id, pinned }` + * @param {boolean} allowed + * @returns {Result} + */ + pin(persona, payload, allowed) { + if (!allowed) return { ok: false, code: ERROR_CODES.NOT_ALLOWED }; + const message = /** @type {any} */ (find(payload.id)); + if (!message) return { ok: false, code: ERROR_CODES.MESSAGE_NOT_FOUND }; + const want = payload.pinned !== false; + const already = pins.some((pin) => pin.id === message.id); + if (want === already) return { ok: true }; + if (want) { + if (pins.length >= MAX_PINS) return { ok: false, code: ERROR_CODES.PIN_LIMIT }; + pins.unshift({ + id: message.id, + userName: message.payload.userName, + username: message.payload.username, + author: + typeof message.payload.author === "number" ? message.payload.author : null, + excerpt: excerptOf(message.payload.content), + at: timestamp(), + by: persona.username, + }); + message.payload.pinned = true; + notice(`${persona.name} fixou uma mensagem de ${message.payload.userName}.`); + } else { + unpinQuietly(message.id); + delete message.payload.pinned; + notice(`${persona.name} desafixou uma mensagem de ${message.payload.userName}.`); + } + broadcast(pinsUpdated()); + return { ok: true }; + }, + + /** O quadro com as fixadas (para quem entra ou volta). */ + pinsUpdated, + + /** Quantas fixadas há (o estado só é enviado se houver). */ + get pinCount() { + return pins.length; + }, + + /** O histórico foi apagado: as fixadas vão junto. */ + reset() { + pins.length = 0; + }, + }; +}; + +/** Limite de texto da descrição de uma sala (F6). */ +export const DESCRIPTION_MAX_LENGTH = LIMITS.roomDescriptionMaxLength; diff --git a/backend/src/room/room.js b/backend/src/room/room.js index 2ab2f7d..3e8fbbf 100644 --- a/backend/src/room/room.js +++ b/backend/src/room/room.js @@ -29,6 +29,7 @@ import crypto from "node:crypto"; import { ERROR_CODES } from "../errors.js"; import { + LIMITS, MESSAGE_KINDS, ROLES, ROOM_LEFT_REASONS, @@ -36,9 +37,10 @@ import { scoped, serverMessage, } from "../protocol.js"; -import { readClientId, readContent } from "../validation.js"; -import { isMuted } from "./policy.js"; +import { normalizeText, readClientId, readContent } from "../validation.js"; +import { isModerator, isMuted } from "./policy.js"; import { createTranscript } from "./transcript.js"; +import { createMessageOps } from "./messageOps.js"; /** Intervalo mínimo entre duas trocas de nome da mesma pessoa. */ export const RENAME_COOLDOWN_MS = 10_000; @@ -165,6 +167,18 @@ export const createRoom = ({ const notice = (tone, text) => broadcast(serverMessage.notice({ id: newMessageId(), tone, text, timestamp: timestamp() })); + /** Responder, editar, apagar, reagir e fixar (comum com as privadas). */ + const ops = createMessageOps({ + transcript, + broadcast, + notice: (text) => notice(TONES.INFO, text), + timestamp, + log, + conversationId: id, + }); + /** Descrição da sala (F6), definida por quem modera. */ + let description = ""; + /** Quem aparece na lista: conectados, com o papel que têm NESTA sala. */ const present = () => [...members].filter(([, membership]) => membership.connected); @@ -229,6 +243,7 @@ export const createRoom = ({ author: authors.get(identity.id) ?? null, memberCount: members.size, historyVersion: transcript.version, + ...(description ? { description } : {}), }); /** @@ -247,6 +262,7 @@ export const createRoom = ({ if (recent.length > 0) { sendTo(identity, serverMessage.history(recent)); } + if (ops.pinCount > 0) sendTo(identity, ops.pinsUpdated()); }; /** Cada participante recebe o resumo atualizado (o papel difere por pessoa). */ @@ -283,6 +299,33 @@ export const createRoom = ({ onPresenceChange(identity); }; + /** + * Recusa por silêncio, com o instante em que ele acaba (F7). Silêncio + * "até liberar" não tem prazo. + * @param {Membership} membership + * @returns {{ok: false, code: string, until?: string}} + */ + const mutedRefusal = (membership) => ({ + ok: false, + code: ERROR_CODES.MUTED, + ...(membership.mutedUntil !== null && Number.isFinite(membership.mutedUntil) + ? { until: new Date(membership.mutedUntil).toISOString() } + : {}), + }); + + /** + * Quem participa, e se pode agir (silêncio vale também para editar e + * reagir). + * @param {Identity} identity + * @param {{speak?: boolean}} [options] + */ + const participant = (identity, { speak = false } = {}) => { + const membership = members.get(identity); + if (!membership) return { ok: false, code: ERROR_CODES.CONVERSATION_NOT_FOUND }; + if (speak && isMuted(membership, nowMs())) return mutedRefusal(membership); + return { ok: true, membership }; + }; + /** * Publica uma mensagem na sala. Único caminho de escrita no histórico — * mensagem digitada e mensagem produzida por comando seguem as mesmas @@ -293,17 +336,17 @@ export const createRoom = ({ */ const publish = ( identity, - { content, kind = MESSAGE_KINDS.TEXT, format = null, clientMsgId = null }, + { content, kind = MESSAGE_KINDS.TEXT, format = null, clientMsgId = null, reference = null }, ) => { const membership = members.get(identity); if (!membership) return { ok: false, code: ERROR_CODES.CONVERSATION_NOT_FOUND }; - if (isMuted(membership, nowMs())) return { ok: false, code: ERROR_CODES.MUTED }; + if (isMuted(membership, nowMs())) return mutedRefusal(membership); // Reenvio da mesma mensagem (retentativa do cliente): a original volta // só para quem enviou, sem duplicar na sala. const { message, duplicate } = transcript.append( identity, - { content, kind, format, clientMsgId }, + { content, kind, format, clientMsgId, reference }, authorOf(identity), ); if (duplicate) { @@ -450,11 +493,72 @@ export const createRoom = ({ return publish(identity, { content: content.content, clientMsgId: readClientId(payload.clientMsgId), + reference: ops.reference(payload.replyTo), }); }, publish, + /** Editar a própria mensagem. @param {Identity} identity @param {Record} payload */ + edit(identity, payload) { + const check = participant(identity, { speak: true }); + return check.ok ? ops.edit(persona(identity), payload) : check; + }, + + /** Apagar (sua, ou qualquer uma se você modera). @param {Identity} identity @param {Record} payload */ + removeMessage(identity, payload) { + const check = participant(identity); + if (!check.ok) return check; + return ops.remove(persona(identity), payload, { + moderator: isModerator(identity, check.membership), + actorId: identity.id, + }); + }, + + /** Reagir. @param {Identity} identity @param {Record} payload */ + react(identity, payload) { + const check = participant(identity, { speak: true }); + return check.ok ? ops.react(persona(identity), payload) : check; + }, + + /** Fixar ou desafixar: quem modera a sala. @param {Identity} identity @param {Record} payload */ + pin(identity, payload) { + const check = participant(identity); + if (!check.ok) return check; + return ops.pin(persona(identity), payload, isModerator(identity, check.membership)); + }, + + /** + * Descrição da sala (F6): só quem modera; até 200 caracteres; vazia + * apaga. + * @param {Identity} identity + * @param {Record} payload `{ description }` + */ + describe(identity, payload) { + const check = participant(identity); + if (!check.ok) return check; + if (!isModerator(identity, check.membership)) { + return { ok: false, code: ERROR_CODES.NOT_ALLOWED }; + } + if (typeof payload.description !== "string") { + return { ok: false, code: ERROR_CODES.INVALID_DESCRIPTION }; + } + const next = normalizeText(payload.description, LIMITS.roomDescriptionMaxLength + 1); + if (next.length > LIMITS.roomDescriptionMaxLength) { + return { ok: false, code: ERROR_CODES.INVALID_DESCRIPTION }; + } + if (next === description) return { ok: true }; + description = next; + notice( + TONES.INFO, + next + ? `${identity.name} mudou a descrição da sala.` + : `${identity.name} apagou a descrição da sala.`, + ); + broadcastSummary(); + return { ok: true }; + }, + /** * Sinal de digitação, só para os outros participantes desta sala. * @param {Identity} identity @@ -494,6 +598,7 @@ export const createRoom = ({ */ clearHistory(actor) { const removed = transcript.clear(members.keys()); + ops.reset(); log("warn", "moderation_action", { action: "clear_history", conversation: id, diff --git a/backend/src/room/transcript.js b/backend/src/room/transcript.js index 97d9113..dd5ec1d 100644 --- a/backend/src/room/transcript.js +++ b/backend/src/room/transcript.js @@ -43,13 +43,19 @@ export const createTranscript = ({ * Registra uma mensagem. Reenvio com o mesmo `clientMsgId` devolve a * original em `duplicate`, sem registrar de novo. * @param {Identity} identity - * @param {{content: string, kind?: string, format?: string | null, clientMsgId?: string | null}} message + * @param {{content: string, kind?: string, format?: string | null, clientMsgId?: string | null, reference?: Record | null}} message * @param {number} [author] número de autor de quem escreve nesta conversa * @returns {{message: ChatMessage, duplicate: boolean}} */ append( identity, - { content, kind = MESSAGE_KINDS.TEXT, format = null, clientMsgId = null }, + { + content, + kind = MESSAGE_KINDS.TEXT, + format = null, + clientMsgId = null, + reference = null, + }, author, ) { const recentKey = clientMsgId ? prefix + clientMsgId : null; @@ -69,6 +75,7 @@ export const createTranscript = ({ kind, format, clientMsgId, + reference, }); history.push(message); if (history.length > historySize) history.shift(); @@ -82,6 +89,24 @@ export const createTranscript = ({ return { message, duplicate: false }; }, + /** + * Uma mensagem do histórico pelo id (null se não existe ou já saiu). + * @param {string} messageId + */ + find: (messageId) => history.find((message) => message.id === messageId) ?? null, + + /** + * Tira uma mensagem do histórico (apagada). + * @param {string} messageId + * @returns {boolean} + */ + remove(messageId) { + const index = history.findIndex((message) => message.id === messageId); + if (index === -1) return false; + history.splice(index, 1); + return true; + }, + /** As `count` mais recentes. @param {number} count */ recent: (count) => (count > 0 ? history.slice(-count) : []), diff --git a/backend/src/transport/connection.js b/backend/src/transport/connection.js index 44f85b5..a45a4ec 100644 --- a/backend/src/transport/connection.js +++ b/backend/src/transport/connection.js @@ -113,7 +113,7 @@ export const createConnectionHandler = ({ * `requestId`) para que ele saiba QUAL envio falhou; `conversationId` * diz a que conversa o erro se refere. */ - const reject = (operation, code, ref = null, conversationId = null) => { + const reject = (operation, code, ref = null, conversationId = null, detail = null) => { const { category } = describeError(code); metrics.count("requestsRejected", code); metrics.count("errorsByCategory", category); @@ -124,7 +124,28 @@ export const createConnectionHandler = ({ category, ...(hub.isLoggedIn(ws) ? { user: hub.userIdOf(ws) } : {}), }); - send(serverMessage.error(code, ref, conversationId)); + send(serverMessage.error(code, ref, conversationId, detail)); + }; + + /** + * Operação sobre uma mensagem ou a conversa (editar, apagar, reagir, + * fixar, descrição). A recusa leva o id da mensagem como referência. + * @param {string} operation + * @param {"edit" | "removeMessage" | "react" | "pin" | "describe"} action + * @param {Record} payload + */ + const conversationAction = (operation, action, payload) => { + const result = hub.conversationAction(ws, payload, action); + if (!result.ok) { + return reject( + operation, + result.code, + readClientId(payload.id), + readConversationId(payload.conversationId), + "until" in result && result.until ? { until: result.until } : null, + ); + } + metrics.count("messageActions", action); }; /** Id de correlação de um pedido de sala. @param {Record} payload */ @@ -150,6 +171,8 @@ export const createConnectionHandler = ({ result.code, readClientId(payload.clientMsgId), readConversationId(payload.conversationId), + // Silêncio com prazo: o cliente mostra até quando (F7). + "until" in result && result.until ? { until: result.until } : null, ); } if (!result.duplicate) metrics.count("messagesAccepted"); @@ -248,6 +271,16 @@ export const createConnectionHandler = ({ metrics.count("blocks"); send(serverMessage.blockList(result.blocked, requestIdOf(payload))); }, + [CLIENT_EVENTS.MESSAGE_EDIT]: (payload) => + conversationAction(CLIENT_EVENTS.MESSAGE_EDIT, "edit", payload), + [CLIENT_EVENTS.MESSAGE_DELETE]: (payload) => + conversationAction(CLIENT_EVENTS.MESSAGE_DELETE, "removeMessage", payload), + [CLIENT_EVENTS.REACTION_TOGGLE]: (payload) => + conversationAction(CLIENT_EVENTS.REACTION_TOGGLE, "react", payload), + [CLIENT_EVENTS.MESSAGE_PIN]: (payload) => + conversationAction(CLIENT_EVENTS.MESSAGE_PIN, "pin", payload), + [CLIENT_EVENTS.ROOM_UPDATE]: (payload) => + conversationAction(CLIENT_EVENTS.ROOM_UPDATE, "describe", payload), [CLIENT_EVENTS.USER_UNBLOCK]: (payload) => { const result = hub.unblock(ws, payload); if (!result.ok) { diff --git a/backend/test/unit/contract.test.js b/backend/test/unit/contract.test.js index 2b546c1..84ce0ff 100644 --- a/backend/test/unit/contract.test.js +++ b/backend/test/unit/contract.test.js @@ -11,6 +11,7 @@ import { fileURLToPath } from "node:url"; import * as server from "../../src/protocol.js"; import { ERROR_CODES } from "../../src/errors.js"; import * as client from "../../../frontend/src/protocol.js"; +import { REACTION_EMOJIS } from "../../src/room/messageOps.js"; const indexHtml = fs.readFileSync( fileURLToPath(new URL("../../../frontend/index.html", import.meta.url)), @@ -38,6 +39,8 @@ test("variedades, formatos, tons e códigos de fechamento coincidem", () => { assert.deepEqual(client.CLOSE_CODES, server.CLOSE_CODES); assert.equal(client.LIMITS.commandMaxLength, server.LIMITS.commandMaxLength); assert.equal(client.LIMITS.roomNameMaxLength, server.LIMITS.roomNameMaxLength); + assert.equal(client.LIMITS.roomDescriptionMaxLength, server.LIMITS.roomDescriptionMaxLength); + assert.deepEqual(client.REACTION_EMOJIS, REACTION_EMOJIS); assert.deepEqual(client.ROLES, server.ROLES); assert.deepEqual(client.ROOM_LEFT_REASONS, server.ROOM_LEFT_REASONS); assert.deepEqual(client.CONVERSATION_KINDS, server.CONVERSATION_KINDS); diff --git a/backend/test/unit/messageFeatures.test.js b/backend/test/unit/messageFeatures.test.js new file mode 100644 index 0000000..b31b0b7 --- /dev/null +++ b/backend/test/unit/messageFeatures.test.js @@ -0,0 +1,271 @@ +// Recursos de mensagem (decisões F1 a F7): responder, editar, apagar, +// reagir, fixar, descrição da sala e silêncio com prazo. Permissões no +// servidor; nenhum id interno sai nos quadros. + +import { test, describe } from "node:test"; +import assert from "node:assert/strict"; +import { setup } from "./harness.js"; +import { MAX_PINS, MAX_REACTIONS_PER_MESSAGE, REACTION_EMOJIS } from "../../src/room/messageOps.js"; + +/** Ana cria a sala (anfitriã); Bia e Caio entram. */ +const room = () => { + const ctx = setup(); + const { member, login, hub } = ctx; + const ana = member("ana"); + const bia = member("bia"); + const caio = member("caio"); + login(ana, { userName: "Ana", username: "ana" }); + login(bia, { userName: "Bia", username: "bia" }); + login(caio, { userName: "Caio", username: "caio" }); + const created = hub.createRoom(ana, { name: "Sala" }).room; + hub.joinRoom(bia, { code: created.code }); + hub.joinRoom(caio, { code: created.code }); + const say = (m, content, extra = {}) => + hub.post(m, { conversationId: created.id, content, ...extra }); + const last = (m, type) => ctx.received(m, type, created.id).at(-1); + const lastId = (m) => last(m, "chat_message").id; + const act = (m, action, payload) => + hub.conversationAction(m, { conversationId: created.id, ...payload }, action); + return { ...ctx, ana, bia, caio, created, say, last, lastId, act }; +}; + +describe("responder (F1)", () => { + test("a resposta leva a cópia de quem escreveu e um trecho da original", () => { + const { ana, bia, say, last, lastId } = room(); + say(bia, "a original, com um texto bem comprido ".repeat(5)); + const original = lastId(ana); + say(ana, "respondendo", { replyTo: original }); + const reference = last(bia, "chat_message").payload.reference; + assert.equal(reference.id, original); + assert.equal(reference.username, "bia"); + assert.equal(reference.author, 2); + assert.ok(reference.excerpt.length <= 100); + assert.ok(!("userId" in reference) && !JSON.stringify(reference).includes("id_")); + }); + + test("id que não é desta conversa é ignorado: vira mensagem comum", () => { + const { hub, ana, bia, say, last, received } = room(); + const other = hub.createRoom(bia, { name: "Outra" }).room; + hub.post(bia, { conversationId: other.id, content: "lá" }); + const foreign = received(bia, "chat_message", other.id).at(-1).id; + assert.equal(say(ana, "oi", { replyTo: foreign }).ok, true); + assert.equal(last(bia, "chat_message").payload.reference, undefined); + assert.equal(say(ana, "oi", { replyTo: "não-existe" }).ok, true); + assert.equal(last(bia, "chat_message").payload.reference, undefined); + }); +}); + +describe("editar (F2)", () => { + test("quem escreveu edita; todos recebem; o histórico de quem entra já vem editado", () => { + const { hub, member, login, ana, bia, created, say, last, lastId, act, received } = room(); + say(bia, "erado"); + const id = lastId(ana); + assert.deepEqual(act(bia, "edit", { id, content: "errado → certo" }), { ok: true }); + const update = last(ana, "message_updated").payload; + assert.equal(update.id, id); + assert.equal(update.content, "errado → certo"); + assert.ok(update.editedAt); + const dani = member("dani"); + login(dani, { userName: "Dani", username: "dani" }); + hub.joinRoom(dani, { code: created.code }); + const history = received(dani, "message_history", created.id).at(-1).payload; + const edited = history.find((m) => m.id === id); + assert.equal(edited.payload.content, "errado → certo"); + assert.ok(edited.payload.editedAt); + }); + + test("outra pessoa (nem a anfitriã) não edita; @ reaproveitado também não", () => { + const { hub, member, login, ana, bia, created, say, lastId, act } = room(); + say(bia, "minha"); + const id = lastId(ana); + assert.deepEqual(act(ana, "edit", { id, content: "x" }), { + ok: false, + code: "not_allowed", + }); + hub.logout(bia); + const impostora = member("bia-nova"); + login(impostora, { userName: "Bia", username: "bia" }); + hub.joinRoom(impostora, { code: created.code }); + assert.deepEqual(act(impostora, "edit", { id, content: "x" }), { + ok: false, + code: "not_allowed", + }); + }); + + test("conteúdo vazio ou mensagem inexistente são recusados", () => { + const { ana, bia, say, lastId, act } = room(); + say(bia, "texto"); + const id = lastId(ana); + assert.equal(act(bia, "edit", { id, content: " " }).code, "empty_message"); + assert.equal(act(bia, "edit", { id: "nada", content: "x" }).code, "message_not_found"); + }); +}); + +describe("apagar (F3)", () => { + test("quem escreveu apaga; some do histórico de todos", () => { + const { hub, member, login, ana, bia, created, say, last, lastId, act, received } = room(); + say(bia, "apague-me"); + const id = lastId(ana); + assert.deepEqual(act(bia, "removeMessage", { id }), { ok: true }); + assert.deepEqual(last(ana, "message_deleted").payload, { id, by: "author" }); + const dani = member("dani"); + login(dani, { userName: "Dani", username: "dani" }); + hub.joinRoom(dani, { code: created.code }); + const history = received(dani, "message_history", created.id).at(-1)?.payload ?? []; + assert.ok(!history.some((m) => m.id === id)); + }); + + test("participante não apaga a dos outros; quem modera apaga, como moderação", () => { + const { ana, bia, caio, say, last, lastId, act, logs } = room(); + say(caio, "do caio"); + const id = lastId(ana); + assert.deepEqual(act(bia, "removeMessage", { id }), { ok: false, code: "not_allowed" }); + assert.deepEqual(act(ana, "removeMessage", { id }), { ok: true }); + assert.deepEqual(last(bia, "message_deleted").payload, { id, by: "moderation" }); + assert.ok( + logs.some((l) => l.event === "moderation_action" && l.action === "delete_message"), + ); + }); + + test("privada: cada um apaga só as próprias", () => { + const ctx = setup(); + const ana = ctx.member("ana"); + const bia = ctx.member("bia"); + ctx.login(ana, { userName: "Ana", username: "ana" }); + ctx.login(bia, { userName: "Bia", username: "bia" }); + const dm = ctx.hub.openDm(ana, { username: "bia" }).conversation; + ctx.hub.post(ana, { conversationId: dm.id, content: "da ana" }); + const id = ctx.received(ana, "chat_message", dm.id).at(-1).id; + const act = (m, payload) => + ctx.hub.conversationAction(m, { conversationId: dm.id, ...payload }, "removeMessage"); + assert.deepEqual(act(bia, { id }), { ok: false, code: "not_allowed" }); + assert.deepEqual(act(ana, { id }), { ok: true }); + }); +}); + +describe("reações (F4)", () => { + test("liga e desliga; os autores são @#número, sem id interno", () => { + const { ana, bia, caio, say, last, lastId, act } = room(); + say(ana, "reaja"); + const id = lastId(bia); + act(bia, "react", { id, emoji: "👍" }); + act(caio, "react", { id, emoji: "👍" }); + let reactions = last(ana, "message_reactions").payload.reactions; + assert.deepEqual(reactions, [{ emoji: "👍", count: 2, authors: ["bia#2", "caio#3"] }]); + act(bia, "react", { id, emoji: "👍" }); + reactions = last(ana, "message_reactions").payload.reactions; + assert.deepEqual(reactions, [{ emoji: "👍", count: 1, authors: ["caio#3"] }]); + act(caio, "react", { id, emoji: "👍" }); + assert.deepEqual(last(ana, "message_reactions").payload.reactions, []); + }); + + test("só a lista fixa de emojis; no máximo 8 diferentes", () => { + const { ana, bia, say, lastId, act } = room(); + say(ana, "reaja"); + const id = lastId(bia); + assert.equal(act(bia, "react", { id, emoji: "" }).code, "invalid_reaction"); + assert.equal(act(bia, "react", { id, emoji: "😀" }).code, "invalid_reaction"); + for (const emoji of REACTION_EMOJIS.slice(0, MAX_REACTIONS_PER_MESSAGE)) { + assert.equal(act(bia, "react", { id, emoji }).ok, true); + } + const extra = REACTION_EMOJIS[MAX_REACTIONS_PER_MESSAGE]; + assert.equal(act(bia, "react", { id, emoji: extra }).code, "reaction_limit"); + }); +}); + +describe("fixar (F5)", () => { + test("na sala, só quem modera; quem entra recebe as fixadas", () => { + const { hub, member, login, ana, bia, created, say, last, lastId, act, received } = room(); + say(bia, "importante"); + const id = lastId(ana); + assert.deepEqual(act(bia, "pin", { id, pinned: true }), { ok: false, code: "not_allowed" }); + assert.deepEqual(act(ana, "pin", { id, pinned: true }), { ok: true }); + const pins = last(bia, "pins_updated").payload.pins; + assert.equal(pins.length, 1); + assert.equal(pins[0].id, id); + assert.equal(pins[0].username, "bia"); + const dani = member("dani"); + login(dani, { userName: "Dani", username: "dani" }); + hub.joinRoom(dani, { code: created.code }); + assert.equal(received(dani, "pins_updated", created.id).at(-1).payload.pins.length, 1); + }); + + test("apagar a mensagem a tira das fixadas; limpar o histórico também", () => { + const { hub, member, login, ana, bia, created, say, last, lastId, act, received } = room(); + say(bia, "fixe"); + const id = lastId(ana); + act(ana, "pin", { id, pinned: true }); + act(bia, "removeMessage", { id }); + assert.deepEqual(last(ana, "pins_updated").payload.pins, []); + say(bia, "fixe de novo"); + act(ana, "pin", { id: lastId(ana), pinned: true }); + const found = hub.resolveConversation(ana, created.id); + assert.ok(found.ok); + found.conversation.clearHistory(found.identity); + const dani = member("dani"); + login(dani, { userName: "Dani", username: "dani" }); + hub.joinRoom(dani, { code: created.code }); + assert.equal( + received(dani, "pins_updated", created.id).length, + 0, + "nada fixado depois de limpar", + ); + }); + + test("limite de fixadas", () => { + const { ana, bia, say, lastId, act } = room(); + for (let i = 0; i < MAX_PINS; i += 1) { + say(bia, `m${i}`); + assert.equal(act(ana, "pin", { id: lastId(ana), pinned: true }).ok, true); + } + say(bia, "mais uma"); + assert.equal(act(ana, "pin", { id: lastId(ana), pinned: true }).code, "pin_limit"); + }); +}); + +describe("descrição da sala (F6)", () => { + test("quem modera define; todos recebem no resumo; participante não pode", () => { + const { ana, bia, last, act } = room(); + assert.deepEqual(act(bia, "describe", { description: "x" }), { + ok: false, + code: "not_allowed", + }); + assert.deepEqual(act(ana, "describe", { description: " Revisão do TCC " }), { ok: true }); + assert.equal(last(bia, "room_updated").payload.description, "Revisão do TCC"); + assert.equal( + act(ana, "describe", { description: "x".repeat(201) }).code, + "invalid_description", + ); + assert.deepEqual(act(ana, "describe", { description: "" }), { ok: true }); + assert.equal(last(bia, "room_updated").payload.description, undefined); + }); +}); + +describe("silêncio com prazo (F7)", () => { + test("a recusa traz até quando; editar e reagir também ficam bloqueados", () => { + const { hub, ana, bia, created, say, lastId, act } = room(); + say(bia, "antes"); + const id = lastId(ana); + const found = hub.resolveConversation(ana, created.id); + const target = hub.resolveConversation(bia, created.id); + assert.ok(found.ok && target.ok); + // O relógio das salas no harness começa em 07/11/2026 10:00 UTC. + const base = Date.UTC(2026, 10, 7, 10, 0, 0); + found.conversation.setMuted(found.identity, target.identity, base + 10 * 60 * 1000); + const until = new Date(base + 10 * 60 * 1000).toISOString(); + assert.deepEqual(say(bia, "agora não"), { ok: false, code: "muted", until }); + assert.deepEqual(act(bia, "edit", { id, content: "mudei" }), { + ok: false, + code: "muted", + until, + }); + assert.deepEqual(act(bia, "react", { id, emoji: "👍" }), { + ok: false, + code: "muted", + until, + }); + // Silêncio "até liberar" não tem prazo. + found.conversation.setMuted(found.identity, target.identity, Infinity); + assert.deepEqual(say(bia, "x"), { ok: false, code: "muted" }); + }); +}); diff --git a/backend/test/unit/roomPhase4.test.js b/backend/test/unit/roomPhase4.test.js index 8776908..5bada8a 100644 --- a/backend/test/unit/roomPhase4.test.js +++ b/backend/test/unit/roomPhase4.test.js @@ -65,10 +65,13 @@ describe("publicação", () => { const hostIdentity = hub.entryOf(host).identity; const targetIdentity = hub.entryOf(target).identity; room.setMuted(hostIdentity, targetIdentity, BASE + 5 * 60 * 1000); - assert.deepEqual(post(target, { content: "x" }), { ok: false, code: "muted" }); + // A recusa diz até quando vale o silêncio (decisão F7). + const until = new Date(BASE + 5 * 60 * 1000).toISOString(); + assert.deepEqual(post(target, { content: "x" }), { ok: false, code: "muted", until }); assert.deepEqual(room.publish(targetIdentity, { content: "/me x", kind: "action" }), { ok: false, code: "muted", + until, }); ctx.tick(5 * 60 * 1000); assert.equal(post(target, { content: "voltei" }).ok, true); diff --git a/frontend/src/protocol.js b/frontend/src/protocol.js index eaa572b..017123b 100644 --- a/frontend/src/protocol.js +++ b/frontend/src/protocol.js @@ -21,6 +21,7 @@ export const LIMITS = Object.freeze({ messageMaxLines: 20, commandMaxLength: 1000, roomNameMaxLength: 40, + roomDescriptionMaxLength: 200, }); /** Eventos que o cliente envia. */ @@ -40,6 +41,11 @@ export const CLIENT_EVENTS = Object.freeze({ DM_CLOSE: "dm_close", USER_BLOCK: "user_block", USER_UNBLOCK: "user_unblock", + MESSAGE_EDIT: "message_edit", + MESSAGE_DELETE: "message_delete", + REACTION_TOGGLE: "reaction_toggle", + MESSAGE_PIN: "message_pin", + ROOM_UPDATE: "room_update", }); /** Eventos que o servidor envia. */ @@ -65,6 +71,10 @@ export const SERVER_EVENTS = Object.freeze({ DM_UPDATED: "dm_updated", DM_CLOSED: "dm_closed", BLOCK_LIST: "block_list", + MESSAGE_UPDATED: "message_updated", + MESSAGE_DELETED: "message_deleted", + MESSAGE_REACTIONS: "message_reactions", + PINS_UPDATED: "pins_updated", }); /** Tipos de conversa (o prefixo do `conversationId` diz qual é). */ @@ -143,4 +153,29 @@ export const ERROR_CODES = Object.freeze({ LOOKUP_LIMITED: "lookup_limited", DM_OPEN_LIMITED: "dm_open_limited", BLOCK_LIMIT: "block_limit", + MESSAGE_NOT_FOUND: "message_not_found", + NOT_ALLOWED: "not_allowed", + INVALID_REACTION: "invalid_reaction", + REACTION_LIMIT: "reaction_limit", + PIN_LIMIT: "pin_limit", + INVALID_DESCRIPTION: "invalid_description", }); + +/** + * Emojis de reação aceitos pelo servidor (lista fixa, sem texto livre). + * Espelho de `REACTION_EMOJIS` em `backend/src/room/messageOps.js`. + */ +export const REACTION_EMOJIS = Object.freeze([ + "👍", + "❤️", + "😂", + "🎉", + "😮", + "😢", + "🙏", + "🔥", + "👀", + "✅", + "❓", + "💯", +]); From bd7ea1b53eb8bce4cee401d267ded33d1bd020b4 Mon Sep 17 00:00:00 2001 From: Guilherme Cruz <100307080+https-shini@users.noreply.github.com> Date: Sat, 14 Nov 2026 04:38:30 +0000 Subject: [PATCH 2/4] =?UTF-8?q?feat(interface):=20responder,=20reagir,=20e?= =?UTF-8?q?ditar,=20apagar,=20fixadas,=20descri=C3=A7=C3=A3o=20e=20sil?= =?UTF-8?q?=C3=AAncio=20com=20prazo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - menu e barra da mensagem: Responder, Reagir (12 emojis), Editar (a própria), Fixar/Desafixar (quem modera; os dois na privada), Apagar com confirmação - barra "Respondendo a…" no campo; Esc cancela; citação clicável leva à original - ↑ no campo vazio edita a última mensagem; edição no lugar (Enter salva, Esc cancela) - reações com contagem e aria-pressed; marca (editada) e Fixada - painel: mensagens fixadas e descrição editável por quem modera; topo mostra a descrição - silêncio mostra até que horas; citações sem marcação e sem revelar spoiler - e2e/12-recursos.mjs; 09 acompanha o texto novo do silêncio --- e2e/09-painel.mjs | 3 +- e2e/12-recursos.mjs | 146 ++++++++++++ frontend/index.html | 31 +++ frontend/src/css/components/composer.css | 28 +++ frontend/src/css/components/members.css | 86 +++++++ frontend/src/css/components/message.css | 147 ++++++++++++ frontend/src/i18n/strings.js | 44 ++++ frontend/src/main.js | 281 ++++++++++++++++++++++- frontend/src/markdown/parse.js | 27 +++ frontend/src/state/events.js | 146 +++++++++++- frontend/src/state/store.js | 74 +++++- frontend/src/ui/composer.js | 18 ++ frontend/src/ui/contextPanel.js | 151 +++++++++++- frontend/src/ui/message.js | 190 ++++++++++++++- frontend/src/ui/messageList.js | 86 ++++++- frontend/src/ui/roomHeader.js | 2 +- frontend/test/markdown.test.js | 18 +- 17 files changed, 1441 insertions(+), 37 deletions(-) create mode 100644 e2e/12-recursos.mjs diff --git a/e2e/09-painel.mjs b/e2e/09-painel.mjs index 6f3345c..8e4c69d 100644 --- a/e2e/09-painel.mjs +++ b/e2e/09-painel.mjs @@ -60,7 +60,8 @@ export default async ({ open, enter, createRoom, user, ok, axe, RUN }) => { await ana.click('.c-menu--sub .c-menu__item:has-text("5 minutos")'); await caio.fill("#campo-mensagem", `silenciado ${RUN}`); await caio.press("#campo-mensagem", "Enter"); - await caio.waitForSelector('.c-toast:has-text("silenciad")'); + await caio.waitForSelector('.c-toast:has-text("silenciou você")'); + await caio.waitForSelector('.c-composer__notice[data-kind="muted"]'); ok(true, "silenciar por 5 minutos vale no servidor"); // Participante não vê moderação no menu. diff --git a/e2e/12-recursos.mjs b/e2e/12-recursos.mjs new file mode 100644 index 0000000..e990df8 --- /dev/null +++ b/e2e/12-recursos.mjs @@ -0,0 +1,146 @@ +// Recursos das mensagens (decisões F1 a F7): responder com citação, reagir, +// editar (inclusive com ↑ no campo vazio), apagar a própria e pela moderação, +// fixar e ver no painel, descrição da sala e silêncio com prazo. +export default async ({ open, enter, createRoom, user, ok, axe, RUN }) => { + const ana = await open({ viewport: { width: 1440, height: 900 } }); + await enter(ana, "Ana Souza", user("ana")); + const hash = await createRoom(ana, "Recursos"); + const bia = await open({ hash, viewport: { width: 1440, height: 900 } }); + const biaUser = user("bia"); + await enter(bia, "Bia Lima", biaUser); + /** @param {import("playwright").Page} page @param {string} text */ + const say = async (page, text) => { + await page.fill("#campo-mensagem", text); + await page.press("#campo-mensagem", "Enter"); + }; + /** @param {string} text */ + const msg = (text) => `.c-message:has-text("${text}")`; + + await say(bia, `original ${RUN} **forte** ||segredo||`); + // A resposta cita o texto da original: o seletor exclui quem tem citação. + const original = `${msg(`original ${RUN}`)}:not(:has(.c-message__reference))`; + await ana.waitForSelector(original); + + // Reagir pela barra: Bia vê a contagem e soma a dela. + await ana.hover(original); + await ana.click(`${original} .c-message-actions [aria-label="Reagir"]`); + await ana.click('.c-menu__item:has-text("👍")'); + await bia.waitForSelector(`${original} .c-reaction`); + await bia.click(`${original} .c-reaction`); + await ana.waitForSelector(`${original} .c-reaction:has-text("2")`); + ok( + (await ana.getAttribute(`${original} .c-reaction`, "aria-pressed")) === "true", + "reação: contagem compartilhada e aria-pressed para quem reagiu", + ); + await bia.click(`${original} .c-reaction`); + await ana.waitForSelector(`${original} .c-reaction:has-text("1")`); + ok(true, "reação: clicar de novo tira a sua"); + + // Responder: barra no campo, Esc cancela; depois envia com citação. + await ana.hover(original); + await ana.click(`${original} .c-message-actions [aria-label="Responder"]`); + ok(await ana.isVisible(".c-composer__reply"), "responder abre a barra acima do campo"); + await ana.press("#campo-mensagem", "Escape"); + ok(!(await ana.isVisible(".c-composer__reply")), "Esc cancela a resposta"); + await ana.hover(original); + await ana.click(`${original} .c-message-actions [aria-label="Responder"]`); + await say(ana, `resposta ${RUN}`); + const reply = msg(`resposta ${RUN}`); + await bia.waitForSelector(`${reply} .c-message__reference`); + const quoted = (await bia.textContent(`${reply} .c-message__reference`)) ?? ""; + ok( + quoted.includes(`original ${RUN} forte`) && + !quoted.includes("**") && + !quoted.includes("segredo"), + "citação sem marcação e sem revelar o spoiler", + ); + await bia.click(`${reply} .c-message__reference`); + await bia.waitForSelector(`${original}.c-message--flash`); + ok(true, "clicar na citação leva à mensagem original"); + + // Editar a última com ↑ no campo vazio. + await say(ana, `rascunho ${RUN}`); + await bia.waitForSelector(msg(`rascunho ${RUN}`)); + await ana.press("#campo-mensagem", "ArrowUp"); + await ana.waitForSelector(".c-message__editor-input"); + await ana.fill(".c-message__editor-input", `corrigido ${RUN}`); + await ana.press(".c-message__editor-input", "Enter"); + await bia.waitForSelector(`${msg(`corrigido ${RUN}`)} .c-message__edited`); + ok( + !(await bia.$(msg(`rascunho ${RUN}`))), + "↑ edita a última mensagem; os outros veem o texto novo e (editada)", + ); + + // Bia não pode editar a de Ana: o menu não oferece. + await bia.click(msg(`corrigido ${RUN}`), { button: "right" }); + await bia.waitForSelector('.c-menu[role="menu"]'); + const biaLabels = await bia.$$eval(".c-menu .c-menu__item", (xs) => + xs.map((x) => x.textContent?.trim() ?? ""), + ); + ok( + !biaLabels.some( + (l) => l.startsWith("Editar") || l.startsWith("Apagar") || l.startsWith("Fixar"), + ), + "participante não edita, não apaga e não fixa mensagem alheia", + ); + await bia.keyboard.press("Escape"); + + // Fixar (anfitriã): aparece no painel; clicar leva à mensagem. + await ana.click(original, { button: "right" }); + await ana.click('.c-menu__item:has-text("Fixar")'); + await bia.waitForSelector('[data-context-block="pins"]:not([hidden]) .c-pin'); + ok( + ((await bia.textContent(".c-pin__text")) ?? "").includes(`original ${RUN}`), + "fixada aparece no painel de todos", + ); + ok(!(await bia.$(".c-pin__remove")), "participante não desafixa"); + await ana.waitForSelector(`${original} .c-message__pinned`); + await ana.waitForTimeout(400); + const issues = await axe(ana); + ok(issues.length === 0, `recursos sem violações sérias ${issues.join("; ")}`); + + // Descrição: anfitriã edita; todos veem no topo. + await ana.click('.c-context__description button:has-text("Adicionar")'); + await ana.fill(".c-context__description-form textarea", `Sobre ${RUN}`); + await ana.click('.c-context__description-form button:has-text("Salvar")'); + await bia.waitForFunction( + (text) => document.querySelector("[data-room-topic]")?.textContent?.includes(text), + `Sobre ${RUN}`, + ); + ok( + !(await bia.$('.c-context__description button:has-text("Adicionar")')) && + !(await bia.$('.c-context__description button:has-text("Editar")')), + "descrição: todos veem, só quem modera edita", + ); + + // Apagar a própria (com confirmação). + await say(bia, `engano ${RUN}`); + await ana.waitForSelector(msg(`engano ${RUN}`)); + await bia.click(msg(`engano ${RUN}`), { button: "right" }); + await bia.click('.c-menu__item:has-text("Apagar")'); + await bia.click(".c-dialog__confirm"); + await ana.waitForSelector(msg(`engano ${RUN}`), { state: "detached" }); + ok(true, "apagar a própria some para todos"); + + // Moderação apaga a de outra pessoa; a fixada sai junto. + await ana.click(original, { button: "right" }); + await ana.click('.c-menu__item:has-text("Apagar")'); + await ana.click(".c-dialog__confirm"); + await bia.waitForSelector(original, { state: "detached" }); + await bia.waitForSelector('.c-message:has-text("removida pela moderação")'); + await bia.waitForSelector('[data-context-block="pins"][hidden]', { state: "attached" }); + ok(true, "moderação apaga, avisa e tira das fixadas"); + + // Silêncio com prazo: o campo diz até quando. + await ana.focus(`.c-member:has-text("Bia Lima")`); + await ana.keyboard.press("Shift+F10"); + await ana.click('.c-menu__item:has-text("Silenciar")'); + await ana.waitForSelector(".c-menu--sub"); + await ana.click('.c-menu--sub .c-menu__item:has-text("5 minutos")'); + await say(bia, `calada ${RUN}`); + await bia.waitForSelector('.c-composer__notice[data-kind="muted"]'); + const notice = (await bia.textContent(".c-composer__notice")) ?? ""; + ok(/até as \d{1,2}:\d{2}/.test(notice), `silêncio mostra o prazo: "${notice}"`); + await bia.waitForTimeout(300); + ok(!(await ana.$(msg(`calada ${RUN}`))), "mensagem silenciada não chega aos outros"); +}; diff --git a/frontend/index.html b/frontend/index.html index 7c2f59a..5104840 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -714,6 +714,19 @@

Conversa

+