Loading replies…
No replies yet.{canPost ? ' Start the side discussion here.' : ''}
} - {(replies || []).map((reply) =>Viewers can read threads but not reply.
)} {sendError &&From d7f22619b71cf3bca4951e1643cd0aa55ccb18fc Mon Sep 17 00:00:00 2001
From: Sahil Abbas <202401050@dau.ac.in>
Date: Sun, 22 Nov 2026 12:00:52 +0530
Subject: [PATCH] Sprint 7 M1: edit and delete channel messages and thread
replies
---
README.md | 1 +
backend/src/lib/channelMessageEdits.js | 117 ++++++
backend/src/lib/channelMessageRules.js | 96 +++++
backend/src/lib/copilotContext.js | 4 +-
backend/src/lib/decisions.js | 3 +-
backend/src/lib/realtime.js | 19 +
backend/src/models/Message.js | 14 +-
backend/src/routes/channels.js | 102 ++++-
backend/src/routes/decisions.js | 2 +-
backend/src/routes/threads.js | 9 +-
backend/test/channelMessageEdits.test.js | 351 ++++++++++++++++++
backend/test/channelMessageRules.test.js | 83 +++++
e2e/tests/sprint7-channel-edit-delete.spec.js | 74 ++++
frontend/src/api.js | 8 +
frontend/src/channelMessages.js | 91 +++++
frontend/src/channelMessages.test.js | 87 +++++
.../src/components/ChannelMessageEdit.jsx | 211 +++++++++++
.../components/ChatPanel.editDelete.test.jsx | 235 ++++++++++++
frontend/src/components/ChatPanel.jsx | 61 ++-
frontend/src/components/ThreadPanel.jsx | 77 +++-
frontend/src/styles.css | 16 +
21 files changed, 1631 insertions(+), 30 deletions(-)
create mode 100644 backend/src/lib/channelMessageEdits.js
create mode 100644 backend/src/lib/channelMessageRules.js
create mode 100644 backend/test/channelMessageEdits.test.js
create mode 100644 backend/test/channelMessageRules.test.js
create mode 100644 e2e/tests/sprint7-channel-edit-delete.spec.js
create mode 100644 frontend/src/channelMessages.js
create mode 100644 frontend/src/channelMessages.test.js
create mode 100644 frontend/src/components/ChannelMessageEdit.jsx
create mode 100644 frontend/src/components/ChatPanel.editDelete.test.jsx
diff --git a/README.md b/README.md
index 3760e73..499664a 100644
--- a/README.md
+++ b/README.md
@@ -288,6 +288,7 @@ DevOrbit was built in six sprints. Sprint 2 was split into pairs (one backend an
| Part | Task | What we built |
|---|---|---|
+| M1 | Edit and delete channel messages | In a project channel or a thread, hover your own message or reply (always shown on touch screens) for **Edit** and **Delete**. Edit happens in place (Enter saves, Esc cancels, @mentions work; a newly mentioned member is notified once) and the message shows *(edited)*. Delete asks first, then the message stays in place as *Message deleted* so its thread still makes sense: replies stay readable and the reply count is kept. Its text and mentions are removed from the database, from the Activity Feed line (so from Catch me up too), from Ask the Copilot and from a Decision that links to it. Other people's messages cannot be changed, the project Owner included: the API answers **403**. Viewers cannot edit but can delete what they wrote earlier. Changes appear live for every member (`message:updated`). `PATCH` / `DELETE /api/projects/:id/channels/:channelId/messages/:messageId` (thread replies use the same URL). Messages from before Sprint 7 work unchanged |
| 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 |
| M5 | Settings page | A **Settings** page in the sidebar and the account menu (`/settings`, shortcut *G then S*). **Change password:** your current password is required, the new one is typed twice (8–128 characters, must differ). On success every *other* session of the account is signed out at once (their tokens, refresh cookies and live connections stop working) and this browser stays signed in; an open reset link is retired too. A wrong current password answers **400** (`current_password_wrong`), never 401, so a typo does not sign you out; 10 wrong tries per account per 15 minutes. `POST /api/settings/password`. The **privacy switches** (collaborator search, public portfolio) moved here from My profile. **Theme:** Dark, Light or System (follows the device), saved in the browser |
diff --git a/backend/src/lib/channelMessageEdits.js b/backend/src/lib/channelMessageEdits.js
new file mode 100644
index 0000000..a888bc0
--- /dev/null
+++ b/backend/src/lib/channelMessageEdits.js
@@ -0,0 +1,117 @@
+import Message from '../models/Message.js';
+import Activity from '../models/Activity.js';
+import { emitMessageUpdated } from './realtime.js';
+import { quote } from './activity.js';
+import { findMentionedMembers, notifyMentions } from './mentions.js';
+import { messageLink } from './notifications.js';
+import { channelMessageView, messageActivitySummary } from './channelMessageRules.js';
+
+/*
+ * [Sprint 7 · M1] Edit and delete your own channel messages and thread replies.
+ *
+ * Both changes are single atomic updates that only match the author's own, not-yet-deleted message,
+ * so an edit racing a delete can never bring the text back. routes/channels.js checks who may do it
+ * first (403 for anyone but the author); the filters here are a second guard.
+ *
+ * After a change every member viewing the project gets 'message:updated'
+ * { projectId, channelId, parentId, message } (lib/realtime.js), so the message changes live for everyone,
+ * in the channel and in an open thread.
+ */
+
+// Same fields as routes/channels.js AUTHOR_FIELDS / MENTION_FIELDS, so the message has the same shape.
+const AUTHOR_FIELDS = 'name username avatarUrl';
+const MENTION_FIELDS = 'name username';
+
+const idOf = (value) => (value === null || value === undefined ? '' : String(value?._id || value));
+
+// The message as the API returns it (author and mentions filled in, "edited" / "deleted" applied).
+export async function channelMessageById(messageId) {
+ const row = await Message.findById(messageId).populate('author', AUTHOR_FIELDS).populate('mentions', MENTION_FIELDS).lean();
+ return channelMessageView(row);
+}
+
+// The message with this ID in this channel (top-level message or thread reply, any author), or null.
+export function findMessageInChannel(channel, messageId) {
+ return Message.findOne({ _id: messageId, channel: channel._id }).lean();
+}
+
+/*
+ * Keeps the Activity Feed in step: an edit shows the new text, a delete removes the text
+ * ("posted in #general: (message deleted)"). Catch Me Up reads the same feed, so it never sees deleted text.
+ * Never throws: the edit or delete itself has already been saved.
+ */
+async function refreshActivity(project, channel, message, quotedText) {
+ try {
+ await Activity.updateMany(
+ { project: project._id, type: 'message.posted', targetType: 'message', targetId: message._id },
+ { $set: { summary: messageActivitySummary({ channelName: channel.name, isReply: Boolean(message.parentMessage), quotedText }) } }
+ );
+ } catch (error) {
+ if (process.env.NODE_ENV !== 'test') console.error('Could not update the activity feed:', error.message);
+ }
+}
+
+/*
+ * The author changes the text. Saving the same text again is not an edit (no "edited" mark, no event).
+ * Someone newly @mentioned by the edit gets a Mention notification; people already notified for this
+ * message are not notified again (notifyMentions uses one dedupeKey per message).
+ * -> { changed: true | false, message } or { changed: false, deleted: true } when it was deleted meanwhile.
+ */
+export async function editChannelMessage({ project, channel, message, editorId, body }) {
+ if (message.deletedAt) return { changed: false, deleted: true };
+ if (message.body === body) return { changed: false, message: await channelMessageById(message._id) };
+
+ const mentioned = await findMentionedMembers(project, body);
+ const result = await Message.updateOne(
+ { _id: message._id, channel: channel._id, author: editorId, deletedAt: null },
+ { $set: { body, editedAt: new Date(), mentions: mentioned.map((user) => user._id) } }
+ );
+ if (!result.matchedCount) return { changed: false, deleted: true };
+
+ const updated = await channelMessageById(message._id);
+ emitMessageUpdated(updated);
+
+ const parentId = idOf(message.parentMessage);
+ const link = parentId
+ ? `${messageLink(project._id, channel._id, parentId)}&thread=${parentId}`
+ : messageLink(project._id, channel._id, message._id);
+ await notifyMentions(mentioned, {
+ project: project._id,
+ actor: editorId,
+ summary: parentId ? `mentioned you in a thread in #${channel.name}` : `mentioned you in #${channel.name}`,
+ targetType: 'message',
+ targetId: message._id,
+ targetLabel: `#${channel.name}`,
+ link,
+ });
+ await refreshActivity(project, channel, message, quote(body, 80));
+
+ return { changed: true, message: updated };
+}
+
+/*
+ * The author deletes the message. The row stays, so the channel still reads in order and a thread keeps
+ * its replies (and its reply count), but it shows "Message deleted": its text and mentions are removed
+ * from the database. Deleting it again changes nothing. -> { changed, message }
+ */
+export async function deleteChannelMessage({ project, channel, message, userId }) {
+ const result = await Message.updateOne(
+ { _id: message._id, channel: channel._id, author: userId, deletedAt: null },
+ { $set: { deletedAt: new Date(), body: '', editedAt: null, mentions: [] } }
+ );
+ if (!result.matchedCount) return { changed: false, message: await channelMessageById(message._id) };
+
+ const updated = await channelMessageById(message._id);
+ emitMessageUpdated(updated);
+ await refreshActivity(project, channel, message, null);
+ return { changed: true, message: updated };
+}
+
+/*
+ * ---------------------------------------------------------------------------
+ * [Sprint 7 · M1] What this file does
+ * Saves an edit or a delete of your own channel message / thread reply,
+ * pushes the change live to project members ('message:updated'), notifies
+ * people newly @mentioned by an edit, and updates the Activity Feed line.
+ * ---------------------------------------------------------------------------
+ */
diff --git a/backend/src/lib/channelMessageRules.js b/backend/src/lib/channelMessageRules.js
new file mode 100644
index 0000000..136e075
--- /dev/null
+++ b/backend/src/lib/channelMessageRules.js
@@ -0,0 +1,96 @@
+/*
+ * [Sprint 7 · M1] Edit and delete your own channel messages and thread replies.
+ *
+ * Small pure helpers (no database, no Express), so they are easy to unit test
+ * (test/channelMessageRules.test.js). The routes are in routes/channels.js and the
+ * database work is in lib/channelMessageEdits.js.
+ *
+ * Rules
+ * - Only the author may edit or delete a message (a thread reply is a message too). Everyone else,
+ * the project Owner included, gets 403.
+ * - Editing needs a role that may post (Owner, Admin, Contributor). Deleting your own message is
+ * allowed in any role, so someone who was later made a Viewer can still take back what they wrote.
+ * - An edited message shows "edited". A deleted message keeps its place (and its thread) and shows
+ * "Message deleted"; its text and mentions are removed from the database.
+ */
+
+export const CHANNEL_MESSAGE_MAX = 4000; // same limit as models/Message.js MESSAGE_MAX
+
+// What a deleted message shows instead of its text (same words as direct messages, Sprint 7 · M2).
+export const CHANNEL_DELETED_TEXT = 'Message deleted';
+
+export const CHANNEL_EDIT_MESSAGES = {
+ invalidMessage: 'Invalid message ID.',
+ messageNotFound: 'Message not found.',
+ notAuthor: 'You can only edit or delete your own messages.',
+ viewerEdit: 'Viewers cannot edit messages.',
+ empty: 'Message cannot be empty. To remove it, use Delete.',
+ tooLong: `Message must be ${CHANNEL_MESSAGE_MAX.toLocaleString('en-US')} characters or fewer.`,
+ 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.',
+};
+
+const idOf = (value) => (value === null || value === undefined ? '' : String(value?._id || value));
+
+// true when `userId` wrote the message. Works for a populated author ({ _id, name }) or a raw ID.
+export function isMessageAuthor(message, userId) {
+ const author = idOf(message?.author);
+ return Boolean(author) && Boolean(idOf(userId)) && author === idOf(userId);
+}
+
+/*
+ * Checks the new text of an edit (same rules as sending: trimmed, not empty, at most 4,000 characters).
+ * -> { ok: true, body } or { ok: false, message }
+ */
+export function readEditedBody(raw) {
+ if (raw !== undefined && raw !== null && typeof raw !== 'string') return { ok: false, message: CHANNEL_EDIT_MESSAGES.empty };
+ const body = String(raw ?? '').trim();
+ if (!body) return { ok: false, message: CHANNEL_EDIT_MESSAGES.empty };
+ if (body.length > CHANNEL_MESSAGE_MAX) return { ok: false, message: CHANNEL_EDIT_MESSAGES.tooLong };
+ return { ok: true, body };
+}
+
+/*
+ * One channel message (or thread reply) as the browser sees it. Every field the API sent before
+ * Sprint 7 is kept as it was; these are added:
+ * edited, editedAt the author changed the text ("edited"). A deleted message is never "edited".
+ * deleted, deletedAt the author deleted it: body is '' and mentions [] (the text is never sent again),
+ * and the browser shows "Message deleted" in its place.
+ * Messages saved before Sprint 7 have neither field and come out as not edited and not deleted.
+ */
+export function channelMessageView(message) {
+ if (!message) return message;
+ const deleted = Boolean(message.deletedAt);
+ return {
+ ...message,
+ body: deleted ? '' : message.body,
+ mentions: deleted ? [] : message.mentions || [],
+ edited: !deleted && Boolean(message.editedAt),
+ editedAt: deleted ? null : message.editedAt || null,
+ deleted,
+ deletedAt: message.deletedAt || null,
+ };
+}
+
+/*
+ * The Activity Feed line of a channel message or thread reply. Same words as when it was posted
+ * (routes/channels.js and routes/threads.js), so an edit only swaps the quoted text, and a delete
+ * replaces it, so the deleted text cannot still be read in the feed or in Catch Me Up.
+ * quotedText: the new text already quoted with lib/activity.js quote(), or null when deleted.
+ */
+export function messageActivitySummary({ channelName, isReply = false, quotedText = null }) {
+ const where = isReply ? `replied in a thread in #${channelName}` : `posted in #${channelName}`;
+ return `${where}: ${quotedText ?? `(${CHANNEL_DELETED_TEXT.toLowerCase()})`}`;
+}
+
+/*
+ * ---------------------------------------------------------------------------
+ * [Sprint 7 · M1] What this file does
+ * Pure rules for editing and deleting your own channel messages and thread
+ * replies: who may do it, the text checks, how an edited / deleted message is
+ * shown ("edited", "Message deleted") and the matching Activity Feed line.
+ * ---------------------------------------------------------------------------
+ */
diff --git a/backend/src/lib/copilotContext.js b/backend/src/lib/copilotContext.js
index f68b775..a649fc7 100644
--- a/backend/src/lib/copilotContext.js
+++ b/backend/src/lib/copilotContext.js
@@ -42,7 +42,9 @@ export async function loadCopilotRecords(project) {
// neither used nor counted: only comments on this project's tasks, only messages in its channels.
const [taskIds, channels] = await Promise.all([Task.distinct('_id', filter), Channel.find(filter).select('name').lean()]);
const commentFilter = { project: project._id, task: { $in: taskIds } };
- const messageFilter = { project: project._id, channel: { $in: channels.map((channel) => channel._id) } };
+ // [Sprint 7 · M1] Deleted messages are left out, so their text can never reach an AI answer.
+ // (`deletedAt: null` also matches messages saved before Sprint 7, which have no such field.)
+ const messageFilter = { project: project._id, channel: { $in: channels.map((channel) => channel._id) }, deletedAt: null };
const [tasks, comments, decisions, messages, github, available] = await Promise.all([
Task.find(filter)
diff --git a/backend/src/lib/decisions.js b/backend/src/lib/decisions.js
index 13d55fd..cf84feb 100644
--- a/backend/src/lib/decisions.js
+++ b/backend/src/lib/decisions.js
@@ -173,7 +173,8 @@ export function decisionLinkView(decision, targets = {}) {
type: 'thread',
id: messageId,
channelId,
- label: `#${channel.name}: ${shortText(message.body)}`,
+ // [Sprint 7 · M1] A linked message its author deleted shows "Message deleted", never its old text.
+ label: `#${channel.name}: ${message.deletedAt ? 'Message deleted' : shortText(message.body)}`,
href: decisionThreadHref(projectId, channelId, messageId),
missing: false,
};
diff --git a/backend/src/lib/realtime.js b/backend/src/lib/realtime.js
index 7cd9f1e..21cb399 100644
--- a/backend/src/lib/realtime.js
+++ b/backend/src/lib/realtime.js
@@ -20,6 +20,9 @@ import { memberRole, validId } from './projectAccess.js';
* listen 'activity:created' { projectId, activity } [US-29] members only, activity = populated feed event
* listen 'project:access-removed' { projectId, reason } [Sprint 3 · M3] sent to a person removed from / leaving a project
* listen 'message:reply' { projectId, channelId, parentId, reply, replyCount, lastReplyAt } [US-17] members only
+ * listen 'message:updated' { projectId, channelId, parentId, message } [Sprint 7 · M1] members only. A channel
+ * message or thread reply was edited or deleted by its author. parentId is null for a top-level
+ * message; message = same shape as the REST API (message.deleted / message.edited)
* listen 'comment:created' { projectId, taskId, comment } [US-20] members only
* listen 'notification:created' { notification, unreadCount } [Sprint 3 · M7 Part 2] only to the recipient
* listen 'notification:read' { notificationId, unreadCount } [Sprint 3 · M7 Part 2] only to the recipient
@@ -181,6 +184,22 @@ export function emitThreadReply(reply, { replyCount = 0, lastReplyAt = null } =
io.to(memberRoom(projectId)).emit('message:reply', { projectId, channelId, parentId, reply, replyCount, lastReplyAt });
}
+/*
+ * [Sprint 7 · M1] A channel message or thread reply was edited or deleted by its author.
+ * Members only, like 'message:created'. One event for both: message.deleted tells them apart.
+ * Payload: { projectId, channelId, parentId, message }
+ * parentId = the thread's first message for a reply, null for a top-level channel message
+ * message = same shape as the REST API (lib/channelMessageRules.js channelMessageView); a deleted one has body ''
+ */
+export function emitMessageUpdated(message) {
+ if (!io || !message) return;
+ const projectId = String(message.project?._id || message.project || '');
+ const channelId = String(message.channel?._id || message.channel || '');
+ if (!projectId || !channelId) return;
+ const parentId = message.parentMessage ? String(message.parentMessage?._id || message.parentMessage) : null;
+ io.to(memberRoom(projectId)).emit('message:updated', { projectId, channelId, parentId, message });
+}
+
/*
* [US-20] A new task comment. Members only: comments are team discussion, so visitors
* watching a Public project's board (projectRoom) do not get them.
diff --git a/backend/src/models/Message.js b/backend/src/models/Message.js
index afe54d8..a3e9c53 100644
--- a/backend/src/models/Message.js
+++ b/backend/src/models/Message.js
@@ -2,6 +2,12 @@ import mongoose from 'mongoose';
export const MESSAGE_MAX = 4000;
+// [Sprint 7 · M1] A deleted message keeps its row (so the channel and its thread still read in order)
+// but not its text.
+function bodyRequired() {
+ return !this.deletedAt;
+}
+
const messageSchema = new mongoose.Schema(
{
project: {
@@ -21,9 +27,10 @@ const messageSchema = new mongoose.Schema(
},
body: {
type: String,
- required: true,
+ required: bodyRequired, // [Sprint 7 · M1] was `true`; still required unless the message was deleted
trim: true,
maxlength: MESSAGE_MAX,
+ default: '',
},
// [Sprint 3 · US-17] Thread replies. null (or missing, for messages saved before threads
// existed) = a normal channel message. Set = a reply inside that message's thread.
@@ -52,6 +59,11 @@ const messageSchema = new mongoose.Schema(
ref: 'User',
},
],
+ // [Sprint 7 · M1] Edit and delete your own messages and thread replies (lib/channelMessageEdits.js).
+ // 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 author changes the text ("edited")
+ deletedAt: { type: Date, default: null }, // set when the author deletes it; body and mentions are emptied
},
{ timestamps: true }
);
diff --git a/backend/src/routes/channels.js b/backend/src/routes/channels.js
index 43ed45d..9225b78 100644
--- a/backend/src/routes/channels.js
+++ b/backend/src/routes/channels.js
@@ -10,6 +10,8 @@ import { emitMessageCreated } from '../lib/realtime.js';
import { logActivity, quote } from '../lib/activity.js'; // [US-29]
import { findMentionedMembers, notifyMentions } from '../lib/mentions.js'; // [Sprint 3] US-18
import { messageLink } from '../lib/notifications.js'; // [Sprint 3] US-18
+import { CHANNEL_EDIT_MESSAGES, channelMessageView, isMessageAuthor, readEditedBody } from '../lib/channelMessageRules.js'; // [Sprint 7 · M1]
+import { deleteChannelMessage, editChannelMessage, findMessageInChannel } from '../lib/channelMessageEdits.js'; // [Sprint 7 · M1]
/*
* Project channels and messages (US-16, FR-5). Mounted at /api/projects/:id/channels
@@ -28,6 +30,19 @@ import { messageLink } from '../lib/notifications.js'; // [Sprint 3] US-18
*
* [Sprint 3 · US-18] @username of a project member in a message: stored in message.mentions
* ([{ _id, name, username }]) and the member gets a Mention notification linking to the message.
+ *
+ * [Sprint 7 · M1] Edit and delete your own messages (thread replies too: they are messages of the same channel).
+ * PATCH /:channelId/messages/:messageId author only, Owner/Admin/Contributor { body }
+ * -> 200 { message, changed, notice }
+ * Same text again -> changed: false (no "edited" mark).
+ * 400 invalid ID / empty / too long, 403 not your message or you are a
+ * Viewer, 404 unknown message, 409 { code: 'message_deleted' } it was deleted.
+ * DELETE /:channelId/messages/:messageId author only, any role -> 200 { message, changed, notice }
+ * It stays in place as "Message deleted" (deleted: true, body ''), so its
+ * thread still makes sense. Already deleted -> changed: false.
+ * 403 not your message (the Owner too), 404 unknown message.
+ * Every message the API returns now also has { edited, editedAt, deleted, deletedAt }.
+ * Live: 'message:updated' { projectId, channelId, parentId, message } to members (lib/realtime.js).
*/
const router = Router({ mergeParams: true });
@@ -57,8 +72,10 @@ export async function loadChannel(req, res, project) {
return channel;
}
+// [Sprint 7 · M1] Returned through channelMessageView: adds edited / deleted and hides a deleted message's text.
export async function findPopulatedMessage(messageId) {
- return Message.findById(messageId).populate('author', AUTHOR_FIELDS).populate('mentions', MENTION_FIELDS).lean();
+ const row = await Message.findById(messageId).populate('author', AUTHOR_FIELDS).populate('mentions', MENTION_FIELDS).lean();
+ return channelMessageView(row);
}
router.get('/', async (req, res, next) => {
@@ -147,7 +164,8 @@ router.get('/:channelId/messages', async (req, res, next) => {
const nextBefore = rows.length > limit ? page[page.length - 1].createdAt : null;
// The chat shows oldest at the top, so send this page oldest first.
- return res.json({ messages: page.reverse(), nextBefore });
+ // [Sprint 7 · M1] channelMessageView: "edited" / "Message deleted" (a deleted message's text is never sent).
+ return res.json({ messages: page.reverse().map(channelMessageView), nextBefore });
} catch (error) {
return next(error);
}
@@ -213,6 +231,84 @@ router.post('/:channelId/messages', async (req, res, next) => {
}
});
+/*
+ * [Sprint 7 · M1] The message in the URL, for its author only.
+ * 400 bad ID, 404 not a message of this channel, 403 someone else's message. Returns null after answering.
+ */
+async function ownMessageFromUrl(req, res, channel) {
+ if (!validId(req.params.messageId)) {
+ res.status(400).json({ message: CHANNEL_EDIT_MESSAGES.invalidMessage });
+ return null;
+ }
+ const message = await findMessageInChannel(channel, req.params.messageId);
+ if (!message) {
+ res.status(404).json({ message: CHANNEL_EDIT_MESSAGES.messageNotFound });
+ return null;
+ }
+ if (!isMessageAuthor(message, req.user.id)) {
+ res.status(403).json({ message: CHANNEL_EDIT_MESSAGES.notAuthor, code: 'not_author' });
+ return null;
+ }
+ return message;
+}
+
+// [Sprint 7 · M1] Edit my own channel message or thread reply.
+router.patch('/:channelId/messages/:messageId', async (req, res, next) => {
+ try {
+ const loaded = await loadProjectForMember(req, res);
+ if (!loaded) return undefined;
+ const channel = await loadChannel(req, res, loaded.project);
+ if (!channel) return undefined;
+ const message = await ownMessageFromUrl(req, res, channel);
+ if (!message) return undefined;
+
+ if (!canPostMessages(loaded.role)) {
+ return res.status(403).json({ message: CHANNEL_EDIT_MESSAGES.viewerEdit, code: 'viewer' });
+ }
+ if (message.deletedAt) return res.status(409).json({ message: CHANNEL_EDIT_MESSAGES.editDeleted, code: 'message_deleted' });
+
+ const checked = readEditedBody(req.body?.body);
+ if (!checked.ok) return res.status(400).json({ message: checked.message });
+
+ const result = await editChannelMessage({
+ project: loaded.project,
+ channel,
+ message,
+ editorId: req.user.id,
+ body: checked.body,
+ });
+ if (result.deleted) return res.status(409).json({ message: CHANNEL_EDIT_MESSAGES.editDeleted, code: 'message_deleted' });
+ return res.json({
+ message: result.message,
+ changed: result.changed,
+ notice: result.changed ? CHANNEL_EDIT_MESSAGES.edited : CHANNEL_EDIT_MESSAGES.unchanged,
+ });
+ } catch (error) {
+ return next(error);
+ }
+});
+
+// [Sprint 7 · M1] Delete my own channel message or thread reply (it stays as "Message deleted").
+router.delete('/:channelId/messages/:messageId', async (req, res, next) => {
+ try {
+ const loaded = await loadProjectForMember(req, res);
+ if (!loaded) return undefined;
+ const channel = await loadChannel(req, res, loaded.project);
+ if (!channel) return undefined;
+ const message = await ownMessageFromUrl(req, res, channel);
+ if (!message) return undefined;
+
+ const result = await deleteChannelMessage({ project: loaded.project, channel, message, userId: req.user.id });
+ return res.json({
+ message: result.message,
+ changed: result.changed,
+ notice: result.changed ? CHANNEL_EDIT_MESSAGES.deleted : CHANNEL_EDIT_MESSAGES.alreadyDeleted,
+ });
+ } catch (error) {
+ return next(error);
+ }
+});
+
export default router;
/*
@@ -221,5 +317,7 @@ export default router;
* REST API for project channels (US-16): list/create channels and read/send
* messages. Members only; Viewers are read-only (403 on send). New messages are
* saved, then pushed live to every member viewing the project (target: < 1 s).
+ * [Sprint 7 · M1] Also: edit and delete your own messages and thread replies
+ * ("edited", "Message deleted"); anyone else gets 403. Changes are pushed live.
* ---------------------------------------------------------------------------
*/
diff --git a/backend/src/routes/decisions.js b/backend/src/routes/decisions.js
index 04cd06a..119de0e 100644
--- a/backend/src/routes/decisions.js
+++ b/backend/src/routes/decisions.js
@@ -63,7 +63,7 @@ async function toViews(decisions) {
const [tasks, messages, channels] = await Promise.all([
taskIds.length ? Task.find({ _id: { $in: taskIds } }).select('title').lean() : [],
- messageIds.length ? Message.find({ _id: { $in: messageIds } }).select('body').lean() : [],
+ messageIds.length ? Message.find({ _id: { $in: messageIds } }).select('body deletedAt').lean() : [], // [Sprint 7 · M1] deletedAt
channelIds.length ? Channel.find({ _id: { $in: channelIds } }).select('name').lean() : [],
]);
const targets = {
diff --git a/backend/src/routes/threads.js b/backend/src/routes/threads.js
index 7347ca5..e3acde5 100644
--- a/backend/src/routes/threads.js
+++ b/backend/src/routes/threads.js
@@ -9,6 +9,7 @@ import { logActivity, quote } from '../lib/activity.js';
import { AUTHOR_FIELDS, MENTION_FIELDS, findPopulatedMessage, loadChannel } from './channels.js';
import { findMentionedMembers, notifyMentions } from '../lib/mentions.js';
import { messageLink } from '../lib/notifications.js';
+import { channelMessageView } from '../lib/channelMessageRules.js'; // [Sprint 7 · M1]
/*
* [Sprint 3 · US-17] Reply in a thread.
@@ -29,6 +30,11 @@ import { messageLink } from '../lib/notifications.js';
*
* The parent's replyCount is increased with $inc in the same step as lastReplyAt, so two people
* replying at the same moment both count. Live: 'message:reply' to members (lib/realtime.js).
+ *
+ * [Sprint 7 · M1] Editing / deleting a reply uses the same endpoint as a channel message:
+ * PATCH / DELETE /api/projects/:id/channels/:channelId/messages/:replyId (routes/channels.js).
+ * A deleted reply stays in the thread as "Message deleted" and still counts in replyCount, so the
+ * conversation keeps making sense. A thread whose first message was deleted stays open for replies.
*/
const router = Router({ mergeParams: true });
@@ -86,7 +92,8 @@ router.get('/', async (req, res, next) => {
.lean(),
]);
- const replies = rows.slice(0, limit);
+ // [Sprint 7 · M1] channelMessageView: edited replies show "edited", deleted ones "Message deleted" (no text sent).
+ const replies = rows.slice(0, limit).map(channelMessageView);
const nextAfter = rows.length > limit ? replies[replies.length - 1].createdAt : null;
return res.json({ parent: populatedParent, replies, nextAfter });
} catch (error) {
diff --git a/backend/test/channelMessageEdits.test.js b/backend/test/channelMessageEdits.test.js
new file mode 100644
index 0000000..5387dfe
--- /dev/null
+++ b/backend/test/channelMessageEdits.test.js
@@ -0,0 +1,351 @@
+// [Sprint 7 · M1] Edit and delete your own channel messages and thread replies.
+// Edited ones show "edited", deleted ones "Message deleted" (so threads still make sense),
+// other people's messages get 403, and changes reach every member live.
+import { test, before, after } 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 mongoose from 'mongoose';
+import Message from '../src/models/Message.js';
+import Activity from '../src/models/Activity.js';
+import Notification from '../src/models/Notification.js';
+import Project from '../src/models/Project.js';
+import { loadCopilotRecords } from '../src/lib/copilotContext.js';
+
+let app;
+let server;
+let baseUrl;
+let owner, contributor, viewer, outsider;
+let projectId;
+let generalId;
+let otherChannelId;
+const sockets = [];
+
+const as = (account) => authed(app, account.token);
+const channels = () => `/api/projects/${projectId}/channels`;
+const messages = (channelId = generalId) => `${channels()}/${channelId}/messages`;
+const one = (messageId, channelId = generalId) => `${messages(channelId)}/${messageId}`;
+const replies = (messageId, channelId = generalId) => `${messages(channelId)}/${messageId}/replies`;
+
+function open(token) {
+ const socket = connect(baseUrl, { auth: { token }, transports: ['websocket'], reconnection: false, forceNew: true });
+ sockets.push(socket);
+ return new Promise((resolve, reject) => {
+ socket.once('connect', () => resolve(socket));
+ socket.once('connect_error', reject);
+ });
+}
+const join = (socket, id) => new Promise((resolve) => { socket.emit('project:join', { projectId: id }, resolve); });
+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 = 300) {
+ return new Promise((resolve, reject) => {
+ const handler = () => reject(new Error(`unexpected ${name}`));
+ socket.once(name, handler);
+ setTimeout(() => { socket.off(name, handler); resolve(); }, ms);
+ });
+}
+
+async function post(account, body, channelId = generalId) {
+ const res = await as(account).post(messages(channelId)).send({ body });
+ assert.equal(res.status, 201, JSON.stringify(res.body));
+ return res.body.message;
+}
+
+async function reply(account, parentId, body) {
+ const res = await as(account).post(replies(parentId)).send({ body });
+ assert.equal(res.status, 201, JSON.stringify(res.body));
+ return res.body.reply;
+}
+
+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}`;
+
+ [owner, contributor, viewer, outsider] = await Promise.all(
+ ['Edit Owner', 'Edit Contributor', 'Edit Viewer', 'Edit Outsider'].map((name) => signup(app, name))
+ );
+ const project = await as(owner).post('/api/projects').send({ name: 'Edit Project', visibility: 'Public' });
+ projectId = project.body.project._id;
+ for (const [account, role] of [[contributor, 'Contributor'], [viewer, 'Viewer']]) {
+ const res = await as(owner).post(`/api/projects/${projectId}/members`).send({ identifier: account.user.username, role });
+ assert.equal(res.status, 201, JSON.stringify(res.body));
+ }
+ generalId = (await as(owner).get(channels())).body.channels[0]._id;
+ const created = await as(owner).post(channels()).send({ name: 'design' });
+ assert.equal(created.status, 201, JSON.stringify(created.body));
+ otherChannelId = created.body.channel._id;
+});
+
+after(async () => {
+ sockets.forEach((socket) => socket.close());
+ await closeRealtime();
+ await teardown();
+});
+
+test('New messages are listed as not edited and not deleted', async () => {
+ const message = await post(contributor, 'Fresh message');
+ assert.equal(message.edited, false);
+ assert.equal(message.deleted, false);
+ const history = await as(viewer).get(messages());
+ const row = history.body.messages.find((m) => m._id === message._id);
+ assert.equal(row.edited, false);
+ assert.equal(row.deleted, false);
+ assert.equal(row.body, 'Fresh message');
+});
+
+test('The author edits their message: new text, marked "edited", in the channel history too', async () => {
+ const message = await post(contributor, 'Standup at 10');
+ const res = await as(contributor).patch(one(message._id)).send({ body: ' Standup at 11 ' });
+ assert.equal(res.status, 200, JSON.stringify(res.body));
+ assert.equal(res.body.changed, true);
+ assert.equal(res.body.message.body, 'Standup at 11');
+ assert.equal(res.body.message.edited, true);
+ assert.ok(res.body.message.editedAt);
+ assert.equal(res.body.message.author.name, 'Edit Contributor');
+
+ const history = await as(viewer).get(messages());
+ const row = history.body.messages.find((m) => m._id === message._id);
+ assert.equal(row.body, 'Standup at 11');
+ assert.equal(row.edited, true);
+});
+
+test('Saving the same text again is not an edit', async () => {
+ const message = await post(contributor, 'No change here');
+ const res = await as(contributor).patch(one(message._id)).send({ body: 'No change here' });
+ assert.equal(res.status, 200, JSON.stringify(res.body));
+ assert.equal(res.body.changed, false);
+ assert.equal(res.body.message.edited, false);
+});
+
+test('An edit follows the same text rules as sending', async () => {
+ const message = await post(contributor, 'Rules apply');
+ assert.equal((await as(contributor).patch(one(message._id)).send({ body: ' ' })).status, 400);
+ assert.equal((await as(contributor).patch(one(message._id)).send({})).status, 400);
+ assert.equal((await as(contributor).patch(one(message._id)).send({ body: 42 })).status, 400);
+ assert.equal((await as(contributor).patch(one(message._id)).send({ body: 'x'.repeat(4001) })).status, 400);
+ const stored = await Message.findById(message._id).lean();
+ assert.equal(stored.body, 'Rules apply');
+ assert.equal(stored.editedAt ?? null, null);
+});
+
+test("Other people's messages get 403, the project Owner included", async () => {
+ const message = await post(contributor, 'Mine, not yours');
+ const ownerEdit = await as(owner).patch(one(message._id)).send({ body: 'Hijacked' });
+ assert.equal(ownerEdit.status, 403);
+ assert.equal(ownerEdit.body.code, 'not_author');
+ assert.equal((await as(owner).delete(one(message._id))).status, 403);
+ assert.equal((await as(viewer).patch(one(message._id)).send({ body: 'Nope' })).status, 403);
+ assert.equal((await as(viewer).delete(one(message._id))).status, 403);
+
+ const stored = await Message.findById(message._id).lean();
+ assert.equal(stored.body, 'Mine, not yours');
+ assert.equal(stored.deletedAt ?? null, null);
+});
+
+test('People outside the project cannot edit or delete anything', async () => {
+ const message = await post(contributor, 'Members only');
+ const edit = await as(outsider).patch(one(message._id)).send({ body: 'Outsider' });
+ const remove = await as(outsider).delete(one(message._id));
+ assert.equal(edit.status, 403);
+ assert.equal(remove.status, 403);
+ const anonymous = await authed(app, 'not-a-token').patch(one(message._id)).send({ body: 'x' });
+ assert.equal(anonymous.status, 401);
+});
+
+test('Bad, unknown and wrong-channel message IDs are refused', async () => {
+ assert.equal((await as(contributor).patch(one('not-an-id')).send({ body: 'x' })).status, 400);
+ assert.equal((await as(contributor).delete(one('64b7f0c2a1b2c3d4e5f60789'))).status, 404);
+ const message = await post(contributor, 'Lives in #general');
+ // Same message, but the URL names #design: it is not a message of that channel.
+ assert.equal((await as(contributor).patch(one(message._id, otherChannelId)).send({ body: 'x' })).status, 404);
+ assert.equal((await as(contributor).delete(one(message._id, otherChannelId))).status, 404);
+});
+
+test('A Viewer cannot edit, but can still delete what they wrote before being made a Viewer', async () => {
+ const old = await Message.create({ project: projectId, channel: generalId, author: viewer.user.id, body: 'Written as a Contributor' });
+ const edit = await as(viewer).patch(one(old._id)).send({ body: 'Changed' });
+ assert.equal(edit.status, 403);
+ assert.equal(edit.body.code, 'viewer');
+ const remove = await as(viewer).delete(one(old._id));
+ assert.equal(remove.status, 200, JSON.stringify(remove.body));
+ assert.equal(remove.body.message.deleted, true);
+});
+
+test('The author deletes a message: it stays in place as "Message deleted" and its text is gone', async () => {
+ const message = await post(contributor, 'Oops, wrong channel');
+ const res = await as(contributor).delete(one(message._id));
+ assert.equal(res.status, 200, JSON.stringify(res.body));
+ assert.equal(res.body.changed, true);
+ assert.equal(res.body.message.deleted, true);
+ assert.equal(res.body.message.body, '');
+ assert.equal(res.body.message.edited, false);
+ assert.deepEqual(res.body.message.mentions, []);
+
+ const history = await as(viewer).get(messages());
+ const row = history.body.messages.find((m) => m._id === message._id);
+ assert.ok(row, 'a deleted message is still listed, so the conversation keeps its order');
+ assert.equal(row.deleted, true);
+ assert.equal(row.body, '');
+
+ const stored = await Message.findById(message._id).lean();
+ assert.ok(stored.deletedAt);
+ assert.equal(stored.body, '', 'the text is removed from the database');
+});
+
+test('A deleted message cannot be edited (409) and deleting again changes nothing', async () => {
+ const message = await post(contributor, 'Short lived');
+ assert.equal((await as(contributor).delete(one(message._id))).status, 200);
+ const edit = await as(contributor).patch(one(message._id)).send({ body: 'Back again' });
+ assert.equal(edit.status, 409);
+ assert.equal(edit.body.code, 'message_deleted');
+ const again = await as(contributor).delete(one(message._id));
+ assert.equal(again.status, 200);
+ assert.equal(again.body.changed, false);
+ assert.equal(again.body.message.deleted, true);
+ assert.equal((await Message.findById(message._id).lean()).body, '');
+});
+
+test('Thread replies can be edited and deleted by their author; the thread keeps making sense', async () => {
+ const parent = await post(owner, 'Vite or Next?');
+ const first = await reply(contributor, parent._id, 'Vite');
+ const second = await reply(owner, parent._id, 'Agreed');
+
+ const edited = await as(contributor).patch(one(first._id)).send({ body: 'Vite, it is lighter' });
+ assert.equal(edited.status, 200, JSON.stringify(edited.body));
+ assert.equal(edited.body.message.edited, true);
+ assert.equal((await as(contributor).delete(one(second._id))).status, 403, 'not your reply');
+
+ assert.equal((await as(owner).delete(one(second._id))).status, 200);
+
+ const thread = await as(viewer).get(replies(parent._id));
+ assert.equal(thread.status, 200);
+ assert.deepEqual(thread.body.replies.map((r) => [r.body, r.edited, r.deleted]), [
+ ['Vite, it is lighter', true, false],
+ ['', false, true],
+ ]);
+ const history = await as(viewer).get(messages());
+ assert.equal(history.body.messages.find((m) => m._id === parent._id).replyCount, 2, 'a deleted reply still holds its place');
+});
+
+test('Deleting the first message of a thread keeps its replies readable and open for new replies', async () => {
+ const parent = await post(contributor, 'Thread starter');
+ await reply(owner, parent._id, 'First answer');
+ assert.equal((await as(contributor).delete(one(parent._id))).status, 200);
+
+ const thread = await as(viewer).get(replies(parent._id));
+ assert.equal(thread.status, 200);
+ assert.equal(thread.body.parent.deleted, true);
+ assert.equal(thread.body.parent.body, '');
+ assert.deepEqual(thread.body.replies.map((r) => r.body), ['First answer']);
+
+ const history = await as(viewer).get(messages());
+ const row = history.body.messages.find((m) => m._id === parent._id);
+ assert.equal(row.deleted, true);
+ assert.equal(row.replyCount, 1);
+
+ const late = await as(owner).post(replies(parent._id)).send({ body: 'Still here' });
+ assert.equal(late.status, 201, JSON.stringify(late.body));
+});
+
+test('The Activity Feed follows edits, and never shows the text of a deleted message', async () => {
+ const message = await post(contributor, 'Feed text one');
+ await as(contributor).patch(one(message._id)).send({ body: 'Feed text two' });
+ let entry = await Activity.findOne({ targetId: message._id, type: 'message.posted' }).lean();
+ assert.equal(entry.summary, 'posted in #general: "Feed text two"');
+
+ await as(contributor).delete(one(message._id));
+ entry = await Activity.findOne({ targetId: message._id, type: 'message.posted' }).lean();
+ assert.equal(entry.summary, 'posted in #general: (message deleted)');
+
+ const parent = await post(owner, 'Feed parent');
+ const answer = await reply(contributor, parent._id, 'Feed reply text');
+ await as(contributor).delete(one(answer._id));
+ entry = await Activity.findOne({ targetId: answer._id, type: 'message.posted' }).lean();
+ assert.equal(entry.summary, 'replied in a thread in #general: (message deleted)');
+});
+
+test('Ask the Copilot never gets the text of a deleted message', async () => {
+ const keep = await post(contributor, 'Copilot may read this');
+ const gone = await post(contributor, 'Copilot must not read this secret');
+ await as(contributor).delete(one(gone._id));
+ const project = await Project.findById(projectId).lean();
+ const { records } = await loadCopilotRecords(project);
+ const text = JSON.stringify(records);
+ assert.ok(text.includes('Copilot may read this'), String(keep._id));
+ assert.ok(!text.includes('must not read this secret'));
+});
+
+test('An edit that adds an @mention notifies that member once', async () => {
+ const message = await post(owner, 'Can someone review?');
+ const count = () => Notification.countDocuments({ recipient: contributor.user.id, type: 'mention', targetId: message._id });
+ assert.equal(await count(), 0);
+
+ const edited = await as(owner).patch(one(message._id)).send({ body: `Can @${contributor.user.username} review?` });
+ assert.equal(edited.status, 200, JSON.stringify(edited.body));
+ assert.deepEqual(edited.body.message.mentions.map((user) => user.username), [contributor.user.username]);
+ assert.equal(await count(), 1);
+
+ await as(owner).patch(one(message._id)).send({ body: `Can @${contributor.user.username} review it today?` });
+ assert.equal(await count(), 1, 'not notified twice for the same message');
+});
+
+test('Edits and deletes reach every member live, and nobody outside the project', async () => {
+ const [ownerSocket, viewerSocket, outsiderSocket] = await Promise.all([open(owner.token), open(viewer.token), open(outsider.token)]);
+ assert.equal((await join(ownerSocket, projectId)).ok, true);
+ assert.equal((await join(viewerSocket, projectId)).ok, true);
+ assert.equal((await join(outsiderSocket, projectId)).ok, false);
+
+ const message = await post(contributor, 'Live before');
+ const editSeen = Promise.all([nextEvent(ownerSocket, 'message:updated'), nextEvent(viewerSocket, 'message:updated')]);
+ const outsiderQuiet = noEvent(outsiderSocket, 'message:updated');
+ await as(contributor).patch(one(message._id)).send({ body: 'Live after' });
+ const [toOwner, toViewer] = await editSeen;
+ for (const payload of [toOwner, toViewer]) {
+ assert.equal(payload.projectId, projectId);
+ assert.equal(payload.channelId, generalId);
+ assert.equal(payload.parentId, null);
+ assert.equal(payload.message._id, message._id);
+ assert.equal(payload.message.body, 'Live after');
+ assert.equal(payload.message.edited, true);
+ }
+ await outsiderQuiet;
+
+ const parent = await post(owner, 'Live thread');
+ const answer = await reply(contributor, parent._id, 'Live reply');
+ const deleteSeen = nextEvent(viewerSocket, 'message:updated');
+ await as(contributor).delete(one(answer._id));
+ const removed = await deleteSeen;
+ assert.equal(removed.parentId, parent._id);
+ assert.equal(removed.message._id, answer._id);
+ assert.equal(removed.message.deleted, true);
+ assert.equal(removed.message.body, '', 'the deleted text is not sent live either');
+});
+
+test('Messages saved before Sprint 7 still work and can be edited', async () => {
+ const legacy = await Message.collection.insertOne({
+ project: new mongoose.Types.ObjectId(projectId),
+ channel: new mongoose.Types.ObjectId(generalId),
+ author: new mongoose.Types.ObjectId(contributor.user.id),
+ body: 'Legacy text',
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ });
+ const history = await as(viewer).get(messages());
+ const row = history.body.messages.find((m) => String(m._id) === String(legacy.insertedId));
+ assert.ok(row, 'legacy message is still listed');
+ assert.equal(row.edited, false);
+ assert.equal(row.deleted, false);
+ const res = await as(contributor).patch(one(legacy.insertedId)).send({ body: 'Legacy text, edited' });
+ assert.equal(res.status, 200, JSON.stringify(res.body));
+ assert.equal(res.body.message.edited, true);
+});
diff --git a/backend/test/channelMessageRules.test.js b/backend/test/channelMessageRules.test.js
new file mode 100644
index 0000000..67466b2
--- /dev/null
+++ b/backend/test/channelMessageRules.test.js
@@ -0,0 +1,83 @@
+// [Sprint 7 · M1] Pure rules for editing and deleting channel messages (no database needed).
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ CHANNEL_DELETED_TEXT,
+ CHANNEL_EDIT_MESSAGES,
+ CHANNEL_MESSAGE_MAX,
+ channelMessageView,
+ isMessageAuthor,
+ messageActivitySummary,
+ readEditedBody,
+} from '../src/lib/channelMessageRules.js';
+
+const at = new Date('2026-11-22T10:00:00Z');
+
+test('isMessageAuthor matches the author whether populated or a raw ID', () => {
+ assert.equal(isMessageAuthor({ author: { _id: 'u1', name: 'Riya' } }, 'u1'), true);
+ assert.equal(isMessageAuthor({ author: 'u1' }, 'u1'), true);
+ assert.equal(isMessageAuthor({ author: 'u1' }, 'u2'), false);
+ assert.equal(isMessageAuthor({ author: null }, 'u1'), false, 'a former member (author gone) matches nobody');
+ assert.equal(isMessageAuthor({ author: 'u1' }, ''), false);
+ assert.equal(isMessageAuthor(null, 'u1'), false);
+});
+
+test('readEditedBody trims and applies the sending rules', () => {
+ assert.deepEqual(readEditedBody(' Hello '), { ok: true, body: 'Hello' });
+ assert.deepEqual(readEditedBody(' '), { ok: false, message: CHANNEL_EDIT_MESSAGES.empty });
+ assert.deepEqual(readEditedBody(undefined), { ok: false, message: CHANNEL_EDIT_MESSAGES.empty });
+ assert.deepEqual(readEditedBody(42), { ok: false, message: CHANNEL_EDIT_MESSAGES.empty });
+ assert.deepEqual(readEditedBody({ body: 'x' }), { ok: false, message: CHANNEL_EDIT_MESSAGES.empty });
+ assert.equal(readEditedBody('x'.repeat(CHANNEL_MESSAGE_MAX)).ok, true);
+ assert.deepEqual(readEditedBody('x'.repeat(CHANNEL_MESSAGE_MAX + 1)), { ok: false, message: CHANNEL_EDIT_MESSAGES.tooLong });
+});
+
+test('channelMessageView keeps every old field and adds edited / deleted', () => {
+ const plain = { _id: 'm1', body: 'Hi @riya', mentions: [{ _id: 'u2' }], replyCount: 2, author: { _id: 'u1' }, createdAt: at };
+ const view = channelMessageView(plain);
+ assert.equal(view.body, 'Hi @riya');
+ assert.equal(view.replyCount, 2);
+ assert.deepEqual(view.mentions, [{ _id: 'u2' }]);
+ assert.equal(view.edited, false);
+ assert.equal(view.deleted, false);
+ assert.equal(view.editedAt, null);
+ assert.equal(view.deletedAt, null);
+ assert.equal(channelMessageView(null), null);
+});
+
+test('an edited message is marked edited', () => {
+ const view = channelMessageView({ _id: 'm1', body: 'Changed', editedAt: at });
+ assert.equal(view.edited, true);
+ assert.equal(view.editedAt, at);
+});
+
+test('a deleted message never carries its text or mentions, and is not "edited"', () => {
+ const view = channelMessageView({ _id: 'm1', body: 'secret', mentions: [{ _id: 'u2' }], editedAt: at, deletedAt: at, replyCount: 3 });
+ assert.equal(view.deleted, true);
+ assert.equal(view.body, '');
+ assert.deepEqual(view.mentions, []);
+ assert.equal(view.edited, false);
+ assert.equal(view.editedAt, null);
+ assert.equal(view.replyCount, 3, 'its thread is kept');
+});
+
+test('activity lines match the wording used when the message was posted', () => {
+ assert.equal(messageActivitySummary({ channelName: 'general', quotedText: '"New text"' }), 'posted in #general: "New text"');
+ assert.equal(
+ messageActivitySummary({ channelName: 'design', isReply: true, quotedText: '"Reply"' }),
+ 'replied in a thread in #design: "Reply"'
+ );
+ assert.equal(messageActivitySummary({ channelName: 'general' }), 'posted in #general: (message deleted)');
+ assert.equal(CHANNEL_DELETED_TEXT, 'Message deleted');
+});
+
+test('a Decision linked to a deleted message shows "Message deleted", not the old text', async () => {
+ const { decisionLinkView } = await import('../src/lib/decisions.js');
+ const decision = { project: 'p1', relatedMessage: 'm1', relatedChannel: 'c1' };
+ const channels = new Map([['c1', { _id: 'c1', name: 'general' }]]);
+ const live = decisionLinkView(decision, { messages: new Map([['m1', { _id: 'm1', body: 'Use Vite' }]]), channels });
+ assert.equal(live.label, '#general: Use Vite');
+ const gone = decisionLinkView(decision, { messages: new Map([['m1', { _id: 'm1', body: '', deletedAt: at }]]), channels });
+ assert.equal(gone.label, '#general: Message deleted');
+ assert.equal(gone.missing, false, 'the thread still exists, so the link still opens it');
+});
diff --git a/e2e/tests/sprint7-channel-edit-delete.spec.js b/e2e/tests/sprint7-channel-edit-delete.spec.js
new file mode 100644
index 0000000..f788f46
--- /dev/null
+++ b/e2e/tests/sprint7-channel-edit-delete.spec.js
@@ -0,0 +1,74 @@
+// [Sprint 7 · M1] Edit and delete your own channel messages and thread replies, end to end.
+// - Edit in place: "(edited)" mark, kept after a reload.
+// - Delete after a confirmation: "Message deleted" in the same place, its thread and reply count kept.
+// - A deleted reply stays in the thread as "Message deleted".
+// (403 for someone else's message and live delivery to other members are covered by
+// backend/test/channelMessageEdits.test.js.)
+import { test, expect } from '@playwright/test';
+import { signUp, createProject, unique } from './helpers.js';
+
+const openTab = (page, name) => page.locator('.project-tabs').getByRole('button', { name, exact: true }).click();
+const channelMessage = (page, text) => page.locator('.chat-messages article.chat-message', { hasText: text });
+
+test('Sprint 7 M1: edit and delete channel messages and thread replies, kept after reload', async ({ page }) => {
+ await signUp(page);
+ await createProject(page);
+ await openTab(page, 'Chat');
+ const room = page.getByRole('region', { name: '#general' });
+
+ const send = async (text) => {
+ await room.getByRole('combobox', { name: 'Message' }).fill(text);
+ await room.getByRole('button', { name: 'Send message' }).click();
+ await expect(channelMessage(page, text)).toBeVisible();
+ };
+
+ // Edit: fix a typo in place.
+ const typo = unique('Standup tommorow');
+ await send(typo);
+ const typoRow = channelMessage(page, typo);
+ await typoRow.hover();
+ await typoRow.getByRole('button', { name: 'Edit message' }).click();
+ const fixed = typo.replace('tommorow', 'tomorrow');
+ await room.getByRole('combobox', { name: 'Edit your message' }).fill(fixed);
+ await room.getByRole('combobox', { name: 'Edit your message' }).press('Enter');
+ const fixedRow = channelMessage(page, fixed);
+ await expect(fixedRow).toBeVisible();
+ await expect(fixedRow.locator('.chat-edited')).toHaveText('(edited)');
+ await expect(room.getByText(typo)).toHaveCount(0);
+
+ // A thread with one reply, then the reply is deleted.
+ const question = unique('Vite or Next?');
+ await send(question);
+ const questionRow = channelMessage(page, question);
+ await questionRow.getByRole('button', { name: 'Reply in thread' }).click();
+ const thread = page.getByRole('complementary', { name: 'Thread' });
+ const answer = unique('Vite, it is lighter');
+ await thread.getByRole('combobox', { name: 'Reply' }).fill(answer);
+ await thread.getByRole('button', { name: 'Send reply' }).click();
+ const answerRow = thread.locator('article.chat-message', { hasText: answer });
+ await expect(answerRow).toBeVisible();
+ await answerRow.hover();
+ await answerRow.getByRole('button', { name: 'Delete message' }).click();
+ await page.getByRole('alertdialog', { name: 'Delete this reply?' }).getByRole('button', { name: 'Delete reply' }).click();
+ await expect(thread.locator('article.chat-message.deleted')).toHaveCount(1);
+ await expect(thread.getByText(answer)).toHaveCount(0);
+ await expect(questionRow.getByRole('button', { name: /1 reply/ })).toBeVisible();
+ await thread.getByRole('button', { name: 'Close thread' }).click();
+
+ // Delete the thread's first message: it stays in place, and its thread can still be opened.
+ await questionRow.hover();
+ await questionRow.getByRole('button', { name: 'Delete message' }).click();
+ await page.getByRole('alertdialog', { name: 'Delete this message?' }).getByRole('button', { name: 'Delete message' }).click();
+ const deletedRows = page.locator('.chat-messages article.chat-message.deleted');
+ await expect(deletedRows).toHaveCount(1);
+ await expect(deletedRows.first()).toContainText('Message deleted');
+ await expect(deletedRows.first().getByRole('button', { name: /1 reply/ })).toBeVisible();
+ await expect(room.getByText(question)).toHaveCount(0);
+
+ // Reload: the edit and both deletes were saved on the server.
+ await page.reload();
+ await openTab(page, 'Chat');
+ await expect(channelMessage(page, fixed).locator('.chat-edited')).toBeVisible();
+ await expect(page.locator('.chat-messages article.chat-message.deleted')).toHaveCount(1);
+ await expect(page.getByText(question)).toHaveCount(0);
+});
diff --git a/frontend/src/api.js b/frontend/src/api.js
index de80b51..70076b8 100644
--- a/frontend/src/api.js
+++ b/frontend/src/api.js
@@ -436,6 +436,14 @@ export const channelApi = {
},
reply: (id, channelId, messageId, body) => api(`${channelPath(id, channelId)}/messages/${encodeURIComponent(messageId)}/replies`, { method: 'POST', body: JSON.stringify({ body }) }),
onReply: (id, handler) => liveApi.onProject(id, 'message:reply', handler),
+
+ // [Sprint 7 · M1] Edit / delete your own message or thread reply (same URL for both). Contract: backend/src/routes/channels.js
+ // edit -> { message, changed, notice } 403 not yours / Viewer, 409 { code: 'message_deleted' }
+ // remove -> { message, changed, notice } the message comes back with deleted: true and body ''
+ // onUpdated(handler) gets { projectId, channelId, parentId, message } (parentId null for a channel message)
+ edit: (id, channelId, messageId, body) => api(`${channelPath(id, channelId)}/messages/${encodeURIComponent(messageId)}`, { method: 'PATCH', body: JSON.stringify({ body }) }),
+ remove: (id, channelId, messageId) => api(`${channelPath(id, channelId)}/messages/${encodeURIComponent(messageId)}`, { method: 'DELETE' }),
+ onUpdated: (id, handler) => liveApi.onProject(id, 'message:updated', handler),
};
// Milestones of one project. Each milestone comes back with taskCount, doneCount, progress (0-100) and completed.
diff --git a/frontend/src/channelMessages.js b/frontend/src/channelMessages.js
new file mode 100644
index 0000000..4bb4d47
--- /dev/null
+++ b/frontend/src/channelMessages.js
@@ -0,0 +1,91 @@
+/*
+ * [Sprint 7 · M1] Edit and delete your own channel messages and thread replies: browser-side helpers.
+ * Server rules: backend/src/lib/channelMessageRules.js. Used by components/ChatPanel.jsx and
+ * components/ThreadPanel.jsx (tested in channelMessages.test.js).
+ */
+
+// What a deleted message shows (same words as the server and as deleted direct messages).
+export const CHANNEL_DELETED_TEXT = 'Message deleted';
+export const CHANNEL_MESSAGE_MAX = 4000;
+
+export const idOf = (value) => String(value?._id || value?.id || value || '');
+
+const timeOf = (value) => {
+ const time = value ? new Date(value).getTime() : 0;
+ return Number.isNaN(time) ? 0 : time;
+};
+
+/*
+ * Which of two copies of the same message to keep. A deleted copy always wins (a message never comes
+ * back after being deleted), then the later edit, so a slow page answer cannot undo a live edit or delete
+ * that arrived first. The reply count only ever goes up, like applyReplyCount in ChatPanel.
+ */
+export function newerMessageCopy(old, incoming) {
+ if (!old) return incoming;
+ if (!incoming) return old;
+ let kept = incoming;
+ if (old.deleted && !incoming.deleted) kept = old;
+ else if (!incoming.deleted && !old.deleted && timeOf(old.editedAt) > timeOf(incoming.editedAt)) kept = old;
+ const replyCount = Math.max(old.replyCount || 0, incoming.replyCount || 0);
+ const lastReplyAt = timeOf(old.lastReplyAt) > timeOf(incoming.lastReplyAt) ? old.lastReplyAt : incoming.lastReplyAt;
+ if (replyCount === (kept.replyCount || 0) && lastReplyAt === kept.lastReplyAt) return kept;
+ return { ...kept, replyCount, ...(lastReplyAt !== undefined ? { lastReplyAt } : {}) };
+}
+
+// Adds or replaces messages by ID and keeps them oldest first (same order as the API).
+export function mergeChannelMessages(list, incoming) {
+ const byId = new Map((list || []).map((message) => [idOf(message), message]));
+ for (const message of incoming || []) {
+ if (message && idOf(message)) byId.set(idOf(message), newerMessageCopy(byId.get(idOf(message)), message));
+ }
+ return [...byId.values()].sort((a, b) => timeOf(a.createdAt) - timeOf(b.createdAt) || idOf(a).localeCompare(idOf(b)));
+}
+
+/*
+ * Updates a message only if it is already in the list. Used for live edits / deletes: a change to a
+ * message on an older page that is not loaded must not be pushed into the middle of the list.
+ */
+export function replaceChannelMessage(list, message) {
+ if (!list || !message) return list;
+ const id = idOf(message);
+ if (!list.some((item) => idOf(item) === id)) return list;
+ return list.map((item) => (idOf(item) === id ? newerMessageCopy(item, message) : item));
+}
+
+// true when the signed-in user wrote this message.
+export function isOwnMessage(message, meId) {
+ return Boolean(meId) && Boolean(idOf(message?.author)) && idOf(message.author) === String(meId);
+}
+
+// Edit: my own message, not deleted, and my role may post (Owner, Admin, Contributor).
+export function canEditMessage(message, meId, canPost) {
+ return Boolean(canPost) && isOwnMessage(message, meId) && !message.deleted;
+}
+
+// Delete: my own message, not deleted yet. Any role (a Viewer can take back what they wrote earlier).
+export function canDeleteMessage(message, meId) {
+ return isOwnMessage(message, meId) && !message.deleted;
+}
+
+/*
+ * Checks the new text before saving an edit (the server checks again).
+ * -> { ok: true, body } | { ok: false, message } | { ok: true, unchanged: true } when nothing changed
+ */
+export function checkEdit(original, draft) {
+ const body = String(draft ?? '').trim();
+ if (!body) return { ok: false, message: 'Message cannot be empty. To remove it, use Delete.' };
+ if (body.length > CHANNEL_MESSAGE_MAX) {
+ return { ok: false, message: `Message must be ${CHANNEL_MESSAGE_MAX.toLocaleString('en-US')} characters or fewer.` };
+ }
+ if (body === String(original?.body ?? '')) return { ok: true, unchanged: true, body };
+ return { ok: true, body };
+}
+
+/*
+ * ---------------------------------------------------------------------------
+ * [Sprint 7 · M1] What this file does
+ * Helpers for editing / deleting channel messages in the browser: who sees
+ * Edit and Delete, the text check before saving, and merging copies of a
+ * message so a deleted or newer edited copy is never replaced by an older one.
+ * ---------------------------------------------------------------------------
+ */
diff --git a/frontend/src/channelMessages.test.js b/frontend/src/channelMessages.test.js
new file mode 100644
index 0000000..f08d0a6
--- /dev/null
+++ b/frontend/src/channelMessages.test.js
@@ -0,0 +1,87 @@
+// [Sprint 7 · M1] Browser helpers for editing / deleting channel messages.
+import { describe, expect, it } from 'vitest';
+import {
+ CHANNEL_DELETED_TEXT,
+ canDeleteMessage,
+ canEditMessage,
+ checkEdit,
+ isOwnMessage,
+ mergeChannelMessages,
+ newerMessageCopy,
+ replaceChannelMessage,
+} from './channelMessages';
+
+const at = (minute) => new Date(Date.UTC(2026, 10, 22, 10, minute)).toISOString();
+const msg = (id, body, minute, extra = {}) => ({ _id: id, body, createdAt: at(minute), author: { _id: 'me', name: 'Me' }, ...extra });
+
+describe('who may edit or delete', () => {
+ it('only the author, and Edit only with a role that can post', () => {
+ const mine = msg('m1', 'Hi', 1);
+ const theirs = msg('m2', 'Hi', 1, { author: { _id: 'u2' } });
+ expect(isOwnMessage(mine, 'me')).toBe(true);
+ expect(isOwnMessage(theirs, 'me')).toBe(false);
+ expect(isOwnMessage(mine, '')).toBe(false);
+ expect(isOwnMessage({ ...mine, author: null }, 'me')).toBe(false);
+ expect(canEditMessage(mine, 'me', true)).toBe(true);
+ expect(canEditMessage(mine, 'me', false)).toBe(false); // Viewer
+ expect(canDeleteMessage(mine, 'me')).toBe(true);
+ expect(canEditMessage(theirs, 'me', true)).toBe(false);
+ expect(canDeleteMessage(theirs, 'me')).toBe(false);
+ });
+
+ it('nothing can be done to a deleted message', () => {
+ const gone = msg('m1', '', 1, { deleted: true });
+ expect(canEditMessage(gone, 'me', true)).toBe(false);
+ expect(canDeleteMessage(gone, 'me')).toBe(false);
+ });
+});
+
+describe('checkEdit', () => {
+ it('trims, refuses empty or too long text, and spots "nothing changed"', () => {
+ expect(checkEdit(msg('m1', 'Old', 1), ' New ')).toEqual({ ok: true, body: 'New' });
+ expect(checkEdit(msg('m1', 'Old', 1), ' ').ok).toBe(false);
+ expect(checkEdit(msg('m1', 'Old', 1), 'x'.repeat(4001)).ok).toBe(false);
+ expect(checkEdit(msg('m1', 'Old', 1), ' Old ')).toEqual({ ok: true, unchanged: true, body: 'Old' });
+ });
+});
+
+describe('merging copies of a message', () => {
+ it('a deleted copy is never replaced by an older live copy', () => {
+ const deleted = msg('m1', '', 1, { deleted: true });
+ expect(newerMessageCopy(deleted, msg('m1', 'Back?', 1)).deleted).toBe(true);
+ expect(newerMessageCopy(msg('m1', 'Hi', 1), deleted).deleted).toBe(true);
+ });
+
+ it('the later edit wins', () => {
+ const early = msg('m1', 'First edit', 1, { edited: true, editedAt: at(5) });
+ const late = msg('m1', 'Second edit', 1, { edited: true, editedAt: at(6) });
+ expect(newerMessageCopy(late, early).body).toBe('Second edit');
+ expect(newerMessageCopy(early, late).body).toBe('Second edit');
+ });
+
+ it('keeps the higher reply count', () => {
+ const counted = msg('m1', 'Hi', 1, { replyCount: 3, lastReplyAt: at(9) });
+ const edited = msg('m1', 'Hi!', 1, { replyCount: 2, edited: true, editedAt: at(7) });
+ const kept = newerMessageCopy(counted, edited);
+ expect(kept.body).toBe('Hi!');
+ expect(kept.replyCount).toBe(3);
+ expect(kept.lastReplyAt).toBe(at(9));
+ });
+
+ it('mergeChannelMessages adds once and keeps the oldest first', () => {
+ const merged = mergeChannelMessages([msg('b', 'two', 2)], [msg('a', 'one', 1), msg('b', 'two (edited)', 2, { editedAt: at(3) })]);
+ expect(merged.map((m) => m._id)).toEqual(['a', 'b']);
+ expect(merged[1].body).toBe('two (edited)');
+ });
+
+ it('replaceChannelMessage only updates a message that is already shown', () => {
+ const list = [msg('a', 'one', 1)];
+ expect(replaceChannelMessage(list, msg('zzz', 'not loaded', 0))).toBe(list);
+ expect(replaceChannelMessage(list, msg('a', '', 1, { deleted: true }))[0].deleted).toBe(true);
+ expect(replaceChannelMessage(null, msg('a', 'x', 1))).toBeNull();
+ });
+
+ it('uses the same deleted text as the server', () => {
+ expect(CHANNEL_DELETED_TEXT).toBe('Message deleted');
+ });
+});
diff --git a/frontend/src/components/ChannelMessageEdit.jsx b/frontend/src/components/ChannelMessageEdit.jsx
new file mode 100644
index 0000000..e8c95e8
--- /dev/null
+++ b/frontend/src/components/ChannelMessageEdit.jsx
@@ -0,0 +1,211 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { Ban, Check, Loader2, Pencil, Trash2 } from 'lucide-react';
+import ConfirmDialog from './ConfirmDialog';
+import MentionTextarea from './MentionTextarea';
+import MentionText from './MentionText';
+import { CHANNEL_DELETED_TEXT, CHANNEL_MESSAGE_MAX, checkEdit, idOf } from '../channelMessages';
+
+/*
+ * [Sprint 7 · M1] Edit and delete your own channel messages and thread replies.
+ * Shared by ChatPanel (channel messages) and ThreadPanel (the thread's first message and its replies).
+ *
+ * const edits = useChannelMessageEdits({ api, projectId, channelId, onChanged });
+ *
+ {CHANNEL_DELETED_TEXT} +
+ ); + } + return ( +
+
Loading replies…
No replies yet.{canPost ? ' Start the side discussion here.' : ''}
} - {(replies || []).map((reply) =>Viewers can read threads but not reply.
)} {sendError &&