Skip to content

Conversation

@ricardogarim
Copy link
Contributor

@ricardogarim ricardogarim commented Sep 23, 2025

Proposed changes (including videos or screenshots)

Issue(s)

Steps to test or reproduce

Further comments

Summary by CodeRabbit

  • New Features

    • Automatic detection of federated participants when creating rooms or direct messages.
    • Rooms are now flagged as federated when members include federated-style usernames, enabling federation features without extra steps.
  • Bug Fixes

    • More reliable creation and recognition of federated users locally, reducing errors when starting DMs or inviting external users.
    • Smoother room/DM creation flows with mixed local and federated members.

@dionisio-bot
Copy link
Contributor

dionisio-bot bot commented Sep 23, 2025

Looks like this PR is not ready to merge, because of the following issues:

  • This PR is missing the 'stat: QA assured' label

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@changeset-bot
Copy link

changeset-bot bot commented Sep 23, 2025

⚠️ No Changeset found

Latest commit: 225624a

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 Sep 23, 2025

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Title Check ⚠️ Warning The title specifies a narrow fix around federated user creation on direct messages from an “RC > remote flow,” but the actual changes span typing adjustments, callback reordering in createDirectRoom, federated flag detection in createRoom, and signature updates across federation services, none of which are accurately captured by the given title. Please revise the title to concisely reflect the main updates, for example “refactor: add federated handling in room creation and update direct room callbacks,” so that it clearly summarizes the scope and intent of the changeset.
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 (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/federation-dms

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.

@codecov
Copy link

codecov bot commented Sep 23, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 69.75%. Comparing base (9e151c0) to head (225624a).
⚠️ Report is 17 commits behind head on chore/federation-backup.

Additional details and impacted files

Impacted file tree graph

@@                     Coverage Diff                     @@
##           chore/federation-backup   #37043      +/-   ##
===========================================================
+ Coverage                    67.30%   69.75%   +2.45%     
===========================================================
  Files                         3342     3035     -307     
  Lines                       113648   103432   -10216     
  Branches                     20757    18385    -2372     
===========================================================
- Hits                         76486    72148    -4338     
+ Misses                       34554    29404    -5150     
+ Partials                      2608     1880     -728     
Flag Coverage Δ
e2e-api ?
unit 71.25% <ø> (+0.10%) ⬆️

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.

@ricardogarim ricardogarim force-pushed the fix/federation-dms branch 2 times, most recently from bb8ada2 to ecce9ce Compare September 23, 2025 23:42
@ricardogarim ricardogarim changed the base branch from chore/federation-backup to use-published-package September 24, 2025 12:36
@ricardogarim ricardogarim force-pushed the fix/federation-dms branch 3 times, most recently from d90d476 to 0bb97a8 Compare September 24, 2025 15:57
@ricardogarim ricardogarim marked this pull request as ready for review September 24, 2025 16:09
@ricardogarim ricardogarim requested a review from a team as a code owner September 24, 2025 16:09
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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
apps/meteor/app/lib/server/functions/createRoom.ts (1)

166-167: Fix creatorId fallback: use owner._id, not username

Passing owner?.username as creator breaks DM federation and subscription opening. Downstream expects a user ID (see FederationMatrix.createDirectMessageRoom → Users.findOneById and createDirectRoom subscription logic).

Apply this diff:

-		return createDirectRoom(members as IUser[], extraData, { ...options, creator: options?.creator || owner?.username });
+		return createDirectRoom(members as IUser[], extraData, { ...options, creator: options?.creator || owner?._id });
ee/packages/federation-matrix/src/FederationMatrix.ts (2)

261-291: Normalize/relax federated username handling, fix origin parsing, and use a supported insert API

  • Filter currently requires both “@” and “:”, skipping user:domain.
  • origin via split(':')[1] loses ports (e.g., :8448).
  • Users.create may not exist on the model; elsewhere this file uses insertOne.

Apply this diff:

-			const federatedUsers = usernames.filter((username) => username?.includes(':') && username?.includes('@'));
-			for await (const username of federatedUsers) {
+			const federatedUsers = usernames
+				.filter((u): u is string => typeof u === 'string' && u.includes(':'))
+				.map((u) => (u.startsWith('@') ? u : `@${u}`));
+			for await (const username of federatedUsers) {
 				if (!username) {
 					continue;
 				}
 
 				const existingUser = await Users.findOneByUsername(username);
 				if (existingUser) {
 					continue;
 				}
 
-				await Users.create({
+				const origin = username.split(':').slice(1).join(':');
+				await Users.insertOne({
 					username,
 					name: username,
 					type: 'user' as const,
 					status: UserStatus.OFFLINE,
 					active: true,
 					roles: ['user'],
 					requirePasswordChange: false,
 					federated: true,
 					federation: {
 						version: 1,
-						mui: username,
-						origin: username.split(':')[1],
+						mui: username,
+						origin,
 					},
 					createdAt: new Date(),
 					_updatedAt: new Date(),
 				});

365-388: Bug: wrong lookup and user creation for remote IUser members

Users.findOne({ 'federation.mui': memberId }) compares a Matrix user ID field to a Mongo user ID. This will never match and can lead to inserting bogus users with username = memberId.

Prefer checking by the Matrix ID and using the member’s existing data:

-					if (memberId) {
-						const existingMemberMatrixUserId = await Users.findOne({ 'federation.mui': memberId });
-						if (!existingMemberMatrixUserId) {
-							const newUser = {
-								username: memberId,
-								name: memberId,
+					if (memberId) {
+						const existingByMui = await Users.findOne({ 'federation.mui': memberMatrixUserId });
+						if (!existingByMui) {
+							const newUser = {
+								username: typeof member !== 'string' ? member.username ?? memberMatrixUserId : memberMatrixUserId,
+								name: typeof member !== 'string' ? member.name ?? member.username ?? memberMatrixUserId : memberMatrixUserId,
 								type: 'user' as const,
 								status: UserStatus.OFFLINE,
 								active: true,
 								roles: ['user'],
 								requirePasswordChange: false,
 								federated: true,
 								federation: {
 									version: 1,
-									mui: memberId,
-									origin: memberMatrixUserId.split(':').pop(),
+									mui: memberMatrixUserId,
+									origin: memberMatrixUserId.split(':').slice(1).join(':'),
 								},
 								createdAt: new Date(),
 								_updatedAt: new Date(),
 							};
 
 							await Users.insertOne(newUser);
 						}
 					}
📜 Review details

Configuration used: CodeRabbit 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 a7f8c73 and 0bb97a8.

📒 Files selected for processing (6)
  • apps/meteor/app/lib/server/functions/createDirectRoom.ts (3 hunks)
  • apps/meteor/app/lib/server/functions/createRoom.ts (1 hunks)
  • apps/meteor/lib/callbacks.ts (2 hunks)
  • apps/meteor/server/services/room/hooks/BeforeFederationActions.ts (1 hunks)
  • ee/packages/federation-matrix/src/FederationMatrix.ts (2 hunks)
  • packages/core-services/src/types/IFederationMatrixService.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (4)
ee/packages/federation-matrix/src/FederationMatrix.ts (1)
packages/models/src/index.ts (1)
  • Users (211-211)
apps/meteor/server/services/room/hooks/BeforeFederationActions.ts (1)
packages/core-typings/src/IRoom.ts (2)
  • IRoom (21-95)
  • IRoomNativeFederated (114-120)
apps/meteor/lib/callbacks.ts (1)
packages/core-typings/src/IRoom.ts (2)
  • IRoomNativeFederated (114-120)
  • IRoom (21-95)
apps/meteor/app/lib/server/functions/createDirectRoom.ts (2)
packages/core-typings/src/IRoom.ts (2)
  • IRoomNativeFederated (114-120)
  • IRoom (21-95)
apps/meteor/lib/callbacks.ts (1)
  • callbacks (252-260)
⏰ 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: 🚢 Build Docker Images for Testing (alpine)
🔇 Additional comments (5)
apps/meteor/server/services/room/hooks/BeforeFederationActions.ts (1)

7-17: LGTM: widened input type while preserving runtime checks

Accepting Partial<IRoom | IRoomNativeFederated> matches upstream callers that pass partial room shapes. Behavior unchanged.

apps/meteor/lib/callbacks.ts (1)

82-83: LGTM: updated beforeCreateDirectRoom signature

Using string[] and Partial<IRoomNativeFederated | IRoom> aligns with the new DM pre-create flow.

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

45-51: LGTM: widen roomExtraData to Partial<IRoomNativeFederated | IRoom>

Matches federation-native room shapes without over-constraining callers.


72-73: Pre-create hook ensures federated users are created/normalized

The beforeCreateDirectRoom callback in apps/meteor/ee/server/hooks/federation/index.ts calls FederationMatrix.ensureFederatedUsersExistLocally(members) when FederationActions.shouldPerformFederationAction(room) is true.

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

10-11: LGTM — callers verified: all pass string[]

beforeCreateDirectRoom is typed (members: string[]) (apps/meteor/lib/callbacks.ts); createDirectRoom passes membersUsernames (string[]) and the hook (apps/meteor/ee/server/hooks/federation/index.ts) calls ensureFederatedUsersExistLocally(members). No callers pass IUser or mixed arrays.

Comment on lines +137 to +143
const hasFederatedMembers = members.some((member) => {
if (typeof member === 'string') {
return member.includes(':') && member.includes('@');
}
return member.username?.includes(':') && member.username?.includes('@');
});

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Broaden federated member detection (don’t require '@')

Requiring both “@” and “:” misses valid inputs like user:domain. This can prevent extraData.federated from being set and skip federation handling.

Apply this diff:

-	const hasFederatedMembers = members.some((member) => {
-		if (typeof member === 'string') {
-			return member.includes(':') && member.includes('@');
-		}
-		return member.username?.includes(':') && member.username?.includes('@');
-	});
+	const hasFederatedMembers = members.some((member) => {
+		const username = typeof member === 'string' ? member : member.username;
+		return typeof username === 'string' && username.includes(':');
+	});
📝 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
const hasFederatedMembers = members.some((member) => {
if (typeof member === 'string') {
return member.includes(':') && member.includes('@');
}
return member.username?.includes(':') && member.username?.includes('@');
});
const hasFederatedMembers = members.some((member) => {
const username = typeof member === 'string' ? member : member.username;
return typeof username === 'string' && username.includes(':');
});
🤖 Prompt for AI Agents
In apps/meteor/app/lib/server/functions/createRoom.ts around lines 137 to 143,
the federated-member detection currently requires both ':' and '@', which misses
valid forms like "user:domain"; change the predicate to detect federation if the
string (or member.username) contains ':' OR contains '@' (use || instead of &&)
so hasFederatedMembers returns true for inputs like "user:domain" as well as
"@user:domain" or "user@domain".

Base automatically changed from use-published-package to chore/federation-backup September 24, 2025 19:08
@ggazzo ggazzo requested a review from a team as a code owner September 24, 2025 19:08
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: 3

🧹 Nitpick comments (1)
apps/meteor/server/services/room/hooks/BeforeFederationActions.ts (1)

7-7: Good use of type guard but consider parameter naming

The type guard pattern is excellent for type safety. However, the parameter type Partial<IRoom | IRoomNativeFederated> is unusual - typically we'd see Partial<IRoom> | Partial<IRoomNativeFederated>.

If the current union is intentional, consider documenting why. Otherwise:

-public static shouldPerformFederationAction(room: Partial<IRoom | IRoomNativeFederated>): room is IRoomNativeFederated {
+public static shouldPerformFederationAction(room: Partial<IRoom> | Partial<IRoomNativeFederated>): room is IRoomNativeFederated {
📜 Review details

Configuration used: CodeRabbit 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 0bb97a8 and aa1454a.

📒 Files selected for processing (6)
  • apps/meteor/app/lib/server/functions/createDirectRoom.ts (3 hunks)
  • apps/meteor/app/lib/server/functions/createRoom.ts (1 hunks)
  • apps/meteor/lib/callbacks.ts (2 hunks)
  • apps/meteor/server/services/room/hooks/BeforeFederationActions.ts (1 hunks)
  • ee/packages/federation-matrix/src/FederationMatrix.ts (2 hunks)
  • packages/core-services/src/types/IFederationMatrixService.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/meteor/app/lib/server/functions/createRoom.ts
  • packages/core-services/src/types/IFederationMatrixService.ts
🧰 Additional context used
🧬 Code graph analysis (4)
apps/meteor/server/services/room/hooks/BeforeFederationActions.ts (1)
packages/core-typings/src/IRoom.ts (2)
  • IRoom (21-95)
  • IRoomNativeFederated (114-120)
ee/packages/federation-matrix/src/FederationMatrix.ts (1)
packages/models/src/index.ts (1)
  • Users (211-211)
apps/meteor/app/lib/server/functions/createDirectRoom.ts (2)
packages/core-typings/src/IRoom.ts (2)
  • IRoomNativeFederated (114-120)
  • IRoom (21-95)
apps/meteor/lib/callbacks.ts (1)
  • callbacks (252-260)
apps/meteor/lib/callbacks.ts (1)
packages/core-typings/src/IRoom.ts (2)
  • IRoomNativeFederated (114-120)
  • IRoom (21-95)
⏰ 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 (7)
apps/meteor/lib/callbacks.ts (2)

24-24: LGTM! Type import added correctly

The import of IRoomNativeFederated is correctly added to support the updated callback signature.


82-82: Verify external callback handlers No internal registrations of beforeCreateDirectRoom were found—only its invocation at apps/meteor/app/lib/server/functions/createDirectRoom.ts:72. Ensure any plugin or app-level handlers for this callback are updated to the new signature (members: string[], room: Partial<IRoomNativeFederated | IRoom>) instead of (IUser[], IRoom).

apps/meteor/app/lib/server/functions/createDirectRoom.ts (3)

4-4: LGTM! Type imports updated correctly

The addition of IRoomNativeFederated type import aligns with the federation flow changes.


45-45: Type safety improvement for federated rooms

Good change to explicitly support federated room metadata in the roomExtraData parameter type.


72-73: Ignore callback placement concern beforeCreateDirectRoom is defined to receive usernames (string[]), and the only registered implementation (federation hook) uses only usernames without accessing user properties. No break introduced.

Likely an incorrect or invalid review comment.

ee/packages/federation-matrix/src/FederationMatrix.ts (1)

274-290: Simplified user creation logic looks good

The refactored code is cleaner and more straightforward. The federation metadata is now derived directly from the username which is appropriate.

apps/meteor/server/services/room/hooks/BeforeFederationActions.ts (1)

8-16: Logic is correct and handles all cases appropriately

The method correctly:

  1. Returns false for non-federated rooms
  2. Throws an error for federated but non-native rooms
  3. Returns true (with type narrowing) for native federated rooms

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: 0

🧹 Nitpick comments (1)
apps/meteor/lib/callbacks.ts (1)

81-81: Prefer Username[] over raw string[].

We already import Username, and the callback now receives usernames. Keeping the Username[] typing preserves intent and avoids eroding type-safety downstream.

-	'beforeCreateDirectRoom': (members: string[], room: IRoom) => void;
+	'beforeCreateDirectRoom': (members: Username[], room: IRoom) => void;
📜 Review details

Configuration used: CodeRabbit 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 aa1454a and 225624a.

📒 Files selected for processing (2)
  • apps/meteor/app/lib/server/functions/createDirectRoom.ts (2 hunks)
  • apps/meteor/lib/callbacks.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/meteor/app/lib/server/functions/createDirectRoom.ts
🧰 Additional context used
🧬 Code graph analysis (1)
apps/meteor/lib/callbacks.ts (1)
packages/core-typings/src/IRoom.ts (1)
  • IRoom (21-95)
⏰ 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

@ggazzo ggazzo added this to the 7.11.0 milestone Sep 24, 2025
@ggazzo ggazzo merged commit 0b894f7 into chore/federation-backup Sep 24, 2025
20 checks passed
@ggazzo ggazzo deleted the fix/federation-dms branch September 24, 2025 22:23
ggazzo added a commit that referenced this pull request Sep 25, 2025
Co-authored-by: Guilherme Gazzo <guilherme@gazzo.xyz>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants