Skip to content

refactor(client): inline UserProvider.queryPreference subscribe/getSnapshot#40491

Open
ggazzo wants to merge 1 commit into
developfrom
refactor/sync-store-providers-authorization-user
Open

refactor(client): inline UserProvider.queryPreference subscribe/getSnapshot#40491
ggazzo wants to merge 1 commit into
developfrom
refactor/sync-store-providers-authorization-user

Conversation

@ggazzo
Copy link
Copy Markdown
Member

@ggazzo ggazzo commented May 12, 2026

Summary

`queryPreference` was the last context value in `UserProvider` going through `createReactiveSubscriptionFactory` — i.e., through `Tracker.autorun`. `getUserPreference` reads two sources:

  • `Users.use.getState()` (zustand, non-reactive)
  • `settings.watch(\`Accounts_Default_User_Preferences_${key}\`)` as a fallback when the user record has no override

Replace the factory call with a hand-rolled `[subscribe, getSnapshot]` pair that subscribes to `Users.use` directly and to the specific setting key via `settings.observe` — no Tracker computation, same fan-out behaviour. Same shape as #40446's migration of `ServerProvider` / `AuthenticationProvider`.

`AuthorizationProvider` still uses `createReactiveSubscriptionFactory` — the permission-check helpers (`hasPermission` / `hasRole`) read via `watch()` and will get their own plan in a follow-up. The factory file stays in place for that consumer.

Test plan

  • `yarn eslint` on the changed file: 0 errors.
  • `tsc --noEmit` on `apps/meteor` is clean.
  • Manual: open the account profile, toggle a preference (e.g. notification sound) and confirm UI updates in real time.
  • Manual: as admin change `Accounts_Default_User_Preferences_*` and confirm clients without an override pick up the new default without reload.

Task: ARCH-2141

Summary by CodeRabbit

  • Bug Fixes

    • Improved user preference synchronization to ensure settings updates are reliably reflected across the application in real-time.
  • Chores

    • Enhanced internal preference handling mechanism for better stability and consistency with system configuration changes.

Review Change Stack

…apshot

queryPreference was the last context value in UserProvider going through
createReactiveSubscriptionFactory — i.e., through Tracker.autorun.
getUserPreference reads two sources:
- Users.use.getState() (zustand, non-reactive)
- settings.watch(`Accounts_Default_User_Preferences_${key}`) as a fallback
  when the user record has no override

Replace the factory call with a hand-rolled [subscribe, getSnapshot] pair
that subscribes to Users.use directly and to the specific setting key via
settings.observe — no Tracker computation, same fan-out behaviour. Same
shape as the useSyncExternalStore migration #40446 did for ServerProvider /
AuthenticationProvider.

AuthorizationProvider still uses createReactiveSubscriptionFactory; the
permission-check helpers (hasPermission / hasRole) read via watch() and
will get their own plan in a follow-up. The factory file stays in place
for that consumer.
@ggazzo ggazzo requested a review from a team as a code owner May 12, 2026 13:10
@ggazzo
Copy link
Copy Markdown
Member Author

ggazzo commented May 12, 2026

/jira ARCH-2116

@dionisio-bot
Copy link
Copy Markdown
Contributor

dionisio-bot Bot commented May 12, 2026

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

  • This PR is missing the 'stat: QA assured' label
  • This PR is missing the required milestone or project

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 12, 2026

Walkthrough

The UserProvider refactors its queryPreference implementation to accept both string and ObjectId keys while subscribing to dual data sources: live user-store updates and admin default preference settings, with explicit cleanup for both subscriptions.

Changes

User Preference Subscription Enhancement

Layer / File(s) Summary
queryPreference subscription implementation
apps/meteor/client/providers/UserProvider/UserProvider.tsx
MongoDB ObjectId import added to support expanded key type. Provider imports updated: createReactiveSubscriptionFactory removed, getDdpSdk and settings added. queryPreference now accepts key: string | ObjectId, subscribes to Users.use changes and observes settings.observe(Accounts_Default_User_Preferences_${key}), unsubscribes both on cleanup, and reads snapshots via getUserPreference(userId, String(key), defaultValue).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Suggested labels

