diff --git a/README.md b/README.md index e2a15d6..e6b504d 100644 --- a/README.md +++ b/README.md @@ -288,6 +288,8 @@ DevOrbit was built in six sprints. Sprint 2 was split into pairs (one backend an | Part | Task | What we built | |---|---|---| +| M2 | Edit and delete DMs | In a direct conversation, hover your own message (always shown on touch screens) for **Edit** and **Delete**. An edited message shows *edited*; a deleted one stays in place as *Message deleted* for both people (its text is removed from the database), after a confirmation. The other person's messages cannot be changed: the API answers **403**. Changes appear live on both sides (`dm:updated`) and in the inbox line. `PATCH` / `DELETE /api/direct-messages/:conversationId/messages/:messageId` | +| M2 | Sent / Seen | Each of your messages shows **Sent**, then **Seen** once the other person has opened the conversation. Based on the read time already saved per person in the conversation, so it survives reloads; the sender is told live (`dm:seen`). Messages also carry `status`, and conversations `otherReadAt`. Messages from before Sprint 7 work unchanged | | M7 | Transfer ownership | The Owner makes another member the Owner (crown button in Team & roles, after confirming) and becomes an Admin, in one step, so a project always has exactly one Owner. The former Owner can then leave. Logged in the activity feed; both people's open pages switch role live. `POST /api/projects/:id/transfer-ownership` | | M7 | Overdue on the dashboard (FR-15) | The project Dashboard tab now also shows **overdue** tasks (open, due day passed), most overdue first with *N days overdue*, using the same rule as project health. Every member sees it | | M7 | D7 | The Dashboard's progress card shows the real **weekly goal**: *X of Y done* for your tasks due this week (Mon–Sun, UTC), instead of the fixed "4 of 5". `GET /api/tasks/stats` returns `weekGoal` | diff --git a/backend/src/lib/directMessageRules.js b/backend/src/lib/directMessageRules.js index ed69ea5..78b9f5a 100644 --- a/backend/src/lib/directMessageRules.js +++ b/backend/src/lib/directMessageRules.js @@ -24,8 +24,24 @@ export const DM_MESSAGES = { empty: 'Message cannot be empty.', tooLong: `Message must be ${DM_BODY_MAX.toLocaleString('en-US')} characters or fewer.`, tooFast: 'You are sending messages too quickly. Wait a moment and try again.', + // [Sprint 7 · M2] Edit and delete your own direct messages + invalidMessage: 'Invalid message ID.', + messageNotFound: 'Message not found.', + notSender: 'You can only edit or delete your own messages.', + editDeleted: 'This message was deleted, so it can no longer be edited.', + edited: 'Message updated.', + unchanged: 'Nothing changed.', + deleted: 'Message deleted.', + alreadyDeleted: 'This message was already deleted.', }; +// [Sprint 7 · M2] What a deleted message shows instead of its text (in the conversation and the inbox). +export const DM_DELETED_TEXT = 'Message deleted'; + +// [Sprint 7 · M2] Delivery status of my own messages: 'sent' until the other person has opened the +// conversation after it arrived, then 'seen'. +export const DM_STATUS = Object.freeze({ sent: 'sent', seen: 'seen' }); + export const idOf = (value) => String(value?._id || value || ''); // One conversation per pair of users, whoever opens it first: "a:b" with the smaller ID first. @@ -98,19 +114,66 @@ export function userView(user) { return { _id: idOf(user), name: user.name, username: user.username || '', avatarUrl: user.avatarUrl || '' }; } -export function messageView(message) { +/* + * [Sprint 7 · M2] true when the message was sent before (or at) the moment the other person last read the + * conversation, i.e. they have seen it. `readAt` comes from conversation.reads (readAtFor), which only moves + * forward, so once a message is seen it stays seen. + */ +export function isSeenAt(message, readAt) { + if (!message?.createdAt || !readAt) return false; + const sent = new Date(message.createdAt).getTime(); + const read = new Date(readAt).getTime(); + return Number.isFinite(sent) && Number.isFinite(read) && sent <= read; +} + +export function isMessageSender(message, userId) { + const sender = idOf(message?.sender); + return Boolean(sender) && sender === idOf(userId); +} + +/* + * One message as the browser sees it: + * { _id, conversation, sender, body, createdAt, edited, editedAt, deleted, deletedAt, status } + * [Sprint 7 · M2] + * - deleted: the text is never sent again (body ''); the browser shows "Message deleted" in its place. + * - edited / editedAt: the sender changed the text; shown as "edited". A deleted message is not "edited". + * - status: only on the viewer's own messages: 'sent' or 'seen' (otherReadAt = when the other person last + * read the conversation). null on the other person's messages, and when no viewer is given. + * Messages saved before Sprint 7 (no editedAt / deletedAt) come out as not edited and not deleted. + */ +export function messageView(message, { viewerId = null, otherReadAt = null } = {}) { + const deleted = Boolean(message.deletedAt); + const mine = Boolean(viewerId) && isMessageSender(message, viewerId); + let status = null; + if (mine) status = isSeenAt(message, otherReadAt) ? DM_STATUS.seen : DM_STATUS.sent; return { _id: idOf(message), conversation: idOf(message.conversation), sender: userView(message.sender), - body: message.body, + body: deleted ? '' : message.body, createdAt: message.createdAt, + edited: !deleted && Boolean(message.editedAt), + editedAt: deleted ? null : message.editedAt || null, + deleted, + deletedAt: message.deletedAt || null, + status, }; } +// [Sprint 7 · M2] The inbox line for a message: its text, or "Message deleted". +export function messagePreview(message) { + return message?.deletedAt ? DM_DELETED_TEXT : previewOf(message?.body); +} + +// [Sprint 7 · M2] When the other person (not `meId`) last read the conversation, or null. +export function otherReadAtFor(conversation, meId) { + const other = otherParticipant(conversation, meId); + return other ? readAtFor(conversation, other) : null; +} + /* * One inbox row / conversation header, as seen by `meId`: - * { _id, otherUser, lastMessage: { preview, at, fromMe } | null, unreadCount, activityAt, createdAt } + * { _id, otherUser, lastMessage: { preview, at, fromMe } | null, unreadCount, otherReadAt, activityAt, createdAt } * The two participants each get their own view (different otherUser and unreadCount). */ export function conversationView(conversation, meId, unreadCount = 0) { @@ -126,6 +189,8 @@ export function conversationView(conversation, meId, unreadCount = 0) { } : null, unreadCount: Number.isFinite(count) && count > 0 ? Math.floor(count) : 0, + // [Sprint 7 · M2] When the other person last read it: my messages up to this time show "Seen". + otherReadAt: otherReadAtFor(conversation, meId), activityAt: conversation.activityAt || conversation.createdAt || null, createdAt: conversation.createdAt || null, }; @@ -167,5 +232,7 @@ export function createSendLimiter({ limit = DM_SEND_LIMIT, windowMs = DM_SEND_WI * Small pure helpers for direct messages (US-19): one key per pair of users, * message checks (text, not empty, at most 4,000 characters), inbox previews, * the safe views sent to the browser and the per-user send limit. + * [Sprint 7 · M2] Also: edited / deleted messages ("edited", "Message deleted") + * and the Sent / Seen status of the viewer's own messages. * --------------------------------------------------------------------------- */ diff --git a/backend/src/lib/directMessages.js b/backend/src/lib/directMessages.js index 72dbf74..610dd29 100644 --- a/backend/src/lib/directMessages.js +++ b/backend/src/lib/directMessages.js @@ -8,8 +8,10 @@ import { conversationView, idOf, mayHaveUnread, + messagePreview, messageView, otherParticipant, + otherReadAtFor, pairKeyOf, previewOf, readAtFor, @@ -58,7 +60,8 @@ export async function openConversation(meId, otherId) { export async function unreadCountFor(conversation, userId) { if (!mayHaveUnread(conversation, userId)) return 0; const readAt = readAtFor(conversation, userId); - const filter = { conversation: conversation._id, sender: { $ne: objectId(userId) } }; + // [Sprint 7 · M2] A message deleted before it was read no longer counts as unread. + const filter = { conversation: conversation._id, sender: { $ne: objectId(userId) }, deletedAt: null }; if (readAt) filter.createdAt = { $gt: readAt }; return DirectMessage.countDocuments(filter); } @@ -93,9 +96,11 @@ export async function inboxFor(userId) { /* * One page of messages, oldest first, like project chat. `before` = the ID of the oldest message the * browser already has; ties on the same millisecond are broken by ID so no message is skipped or repeated. - * -> { messages, nextBefore } or null when `before` is not a message of this conversation. + * [Sprint 7 · M2] `viewerId` = who is reading: their own messages get status 'sent' / 'seen', and the page + * carries otherReadAt (when the other person last read) so the browser can keep the marks up to date. + * -> { messages, nextBefore, otherReadAt } or null when `before` is not a message of this conversation. */ -export async function messagePage(conversation, { limit, before } = {}) { +export async function messagePage(conversation, { limit, before, viewerId = null } = {}) { const filter = { conversation: conversation._id }; if (before) { const anchor = await DirectMessage.findOne({ _id: before, conversation: conversation._id }).select('_id createdAt').lean(); @@ -109,23 +114,39 @@ export async function messagePage(conversation, { limit, before } = {}) { .lean(); const page = rows.slice(0, limit); const nextBefore = rows.length > limit ? idOf(page[page.length - 1]) : null; - return { messages: page.reverse().map(messageView), nextBefore }; + const otherReadAt = viewerId ? otherReadAtFor(conversation, viewerId) : null; + return { + messages: page.reverse().map((message) => messageView(message, { viewerId, otherReadAt })), + nextBefore, + otherReadAt, + }; } /* * Marks everything up to the newest message as read for this user. $max: a slow request can never move * the read time backwards. Tells the user's other tabs, so their badges drop too. - * -> { unreadCount: 0, unreadTotal } + * [Sprint 7 · M2] The read time is saved in the conversation (reads.), so "Seen" survives reloads. + * The other person gets 'dm:seen' { conversationId, readAt } at once: their messages sent up to readAt + * turn from "Sent" to "Seen". + * -> { unreadCount: 0, unreadTotal } (the same answer as in Sprint 6) */ export async function markRead(conversation, userId) { + let readAt = readAtFor(conversation, userId); if (conversation.lastMessageAt) { - await DirectConversation.updateOne( + const updated = await DirectConversation.findOneAndUpdate( { _id: conversation._id }, - { $max: { [`reads.${idOf(userId)}`]: new Date(conversation.lastMessageAt) } } - ); + { $max: { [`reads.${idOf(userId)}`]: new Date(conversation.lastMessageAt) } }, + { new: true } + ) + .select('reads') + .lean(); + readAt = readAtFor(updated, userId) || readAt; } const unreadTotal = await unreadTotalFor(userId); - emitToUser(userId, 'dm:read', { conversationId: idOf(conversation), unreadTotal }); + const conversationId = idOf(conversation); + emitToUser(userId, 'dm:read', { conversationId, unreadTotal }); + const other = otherParticipant(conversation, userId); + if (other && readAt) emitToUser(idOf(other), 'dm:seen', { conversationId, readAt }); return { unreadCount: 0, unreadTotal }; } @@ -155,7 +176,9 @@ export async function sendMessage(conversation, senderId, body) { DirectConversation.findById(conversation._id).populate('participants', DM_USER_FIELDS).lean(), DirectMessage.findById(created._id).populate('sender', DM_USER_FIELDS).lean(), ]); + // [Sprint 7 · M2] The recipient sees a plain message; the sender sees it with status 'sent'. const message = messageView(populated); + const senderMessage = messageView(populated, { viewerId: sender, otherReadAt: otherReadAtFor(updated, sender) }); const conversationId = idOf(conversation); const [recipientUnread, recipientTotal, senderTotal] = await Promise.all([ @@ -170,9 +193,114 @@ export async function sendMessage(conversation, senderId, body) { unreadTotal: recipientTotal, }); const senderView = conversationView(updated, sender, 0); - emitToUser(sender, 'dm:message', { conversationId, message, conversation: senderView, unreadTotal: senderTotal }); + emitToUser(sender, 'dm:message', { conversationId, message: senderMessage, conversation: senderView, unreadTotal: senderTotal }); + + return { message: senderMessage, conversation: senderView }; +} + +/* + * [Sprint 7 · M2] Edit and delete your own direct messages. + * + * Both are single atomic updates that only match the sender's own, not-yet-deleted message, so an edit + * racing a delete can never bring the text back. The routes check who may do it first (403 for the other + * person); the filters here are a second guard. + * + * After a change both participants get 'dm:updated' { conversationId, message, conversation, unreadTotal } + * in their own rooms (nobody else), so the message changes live on both sides and in every open tab. + */ + +// The message with this ID in this conversation (any sender), or null. +export function findMessageIn(conversation, messageId) { + return DirectMessage.findOne({ _id: messageId, conversation: conversation._id }).lean(); +} + +/* + * When the changed message is the newest one, the inbox line follows it (new text, or "Message deleted"). + * The filter on lastMessageAt makes this a no-op if a newer message arrived in the meantime. + */ +async function refreshInboxPreview(conversation, messageId) { + const newest = await DirectMessage.findOne({ conversation: conversation._id }) + .sort({ createdAt: -1, _id: -1 }) + .select('_id body deletedAt createdAt') + .lean(); + if (!newest || idOf(newest) !== idOf(messageId)) return; + await DirectConversation.updateOne( + { _id: conversation._id, lastMessageAt: newest.createdAt }, + { $set: { lastMessagePreview: messagePreview(newest) } } + ); +} - return { message, conversation: senderView }; +// The message and conversation as they are now, as `viewerId` sees them (used when nothing changed). +async function currentView(conversation, messageId, viewerId) { + const [populated, fresh] = await Promise.all([ + DirectMessage.findById(messageId).populate('sender', DM_USER_FIELDS).lean(), + DirectConversation.findById(conversation._id).populate('participants', DM_USER_FIELDS).lean(), + ]); + const unread = await unreadCountFor(fresh, viewerId); + return { + message: messageView(populated, { viewerId, otherReadAt: otherReadAtFor(fresh, viewerId) }), + conversation: conversationView(fresh, viewerId, unread), + }; +} + +// Sends the changed message to both participants and returns what the person who changed it sees. +async function announceChange(conversation, messageId, actorId) { + const actor = objectId(actorId); + const other = otherParticipant(conversation, actor); + const [updated, populated] = await Promise.all([ + DirectConversation.findById(conversation._id).populate('participants', DM_USER_FIELDS).lean(), + DirectMessage.findById(messageId).populate('sender', DM_USER_FIELDS).lean(), + ]); + const conversationId = idOf(conversation); + const people = [actor, ...(other ? [objectId(other)] : [])]; + const views = await Promise.all( + people.map(async (person) => { + const [unread, unreadTotal] = await Promise.all([unreadCountFor(updated, person), unreadTotalFor(person)]); + return { + person, + payload: { + conversationId, + message: messageView(populated, { viewerId: person, otherReadAt: otherReadAtFor(updated, person) }), + conversation: conversationView(updated, person, unread), + unreadTotal, + }, + }; + }) + ); + for (const { person, payload } of views) emitToUser(person, 'dm:updated', payload); + const mine = views[0].payload; + return { message: mine.message, conversation: mine.conversation }; +} + +/* + * The sender changes the text. Saving the same text again is not an edit (no "edited" mark, no event). + * -> { changed: true | false, message, conversation } or { changed: false, deleted: true } when the message + * was deleted in the meantime. + */ +export async function editMessage(conversation, message, editorId, body) { + if (message.body === body && !message.deletedAt) return { changed: false, ...(await currentView(conversation, message._id, editorId)) }; + const result = await DirectMessage.updateOne( + { _id: message._id, conversation: conversation._id, sender: objectId(editorId), deletedAt: null }, + { $set: { body, editedAt: new Date() } } + ); + if (!result.matchedCount) return { changed: false, deleted: true }; + await refreshInboxPreview(conversation, message._id); + return { changed: true, ...(await announceChange(conversation, message._id, editorId)) }; +} + +/* + * The sender deletes the message. The row stays (so the conversation still reads in order and replies + * keep their context) as "Message deleted"; its text is removed from the database. Deleting it again + * changes nothing. -> { changed, message, conversation } + */ +export async function deleteMessage(conversation, message, senderId) { + const result = await DirectMessage.updateOne( + { _id: message._id, conversation: conversation._id, sender: objectId(senderId), deletedAt: null }, + { $set: { deletedAt: new Date(), body: '', editedAt: null } } + ); + if (!result.matchedCount) return { changed: false, ...(await currentView(conversation, message._id, senderId)) }; + await refreshInboxPreview(conversation, message._id); + return { changed: true, ...(await announceChange(conversation, message._id, senderId)) }; } /* @@ -182,5 +310,7 @@ export async function sendMessage(conversation, senderId, body) { * between two users, list a user's inbox with unread counts, read pages of * messages, send a message (saved, then pushed live to the two participants * only) and mark a conversation read. + * [Sprint 7 · M2] Edit and delete your own messages (pushed live as + * 'dm:updated'), and tell the sender when their messages were seen ('dm:seen'). * --------------------------------------------------------------------------- */ diff --git a/backend/src/models/DirectMessage.js b/backend/src/models/DirectMessage.js index 3679a31..bad6adc 100644 --- a/backend/src/models/DirectMessage.js +++ b/backend/src/models/DirectMessage.js @@ -1,6 +1,11 @@ import mongoose from 'mongoose'; import { DM_BODY_MAX } from '../lib/directMessageRules.js'; +// [Sprint 7 · M2] A deleted message keeps its row (so the conversation still reads in order) but not its text. +function bodyRequired() { + return !this.deletedAt; +} + /* * [Sprint 6 · M2] US-19 One message in a direct conversation (models/DirectConversation.js). * Kept apart from project channel messages (models/Message.js): a different collection with no project @@ -10,7 +15,11 @@ const directMessageSchema = new mongoose.Schema( { conversation: { type: mongoose.Schema.Types.ObjectId, ref: 'DirectConversation', required: true }, sender: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }, - body: { type: String, required: true, trim: true, maxlength: DM_BODY_MAX }, + body: { type: String, required: bodyRequired, trim: true, maxlength: DM_BODY_MAX, default: '' }, + // [Sprint 7 · M2] Edit and delete your own messages. Messages saved before Sprint 7 have neither field, + // which reads as "not edited, not deleted" (a missing field matches `null` in MongoDB queries). + editedAt: { type: Date, default: null }, // set when the sender changes the text ("edited") + deletedAt: { type: Date, default: null }, // set when the sender deletes it; body is emptied ("Message deleted") }, { timestamps: { createdAt: true, updatedAt: false } } ); diff --git a/backend/src/routes/directMessages.js b/backend/src/routes/directMessages.js index 43c2b31..b2437b2 100644 --- a/backend/src/routes/directMessages.js +++ b/backend/src/routes/directMessages.js @@ -10,11 +10,15 @@ import { createSendLimiter, conversationView, idOf, + isMessageSender, otherParticipant, readBody, readLimit, } from '../lib/directMessageRules.js'; import { + deleteMessage, + editMessage, + findMessageIn, inboxFor, loadConversationFor, markRead, @@ -40,14 +44,30 @@ import { * 400 empty / too long / not text, 429 after 30 messages in a minute * (Retry-After header), 410 the other account no longer exists * POST /:conversationId/read -> { unreadCount: 0, unreadTotal } + * [Sprint 7 · M2] also tells the other person 'dm:seen' { conversationId, readAt } + * (their messages up to readAt now show "Seen"). The read time is saved in the + * conversation, so "Seen" survives reloads (otherReadAt / status below). + * PATCH /:conversationId/messages/:messageId { body } -> 200 { message, conversation, changed, notice } + * [Sprint 7 · M2] edit your own message ("edited"). Same text rules as sending. + * Same text again -> 200 changed: false (no "edited" mark). + * 400 invalid ID / empty / too long, 403 not your message, + * 404 unknown message, 409 { code: 'message_deleted' } it was deleted. + * DELETE /:conversationId/messages/:messageId -> 200 { message, conversation, changed, notice } + * [Sprint 7 · M2] delete your own message. It stays in the conversation as + * "Message deleted" (deleted: true, body ''); its text is removed. + * Already deleted -> 200 changed: false. 403 not your message, 404 unknown. * * conversation = { _id, otherUser: { _id, name, username, avatarUrl }, lastMessage: { preview, at, fromMe } | null, - * unreadCount, activityAt, createdAt } - * message = { _id, conversation, sender: { _id, name, username, avatarUrl }, body, createdAt } + * unreadCount, otherReadAt, activityAt, createdAt } + * message = { _id, conversation, sender: { _id, name, username, avatarUrl }, body, createdAt, + * edited, editedAt, deleted, deletedAt, status } + * status ('sent' | 'seen') is only on the caller's own messages; null on the other person's. + * GET /:conversationId/messages also returns otherReadAt (when the other person last read the conversation). * * AC2 privacy: only the two participants can read a conversation. Anyone else gets 404, the same answer as * for a conversation that does not exist, so its existence is not revealed either. Live events - * ('dm:message', 'dm:read', lib/realtime.js) go only to the participants' own rooms. + * ('dm:message', 'dm:read', and [Sprint 7 · M2] 'dm:updated', 'dm:seen'; lib/realtime.js) go only to the + * participants' own rooms. [Sprint 7 · M2] The other participant trying to edit or delete my message gets 403. * Separate from project channels (AC1): nothing here touches projects, channels or the Activity Feed. */ @@ -125,7 +145,7 @@ router.get('/:conversationId/messages', async (req, res, next) => { const { before } = req.query; if (before !== undefined && !validId(before)) return res.status(400).json({ message: DM_MESSAGES.invalidBefore }); - const page = await messagePage(conversation, { limit: readLimit(req.query.limit), before }); + const page = await messagePage(conversation, { limit: readLimit(req.query.limit), before, viewerId: req.user.id }); if (!page) return res.status(400).json({ message: DM_MESSAGES.invalidBefore }); return res.json(page); } catch (error) { @@ -159,6 +179,72 @@ router.post('/:conversationId/messages', async (req, res, next) => { } }); +/* + * [Sprint 7 · M2] The message in the URL, for its sender only. + * 400 bad ID, 404 not a message of this conversation, 403 someone else's message. Returns null after answering. + */ +async function ownMessageFromUrl(req, res, conversation) { + if (!validId(req.params.messageId)) { + res.status(400).json({ message: DM_MESSAGES.invalidMessage }); + return null; + } + const message = await findMessageIn(conversation, req.params.messageId); + if (!message) { + res.status(404).json({ message: DM_MESSAGES.messageNotFound }); + return null; + } + if (!isMessageSender(message, req.user.id)) { + res.status(403).json({ message: DM_MESSAGES.notSender, code: 'not_sender' }); + return null; + } + return message; +} + +// [Sprint 7 · M2] Edit my own message. +router.patch('/:conversationId/messages/:messageId', async (req, res, next) => { + try { + const conversation = await conversationFromUrl(req, res); + if (!conversation) return undefined; + const message = await ownMessageFromUrl(req, res, conversation); + if (!message) return undefined; + if (message.deletedAt) return res.status(409).json({ message: DM_MESSAGES.editDeleted, code: 'message_deleted' }); + + const checked = readBody(req.body?.body); + if (!checked.ok) return res.status(400).json({ message: checked.message }); + + const result = await editMessage(conversation, message, req.user.id, checked.body); + if (result.deleted) return res.status(409).json({ message: DM_MESSAGES.editDeleted, code: 'message_deleted' }); + return res.json({ + message: result.message, + conversation: result.conversation, + changed: result.changed, + notice: result.changed ? DM_MESSAGES.edited : DM_MESSAGES.unchanged, + }); + } catch (error) { + return next(error); + } +}); + +// [Sprint 7 · M2] Delete my own message (it stays as "Message deleted"). +router.delete('/:conversationId/messages/:messageId', async (req, res, next) => { + try { + const conversation = await conversationFromUrl(req, res); + if (!conversation) return undefined; + const message = await ownMessageFromUrl(req, res, conversation); + if (!message) return undefined; + + const result = await deleteMessage(conversation, message, req.user.id); + return res.json({ + message: result.message, + conversation: result.conversation, + changed: result.changed, + notice: result.changed ? DM_MESSAGES.deleted : DM_MESSAGES.alreadyDeleted, + }); + } catch (error) { + return next(error); + } +}); + router.post('/:conversationId/read', async (req, res, next) => { try { const conversation = await conversationFromUrl(req, res); @@ -178,5 +264,7 @@ export default router; * on a profile (open or create the conversation), reading and sending messages * and marking a conversation read. Only the two people in a conversation can * use it; everyone else gets 404. + * [Sprint 7 · M2] Also: edit and delete your own messages (the other person + * gets 403) and Sent / Seen marks on your own messages. * --------------------------------------------------------------------------- */ diff --git a/backend/test/directMessageEdits.test.js b/backend/test/directMessageEdits.test.js new file mode 100644 index 0000000..dee4b38 --- /dev/null +++ b/backend/test/directMessageEdits.test.js @@ -0,0 +1,430 @@ +// [Sprint 7 · M2] Edit and delete your own direct messages, and Sent / Seen, against a real MongoDB. +// - Edit: own messages only (403 for the other person), "edited" mark, same text rules as sending. +// - Delete: own messages only (403), the message stays as "Message deleted" with its text removed. +// - Sent / Seen: my own messages are 'sent' until the other person opens the conversation, then 'seen'; +// the read time is stored, so it survives reloads. +// Live delivery of these changes is in directMessageEditsRealtime.test.js. +import { test, before, after, beforeEach } from 'node:test'; +import assert from 'node:assert/strict'; +import request from 'supertest'; +import mongoose from 'mongoose'; +import { setup, teardown, signup, authed } from './helpers.js'; +import DirectConversation from '../src/models/DirectConversation.js'; +import DirectMessage from '../src/models/DirectMessage.js'; +import { DM_BODY_MAX, DM_MESSAGES } from '../src/lib/directMessageRules.js'; +import { dmSendLimiter } from '../src/routes/directMessages.js'; + +const BASE = '/api/direct-messages'; +let app; +let alice, bob, carol; + +const as = (account) => authed(app, account.token); +const messageUrl = (conversationId, messageId) => `${BASE}/${conversationId}/messages/${messageId}`; +const edit = (who, conversationId, messageId, body) => as(who).patch(messageUrl(conversationId, messageId)).send({ body }); +const remove = (who, conversationId, messageId) => as(who).delete(messageUrl(conversationId, messageId)); + +async function conversationBetween(a, b) { + const res = await as(a).post(BASE).send({ username: b.user.username }); + assert.equal(res.status, 200, JSON.stringify(res.body)); + return res.body.conversation._id; +} +async function sendOk(from, conversationId, body) { + const res = await as(from).post(`${BASE}/${conversationId}/messages`).send({ body }); + assert.equal(res.status, 201, JSON.stringify(res.body)); + return res.body.message; +} +async function page(who, conversationId) { + const res = await as(who).get(`${BASE}/${conversationId}/messages`); + assert.equal(res.status, 200, JSON.stringify(res.body)); + return res.body; +} +async function inboxRow(who, conversationId) { + const res = await as(who).get(BASE); + assert.equal(res.status, 200, JSON.stringify(res.body)); + return res.body.conversations.find((row) => row._id === conversationId); +} +const unreadTotal = async (who) => (await as(who).get(`${BASE}/unread-count`)).body.unreadTotal; +const pause = (ms) => + new Promise((resolve) => { + setTimeout(resolve, ms); + }); + +before(async () => { + ({ app } = await setup()); + [alice, bob, carol] = await Promise.all(['Alice Editor', 'Bob Reader', 'Carol Outsider'].map((name) => signup(app, name))); +}); + +beforeEach(async () => { + await Promise.all([DirectConversation.deleteMany({}), DirectMessage.deleteMany({})]); + dmSendLimiter.reset(); +}); + +after(teardown); + +// --- Login ----------------------------------------------------------------------------------------- + +test('[Sprint 7 · M2] login is required to edit or delete a message', async () => { + const url = messageUrl('64b000000000000000000001', '64b000000000000000000002'); + assert.equal((await request(app).patch(url).send({ body: 'x' })).status, 401); + assert.equal((await request(app).delete(url)).status, 401); +}); + +// --- Edit ------------------------------------------------------------------------------------------ + +test('[Sprint 7 · M2] the sender edits a message: saved, marked "edited", and the other person sees the new text', async () => { + const id = await conversationBetween(alice, bob); + const sent = await sendOk(alice, id, 'See you at 4'); + assert.equal(sent.edited, false); + assert.equal(sent.deleted, false); + + const res = await edit(alice, id, sent._id, ' See you at 5 '); + assert.equal(res.status, 200, JSON.stringify(res.body)); + assert.equal(res.body.changed, true); + assert.equal(res.body.notice, DM_MESSAGES.edited); + assert.equal(res.body.message._id, sent._id); + assert.equal(res.body.message.body, 'See you at 5', 'trimmed like a new message'); + assert.equal(res.body.message.edited, true); + assert.ok(res.body.message.editedAt); + assert.equal(res.body.message.createdAt, sent.createdAt, 'the time it was sent does not change'); + + // Stored in the database. + const saved = await DirectMessage.findById(sent._id).lean(); + assert.equal(saved.body, 'See you at 5'); + assert.ok(saved.editedAt instanceof Date); + assert.equal(saved.deletedAt, null); + + // Bob sees the new text and the "edited" mark after a reload; still one message. + const forBob = await page(bob, id); + assert.equal(forBob.messages.length, 1); + assert.equal(forBob.messages[0].body, 'See you at 5'); + assert.equal(forBob.messages[0].edited, true); +}); + +test('[Sprint 7 · M2] saving the same text again is not an edit', async () => { + const id = await conversationBetween(alice, bob); + const sent = await sendOk(alice, id, 'No change'); + const res = await edit(alice, id, sent._id, 'No change'); + assert.equal(res.status, 200, JSON.stringify(res.body)); + assert.equal(res.body.changed, false); + assert.equal(res.body.message.edited, false); + assert.equal((await DirectMessage.findById(sent._id).lean()).editedAt, null); +}); + +test('[Sprint 7 · M2] an edit follows the same text rules as sending (NFR-21); a refused edit changes nothing', async () => { + const id = await conversationBetween(alice, bob); + const sent = await sendOk(alice, id, 'Original'); + const cases = [ + [undefined, DM_MESSAGES.empty], + [' ', DM_MESSAGES.empty], + [{ $set: 'x' }, DM_MESSAGES.notText], + [42, DM_MESSAGES.notText], + ['x'.repeat(DM_BODY_MAX + 1), DM_MESSAGES.tooLong], + ]; + for (const [body, message] of cases) { + const res = await as(alice) + .patch(messageUrl(id, sent._id)) + .send(body === undefined ? {} : { body }); + assert.equal(res.status, 400, `${JSON.stringify(body)?.slice(0, 30)} -> ${res.status}`); + assert.equal(res.body.message, message); + } + assert.equal((await edit(alice, id, sent._id, 'x'.repeat(DM_BODY_MAX))).status, 200, 'exactly 4,000 characters is fine'); + const saved = await DirectMessage.findById(sent._id).lean(); + assert.equal(saved.body.length, DM_BODY_MAX); +}); + +test("[Sprint 7 · M2] editing or deleting the other person's message is refused with 403 and changes nothing", async () => { + const id = await conversationBetween(alice, bob); + const fromAlice = await sendOk(alice, id, 'Only Alice may change this'); + + const editByBob = await edit(bob, id, fromAlice._id, 'Bob was here'); + assert.equal(editByBob.status, 403); + assert.equal(editByBob.body.message, DM_MESSAGES.notSender); + assert.equal(editByBob.body.code, 'not_sender'); + + const deleteByBob = await remove(bob, id, fromAlice._id); + assert.equal(deleteByBob.status, 403); + assert.equal(deleteByBob.body.message, DM_MESSAGES.notSender); + + const saved = await DirectMessage.findById(fromAlice._id).lean(); + assert.equal(saved.body, 'Only Alice may change this'); + assert.equal(saved.editedAt, null); + assert.equal(saved.deletedAt, null); +}); + +test('[Sprint 7 · M2] someone outside the conversation gets 404 (its existence is not revealed); bad and unknown IDs', async () => { + const id = await conversationBetween(alice, bob); + const sent = await sendOk(alice, id, 'Private'); + + assert.equal((await edit(carol, id, sent._id, 'Carol')).status, 404); + assert.equal((await remove(carol, id, sent._id)).status, 404); + + const badId = await edit(alice, id, 'not-an-id', 'x'); + assert.equal(badId.status, 400); + assert.equal(badId.body.message, DM_MESSAGES.invalidMessage); + assert.equal((await remove(alice, id, 'not-an-id')).status, 400); + + const unknown = await edit(alice, id, '64b0000000000000000000ff', 'x'); + assert.equal(unknown.status, 404); + assert.equal(unknown.body.message, DM_MESSAGES.messageNotFound); + assert.equal((await remove(alice, id, '64b0000000000000000000ff')).status, 404); + + // A message of another conversation cannot be reached through this one. + const other = await conversationBetween(alice, carol); + const elsewhere = await sendOk(alice, other, 'To Carol'); + assert.equal((await edit(alice, id, elsewhere._id, 'moved?')).status, 404); + assert.equal((await remove(alice, id, elsewhere._id)).status, 404); + assert.equal((await DirectMessage.findById(elsewhere._id).lean()).body, 'To Carol'); + assert.equal((await DirectMessage.findById(sent._id).lean()).body, 'Private'); +}); + +// --- Delete ---------------------------------------------------------------------------------------- + +test('[Sprint 7 · M2] delete: the message stays in place as "Message deleted", its text is removed', async () => { + const id = await conversationBetween(alice, bob); + const first = await sendOk(alice, id, 'one'); + await pause(5); + const second = await sendOk(alice, id, 'two (oops)'); + await pause(5); + const third = await sendOk(bob, id, 'three'); + + const res = await remove(alice, id, second._id); + assert.equal(res.status, 200, JSON.stringify(res.body)); + assert.equal(res.body.changed, true); + assert.equal(res.body.notice, DM_MESSAGES.deleted); + assert.equal(res.body.message.deleted, true); + assert.equal(res.body.message.body, ''); + assert.ok(res.body.message.deletedAt); + + const saved = await DirectMessage.findById(second._id).lean(); + assert.ok(saved, 'the row is kept so the conversation still reads in order'); + assert.equal(saved.body, '', 'the text is removed from the database'); + assert.ok(saved.deletedAt instanceof Date); + + for (const who of [alice, bob]) { + const { messages } = await page(who, id); + assert.deepEqual( + messages.map((message) => message._id), + [first._id, second._id, third._id], + 'same messages, same order' + ); + assert.deepEqual( + messages.map((message) => [message.body, message.deleted]), + [ + ['one', false], + ['', true], + ['three', false], + ] + ); + assert.equal(JSON.stringify(messages).includes('oops'), false, 'the deleted text is never sent'); + } +}); + +test('[Sprint 7 · M2] deleting twice changes nothing; a deleted message can no longer be edited (409)', async () => { + const id = await conversationBetween(alice, bob); + const sent = await sendOk(alice, id, 'temporary'); + assert.equal((await remove(alice, id, sent._id)).status, 200); + const deletedAt = (await DirectMessage.findById(sent._id).lean()).deletedAt; + + const again = await remove(alice, id, sent._id); + assert.equal(again.status, 200); + assert.equal(again.body.changed, false); + assert.equal(again.body.notice, DM_MESSAGES.alreadyDeleted); + assert.equal(again.body.message.deleted, true); + assert.equal((await DirectMessage.findById(sent._id).lean()).deletedAt.getTime(), deletedAt.getTime()); + + const editDeleted = await edit(alice, id, sent._id, 'back again'); + assert.equal(editDeleted.status, 409); + assert.equal(editDeleted.body.code, 'message_deleted'); + assert.equal(editDeleted.body.message, DM_MESSAGES.editDeleted); + assert.equal((await DirectMessage.findById(sent._id).lean()).body, ''); + + // Bob still gets 403, not 409, for Alice's deleted message. + assert.equal((await edit(bob, id, sent._id, 'x')).status, 403); +}); + +test('[Sprint 7 · M2] an edited message that is then deleted is shown only as deleted', async () => { + const id = await conversationBetween(alice, bob); + const sent = await sendOk(alice, id, 'draft'); + assert.equal((await edit(alice, id, sent._id, 'draft v2')).status, 200); + const res = await remove(alice, id, sent._id); + assert.equal(res.body.message.deleted, true); + assert.equal(res.body.message.edited, false); + assert.equal(res.body.message.body, ''); +}); + +test('[Sprint 7 · M2] an edit and a delete at the same moment never bring the text back', async () => { + const id = await conversationBetween(alice, bob); + const sent = await sendOk(alice, id, 'race'); + const results = await Promise.all([edit(alice, id, sent._id, 'race edited'), remove(alice, id, sent._id)]); + assert.ok( + results.every((res) => [200, 409].includes(res.status)), + results.map((res) => res.status).join(',') + ); + const saved = await DirectMessage.findById(sent._id).lean(); + assert.ok(saved.deletedAt, 'the delete always wins'); + assert.equal(saved.body, ''); +}); + +// --- Inbox line and unread counts ------------------------------------------------------------------ + +test('[Sprint 7 · M2] the inbox line follows the newest message: edited text, or "Message deleted"', async () => { + const id = await conversationBetween(alice, bob); + const older = await sendOk(alice, id, 'older'); + await pause(5); + const newest = await sendOk(alice, id, 'newest'); + + await edit(alice, id, older._id, 'older, edited'); + assert.equal((await inboxRow(bob, id)).lastMessage.preview, 'newest', 'editing an older message leaves the inbox line alone'); + + await edit(alice, id, newest._id, 'newest, edited'); + assert.equal((await inboxRow(bob, id)).lastMessage.preview, 'newest, edited'); + assert.equal((await inboxRow(alice, id)).lastMessage.preview, 'newest, edited'); + + const before = await DirectConversation.findById(id).lean(); + await remove(alice, id, newest._id); + const bobRow = await inboxRow(bob, id); + assert.equal(bobRow.lastMessage.preview, 'Message deleted'); + assert.equal(bobRow.lastMessage.fromMe, false); + const after = await DirectConversation.findById(id).lean(); + assert.equal(after.activityAt.getTime(), before.activityAt.getTime(), 'edits and deletes do not move the conversation up'); +}); + +test('[Sprint 7 · M2] deleting a message the other person had not read yet removes it from their unread count', async () => { + const id = await conversationBetween(alice, bob); + const first = await sendOk(alice, id, 'unread one'); + await sendOk(alice, id, 'unread two'); + assert.equal(await unreadTotal(bob), 2); + assert.equal((await inboxRow(bob, id)).unreadCount, 2); + + await remove(alice, id, first._id); + assert.equal(await unreadTotal(bob), 1); + assert.equal((await inboxRow(bob, id)).unreadCount, 1); + + await edit(alice, id, (await page(alice, id)).messages[1]._id, 'unread two, edited'); + assert.equal(await unreadTotal(bob), 1, 'an edit does not change the unread count'); +}); + +// --- Sent / Seen ----------------------------------------------------------------------------------- + +test('[Sprint 7 · M2] my messages are "sent" until the other person opens the conversation, then "seen" (saved)', async () => { + const id = await conversationBetween(alice, bob); + const one = await sendOk(alice, id, 'first'); + assert.equal(one.status, 'sent', 'the send answer already says "sent"'); + await pause(5); + await sendOk(alice, id, 'second'); + + let forAlice = await page(alice, id); + assert.deepEqual( + forAlice.messages.map((message) => message.status), + ['sent', 'sent'] + ); + assert.equal(forAlice.otherReadAt, null); + assert.equal((await as(alice).get(`${BASE}/${id}`)).body.conversation.otherReadAt, null); + + // Bob only loading the page does not count as seen; opening it (the browser then calls /read) does. + const forBob = await page(bob, id); + assert.deepEqual( + forBob.messages.map((message) => message.status), + [null, null], + "no status on the other person's messages" + ); + assert.deepEqual( + (await page(alice, id)).messages.map((message) => message.status), + ['sent', 'sent'] + ); + + const read = await as(bob).post(`${BASE}/${id}/read`); + assert.equal(read.status, 200, JSON.stringify(read.body)); + assert.deepEqual(read.body, { unreadCount: 0, unreadTotal: 0 }, 'same answer as before Sprint 7'); + + // Persisted: Bob's read time is saved in the conversation document... + const stored = await DirectConversation.findById(id).lean(); + const bobReadAt = new Date(stored.reads[bob.user.id]).getTime(); + assert.ok(bobReadAt >= new Date(one.createdAt).getTime()); + + // ...so after a reload Alice sees both messages as "seen", and when Bob read. + forAlice = await page(alice, id); + assert.deepEqual( + forAlice.messages.map((message) => message.status), + ['seen', 'seen'] + ); + assert.equal(new Date(forAlice.otherReadAt).getTime(), bobReadAt); + assert.equal(new Date((await as(alice).get(`${BASE}/${id}`)).body.conversation.otherReadAt).getTime(), bobReadAt); + + // A newer message is "sent" again until Bob opens the conversation again. + await pause(5); + await sendOk(alice, id, 'third'); + assert.deepEqual( + (await page(alice, id)).messages.map((message) => message.status), + ['seen', 'seen', 'sent'] + ); +}); + +test('[Sprint 7 · M2] replying counts as having seen the conversation; reads never move backwards', async () => { + const id = await conversationBetween(alice, bob); + await sendOk(alice, id, 'question?'); + await pause(5); + await sendOk(bob, id, 'answer!'); + assert.deepEqual( + (await page(alice, id)).messages.map((message) => [message.body, message.status]), + [ + ['question?', 'seen'], + ['answer!', null], + ] + ); + // Bob's own message is "sent" for him until Alice opens it. + assert.deepEqual( + (await page(bob, id)).messages.map((message) => message.status), + [null, 'sent'] + ); + await as(alice).post(`${BASE}/${id}/read`); + assert.deepEqual( + (await page(bob, id)).messages.map((message) => message.status), + [null, 'seen'] + ); + + // Marking read again (e.g. a slow second tab) never turns a message back to "sent". + const before = (await DirectConversation.findById(id).lean()).reads[alice.user.id]; + await as(alice).post(`${BASE}/${id}/read`); + const after = (await DirectConversation.findById(id).lean()).reads[alice.user.id]; + assert.ok(new Date(after).getTime() >= new Date(before).getTime()); +}); + +test('[Sprint 7 · M2] editing keeps the Seen status; a deleted message has no status', async () => { + const id = await conversationBetween(alice, bob); + const sent = await sendOk(alice, id, 'seen soon'); + await as(bob).post(`${BASE}/${id}/read`); + const edited = await edit(alice, id, sent._id, 'seen soon (edited)'); + assert.equal(edited.body.message.status, 'seen', 'it was seen before the edit, so it stays "seen"'); + const deleted = await remove(alice, id, sent._id); + assert.equal(deleted.body.message.deleted, true); +}); + +// --- Messages saved before Sprint 7 ----------------------------------------------------------------- + +test('[Sprint 7 · M2] messages saved before Sprint 7 (no editedAt / deletedAt) still load, count and can be edited', async () => { + const id = await conversationBetween(alice, bob); + const at = new Date(); + // Written straight to the collection, exactly like a Sprint 6 message (no new fields at all). + const { insertedId } = await DirectMessage.collection.insertOne({ + conversation: new mongoose.Types.ObjectId(id), + sender: new mongoose.Types.ObjectId(alice.user.id), + body: 'from Sprint 6', + createdAt: at, + }); + await DirectConversation.updateOne( + { _id: id }, + { $set: { lastMessageAt: at, lastMessagePreview: 'from Sprint 6', lastMessageSender: alice.user.id, activityAt: at } } + ); + + const [old] = (await page(bob, id)).messages; + assert.equal(old.body, 'from Sprint 6'); + assert.equal(old.edited, false); + assert.equal(old.deleted, false); + assert.equal(await unreadTotal(bob), 1, 'an old message still counts as unread'); + + const res = await edit(alice, id, String(insertedId), 'from Sprint 6, edited in Sprint 7'); + assert.equal(res.status, 200, JSON.stringify(res.body)); + assert.equal(res.body.message.edited, true); + assert.equal((await inboxRow(bob, id)).lastMessage.preview, 'from Sprint 6, edited in Sprint 7'); +}); diff --git a/backend/test/directMessageEditsRealtime.test.js b/backend/test/directMessageEditsRealtime.test.js new file mode 100644 index 0000000..b2625b5 --- /dev/null +++ b/backend/test/directMessageEditsRealtime.test.js @@ -0,0 +1,174 @@ +// [Sprint 7 · M2] Edits, deletes and "Seen" reach both participants live, over the shared Socket.IO server, +// and nobody else. Same set-up as directMessagesRealtime.test.js. +import { test, before, after, beforeEach } from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import { io as connect } from 'socket.io-client'; +import { setup, teardown, signup, authed } from './helpers.js'; +import { initRealtime, closeRealtime } from '../src/lib/realtime.js'; +import DirectConversation from '../src/models/DirectConversation.js'; +import DirectMessage from '../src/models/DirectMessage.js'; +import { dmSendLimiter } from '../src/routes/directMessages.js'; + +const BASE = '/api/direct-messages'; +let app; +let server; +let baseUrl; +let alice, bob, carol; +const sockets = []; + +const as = (account) => authed(app, account.token); + +function open(token) { + const socket = connect(baseUrl, { auth: { token }, transports: ['websocket'], reconnection: false, forceNew: true }); + sockets.push(socket); + return socket; +} +function connected(socket) { + return new Promise((resolve, reject) => { + socket.once('connect', resolve); + socket.once('connect_error', reject); + }); +} +async function online(account) { + const socket = open(account.token); + await connected(socket); + return socket; +} +function nextEvent(socket, name, ms = 2000) { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(`no ${name} within ${ms} ms`)), ms); + socket.once(name, (payload) => { + clearTimeout(timer); + resolve(payload); + }); + }); +} +function noEvent(socket, name, ms = 400) { + return new Promise((resolve, reject) => { + const handler = (payload) => reject(new Error(`unexpected ${name}: ${JSON.stringify(payload)}`)); + socket.once(name, handler); + setTimeout(() => { + socket.off(name, handler); + resolve(); + }, ms); + }); +} + +async function conversationBetween(a, b) { + const res = await as(a).post(BASE).send({ username: b.user.username }); + assert.equal(res.status, 200, JSON.stringify(res.body)); + return res.body.conversation._id; +} +async function sendOk(from, conversationId, body) { + const res = await as(from).post(`${BASE}/${conversationId}/messages`).send({ body }); + assert.equal(res.status, 201, JSON.stringify(res.body)); + return res.body.message; +} + +before(async () => { + ({ app } = await setup()); + server = http.createServer(app); + initRealtime(server, { origins: ['http://localhost:5173'] }); + await new Promise((resolve) => { + server.listen(0, '127.0.0.1', resolve); + }); + baseUrl = `http://127.0.0.1:${server.address().port}`; + [alice, bob, carol] = await Promise.all(['Alice Live Edit', 'Bob Live Edit', 'Carol Live Edit'].map((name) => signup(app, name))); +}); + +beforeEach(async () => { + await Promise.all([DirectConversation.deleteMany({}), DirectMessage.deleteMany({})]); + dmSendLimiter.reset(); +}); + +after(async () => { + for (const socket of sockets) socket.disconnect(); + await closeRealtime(); + await teardown(); +}); + +test('[Sprint 7 · M2] an edit reaches both participants live (each with their own view), and nobody else', async () => { + const id = await conversationBetween(alice, bob); + const sent = await sendOk(alice, id, 'Meet at 4'); + const [bobSocket, aliceTab, carolSocket] = await Promise.all([online(bob), online(alice), online(carol)]); + + const toBob = nextEvent(bobSocket, 'dm:updated', 1000); + const toAlice = nextEvent(aliceTab, 'dm:updated', 1000); + const toCarol = noEvent(carolSocket, 'dm:updated'); + const res = await as(alice).patch(`${BASE}/${id}/messages/${sent._id}`).send({ body: 'Meet at 5' }); + assert.equal(res.status, 200, JSON.stringify(res.body)); + + const forBob = await toBob; + assert.equal(forBob.conversationId, id); + assert.equal(forBob.message._id, sent._id); + assert.equal(forBob.message.body, 'Meet at 5'); + assert.equal(forBob.message.edited, true); + assert.equal(forBob.message.status, null, "Bob's copy has no Sent/Seen (it is not his message)"); + assert.equal(forBob.conversation.otherUser.username, alice.user.username); + assert.equal(forBob.conversation.lastMessage.preview, 'Meet at 5'); + assert.equal(forBob.unreadTotal, 1); + + const forAlice = await toAlice; + assert.equal(forAlice.message.body, 'Meet at 5'); + assert.equal(forAlice.message.status, 'sent'); + assert.equal(forAlice.conversation.otherUser.username, bob.user.username); + await toCarol; +}); + +test('[Sprint 7 · M2] a delete reaches the other person live as "Message deleted" without its text, and lowers their unread count', async () => { + const id = await conversationBetween(alice, bob); + const sent = await sendOk(alice, id, 'wrong chat, sorry'); + const [bobSocket, carolSocket] = await Promise.all([online(bob), online(carol)]); + + const toBob = nextEvent(bobSocket, 'dm:updated', 1000); + const toCarol = noEvent(carolSocket, 'dm:updated'); + const res = await as(alice).delete(`${BASE}/${id}/messages/${sent._id}`); + assert.equal(res.status, 200, JSON.stringify(res.body)); + + const payload = await toBob; + assert.equal(payload.message._id, sent._id); + assert.equal(payload.message.deleted, true); + assert.equal(payload.message.body, ''); + assert.equal(JSON.stringify(payload).includes('wrong chat'), false, 'the deleted text is never sent live'); + assert.equal(payload.conversation.lastMessage.preview, 'Message deleted'); + assert.equal(payload.conversation.unreadCount, 0); + assert.equal(payload.unreadTotal, 0); + await toCarol; +}); + +test('[Sprint 7 · M2] a refused edit (403) or an unchanged one sends no event', async () => { + const id = await conversationBetween(alice, bob); + const sent = await sendOk(alice, id, 'stable'); + const [aliceSocket, bobSocket] = await Promise.all([online(alice), online(bob)]); + const quietAlice = noEvent(aliceSocket, 'dm:updated'); + const quietBob = noEvent(bobSocket, 'dm:updated'); + assert.equal((await as(bob).patch(`${BASE}/${id}/messages/${sent._id}`).send({ body: 'hijack' })).status, 403); + assert.equal((await as(bob).delete(`${BASE}/${id}/messages/${sent._id}`)).status, 403); + assert.equal((await as(alice).patch(`${BASE}/${id}/messages/${sent._id}`).send({ body: 'stable' })).body.changed, false); + await Promise.all([quietAlice, quietBob]); +}); + +test('[Sprint 7 · M2] when the recipient opens the conversation, the sender is told live: "Seen"', async () => { + const id = await conversationBetween(alice, bob); + const sent = await sendOk(alice, id, 'did you see this?'); + const [aliceSocket, bobSocket, carolSocket] = await Promise.all([online(alice), online(bob), online(carol)]); + + const started = Date.now(); + const toAlice = nextEvent(aliceSocket, 'dm:seen', 1000); + const notToBob = noEvent(bobSocket, 'dm:seen'); // the reader gets 'dm:read' (badge), not 'dm:seen' + const notToCarol = noEvent(carolSocket, 'dm:seen'); + const read = await as(bob).post(`${BASE}/${id}/read`); + assert.equal(read.status, 200); + + const payload = await toAlice; + assert.ok(Date.now() - started < 1000); + assert.equal(payload.conversationId, id); + assert.ok(new Date(payload.readAt).getTime() >= new Date(sent.createdAt).getTime(), 'covers the message Alice sent'); + assert.deepEqual(Object.keys(payload).sort(), ['conversationId', 'readAt']); + await Promise.all([notToBob, notToCarol]); + + // And it is saved: Alice reloads and the message is still "seen". + const history = await as(alice).get(`${BASE}/${id}/messages`); + assert.equal(history.body.messages[0].status, 'seen'); +}); diff --git a/backend/test/directMessageRules.test.js b/backend/test/directMessageRules.test.js index 9b8faca..614d225 100644 --- a/backend/test/directMessageRules.test.js +++ b/backend/test/directMessageRules.test.js @@ -20,6 +20,12 @@ import { readBody, readLimit, userView, + DM_DELETED_TEXT, + DM_STATUS, + isMessageSender, + isSeenAt, + messagePreview, + otherReadAtFor, } from '../src/lib/directMessageRules.js'; const A = '64b000000000000000000001'; @@ -107,6 +113,12 @@ test('messageView: safe sender fields only', () => { sender: { _id: A, name: 'Alice', username: 'alice', avatarUrl: '/uploads/avatars/a.png' }, body: 'Hi', createdAt: at, + // [Sprint 7 · M2] a message saved before Sprint 7 (no editedAt / deletedAt) is not edited and not deleted + edited: false, + editedAt: null, + deleted: false, + deletedAt: null, + status: null, }); }); @@ -154,3 +166,88 @@ test('createSendLimiter: 30 messages per minute per user, then a wait time', () limiter.reset(); assert.equal(limiter.size, 0); }); + +// --------------------------------------------------------------------------------------------------- +// [Sprint 7 · M2] Edit and delete your own direct messages, and Sent / Seen. + +test('[Sprint 7 · M2] messageView: an edited message says so; a deleted one never sends its text', () => { + const at = new Date('2026-11-20T10:00:00Z'); + const editedAt = new Date('2026-11-20T10:05:00Z'); + const edited = messageView({ + _id: 'm1', + conversation: 'c1', + sender: alice, + body: 'Hi (fixed)', + createdAt: at, + editedAt, + deletedAt: null, + }); + assert.equal(edited.body, 'Hi (fixed)'); + assert.equal(edited.edited, true); + assert.equal(edited.editedAt, editedAt); + assert.equal(edited.deleted, false); + + const deletedAt = new Date('2026-11-20T10:06:00Z'); + const deleted = messageView({ _id: 'm2', conversation: 'c1', sender: alice, body: 'secret', createdAt: at, editedAt, deletedAt }); + assert.equal(deleted.deleted, true); + assert.equal(deleted.deletedAt, deletedAt); + assert.equal(deleted.body, '', 'the old text is never sent'); + assert.equal(deleted.edited, false, 'a deleted message is not shown as edited'); + assert.equal(deleted.editedAt, null); + assert.equal(JSON.stringify(deleted).includes('secret'), false); + assert.equal(DM_DELETED_TEXT, 'Message deleted'); +}); + +test('[Sprint 7 · M2] isSeenAt: seen once the other person read at or after the message time', () => { + const sent = { createdAt: new Date('2026-11-20T10:00:00.000Z') }; + assert.equal(isSeenAt(sent, null), false); + assert.equal(isSeenAt(sent, new Date('2026-11-20T09:59:59.999Z')), false); + assert.equal(isSeenAt(sent, new Date('2026-11-20T10:00:00.000Z')), true, 'the same millisecond counts as seen'); + assert.equal(isSeenAt(sent, '2026-11-20T10:00:01.000Z'), true, 'ISO strings work too'); + assert.equal(isSeenAt({}, new Date()), false); + assert.equal(isSeenAt(sent, 'not a date'), false); +}); + +test('[Sprint 7 · M2] messageView status: "sent" / "seen" only on the viewer\'s own messages', () => { + const at = new Date('2026-11-20T10:00:00Z'); + const mine = { _id: 'm1', conversation: 'c1', sender: alice, body: 'Hi', createdAt: at }; + assert.equal(messageView(mine, { viewerId: A, otherReadAt: null }).status, DM_STATUS.sent); + assert.equal(messageView(mine, { viewerId: A, otherReadAt: new Date('2026-11-20T09:00:00Z') }).status, 'sent'); + assert.equal(messageView(mine, { viewerId: A, otherReadAt: new Date('2026-11-20T10:00:00Z') }).status, 'seen'); + assert.equal(messageView(mine, { viewerId: B, otherReadAt: at }).status, null, "not on the other person's messages"); + assert.equal(messageView(mine).status, null, 'no viewer, no status'); + // The sender can be a plain ID (not populated) too. + assert.equal(messageView({ ...mine, sender: A }, { viewerId: A }).status, 'sent'); +}); + +test('[Sprint 7 · M2] isMessageSender: only the sender, whether populated or a plain ID', () => { + assert.equal(isMessageSender({ sender: alice }, A), true); + assert.equal(isMessageSender({ sender: A }, A), true); + assert.equal(isMessageSender({ sender: alice }, B), false); + assert.equal(isMessageSender({ sender: null }, A), false); + assert.equal(isMessageSender({ sender: alice }, null), false); +}); + +test('[Sprint 7 · M2] messagePreview: the inbox line, or "Message deleted"', () => { + assert.equal(messagePreview({ body: 'Hello\n\n there' }), 'Hello there'); + assert.equal(messagePreview({ body: '', deletedAt: new Date() }), 'Message deleted'); + assert.equal(messagePreview(null), ''); +}); + +test('[Sprint 7 · M2] conversationView.otherReadAt: when the OTHER person last read it', () => { + const aliceRead = new Date('2026-11-20T10:00:00Z'); + const bobRead = new Date('2026-11-20T11:00:00Z'); + const conversation = { _id: 'c1', participants: [alice, bob], reads: { [A]: aliceRead, [B]: bobRead }, lastMessageAt: bobRead }; + assert.equal(conversationView(conversation, A).otherReadAt.getTime(), bobRead.getTime(), "Alice sees Bob's read time"); + assert.equal(conversationView(conversation, B).otherReadAt.getTime(), aliceRead.getTime(), "Bob sees Alice's read time"); + assert.equal(otherReadAtFor({ ...conversation, reads: undefined }, A), null, 'nobody has read yet'); + assert.equal(otherReadAtFor({ ...conversation, reads: new Map([[B, bobRead]]) }, A).getTime(), bobRead.getTime(), 'Map on a document'); + assert.equal(otherReadAtFor({ ...conversation, participants: [alice, null] }, A), null, 'the other account is gone'); +}); + +test('[Sprint 7 · M2] messages for edit/delete answers', () => { + assert.equal(DM_MESSAGES.notSender, 'You can only edit or delete your own messages.'); + assert.equal(DM_MESSAGES.messageNotFound, 'Message not found.'); + assert.equal(DM_MESSAGES.invalidMessage, 'Invalid message ID.'); + assert.match(DM_MESSAGES.editDeleted, /deleted/); +}); diff --git a/e2e/tests/direct-messages-edit-seen.spec.js b/e2e/tests/direct-messages-edit-seen.spec.js new file mode 100644 index 0000000..01fcdcd --- /dev/null +++ b/e2e/tests/direct-messages-edit-seen.spec.js @@ -0,0 +1,85 @@ +// [Sprint 7 · M2] Direct messages: edit and delete your own messages, and Sent / Seen, end to end in two browsers. +// - "Sent" under my message until the other person opens the conversation, then "Seen" (live, and after a reload). +// - Edit: "edited" mark on both sides, live. Delete: "Message deleted" on both sides, in the same place, live. +// - Only my own messages have Edit / Delete; the API answers 403 for someone else's message. +import { test, expect } from '@playwright/test'; +import { signUp, unique } from './helpers.js'; + +const usernameOf = (page) => page.evaluate(() => JSON.parse(localStorage.getItem('devorbit_user') || '{}').username); + +test('Sprint 7 M2: Sent/Seen, edit and delete direct messages, live on both sides and kept after reload', async ({ browser }) => { + const aliceContext = await browser.newContext(); + const alice = await aliceContext.newPage(); + await signUp(alice, unique('Alice')); + + const bobContext = await browser.newContext(); + const bob = await bobContext.newPage(); + const bobUser = await signUp(bob, unique('Bob')); + const bobUsername = await usernameOf(bob); + + // Bob waits on his Messages page; Alice opens a conversation with him from his profile. + await bob.getByRole('link', { name: /^Messages/ }).click(); + await expect(bob).toHaveURL(/\/messages$/); + await alice.goto(`/people/${bobUsername}`); + await alice.getByRole('button', { name: `Message ${bobUser.name}` }).click(); + await expect(alice).toHaveURL(/\/messages\/[a-f0-9]{24}$/); + const conversationPath = new URL(alice.url()).pathname; + const aliceRoom = alice.getByRole('region', { name: `Conversation with ${bobUser.name}` }); + + // Sent: Bob has not opened the conversation yet. + const first = `Are we on for 4pm? ${unique('m')}`; + await aliceRoom.getByLabel('Write a direct message').fill(first); + await aliceRoom.getByLabel('Write a direct message').press('Enter'); + const firstOnAlice = aliceRoom.locator('.dm-message.mine', { hasText: first }); + await expect(firstOnAlice.locator('.dm-status')).toContainText('Sent'); + + // Seen: Bob opens it; Alice's message changes without a reload. + await bob.getByRole('navigation', { name: 'Conversations' }).getByRole('link', { name: /Alice/ }).click(); + const bobRoom = bob.getByRole('region', { name: /^Conversation with Alice/ }); + await expect(bobRoom.locator('.dm-message.theirs', { hasText: first })).toBeVisible(); + await expect(firstOnAlice.locator('.dm-status')).toContainText('Seen'); + await expect(bobRoom.locator('.dm-message.theirs', { hasText: first }).locator('.dm-status')).toHaveCount(0); + + // Only my own messages have Edit / Delete. + await expect(bobRoom.locator('.dm-message.theirs').getByRole('button', { name: 'Edit message' })).toHaveCount(0); + await expect(bobRoom.locator('.dm-message.theirs').getByRole('button', { name: 'Delete message' })).toHaveCount(0); + + // Edit: Alice fixes a typo; Bob sees the new text and "edited" live. + const typo = `See you tommorow ${unique('m')}`; + await aliceRoom.getByLabel('Write a direct message').fill(typo); + await aliceRoom.getByLabel('Write a direct message').press('Enter'); + const typoOnAlice = aliceRoom.locator('.dm-message.mine', { hasText: typo }); + await typoOnAlice.hover(); + await typoOnAlice.getByRole('button', { name: 'Edit message' }).click(); + const fixed = typo.replace('tommorow', 'tomorrow'); + await aliceRoom.getByLabel('Edit your message').fill(fixed); + await aliceRoom.getByLabel('Edit your message').press('Enter'); + const fixedOnBob = bobRoom.locator('.dm-message.theirs', { hasText: fixed }); + await expect(fixedOnBob).toBeVisible(); + await expect(fixedOnBob.locator('.dm-edited')).toBeVisible(); + await expect(bobRoom.getByText(typo)).toHaveCount(0); + + // Delete: confirmation, then "Message deleted" on both sides, in the same place. + await firstOnAlice.hover(); + await firstOnAlice.getByRole('button', { name: 'Delete message' }).click(); + await alice.getByRole('alertdialog').getByRole('button', { name: 'Delete message' }).click(); + await expect(aliceRoom.locator('.dm-message.deleted')).toHaveCount(1); + await expect(bobRoom.locator('.dm-message.deleted')).toHaveCount(1); + await expect(bobRoom.getByText(first)).toHaveCount(0); + await expect(bobRoom.locator('.dm-message').first()).toContainText('Message deleted'); + + // (403 for someone else's message is covered by backend/test/directMessageEdits.test.js.) + + // Reload both: edited, deleted and Seen are kept (saved on the server). + await alice.reload(); + await bob.reload(); + await expect(bob).toHaveURL(new RegExp(`${conversationPath}$`)); + await expect(aliceRoom.locator('.dm-message.deleted')).toHaveCount(1); + await expect(aliceRoom.locator('.dm-message.mine', { hasText: fixed }).locator('.dm-edited')).toBeVisible(); + await expect(aliceRoom.locator('.dm-message.mine', { hasText: fixed }).locator('.dm-status')).toContainText('Seen'); + await expect(bobRoom.locator('.dm-message.deleted')).toHaveCount(1); + await expect(bobRoom.locator('.dm-message.theirs', { hasText: fixed }).locator('.dm-edited')).toBeVisible(); + + await aliceContext.close(); + await bobContext.close(); +}); diff --git a/frontend/src/api.js b/frontend/src/api.js index 9fab56c..dbaab37 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -646,10 +646,17 @@ export const userApi = { // conversation(id) -> { conversation } 404 when it is not yours // messages(id, { before, limit }) -> { messages (oldest first), nextBefore } pass nextBefore back as `before` // send(id, body) -> { message, conversation } 429 when sending too fast -// markRead(id) -> { unreadCount: 0, unreadTotal } -// conversation = { _id, otherUser: { _id, name, username, avatarUrl }, lastMessage: { preview, at, fromMe } | null, unreadCount, activityAt } +// markRead(id) -> { unreadCount: 0, unreadTotal, readAt } +// edit(id, messageId, body) -> { message, conversation, changed, notice } [Sprint 7 · M2] own messages only (403 otherwise), +// 409 { code: 'message_deleted' } +// remove(id, messageId) -> { message, conversation, changed, notice } [Sprint 7 · M2] stays as "Message deleted" +// conversation = { _id, otherUser: { _id, name, username, avatarUrl }, lastMessage: { preview, at, fromMe } | null, unreadCount, +// otherReadAt, activityAt } +// message = { _id, sender, body, createdAt, edited, editedAt, deleted, status ('sent' | 'seen' on my own messages) } // onMessage(handler) gets { conversationId, message, conversation, unreadTotal } only the two participants receive it // onRead(handler) gets { conversationId, unreadTotal } my other tabs, after I read +// onUpdated(handler) gets { conversationId, message, conversation, unreadTotal } [Sprint 7 · M2] a message was edited/deleted +// onSeen(handler) gets { conversationId, readAt } [Sprint 7 · M2] the other person read up to readAt const dmPath = (id = '') => `/direct-messages${id ? `/${encodeURIComponent(id)}` : ''}`; export const directMessageApi = { inbox: () => api(dmPath()), @@ -663,8 +670,14 @@ export const directMessageApi = { }, send: (id, body) => api(`${dmPath(id)}/messages`, { method: 'POST', body: JSON.stringify({ body }) }), markRead: (id) => api(`${dmPath(id)}/read`, { method: 'POST', body: JSON.stringify({}) }), + // [Sprint 7 · M2] Edit / delete my own direct messages, and live edits, deletes and "Seen" marks. + edit: (id, messageId, body) => + api(`${dmPath(id)}/messages/${encodeURIComponent(messageId)}`, { method: 'PATCH', body: JSON.stringify({ body }) }), + remove: (id, messageId) => api(`${dmPath(id)}/messages/${encodeURIComponent(messageId)}`, { method: 'DELETE' }), onMessage: (handler) => liveApi.onUser('dm:message', handler), onRead: (handler) => liveApi.onUser('dm:read', handler), + onUpdated: (handler) => liveApi.onUser('dm:updated', handler), + onSeen: (handler) => liveApi.onUser('dm:seen', handler), }; // [Sprint 6 · M8] US-57, US-58 Platform Admin panel. Contract: backend/src/routes/admin.js (Platform Admins only, else 403) diff --git a/frontend/src/components/DmConversation.jsx b/frontend/src/components/DmConversation.jsx index 854938e..c2bc5cc 100644 --- a/frontend/src/components/DmConversation.jsx +++ b/frontend/src/components/DmConversation.jsx @@ -1,10 +1,33 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import { Link } from 'react-router-dom'; -import { AlertCircle, ArrowLeft, Loader2, Lock, MessageCircle, RefreshCw, Send } from 'lucide-react'; +import { + AlertCircle, + ArrowLeft, + Ban, + Check, + CheckCheck, + Loader2, + Lock, + MessageCircle, + Pencil, + RefreshCw, + Send, + Trash2, +} from 'lucide-react'; import { assetUrl, directMessageApi } from '../api'; import { Avatar, initialsOf } from './ui'; import { timeAgo } from './activityDisplay'; -import { DM_COUNTER_FROM, DM_MAX, announceUnreadTotal, idOf, mergeDirectMessages } from '../directMessages'; +import ConfirmDialog from './ConfirmDialog'; +import { + DM_COUNTER_FROM, + DM_DELETED_TEXT, + DM_MAX, + announceUnreadTotal, + deliveryLabel, + idOf, + laterTime, + mergeDirectMessages, +} from '../directMessages'; export const DM_NOT_FOUND = 'This conversation does not exist, or you are not part of it.'; @@ -15,6 +38,10 @@ export const DM_NOT_FOUND = 'This conversation does not exist, or you are not pa * - AC2: new messages from the other person arrive live ('dm:message'), and are marked read while this * conversation is open and the tab is visible. Only the two participants ever receive them. * - Enter sends, Shift+Enter starts a new line. 1-4,000 characters (the server checks again). + * - [Sprint 7 · M2] My own messages have Edit and Delete. An edited message shows "edited"; a deleted one stays + * in place as "Message deleted" for both of us. Changes arrive live ('dm:updated'). + * - [Sprint 7 · M2] My own messages show "Sent", and "Seen" once the other person has opened the conversation + * (otherReadAt from the API, moved forward live by 'dm:seen'). * * Props * conversationId which conversation (from the URL) @@ -34,6 +61,15 @@ export default function DmConversation({ conversationId, summary = null, meId = const [draft, setDraft] = useState(''); const [sending, setSending] = useState(false); const [sendError, setSendError] = useState(''); + // [Sprint 7 · M2] Sent / Seen, edit and delete + const [otherReadAt, setOtherReadAt] = useState(null); + const [editingId, setEditingId] = useState(''); + const [editDraft, setEditDraft] = useState(''); + const [editBusy, setEditBusy] = useState(false); + const [editError, setEditError] = useState(''); + const [pendingDelete, setPendingDelete] = useState(null); + const [deleteBusy, setDeleteBusy] = useState(false); + const [deleteError, setDeleteError] = useState(''); const listRef = useRef(null); const inputRef = useRef(null); const stickToBottom = useRef(true); @@ -70,12 +106,16 @@ export default function DmConversation({ conversationId, summary = null, meId = setMessages(null); setNextBefore(null); setSendError(''); + setOtherReadAt(null); + setEditingId(''); + setPendingDelete(null); stickToBottom.current = true; Promise.all([api.conversation(conversationId), api.messages(conversationId)]) .then(([one, page]) => { if (!active) return; setConversation(one.conversation); if (one.conversation) onUpdateRef.current?.(one.conversation); + setOtherReadAt((old) => laterTime(old, laterTime(one.conversation?.otherReadAt, page.otherReadAt))); setMessages(mergeDirectMessages(page.messages || [], pendingLive.current)); pendingLive.current = []; setNextBefore(page.nextBefore || null); @@ -100,10 +140,38 @@ export default function DmConversation({ conversationId, summary = null, meId = pendingLive.current = mergeDirectMessages(pendingLive.current, [payload.message]); return old; }); + // [Sprint 7 · M2] When the other person sends, they have read everything before it ("Seen"). + if (payload.conversation?.otherReadAt) setOtherReadAt((old) => laterTime(old, payload.conversation.otherReadAt)); if (idOf(payload.message.sender) !== String(meId)) markRead(); }); }, [api, conversationId, meId, markRead]); + // [Sprint 7 · M2] A message in this conversation was edited or deleted (by me in another tab, or by them). + useEffect(() => { + if (!api.onUpdated) return undefined; + return api.onUpdated((payload) => { + if (String(payload?.conversationId) !== conversationId || !payload.message) return; + setMessages((old) => { + if (old) return mergeDirectMessages(old, [payload.message]); + pendingLive.current = mergeDirectMessages(pendingLive.current, [payload.message]); + return old; + }); + if (payload.conversation?.otherReadAt) setOtherReadAt((old) => laterTime(old, payload.conversation.otherReadAt)); + if (payload.message.deleted) { + setEditingId((current) => (current === idOf(payload.message) ? '' : current)); + setPendingDelete((current) => (current && idOf(current) === idOf(payload.message) ? null : current)); + } + }); + }, [api, conversationId]); + + // [Sprint 7 · M2] The other person opened the conversation: my messages up to readAt are "Seen". + useEffect(() => { + if (!api.onSeen) return undefined; + return api.onSeen((payload) => { + if (String(payload?.conversationId) === conversationId && payload.readAt) setOtherReadAt((old) => laterTime(old, payload.readAt)); + }); + }, [api, conversationId]); + // A message that arrived in a background tab is marked read when the tab is shown again. useEffect(() => { if (typeof document === 'undefined') return undefined; @@ -156,6 +224,7 @@ export default function DmConversation({ conversationId, summary = null, meId = if (result?.message) setMessages((old) => mergeDirectMessages(old || [], [result.message])); setDraft(''); if (result?.conversation) onUpdateRef.current?.(result.conversation); + if (result?.conversation?.otherReadAt) setOtherReadAt((old) => laterTime(old, result.conversation.otherReadAt)); } catch (error) { setSendError(error?.message || 'Could not send the message. Please try again.'); } finally { @@ -168,6 +237,84 @@ export default function DmConversation({ conversationId, summary = null, meId = if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent?.isComposing) send(event); }; + // [Sprint 7 · M2] Edit my own message in place. + const startEdit = (message) => { + setEditingId(idOf(message)); + setEditDraft(message.body || ''); + setEditError(''); + }; + const cancelEdit = () => { + setEditingId(''); + setEditDraft(''); + setEditError(''); + }; + const saveEdit = async (event, message) => { + event?.preventDefault(); + if (editBusy) return; + const body = editDraft.trim(); + if (!body) { + setEditError('Message cannot be empty. To remove it, use Delete.'); + return; + } + if (body.length > DM_MAX) { + setEditError(`Message must be ${DM_MAX.toLocaleString('en-US')} characters or fewer.`); + return; + } + if (body === message.body) { + cancelEdit(); // nothing changed, so it is not marked "edited" + return; + } + setEditBusy(true); + setEditError(''); + try { + const result = await api.edit(conversationId, idOf(message), body); + if (result?.message) setMessages((old) => mergeDirectMessages(old || [], [result.message])); + if (result?.conversation) onUpdateRef.current?.(result.conversation); + cancelEdit(); + } catch (error) { + if (error?.status === 409) { + // It was deleted in the meantime (e.g. in another tab). + setMessages((old) => mergeDirectMessages(old || [], [{ ...message, deleted: true, edited: false, body: '' }])); + cancelEdit(); + setSendError(error.message || 'This message was deleted, so it can no longer be edited.'); + } else { + setEditError(error?.message || 'Could not save your changes. Please try again.'); + } + } finally { + setEditBusy(false); + } + }; + const onEditKeyDown = (event, message) => { + if (event.key === 'Escape') { + event.preventDefault(); + cancelEdit(); + } else if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent?.isComposing) { + saveEdit(event, message); + } + }; + + // [Sprint 7 · M2] Delete my own message, after confirming. + const askDelete = (message) => { + setPendingDelete(message); + setDeleteError(''); + }; + const confirmDelete = async () => { + if (!pendingDelete || deleteBusy) return; + setDeleteBusy(true); + setDeleteError(''); + try { + const result = await api.remove(conversationId, idOf(pendingDelete)); + if (result?.message) setMessages((old) => mergeDirectMessages(old || [], [result.message])); + if (result?.conversation) onUpdateRef.current?.(result.conversation); + if (editingId === idOf(pendingDelete)) cancelEdit(); + setPendingDelete(null); + } catch (error) { + setDeleteError(error?.message || 'Could not delete the message. Please try again.'); + } finally { + setDeleteBusy(false); + } + }; + if (loadError) { return (
@@ -235,14 +382,78 @@ export default function DmConversation({ conversationId, summary = null, meId = {(messages || []).map((message) => { const id = idOf(message); const mine = Boolean(meId) && idOf(message.sender) === String(meId); + const deleted = Boolean(message.deleted); + const editing = mine && !deleted && editingId === id; + const status = deliveryLabel(message, meId, otherReadAt); // [Sprint 7 · M2] 'Sent' | 'Seen' | '' return ( -
-
-

{message.body}

+
+ {editing ? ( +
saveEdit(event, message)}> +