fix: remove ghost reactions when a user is deleted#39844
fix: remove ghost reactions when a user is deleted#39844Sanskar-Agrawal01 wants to merge 1 commit into
Conversation
|
|
Looks like this PR is not ready to merge, because of the following issues:
Please fix the issues and try again If you have any trouble, please check the PR guidelines |
WalkthroughThe PR adds a method to clean up message reactions when a user is deleted. During user deletion, the system now calls Changes
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Suggested labels
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
1 issue found across 3 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="packages/models/src/models/Messages.ts">
<violation number="1" location="packages/models/src/models/Messages.ts:1849">
P1: Reaction cleanup uses arrayFilters on `reactions` as if it were an array, but `reactions` is an object map, so the update is invalid or ineffective.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
| await this.col.updateMany( | ||
| { 'reactions': { $exists: true } }, | ||
| { | ||
| $pull: { 'reactions.$[bucket].usernames': username } as any, |
There was a problem hiding this comment.
P1: Reaction cleanup uses arrayFilters on reactions as if it were an array, but reactions is an object map, so the update is invalid or ineffective.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/models/src/models/Messages.ts, line 1849:
<comment>Reaction cleanup uses arrayFilters on `reactions` as if it were an array, but `reactions` is an object map, so the update is invalid or ineffective.</comment>
<file context>
@@ -1842,4 +1842,15 @@ export class MessagesRaw extends BaseRaw<IMessage> implements IMessagesModel {
+ await this.col.updateMany(
+ { 'reactions': { $exists: true } },
+ {
+ $pull: { 'reactions.$[bucket].usernames': username } as any,
+ },
+ {
</file context>
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@apps/meteor/app/lib/server/functions/deleteUser.ts`:
- Around line 113-114: The two added lines (the comment and the await call to
Messages.removeReactionsByUsername(user.username)) use spaces for indentation
while the file uses tabs; change their leading whitespace to tabs so they align
with surrounding lines in deleteUser.ts and the surrounding block where the
function removeReactionsByUsername is invoked, ensuring consistent indentation
with other statements in the same scope.
In `@packages/models/src/models/Messages.ts`:
- Around line 1845-1855: The method removeReactionsByUsername uses spaces for
indentation while the rest of the file uses tabs; re-indent the method body
(everything inside async removeReactionsByUsername) to use tabs instead of
spaces so it matches the file's tab-based formatting, keeping the same
statements (this.col.updateMany, $pull, arrayFilters) and behavior unchanged.
- Around line 1845-1855: The method removeReactionsByUsername uses spaces for
indentation; convert its body (the updateMany call and options) to use tabs to
match file convention (see other methods like setReactions) so indentation is
consistent; locate the removeReactionsByUsername method and replace leading
spaces on lines containing the await this.col.updateMany call, its query, update
and options, and the closing brace with tabs only.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 99114104-3a7b-4b20-baea-c39248ac2134
📒 Files selected for processing (3)
apps/meteor/app/lib/server/functions/deleteUser.tspackages/model-typings/src/models/IMessagesModel.tspackages/models/src/models/Messages.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: cubic · AI code reviewer
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}
📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)
**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation
Files:
packages/model-typings/src/models/IMessagesModel.tsapps/meteor/app/lib/server/functions/deleteUser.tspackages/models/src/models/Messages.ts
🧠 Learnings (11)
📓 Common learnings
Learnt from: smirk-dev
Repo: RocketChat/Rocket.Chat PR: 39625
File: apps/meteor/app/api/server/v1/push.ts:85-97
Timestamp: 2026-03-14T14:58:58.834Z
Learning: In RocketChat/Rocket.Chat, the `push.token` POST/DELETE endpoints in `apps/meteor/app/api/server/v1/push.ts` were already migrated to the chained router API pattern on `develop` prior to PR `#39625`. `cleanTokenResult` (which strips `authToken` and returns `PushTokenResult`) and `isPushTokenPOSTProps`/`isPushTokenDELETEProps` validators already exist on `develop`. PR `#39625` only migrates `push.get` and `push.info` to the chained pattern. Do not flag `cleanTokenResult` or `PushTokenResult` as newly introduced behavior-breaking changes when reviewing this PR.
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.
Applied to files:
packages/model-typings/src/models/IMessagesModel.tsapps/meteor/app/lib/server/functions/deleteUser.tspackages/models/src/models/Messages.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.
Applied to files:
packages/model-typings/src/models/IMessagesModel.tsapps/meteor/app/lib/server/functions/deleteUser.tspackages/models/src/models/Messages.ts
📚 Learning: 2026-03-09T18:39:21.178Z
Learnt from: Harxhit
Repo: RocketChat/Rocket.Chat PR: 39476
File: apps/meteor/server/methods/addAllUserToRoom.ts:0-0
Timestamp: 2026-03-09T18:39:21.178Z
Learning: In apps/meteor/server/methods/addAllUserToRoom.ts, the implementation uses a single cursor pass (Users.find(userFilter).batchSize(100)) that collects both the full user objects (collectedUsers: IUser[]) and their usernames (usernames: string[]) in one iteration. `beforeAddUserToRoom` is then called once with the full usernames batch (preserving batch-validation semantics), and the subsequent subscription/message processing loop iterates over the same stable `collectedUsers` array — no second DB query is made. This avoids any race condition between validation and processing while preserving the original batch-validation behavior.
Applied to files:
apps/meteor/app/lib/server/functions/deleteUser.tspackages/models/src/models/Messages.ts
📚 Learning: 2026-03-11T22:04:20.529Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 39545
File: apps/meteor/client/views/room/body/hooks/useHasNewMessages.ts:59-61
Timestamp: 2026-03-11T22:04:20.529Z
Learning: In `apps/meteor/client/views/room/body/hooks/useHasNewMessages.ts`, the `msg.u._id === uid` early-return in the `streamNewMessage` handler is intentional: the "New messages" indicator is designed to notify about messages from other users only. Self-sent messages — including those sent from a different session/device — are always skipped, by design. Do not flag this as a multi-session regression.
Applied to files:
apps/meteor/app/lib/server/functions/deleteUser.ts
📚 Learning: 2026-03-12T10:26:26.697Z
Learnt from: ahmed-n-abdeltwab
Repo: RocketChat/Rocket.Chat PR: 39340
File: apps/meteor/app/api/server/v1/im.ts:1349-1398
Timestamp: 2026-03-12T10:26:26.697Z
Learning: In `apps/meteor/app/api/server/v1/im.ts` (PR `#39340`), the `DmEndpoints` type intentionally includes temporary stub entries for `/v1/im.kick`, `/v1/dm.kick`, `/v1/im.leave`, and `/v1/dm.leave` (using `DmKickProps` and `DmLeaveProps`) even though no route handlers exist for them yet. These stubs were added to preserve type compatibility after removing the original `DmLeaveProps` and related files. They are planned for cleanup in a follow-up PR. Do not flag these as missing implementations when reviewing this file until the follow-up is merged.
Applied to files:
apps/meteor/app/lib/server/functions/deleteUser.ts
📚 Learning: 2025-09-25T09:59:26.461Z
Learnt from: Dnouv
Repo: RocketChat/Rocket.Chat PR: 37057
File: packages/apps-engine/src/definition/accessors/IUserRead.ts:23-27
Timestamp: 2025-09-25T09:59:26.461Z
Learning: AppUserBridge.getUserRoomIds in apps/meteor/app/apps/server/bridges/users.ts always returns an array of strings (mapping subscription documents to room IDs), never undefined, even when user has no room subscriptions.
Applied to files:
apps/meteor/app/lib/server/functions/deleteUser.ts
📚 Learning: 2025-09-25T09:59:26.461Z
Learnt from: Dnouv
Repo: RocketChat/Rocket.Chat PR: 37057
File: packages/apps-engine/src/definition/accessors/IUserRead.ts:23-27
Timestamp: 2025-09-25T09:59:26.461Z
Learning: AppUserBridge.getUserRoomIds in apps/meteor/app/apps/server/bridges/users.ts always returns an array of strings by mapping subscription documents to room IDs, never undefined, even when user has no room subscriptions.
Applied to files:
apps/meteor/app/lib/server/functions/deleteUser.ts
📚 Learning: 2025-09-30T13:00:05.465Z
Learnt from: d-gubert
Repo: RocketChat/Rocket.Chat PR: 36990
File: apps/meteor/ee/server/apps/storage/AppRealStorage.ts:55-58
Timestamp: 2025-09-30T13:00:05.465Z
Learning: In AppRealStorage (apps/meteor/ee/server/apps/storage/AppRealStorage.ts), the `remove` method is designed to be idempotent and returns `{ success: true }` unconditionally because the goal is to ensure the app is removed, not to distinguish whether this specific call performed the deletion. Database errors will throw exceptions.
Applied to files:
apps/meteor/app/lib/server/functions/deleteUser.ts
📚 Learning: 2026-01-17T01:51:47.764Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 38219
File: packages/core-typings/src/cloud/Announcement.ts:5-6
Timestamp: 2026-01-17T01:51:47.764Z
Learning: In packages/core-typings/src/cloud/Announcement.ts, the AnnouncementSchema.createdBy field intentionally overrides IBannerSchema.createdBy (object with _id and optional username) with a string enum ['cloud', 'system'] to match existing runtime behavior. This is documented as technical debt with a FIXME comment at apps/meteor/app/cloud/server/functions/syncWorkspace/handleCommsSync.ts:53 and should not be flagged as an error until the runtime behavior is corrected.
Applied to files:
apps/meteor/app/lib/server/functions/deleteUser.ts
📚 Learning: 2025-12-09T20:01:07.355Z
Learnt from: sampaiodiego
Repo: RocketChat/Rocket.Chat PR: 37532
File: ee/packages/federation-matrix/src/FederationMatrix.ts:920-927
Timestamp: 2025-12-09T20:01:07.355Z
Learning: In Rocket.Chat's federation invite handling (ee/packages/federation-matrix/src/FederationMatrix.ts), when a user rejects an invite via federationSDK.rejectInvite(), the subscription cleanup happens automatically through an event-driven flow: Matrix emits a leave event back, which is processed by handleLeave() in ee/packages/federation-matrix/src/events/member.ts, and that function calls Room.performUserRemoval() to clean up the subscription. No explicit cleanup is needed in the reject branch of handleInvite() because the leave event handler takes care of it.
<!-- </add_learning>
Applied to files:
apps/meteor/app/lib/server/functions/deleteUser.ts
🔇 Additional comments (1)
packages/model-typings/src/models/IMessagesModel.ts (1)
300-300: LGTM!The interface method signature is well-typed and follows existing patterns in
IMessagesModelfor similar operations likeremoveByUserIdandremoveByRoomId.
| // Remove deleted user's username from all message reactions | ||
| await Messages.removeReactionsByUsername(user.username); |
There was a problem hiding this comment.
Fix inconsistent indentation.
The added lines use spaces instead of tabs, which is inconsistent with the rest of the file's formatting. The code should align with the surrounding indentation style.
🔧 Proposed fix
- // Remove deleted user's username from all message reactions
- await Messages.removeReactionsByUsername(user.username);
+ // Remove deleted user's username from all message reactions
+ await Messages.removeReactionsByUsername(user.username);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // Remove deleted user's username from all message reactions | |
| await Messages.removeReactionsByUsername(user.username); | |
| // Remove deleted user's username from all message reactions | |
| await Messages.removeReactionsByUsername(user.username); |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/meteor/app/lib/server/functions/deleteUser.ts` around lines 113 - 114,
The two added lines (the comment and the await call to
Messages.removeReactionsByUsername(user.username)) use spaces for indentation
while the file uses tabs; change their leading whitespace to tabs so they align
with surrounding lines in deleteUser.ts and the surrounding block where the
function removeReactionsByUsername is invoked, ensuring consistent indentation
with other statements in the same scope.
| async removeReactionsByUsername(username: string): Promise<void> { | ||
| await this.col.updateMany( | ||
| { 'reactions': { $exists: true } }, | ||
| { | ||
| $pull: { 'reactions.$[bucket].usernames': username } as any, | ||
| }, | ||
| { | ||
| arrayFilters: [{ 'bucket.usernames': username }], | ||
| }, | ||
| ); | ||
| } |
There was a problem hiding this comment.
Fix inconsistent indentation.
The method body uses spaces instead of tabs, which is inconsistent with the rest of the file.
🔧 Proposed indentation fix
async removeReactionsByUsername(username: string): Promise<void> {
- await this.col.updateMany(
- { 'reactions': { $exists: true } },
- {
- $pull: { 'reactions.$[bucket].usernames': username } as any,
- },
- {
- arrayFilters: [{ 'bucket.usernames': username }],
- },
- );
-}
+ await this.col.updateMany(
+ { reactions: { $exists: true } },
+ {
+ $pull: { 'reactions.$[bucket].usernames': username } as any,
+ },
+ {
+ arrayFilters: [{ 'bucket.usernames': username }],
+ },
+ );
+}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| async removeReactionsByUsername(username: string): Promise<void> { | |
| await this.col.updateMany( | |
| { 'reactions': { $exists: true } }, | |
| { | |
| $pull: { 'reactions.$[bucket].usernames': username } as any, | |
| }, | |
| { | |
| arrayFilters: [{ 'bucket.usernames': username }], | |
| }, | |
| ); | |
| } | |
| async removeReactionsByUsername(username: string): Promise<void> { | |
| await this.col.updateMany( | |
| { reactions: { $exists: true } }, | |
| { | |
| $pull: { 'reactions.$[bucket].usernames': username } as any, | |
| }, | |
| { | |
| arrayFilters: [{ 'bucket.usernames': username }], | |
| }, | |
| ); | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/models/src/models/Messages.ts` around lines 1845 - 1855, The method
removeReactionsByUsername uses spaces for indentation while the rest of the file
uses tabs; re-indent the method body (everything inside async
removeReactionsByUsername) to use tabs instead of spaces so it matches the
file's tab-based formatting, keeping the same statements (this.col.updateMany,
$pull, arrayFilters) and behavior unchanged.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check how reactions are handled elsewhere in the codebase to understand cleanup patterns
# Search for existing reaction cleanup logic
rg -n -A 5 'reactions.*usernames.*\[\]|unsetReactions' --type tsRepository: RocketChat/Rocket.Chat
Length of output: 6768
🏁 Script executed:
#!/bin/bash
# Find where removeReactionsByUsername is called
rg -n 'removeReactionsByUsername' --type tsRepository: RocketChat/Rocket.Chat
Length of output: 413
🏁 Script executed:
#!/bin/bash
# Check the actual indentation and context around lines 1845-1855
head -n 1860 packages/models/src/models/Messages.ts | tail -n 30Repository: RocketChat/Rocket.Chat
Length of output: 779
🏁 Script executed:
#!/bin/bash
# Search for cleanup patterns after reaction operations
rg -n -B 3 -A 3 'removeReactionsByUsername|removeReaction' apps/meteor --type ts | head -100Repository: RocketChat/Rocket.Chat
Length of output: 3273
🏁 Script executed:
#!/bin/bash
# Look for other reactions manipulation methods to understand the pattern
rg -n 'setReactions|reactions\.' packages/models/src/models/Messages.ts | head -30Repository: RocketChat/Rocket.Chat
Length of output: 639
🏁 Script executed:
#!/bin/bash
# Check if there's any documentation or comments about reaction cleanup expectations
rg -n -B 2 -A 2 'removeReactionsByUsername|unsetReactions' packages/models/src/models/Messages.tsRepository: RocketChat/Rocket.Chat
Length of output: 406
🏁 Script executed:
#!/bin/bash
# Check what indentation style is used in the file (tabs vs spaces)
head -n 100 packages/models/src/models/Messages.ts | cat -A | grep -E '^\t|^ ' | head -10Repository: RocketChat/Rocket.Chat
Length of output: 121
🏁 Script executed:
#!/bin/bash
# Look at the complete removeReactionsByUsername method with visible whitespace
sed -n '1845,1855p' packages/models/src/models/Messages.ts | cat -ARepository: RocketChat/Rocket.Chat
Length of output: 406
🏁 Script executed:
#!/bin/bash
# Check how setReactions method is implemented for comparison
sed -n '673,680p' packages/models/src/models/Messages.ts | cat -ARepository: RocketChat/Rocket.Chat
Length of output: 387
Fix indentation to use tabs consistently with the rest of the file.
The method body uses spaces instead of tabs. The file convention throughout is tabs (as seen in setReactions and other methods). Change lines 1846-1854 to use tab indentation.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/models/src/models/Messages.ts` around lines 1845 - 1855, The method
removeReactionsByUsername uses spaces for indentation; convert its body (the
updateMany call and options) to use tabs to match file convention (see other
methods like setReactions) so indentation is consistent; locate the
removeReactionsByUsername method and replace leading spaces on lines containing
the await this.col.updateMany call, its query, update and options, and the
closing brace with tabs only.
When a user is deleted from the workspace, their username was not being removed from message reactions stored in the rocketchat_message collection. Rocket.Chat stores reactions using usernames directly inside the message document as reactions: { ":emoji:": { usernames: ["userA", "userB"] } } instead of user IDs, which means the standard user deletion cascade does not clean up these references. As a result, deleted users continued to appear as having reacted to messages, creating ghost reactions that reference usernames no longer present in the users collection.
To fix this, a new method removeReactionsByUsername() was added to the MessagesRaw model and the IMessagesModel interface. This method uses MongoDB's arrayFilters with the $[bucket] positional operator to efficiently remove the deleted user's username from every reaction bucket across all message documents in a single updateMany call. The method is then invoked inside deleteUser.ts as part of the existing user deletion flow, right before subscriptions are removed, ensuring no orphan reaction references remain after a user is deleted
Summary by CodeRabbit