Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
117 changes: 117 additions & 0 deletions backend/src/lib/channelMessageEdits.js
Original file line number Diff line number Diff line change
@@ -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.
* ---------------------------------------------------------------------------
*/
96 changes: 96 additions & 0 deletions backend/src/lib/channelMessageRules.js
Original file line number Diff line number Diff line change
@@ -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.
* ---------------------------------------------------------------------------
*/
4 changes: 3 additions & 1 deletion backend/src/lib/copilotContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion backend/src/lib/decisions.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand Down
19 changes: 19 additions & 0 deletions backend/src/lib/realtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
14 changes: 13 additions & 1 deletion backend/src/models/Message.js
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand All @@ -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.
Expand Down Expand Up @@ -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 }
);
Expand Down
Loading
Loading