type: chore

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main refactoring change: inlining the subscribe/getSnapshot implementation for UserProvider.queryPreference instead of using createReactiveSubscriptionFactory.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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.

❤️ Share

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

Copy link
Copy Markdown
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.

🧹 Nitpick comments (2)
apps/meteor/client/providers/UserProvider/UserProvider.tsx (2)

147-149: 💤 Low value

Consider removing implementation comment per coding guidelines.

The comment explains the internal behavior of getUserPreference and why the settings subscription is needed. While this is architecturally useful context, the coding guideline for TypeScript files asks to avoid code comments in implementation.

Consider whether this comment adds sufficient value to warrant an exception, or if the behavior could be documented elsewhere (e.g., in PR description, commit message, or the getUserPreference function itself).

As per coding guidelines: "Avoid code comments in the implementation" for **/*.{ts,tsx,js}.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/meteor/client/providers/UserProvider/UserProvider.tsx` around lines 147
- 149, Remove the implementation comment explaining getUserPreference's fallback
and the settings.watch subscription from UserProvider.tsx; either delete it or
relocate that rationale to the getUserPreference function's JSDoc or the
PR/commit message. Specifically, update the comment near the settings.watch
invocation in the UserProvider component and ensure any necessary documentation
lives on getUserPreference (its function comment) or external documentation so
the implementation file follows the "avoid code comments in implementation"
guideline.

141-158: 💤 Low value

Consider using .toString() for explicit ObjectId conversion.

The code uses String(key) to convert ObjectId | string to string (lines 150, 156). While String() coercion works, using String(key) on mixed types is less explicit than checking the type and calling .toString() when needed, or using a type guard.

📝 More explicit conversion approach
-			const subscribe = (onStoreChange: () => void): (() => void) => {
+			const keyStr = String(key);
+			const subscribe = (onStoreChange: () => void): (() => void) => {
 				const unsubUsers = Users.use.subscribe(onStoreChange);
 				// getUserPreference falls back to settings.watch(`Accounts_Default_User_Preferences_${key}`)
 				// when the user record has no override. Subscribe to that specific
 				// setting key so admin-side default changes still propagate.
-				const unsubSettings = settings.observe(`Accounts_Default_User_Preferences_${String(key)}`, onStoreChange);
+				const unsubSettings = settings.observe(`Accounts_Default_User_Preferences_${keyStr}`, onStoreChange);
 				return () => {
 					unsubUsers();
 					unsubSettings();
 				};
 			};
-			const getSnapshot = (): T | undefined => getUserPreference(userId, String(key), defaultValue);
+			const getSnapshot = (): T | undefined => getUserPreference(userId, keyStr, defaultValue);
 			return [subscribe, getSnapshot];

This hoists the conversion to clarify that both subscribe and getSnapshot use the same string representation.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/meteor/client/providers/UserProvider/UserProvider.tsx` around lines 141
- 158, The queryPreference helper currently uses String(key) in both subscribe
and getSnapshot; change this to compute a single stringKey by checking the type
of key and calling key.toString() when key is an ObjectId (or otherwise using
the existing string), then use stringKey in Users.use.subscribe/settings.observe
and in getUserPreference(userId, stringKey, defaultValue) so the conversion is
explicit and consistent across subscribe and getSnapshot (refer to
queryPreference, subscribe, getSnapshot, getUserPreference, settings.observe,
and Users.use.subscribe).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@apps/meteor/client/providers/UserProvider/UserProvider.tsx`:
- Around line 147-149: Remove the implementation comment explaining
getUserPreference's fallback and the settings.watch subscription from
UserProvider.tsx; either delete it or relocate that rationale to the
getUserPreference function's JSDoc or the PR/commit message. Specifically,
update the comment near the settings.watch invocation in the UserProvider
component and ensure any necessary documentation lives on getUserPreference (its
function comment) or external documentation so the implementation file follows
the "avoid code comments in implementation" guideline.
- Around line 141-158: The queryPreference helper currently uses String(key) in
both subscribe and getSnapshot; change this to compute a single stringKey by
checking the type of key and calling key.toString() when key is an ObjectId (or
otherwise using the existing string), then use stringKey in
Users.use.subscribe/settings.observe and in getUserPreference(userId, stringKey,
defaultValue) so the conversion is explicit and consistent across subscribe and
getSnapshot (refer to queryPreference, subscribe, getSnapshot,
getUserPreference, settings.observe, and Users.use.subscribe).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8ecb3023-661b-4960-babd-3838702b886a

📥 Commits

Reviewing files that changed from the base of the PR and between 6b2afb3 and d1d2090.

📒 Files selected for processing (1)
  • apps/meteor/client/providers/UserProvider/UserProvider.tsx
📜 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). (3)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build
🧰 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:

  • apps/meteor/client/providers/UserProvider/UserProvider.tsx
🧠 Learnings (2)
📚 Learning: 2026-03-27T14:52:56.865Z
Learnt from: dougfabris
Repo: RocketChat/Rocket.Chat PR: 39892
File: apps/meteor/client/views/room/contextualBar/Threads/Thread.tsx:150-155
Timestamp: 2026-03-27T14:52:56.865Z
Learning: In Rocket.Chat, there are two different `ModalBackdrop` components with different prop APIs. During review, confirm the import source: (1) `rocket.chat/fuselage` `ModalBackdrop` uses `ModalBackdropProps` based on `BoxProps` (so it supports `onClick` and other Box/DOM props) and does not have an `onDismiss` prop; (2) `rocket.chat/ui-client` `ModalBackdrop` uses a narrower props interface like `{ children?: ReactNode; onDismiss?: () => void }` and handles Escape keypress and outside mouse-up, and it does not forward arbitrary DOM props such as `onClick`. Flag mismatched props (e.g., `onDismiss` passed to the fuselage component or `onClick` passed to the ui-client component) and ensure the usage matches the correct component being imported.

Applied to files:

  • apps/meteor/client/providers/UserProvider/UserProvider.tsx
📚 Learning: 2026-05-06T12:21:44.083Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 40256
File: apps/meteor/client/components/CreateDiscussion/CreateDiscussion.tsx:121-149
Timestamp: 2026-05-06T12:21:44.083Z
Learning: Field wrappers in rocket.chat/fuselage-forms (Field, FieldLabel, FieldRow, FieldError, FieldHint) auto-create htmlFor/id associations, aria-describedby, and role="alert" for errors. Do not manually set htmlFor, id, aria-describedby, or role attributes when using these wrappers. This automatic wiring does not apply to plain rocket.chat/fuselage components, which require explicit ID wiring per the accessibility docs. In code reviews, prefer using fuselage-forms wrappers for form fields and verify there is no unnecessary manual ID/aria wiring in files that use these wrappers. If a component uses plain fuselage components, ensure proper id wiring as per docs.

Applied to files:

  • apps/meteor/client/providers/UserProvider/UserProvider.tsx
🔇 Additional comments (2)
apps/meteor/client/providers/UserProvider/UserProvider.tsx (2)

150-150: settings.observe API exists and correctly returns a cleanup function.

The observe(key: string, callback: SettingCallback): () => void signature confirms the code on line 150 properly captures the unsubscribe function.


156-156: getUserPreference explicitly handles undefined userId.

The function overloads document that undefined is an accepted parameter type (lines 12, 19, 27, 35-39), and the implementation uses optional chaining (user?.settings?.preferences?.[key]) to safely handle undefined values with proper fallback behavior to defaultValue or settings.watch(). No runtime errors will occur when userId is undefined.

			> Likely an incorrect or invalid review comment.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 12, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 69.66%. Comparing base (6b2afb3) to head (d1d2090).

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #40491      +/-   ##
===========================================
+ Coverage    69.64%   69.66%   +0.02%     
===========================================
  Files         3318     3318              
  Lines       121981   121980       -1     
  Branches     21791    21808      +17     
===========================================
+ Hits         84948    84978      +30     
+ Misses       33701    33675      -26     
+ Partials      3332     3327       -5     
Flag Coverage Δ
unit 70.49% <ø> (+0.04%) ⬆️

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant