Skip to content

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

Open
ggazzo wants to merge 2 commits into
developfrom
refactor/sync-store-providers-authorization-user
Open

refactor(client): inline UserProvider.queryPreference subscribe/getSnapshot#40491
ggazzo wants to merge 2 commits 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

    • User preference changes (personal or admin-default) now synchronize and update in real time across the app.
  • Chores

    • Improved internal preference handling for more reliable, consistent behavior when preferences or system defaults change.

Review Change Stack

@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

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0a9e1661-8e9a-4927-b8c9-0d3b08fdfebd

📥 Commits

Reviewing files that changed from the base of the PR and between defb98e and 33470dd.

📒 Files selected for processing (1)
  • apps/meteor/client/providers/UserProvider/UserProvider.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/meteor/client/providers/UserProvider/UserProvider.tsx
📜 Recent 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). (4)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build

Walkthrough

UserProvider.queryPreference now accepts string | ObjectId, replaces the factory with an inline subscribe/getSnapshot that listens to Users.use and settings.observe("Accounts_Default_User_Preferences_${String(key)}"), unsubscribes both on cleanup, and resolves snapshots from user preference → defaultValue → settings.peek.

Changes

User Preference Subscription Enhancement

Layer / File(s) Summary
queryPreference subscription implementation
apps/meteor/client/providers/UserProvider/UserProvider.tsx
Added ObjectId import. Adjusted provider imports (removed createReactiveSubscriptionFactory, added settings). queryPreference(key: string | ObjectId) now uses effectiveKey = String(key), subscribes to Users.use and settings.observe("Accounts_Default_User_Preferences_"+effectiveKey), returns cleanup unsubscribing both, and snapshot resolution prefers the user-store preference, then defaultValue, then settings.peek("Accounts_Default_User_Preferences_"+effectiveKey).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • RocketChat/Rocket.Chat#40446: Also modifies UserProvider.queryPreference subscription/snapshot approach; related follow-up to replace factory usage.
  • RocketChat/Rocket.Chat#40495: Changes how Accounts_Default_User_Preferences_* defaults are read (switch to settings.peek), related to preference default handling.

Suggested reviewers

  • tassoevan
  • MartinSchoeler

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 clearly and specifically describes the main refactoring change: inlining the subscribe/getSnapshot implementation in UserProvider.queryPreference.
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.

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • ARCH-2141: Request failed with status code 401

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.63%. Comparing base (0ae9ab0) to head (33470dd).
⚠️ Report is 16 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #40491      +/-   ##
===========================================
+ Coverage    69.61%   69.63%   +0.02%     
===========================================
  Files         3324     3325       +1     
  Lines       122651   122797     +146     
  Branches     21864    21897      +33     
===========================================
+ Hits         85381    85508     +127     
- Misses       33939    33946       +7     
- Partials      3331     3343      +12     
Flag Coverage Δ
e2e 59.16% <100.00%> (-0.04%) ⬇️
e2e-api 46.24% <ø> (+<0.01%) ⬆️
unit 70.34% <ø> (+0.02%) ⬆️

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.

…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 force-pushed the refactor/sync-store-providers-authorization-user branch from d1d2090 to defb98e Compare May 14, 2026 12:33
@ggazzo ggazzo added this to the 8.5.0 milestone May 14, 2026
@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented May 15, 2026

⚠️ No Changeset found

Latest commit: 33470dd

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

Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

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

No issues found across 1 file

Re-trigger cubic

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.

2 participants