Skip to content

Conversation

@sampaiodiego
Copy link
Member

@sampaiodiego sampaiodiego commented Dec 15, 2025

Proposed changes (including videos or screenshots)

FB-151

Issue(s)

Steps to test or reproduce

Further comments

Summary by CodeRabbit

Release Notes

  • New Features

    • Improved direct message naming consistency and user management workflows.
  • Bug Fixes

    • Enhanced cleanup of direct message references when users are removed from rooms.
    • Strengthened username validation during user removal operations.
  • Tests

    • Added comprehensive unit and integration test coverage for direct message operations and name handling.

✏️ Tip: You can customize this high-level summary in your review settings.

@dionisio-bot
Copy link
Contributor

dionisio-bot bot commented Dec 15, 2025

Looks like this PR is ready to merge! 🎉
If you have any trouble, please check the PR guidelines

@changeset-bot
Copy link

changeset-bot bot commented Dec 15, 2025

⚠️ No Changeset found

Latest commit: 3692b7a

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 15, 2025

Walkthrough

This PR refactors direct message room naming by introducing a new getNameForDMs service function that computes display names for DM members, integrates it into the room creation and removal workflows, adds a RoomService.updateDirectMessageRoomName method to update subscriptions, and prevents fname assignment for federated DM rooms while triggering name updates on member leave events.

Changes

Cohort / File(s) Summary
Direct Message Naming Service
apps/meteor/server/services/room/getNameForDMs.ts
New module exporting getNameForDMs() function that maps user IDs to display name objects (fname/name) by analyzing member lists and sorting by display preference.
Room Service Enhancement
apps/meteor/server/services/room/service.ts
Added updateDirectMessageRoomName() method that fetches room subscriptions, loads user details, computes names via getNameForDMs, updates subscription records, and triggers notifications.
Core Service Interfaces
packages/core-services/src/types/IRoomService.ts
Extended interface with new updateDirectMessageRoomName(room: IRoom): Promise<boolean> method signature.
Database Model & Interface
packages/model-typings/src/models/IRoomsModel.ts, packages/models/src/models/Rooms.ts
Added removeUserReferenceFromDMsById() method to remove user references from direct message rooms via $pull operation on usernames and uids arrays.
Direct Room Creation
apps/meteor/app/lib/server/functions/createDirectRoom.ts
Replaced local name-derivation helpers with getNameForDMs() call; subscription data now uses computed fname/name values.
User Removal Flow
apps/meteor/app/lib/server/functions/removeUserFromRoom.ts
Added username validation guard, new branch to remove user from DM room references via removeUserReferenceFromDMsById() when room.t === 'd', and replaced fallback username usage with direct assertion.
Federation Member Events
ee/packages/federation-matrix/src/events/member.ts
Conditionally excludes fname from DM room extraData; calls updateDirectMessageRoomName() after removing users from direct message rooms.
Test Coverage
apps/meteor/tests/unit/server/services/room/getNameForDMs.spec.ts
Unit tests covering empty arrays, single/multiple members, name/username fallbacks, and sorting behavior for getNameForDMs().
Test Utilities
apps/meteor/tests/data/rooms.helper.ts
Enhanced getSubscriptionByRoomId() with optional request injection parameter and explicit rejection on errors or missing subscriptions.
Federation DM Tests
ee/packages/federation-matrix/tests/end-to-end/dms.spec.ts
Expanded 1:1 DM federation test flows with rcUser state tracking, room info assertions, and fname/room-name verification after invitation and leave events.

Sequence Diagram

sequenceDiagram
    actor User
    participant RoomService
    participant UserDB as User Database
    participant getNameForDMs
    participant SubscriptionDB as Subscription Store
    participant NotificationService

    User->>RoomService: updateDirectMessageRoomName(room)
    RoomService->>SubscriptionDB: fetch subscriptions by room ID
    SubscriptionDB-->>RoomService: subscriptions[]
    RoomService->>UserDB: load user details by user IDs
    UserDB-->>RoomService: users[]
    RoomService->>getNameForDMs: compute display names from members
    getNameForDMs-->>RoomService: Map<userId, {fname, name}>
    
    loop For each subscription
        RoomService->>SubscriptionDB: update subscription name/fname
        SubscriptionDB-->>RoomService: update confirmed
        RoomService->>NotificationService: notify on subscription changed
    end
    
    NotificationService-->>User: subscription name updated
    RoomService-->>User: returns true
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • getNameForDMs sorting logic — review member name/username derivation, sorting behavior across single/multiple members, and edge cases (empty names, missing fields)
  • Database operation — verify removeUserReferenceFromDMsById() correctly targets DMs, applies $pull to both usernames and uids arrays, and handles duplicates
  • Federation integration — confirm fname exclusion logic for DM types is sound and updateDirectMessageRoomName is called at the right point in member-leave flow
  • Integration with removeUserFromRoom — ensure DM cleanup path is called only for direct rooms and doesn't interfere with existing system messages or callbacks
  • Test helper refactor — validate error handling (rejection on missing subscription or request errors) and backward compatibility of optional third parameter

Possibly related PRs

Suggested labels

stat: ready to merge, stat: QA assured

Suggested reviewers

  • ggazzo
  • rodrigok

Poem

🐰 A rabbit hops through DM's dance,
Where names compute and subscriptions prance—
When members leave, the room's renamed with care,
Federation knows, no fname's there.
Hopping forward, names so bright! 🌟

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'test(federation): validate empty room state' accurately reflects the main objective: adding federation tests to validate empty room behavior after a user leaves.
Linked Issues check ✅ Passed The PR implements code changes to support empty DM state validation when users leave, including DM cleanup logic and name management, which aligns with FB-151 requirements.
Out of Scope Changes check ✅ Passed All changes are scoped to federation DM handling and test infrastructure; no unrelated modifications detected beyond the stated objective.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch test-federation-empty-dm-state

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@sampaiodiego sampaiodiego force-pushed the test-federation-empty-dm-state branch from 57904f6 to f4cd676 Compare December 15, 2025 22:29
@github-actions
Copy link
Contributor

github-actions bot commented Dec 15, 2025

📦 Docker Image Size Report

📈 Changes

Service Current Baseline Change Percent
sum of all images 1.2GiB 1.2GiB +12MiB
rocketchat 358MiB 347MiB +12MiB
omnichannel-transcript-service 132MiB 132MiB +2.4KiB
queue-worker-service 132MiB 132MiB -257B
ddp-streamer-service 126MiB 126MiB +86B
account-service 113MiB 113MiB -257B
authorization-service 111MiB 111MiB +202B
stream-hub-service 110MiB 110MiB +197B
presence-service 110MiB 110MiB -254B

📊 Historical Trend

---
config:
  theme: "dark"
  xyChart:
    width: 900
    height: 400
---
xychart
  title "Image Size Evolution by Service (Last 30 Days + This PR)"
  x-axis ["11/15 22:28", "11/16 01:28", "11/17 23:50", "11/18 22:53", "11/19 23:02", "11/21 16:49", "11/24 17:34", "11/27 22:32", "11/28 19:05", "12/01 23:01", "12/02 21:57", "12/03 21:00", "12/04 18:17", "12/05 21:56", "12/08 20:15", "12/09 22:17", "12/10 23:26", "12/11 21:56", "12/12 22:45", "12/13 01:34", "12/15 22:31", "12/16 22:18", "12/17 21:04", "12/18 19:04", "12/18 19:24 (PR)"]
  y-axis "Size (GB)" 0 --> 0.5
  line "account-service" [0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11]
  line "authorization-service" [0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11]
  line "ddp-streamer-service" [0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12]
  line "omnichannel-transcript-service" [0.14, 0.14, 0.14, 0.14, 0.14, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13]
  line "presence-service" [0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11]
  line "queue-worker-service" [0.14, 0.14, 0.14, 0.14, 0.14, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13]
  line "rocketchat" [0.36, 0.36, 0.35, 0.35, 0.35, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.35]
  line "stream-hub-service" [0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11, 0.11]
Loading

Statistics (last 24 days):

  • 📊 Average: 1.5GiB
  • ⬇️ Minimum: 1.2GiB
  • ⬆️ Maximum: 1.6GiB
  • 🎯 Current PR: 1.2GiB
ℹ️ About this report

This report compares Docker image sizes from this build against the develop baseline.

  • Tag: pr-37824
  • Baseline: develop
  • Timestamp: 2025-12-18 19:24:55 UTC
  • Historical data points: 24

Updated: Thu, 18 Dec 2025 19:24:56 GMT

@sampaiodiego sampaiodiego force-pushed the test-federation-empty-dm-state branch from f4cd676 to 7030de4 Compare December 15, 2025 22:47
@codecov
Copy link

codecov bot commented Dec 15, 2025

Codecov Report

❌ Patch coverage is 33.33333% with 16 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.81%. Comparing base (65214b6) to head (3692b7a).
⚠️ Report is 3 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #37824      +/-   ##
===========================================
+ Coverage    67.75%   67.81%   +0.06%     
===========================================
  Files         3463     3464       +1     
  Lines       113702   113726      +24     
  Branches     20901    20905       +4     
===========================================
+ Hits         77034    77128      +94     
+ Misses       34501    34415      -86     
- Partials      2167     2183      +16     
Flag Coverage Δ
e2e 57.21% <ø> (+<0.01%) ⬆️
e2e-api 44.94% <33.33%> (+0.89%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@sampaiodiego sampaiodiego force-pushed the test-federation-empty-dm-state branch 5 times, most recently from 75fc3d0 to 6674a96 Compare December 16, 2025 22:05
@ggazzo ggazzo force-pushed the test-federation-empty-dm-state branch 2 times, most recently from 83299a8 to 9b8c873 Compare December 17, 2025 19:42
@sampaiodiego sampaiodiego force-pushed the test-federation-empty-dm-state branch from 56a63e2 to baefb64 Compare December 17, 2025 21:44
@sampaiodiego sampaiodiego force-pushed the test-federation-empty-dm-state branch from baefb64 to 3692b7a Compare December 18, 2025 18:55
@sampaiodiego sampaiodiego marked this pull request as ready for review December 18, 2025 18:55
@sampaiodiego sampaiodiego requested review from a team as code owners December 18, 2025 18:55
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
apps/meteor/server/services/room/service.ts (1)

39-55: Consider edge-case handling for empty subscriptions and missing name mappings.

The method works well for the common case, but consider these edge cases:

  1. If subs is empty (no subscriptions), uids will be empty, roomMembers will be empty, roomNames will be {}, and the loop does nothing. Returning true is misleading—consider returning false or the count of updated subscriptions.

  2. If a subscription's user ID is not in the roomNames map (e.g., due to a deleted user not found by findUsersByIds), roomNames[sub.u._id] will be undefined, and the $set will set undefined fields.

🔎 Suggested defensive check:
 	for await (const sub of subs) {
+		const names = roomNames[sub.u._id];
+		if (!names) {
+			continue;
+		}
-		await Subscriptions.updateOne({ _id: sub._id }, { $set: roomNames[sub.u._id] });
+		await Subscriptions.updateOne({ _id: sub._id }, { $set: names });

 		void notifyOnSubscriptionChangedByRoomIdAndUserId(room._id, sub.u._id, 'updated');
 	}
ee/packages/federation-matrix/tests/end-to-end/dms.spec.ts (1)

205-284: Consider extracting shared test setup logic to reduce duplication.

The "Room list name validations" and "Permission validations" blocks share nearly identical setup code and initial tests (DM creation, invitation acceptance, fname display). While separate describe blocks with independent setup is correct for test isolation, the repetitive test cases (lines 235-284 mirror 124-173) could be:

  1. Extracted into shared helper functions, or
  2. Consolidated if they don't need to run in separate contexts

The unique test in "Permission validations" is should leave the DM from Rocket.Chat (lines 286-303), which justifies a separate block, but the preceding tests could be shared.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Jira integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3b9aab8 and 3692b7a.

📒 Files selected for processing (11)
  • apps/meteor/app/lib/server/functions/createDirectRoom.ts (4 hunks)
  • apps/meteor/app/lib/server/functions/removeUserFromRoom.ts (3 hunks)
  • apps/meteor/server/services/room/getNameForDMs.ts (1 hunks)
  • apps/meteor/server/services/room/service.ts (2 hunks)
  • apps/meteor/tests/data/rooms.helper.ts (1 hunks)
  • apps/meteor/tests/unit/server/services/room/getNameForDMs.spec.ts (1 hunks)
  • ee/packages/federation-matrix/src/events/member.ts (2 hunks)
  • ee/packages/federation-matrix/tests/end-to-end/dms.spec.ts (2 hunks)
  • packages/core-services/src/types/IRoomService.ts (1 hunks)
  • packages/model-typings/src/models/IRoomsModel.ts (1 hunks)
  • packages/models/src/models/Rooms.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{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/core-services/src/types/IRoomService.ts
  • apps/meteor/app/lib/server/functions/createDirectRoom.ts
  • apps/meteor/server/services/room/service.ts
  • apps/meteor/app/lib/server/functions/removeUserFromRoom.ts
  • apps/meteor/server/services/room/getNameForDMs.ts
  • packages/model-typings/src/models/IRoomsModel.ts
  • apps/meteor/tests/unit/server/services/room/getNameForDMs.spec.ts
  • apps/meteor/tests/data/rooms.helper.ts
  • ee/packages/federation-matrix/src/events/member.ts
  • packages/models/src/models/Rooms.ts
  • ee/packages/federation-matrix/tests/end-to-end/dms.spec.ts
**/*.spec.ts

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.spec.ts: Use descriptive test names that clearly communicate expected behavior in Playwright tests
Use .spec.ts extension for test files (e.g., login.spec.ts)

Files:

  • apps/meteor/tests/unit/server/services/room/getNameForDMs.spec.ts
  • ee/packages/federation-matrix/tests/end-to-end/dms.spec.ts
🧠 Learnings (22)
📓 Common learnings
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 37205
File: ee/packages/federation-matrix/src/FederationMatrix.ts:296-301
Timestamp: 2025-10-28T16:53:42.761Z
Learning: In the Rocket.Chat federation-matrix integration (ee/packages/federation-matrix/), the createRoom method from rocket.chat/federation-sdk will support a 4-argument signature (userId, roomName, visibility, displayName) in newer versions. Code using this 4-argument call is forward-compatible with planned library updates and should not be flagged as an error.
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 37205
File: ee/packages/federation-matrix/src/FederationMatrix.ts:296-301
Timestamp: 2025-10-28T16:53:42.761Z
Learning: In the Rocket.Chat federation-matrix integration (ee/packages/federation-matrix/), the createRoom method from rocket.chat/federation-sdk will support a 4-argument signature (userId, roomName, visibility, displayName) in newer versions. Code using this 4-argument call is forward-compatible with planned library updates and should not be flagged as an error.
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 37377
File: apps/meteor/ee/server/hooks/federation/index.ts:86-88
Timestamp: 2025-11-04T16:49:19.107Z
Learning: In Rocket.Chat's federation system (apps/meteor/ee/server/hooks/federation/), permission checks follow two distinct patterns: (1) User-initiated federation actions (creating rooms, adding users to federated rooms, joining from invites) should throw MeteorError to inform users they lack 'access-federation' permission. (2) Remote server-initiated federation events should silently skip/ignore when users lack permission. The beforeAddUserToRoom hook only executes for local user-initiated actions, so throwing an error there is correct. Remote federation events are handled separately by the federation Matrix package with silent skipping logic.
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>
📚 Learning: 2025-10-28T16:53:42.761Z
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 37205
File: ee/packages/federation-matrix/src/FederationMatrix.ts:296-301
Timestamp: 2025-10-28T16:53:42.761Z
Learning: In the Rocket.Chat federation-matrix integration (ee/packages/federation-matrix/), the createRoom method from rocket.chat/federation-sdk will support a 4-argument signature (userId, roomName, visibility, displayName) in newer versions. Code using this 4-argument call is forward-compatible with planned library updates and should not be flagged as an error.

Applied to files:

  • packages/core-services/src/types/IRoomService.ts
  • apps/meteor/app/lib/server/functions/createDirectRoom.ts
  • apps/meteor/server/services/room/service.ts
  • apps/meteor/app/lib/server/functions/removeUserFromRoom.ts
  • apps/meteor/server/services/room/getNameForDMs.ts
  • packages/model-typings/src/models/IRoomsModel.ts
  • apps/meteor/tests/data/rooms.helper.ts
  • ee/packages/federation-matrix/src/events/member.ts
  • packages/models/src/models/Rooms.ts
  • ee/packages/federation-matrix/tests/end-to-end/dms.spec.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/createDirectRoom.ts
  • apps/meteor/server/services/room/service.ts
  • apps/meteor/app/lib/server/functions/removeUserFromRoom.ts
  • apps/meteor/server/services/room/getNameForDMs.ts
  • packages/model-typings/src/models/IRoomsModel.ts
  • apps/meteor/tests/data/rooms.helper.ts
  • packages/models/src/models/Rooms.ts
  • ee/packages/federation-matrix/tests/end-to-end/dms.spec.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/createDirectRoom.ts
  • apps/meteor/server/services/room/service.ts
  • apps/meteor/app/lib/server/functions/removeUserFromRoom.ts
  • apps/meteor/server/services/room/getNameForDMs.ts
  • packages/model-typings/src/models/IRoomsModel.ts
  • apps/meteor/tests/data/rooms.helper.ts
  • packages/models/src/models/Rooms.ts
  • ee/packages/federation-matrix/tests/end-to-end/dms.spec.ts
📚 Learning: 2025-11-04T16:49:19.107Z
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 37377
File: apps/meteor/ee/server/hooks/federation/index.ts:86-88
Timestamp: 2025-11-04T16:49:19.107Z
Learning: In Rocket.Chat's federation system (apps/meteor/ee/server/hooks/federation/), permission checks follow two distinct patterns: (1) User-initiated federation actions (creating rooms, adding users to federated rooms, joining from invites) should throw MeteorError to inform users they lack 'access-federation' permission. (2) Remote server-initiated federation events should silently skip/ignore when users lack permission. The beforeAddUserToRoom hook only executes for local user-initiated actions, so throwing an error there is correct. Remote federation events are handled separately by the federation Matrix package with silent skipping logic.

Applied to files:

  • apps/meteor/app/lib/server/functions/createDirectRoom.ts
  • apps/meteor/server/services/room/service.ts
  • apps/meteor/app/lib/server/functions/removeUserFromRoom.ts
  • ee/packages/federation-matrix/tests/end-to-end/dms.spec.ts
📚 Learning: 2025-09-16T13:33:49.237Z
Learnt from: cardoso
Repo: RocketChat/Rocket.Chat PR: 36890
File: apps/meteor/tests/e2e/e2e-encryption/e2ee-otr.spec.ts:21-26
Timestamp: 2025-09-16T13:33:49.237Z
Learning: The im.delete API endpoint accepts either a `roomId` parameter (requiring the actual DM room _id) or a `username` parameter (for the DM partner's username). Constructing slug-like identifiers like `user2${Users.userE2EE.data.username}` doesn't work for this endpoint.

Applied to files:

  • apps/meteor/app/lib/server/functions/removeUserFromRoom.ts
  • packages/model-typings/src/models/IRoomsModel.ts
  • ee/packages/federation-matrix/src/events/member.ts
  • packages/models/src/models/Rooms.ts
📚 Learning: 2025-09-16T13:33:49.237Z
Learnt from: cardoso
Repo: RocketChat/Rocket.Chat PR: 36890
File: apps/meteor/tests/e2e/e2e-encryption/e2ee-otr.spec.ts:21-26
Timestamp: 2025-09-16T13:33:49.237Z
Learning: In Rocket.Chat test files, the im.delete API endpoint accepts either a `roomId` parameter (requiring the actual DM room _id) or a `username` parameter (for the DM partner's username). It does not accept slug-like constructions such as concatenating usernames together.

Applied to files:

  • apps/meteor/app/lib/server/functions/removeUserFromRoom.ts
  • packages/model-typings/src/models/IRoomsModel.ts
  • ee/packages/federation-matrix/src/events/member.ts
  • packages/models/src/models/Rooms.ts
  • ee/packages/federation-matrix/tests/end-to-end/dms.spec.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: UserBridge.doGetUserRoomIds in packages/apps-engine/src/server/bridges/UserBridge.ts has a bug where it implicitly returns undefined when the app lacks read permission (missing return statement in the else case of the permission check).

Applied to files:

  • apps/meteor/app/lib/server/functions/removeUserFromRoom.ts
  • apps/meteor/tests/data/rooms.helper.ts
  • packages/models/src/models/Rooms.ts
📚 Learning: 2025-11-19T18:20:37.116Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 37419
File: apps/meteor/server/services/media-call/service.ts:141-141
Timestamp: 2025-11-19T18:20:37.116Z
Learning: In apps/meteor/server/services/media-call/service.ts, the sendHistoryMessage method should use call.caller.id or call.createdBy?.id as the message author, not call.transferredBy?.id. Even for transferred calls, the message should appear in the DM between the two users who are calling each other, not sent by the person who transferred the call.

Applied to files:

  • apps/meteor/app/lib/server/functions/removeUserFromRoom.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/removeUserFromRoom.ts
📚 Learning: 2025-11-27T17:56:26.050Z
Learnt from: MartinSchoeler
Repo: RocketChat/Rocket.Chat PR: 37557
File: apps/meteor/client/views/admin/ABAC/AdminABACRooms.tsx:115-116
Timestamp: 2025-11-27T17:56:26.050Z
Learning: In Rocket.Chat, the GET /v1/abac/rooms endpoint (implemented in ee/packages/abac/src/index.ts) only returns rooms where abacAttributes exists and is not an empty array (query: { abacAttributes: { $exists: true, $ne: [] } }). Therefore, in components consuming this endpoint (like AdminABACRooms.tsx), room.abacAttributes is guaranteed to be defined for all returned rooms, and optional chaining before calling array methods like .join() is sufficient without additional null coalescing.

Applied to files:

  • packages/model-typings/src/models/IRoomsModel.ts
  • packages/models/src/models/Rooms.ts
📚 Learning: 2025-10-24T17:32:05.348Z
Learnt from: KevLehman
Repo: RocketChat/Rocket.Chat PR: 37299
File: apps/meteor/ee/server/lib/ldap/Manager.ts:438-454
Timestamp: 2025-10-24T17:32:05.348Z
Learning: In Rocket.Chat, ABAC attributes can only be set on private rooms and teams (type 'p'), not on public rooms (type 'c'). Therefore, when checking for ABAC-protected rooms/teams during LDAP sync or similar operations, it's sufficient to query only private rooms using methods like `findPrivateRoomsByIdsWithAbacAttributes`.

Applied to files:

  • packages/model-typings/src/models/IRoomsModel.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Ensure tests run reliably in parallel without shared state conflicts

Applied to files:

  • apps/meteor/tests/unit/server/services/room/getNameForDMs.spec.ts
  • ee/packages/federation-matrix/tests/end-to-end/dms.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Group related tests in the same file

Applied to files:

  • apps/meteor/tests/unit/server/services/room/getNameForDMs.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to **/*.spec.ts : Use descriptive test names that clearly communicate expected behavior in Playwright tests

Applied to files:

  • apps/meteor/tests/unit/server/services/room/getNameForDMs.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : All test files must be created in `apps/meteor/tests/e2e/` directory

Applied to files:

  • apps/meteor/tests/unit/server/services/room/getNameForDMs.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Utilize Playwright fixtures (`test`, `page`, `expect`) for consistency in test files

Applied to files:

  • apps/meteor/tests/unit/server/services/room/getNameForDMs.spec.ts
📚 Learning: 2025-10-06T20:32:23.658Z
Learnt from: d-gubert
Repo: RocketChat/Rocket.Chat PR: 37152
File: packages/apps-engine/tests/test-data/utilities.ts:557-573
Timestamp: 2025-10-06T20:32:23.658Z
Learning: In packages/apps-engine/tests/test-data/utilities.ts, the field name `isSubscripbedViaBundle` in the `IMarketplaceSubscriptionInfo` type should not be flagged as a typo, as it may match the upstream API's field name.

Applied to files:

  • apps/meteor/tests/data/rooms.helper.ts
📚 Learning: 2025-12-09T20:01:00.324Z
Learnt from: sampaiodiego
Repo: RocketChat/Rocket.Chat PR: 37532
File: ee/packages/federation-matrix/src/FederationMatrix.ts:920-927
Timestamp: 2025-12-09T20:01:00.324Z
Learning: When reviewing federation invite handling in Rocket.Chat (specifically under ee/packages/federation-matrix), understand that rejecting an invite via federationSDK.rejectInvite() triggers an event-driven cleanup: a leave event is emitted and handled by handleLeave() in ee/packages/federation-matrix/src/events/member.ts, which calls Room.performUserRemoval() to remove the subscription. Do not add explicit cleanup in the reject branch of handleInvite(); rely on the existing leave-event flow for cleanup. If making changes, ensure this invariant remains and that any related paths still funnel cleanup through the leave event to avoid duplicate or missing removals.

Applied to files:

  • ee/packages/federation-matrix/src/events/member.ts
  • ee/packages/federation-matrix/tests/end-to-end/dms.spec.ts
📚 Learning: 2025-11-05T21:04:35.787Z
Learnt from: sampaiodiego
Repo: RocketChat/Rocket.Chat PR: 37357
File: ee/packages/federation-matrix/src/setup.ts:103-120
Timestamp: 2025-11-05T21:04:35.787Z
Learning: In Rocket.Chat's federation-matrix setup (ee/packages/federation-matrix/src/setup.ts and apps/meteor/ee/server/startup/federation.ts), configureFederationMatrixSettings does not need to be called before setupFederationMatrix. The SDK's init() establishes infrastructure (database, event handlers, APIs) first, and the configuration can be applied later via settings watchers before actual federation events are processed. The config only matters when events actually occur, at which point all infrastructure is already configured.

Applied to files:

  • ee/packages/federation-matrix/tests/end-to-end/dms.spec.ts
📚 Learning: 2025-12-10T21:00:54.909Z
Learnt from: KevLehman
Repo: RocketChat/Rocket.Chat PR: 37091
File: ee/packages/abac/jest.config.ts:4-7
Timestamp: 2025-12-10T21:00:54.909Z
Learning: Rocket.Chat monorepo: Jest testMatch pattern '<rootDir>/src/**/*.spec.(ts|js|mjs)' is valid in this repo and used across multiple packages (e.g., packages/tools, ee/packages/omnichannel-services). Do not flag it as invalid in future reviews.

Applied to files:

  • ee/packages/federation-matrix/tests/end-to-end/dms.spec.ts
📚 Learning: 2025-09-19T15:15:04.642Z
Learnt from: rodrigok
Repo: RocketChat/Rocket.Chat PR: 36991
File: apps/meteor/server/services/federation/infrastructure/rocket-chat/adapters/Settings.ts:219-221
Timestamp: 2025-09-19T15:15:04.642Z
Learning: The Federation_Matrix_homeserver_domain setting in apps/meteor/server/services/federation/infrastructure/rocket-chat/adapters/Settings.ts is part of the old federation system and is being deprecated/removed, so configuration issues with this setting should not be flagged for improvement.

Applied to files:

  • ee/packages/federation-matrix/tests/end-to-end/dms.spec.ts
🧬 Code graph analysis (7)
packages/core-services/src/types/IRoomService.ts (1)
packages/core-typings/src/IRoom.ts (1)
  • IRoom (22-98)
apps/meteor/app/lib/server/functions/createDirectRoom.ts (1)
apps/meteor/server/services/room/getNameForDMs.ts (1)
  • getNameForDMs (18-33)
apps/meteor/server/services/room/service.ts (2)
packages/models/src/index.ts (2)
  • Subscriptions (213-213)
  • Users (216-216)
apps/meteor/server/services/room/getNameForDMs.ts (1)
  • getNameForDMs (18-33)
apps/meteor/server/services/room/getNameForDMs.ts (1)
packages/core-typings/src/IUser.ts (1)
  • IUser (187-259)
apps/meteor/tests/unit/server/services/room/getNameForDMs.spec.ts (1)
apps/meteor/server/services/room/getNameForDMs.ts (1)
  • getNameForDMs (18-33)
ee/packages/federation-matrix/src/events/member.ts (2)
ee/packages/federation-matrix/src/events/room.ts (1)
  • room (7-87)
packages/core-services/src/index.ts (1)
  • Room (171-171)
packages/models/src/models/Rooms.ts (1)
packages/core-typings/src/IRoom.ts (1)
  • IRoom (22-98)
⏰ 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). (3)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build
🔇 Additional comments (14)
apps/meteor/app/lib/server/functions/createDirectRoom.ts (1)

161-185: Centralized DM naming via getNameForDMs.

The refactoring correctly replaces local helper functions with the shared getNameForDMs utility. The destructuring const { fname, name } = roomNames[member._id] assumes the member exists in the map, which is valid given getNameForDMs iterates over the same roomMembers array.

packages/model-typings/src/models/IRoomsModel.ts (1)

332-332: Interface addition for DM user reference cleanup.

The new method signature is well-typed and consistent with other update methods in the interface.

packages/core-services/src/types/IRoomService.ts (1)

70-70: New service method for DM room name updates.

The method signature is appropriate. The IRoom parameter provides full context for computing updated names via getNameForDMs.

ee/packages/federation-matrix/src/events/member.ts (2)

80-80: Correctly excludes fname for direct message rooms.

DMs compute display names per-user via subscriptions, so omitting fname from room extraData is correct.


235-238: DM room name refresh after member leaves.

This correctly triggers subscription name updates for remaining DM members after a user leaves. Per retrieved learnings, the leave event flow handles cleanup through performUserRemoval, and this addition ensures DM display names stay consistent.

apps/meteor/app/lib/server/functions/removeUserFromRoom.ts (2)

30-33: Early validation ensures username exists.

Throwing early if username is missing prevents silent failures downstream and makes the requirement explicit.


77-80: DM reference cleanup on user removal.

This correctly removes the departing user from the room's usernames and uids arrays for direct messages, keeping the room document consistent with the subscription changes.

apps/meteor/tests/unit/server/services/room/getNameForDMs.spec.ts (1)

5-128: Comprehensive unit tests for getNameForDMs.

Good coverage of edge cases including empty arrays, single members, pairs, group DMs with alphabetical sorting, and fallback to username when name is empty. Test names clearly communicate expected behavior.

packages/models/src/models/Rooms.ts (1)

2348-2363: Implementation of removeUserReferenceFromDMsById.

The method correctly targets DM rooms by ID and type, using $pull to atomically remove the user from both usernames and uids arrays. The implementation aligns with the interface definition.

apps/meteor/tests/data/rooms.helper.ts (1)

115-131: Improved error handling with proper Promise rejection.

The updated signature enables dependency injection, and the function now correctly rejects when the request fails or subscription is not found. This is a breaking change for callers that relied on the promise always resolving. All current test callers properly handle rejected promises through mocha's async test framework.

apps/meteor/server/services/room/getNameForDMs.ts (1)

18-33: LGTM on the overall design.

The function logic for computing per-member display names is sound. The fallback chains on lines 27-28 handle edge cases where other members may not have names. The O(n²) complexity from the filter inside the loop is acceptable given DMs typically have a small number of members.

ee/packages/federation-matrix/tests/end-to-end/dms.spec.ts (3)

124-147: Well-structured async test with proper retry handling.

The test correctly uses the retry helper to handle async federation operations and includes comprehensive assertions verifying room properties (_id, t, uids, absence of fname) and subscription state (status: 'INVITED'). This aligns with the PR objective of validating empty room state.


175-202: Core test for empty room state validation.

This test effectively validates the PR's main objective—ensuring correct room name display when a user is alone in a federated DM. The assertions properly verify:

  • Subscription name and fname reflect the remaining user's identity
  • Room usersCount is 1
  • uids and usernames arrays contain only the remaining user

286-303: LGTM on the leave DM test.

The test correctly verifies that leaving a federated DM from Rocket.Chat side emits the expected Matrix leave event. Good use of the event promise pattern to verify cross-server synchronization.

export function getNameForDMs(members: AtLeast<IUser, '_id' | 'name' | 'username'>[]): NameMap {
const nameMap: NameMap = {};

const sortedMembers = members.sort((u1, u2) => (u1.name! || u1.username!).localeCompare(u2.name! || u2.username!));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Mutates input array and uses unsafe non-null assertions.

Two issues on this line:

  1. members.sort() mutates the input array in place. If callers don't expect mutation, this could cause subtle bugs. Consider using [...members].sort() to sort a copy.

  2. The non-null assertions u1.name! and u1.username! are unsafe—if both name and username are undefined (which is possible per IUser type), the expression evaluates to undefined and localeCompare throws.

🔎 Suggested fix:
-	const sortedMembers = members.sort((u1, u2) => (u1.name! || u1.username!).localeCompare(u2.name! || u2.username!));
+	const sortedMembers = [...members].sort((u1, u2) => (u1.name || u1.username || '').localeCompare(u2.name || u2.username || ''));
🤖 Prompt for AI Agents
In apps/meteor/server/services/room/getNameForDMs.ts around line 21, the current
sort mutates the input array and uses unsafe non-null assertions; change to sort
a shallow copy (e.g., [...members]) and replace u1.name! || u1.username! with a
safe fallback such as (u1.name ?? u1.username ?? '') and same for u2 so
localeCompare never receives undefined; ensure you call localeCompare on a
string (or use String(...).localeCompare(...)) to avoid runtime errors.

{
username: userDm,
password: 'random',
email: `${userDm}}@rocket.chat`,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Fix typo: double closing brace in email template.

The email has an extra } character: ${userDm}}@rocket.chat should be ${userDm}@rocket.chat. This same typo appears in multiple places (lines 110, 221, 362, 373).

🔎 Apply this fix in all occurrences:
-					email: `${userDm}}@rocket.chat`,
+					email: `${userDm}@rocket.chat`,
📝 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.

Suggested change
email: `${userDm}}@rocket.chat`,
email: `${userDm}@rocket.chat`,
🤖 Prompt for AI Agents
In ee/packages/federation-matrix/tests/end-to-end/dms.spec.ts around lines 110,
221, 362 and 373, there's a typo in the email template using a double closing
brace (`${userDm}}@rocket.chat`); remove the extra `}` so the template reads
`${userDm}@rocket.chat` at each occurrence to correct the generated email
addresses.

@ggazzo ggazzo added this to the 7.14.0 milestone Dec 18, 2025
@ggazzo ggazzo added the stat: QA assured Means it has been tested and approved by a company insider label Dec 18, 2025
@dionisio-bot dionisio-bot bot added the stat: ready to merge PR tested and approved waiting for merge label Dec 18, 2025
@ggazzo ggazzo merged commit 5698028 into develop Dec 18, 2025
51 checks passed
@ggazzo ggazzo deleted the test-federation-empty-dm-state branch December 18, 2025 19:58
gaolin1 pushed a commit to gaolin1/medsense.webchat that referenced this pull request Jan 6, 2026
Co-authored-by: Guilherme Gazzo <guilherme@gazzo.xyz>
@dougfabris dougfabris modified the milestones: 7.14.0, 8.0.0 Jan 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stat: QA assured Means it has been tested and approved by a company insider stat: ready to merge PR tested and approved waiting for merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants