Skip to content

refactor(client): remove legacy streamerCentral, migrate user-presence to sdk.onAnyStreamEvent#40542

Open
ggazzo wants to merge 3 commits into
developfrom
refactor/remove-client-streamer-central
Open

refactor(client): remove legacy streamerCentral, migrate user-presence to sdk.onAnyStreamEvent#40542
ggazzo wants to merge 3 commits into
developfrom
refactor/remove-client-streamer-central

Conversation

@ggazzo
Copy link
Copy Markdown
Member

@ggazzo ggazzo commented May 14, 2026

Summary

  • Removes the legacy client-side StreamerCentral / Streamer classes under apps/meteor/client/lib/streamer/ and the streamerAdapter shim. Their only remaining consumer was the side-effect module app/notifications/client/lib/Presence.ts, which used a wildcard listener over the stream-user-presence collection.
  • Adds a generic sdk.onAnyStreamEvent(name, cb) helper to app/utils/client/lib/SDKClient.ts. It bridges raw changed frames into a per-stream @rocket.chat/emitter so subscribers can register/unregister cleanly (no per-subscription leak).
  • Migrates the presence listener into a React hook (useUserPresenceListener) mounted from UserPresenceProvider, which already owns the Presence lifecycle.

How the new bridge works

sdk.onAnyStreamEvent(name, cb) lazily wires, once per stream name:

  1. getDdpSdk().client.onCollection('stream-' + name, ...) — covers transport-OFF (the Meteor-backed SDK shim already wires this from Meteor.connection._stream) and transport-ON (real SDK socket).
  2. When SDK transport is on, also wires Meteor.connection._stream.on('message', ...) with raw DDP parsing. This covers the case where the subscription in client/lib/presence.ts falls back to Meteor.subscribe before the SDK socket has authenticated. This is a temporary bridge that disappears once the SDK transport rollout completes.

The Meteor stream listener has no off(), so the bridges are singletons per stream name; consumers subscribe/unsubscribe on the per-stream Emitter and never touch the raw streams.

user-presence tuple unwrap

StreamerEvents['user-presence'] carries args: [[username, statusChanged, statusText]] — one level deeper than every other stream. The legacy streamerCentral hid this because it spread fields.args before invoking the listener. The new hook destructures the nested tuple explicitly; without that step, username was bound to the inner array and SystemMessage crashed with username.startsWith is not a function.

Files

  • Added: apps/meteor/client/hooks/useUserPresenceListener.ts
  • Modified: apps/meteor/app/utils/client/lib/SDKClient.ts, apps/meteor/client/providers/UserPresenceProvider.tsx, apps/meteor/client/importPackages.ts, apps/meteor/client/lib/sdk/meteorBackedSdk.ts (comment refresh)
  • Deleted: apps/meteor/client/lib/streamer/{streamer,index,ddp,emitter}.ts, apps/meteor/client/lib/sdk/streamerAdapter.ts, apps/meteor/app/notifications/client/{index.ts,lib/Presence.ts}

Test plan

  • Run the client and confirm presence updates (online / away / busy / offline transitions) propagate to avatars in DMs and channels.
  • Repeat with the SDK transport flag both ON and OFF.
  • Trigger a reconnect (kill / restart the WS) and confirm presence resumes streaming.
  • Open a fresh chat and verify the SystemMessage path renders without username.startsWith errors (regression guard for the tuple unwrap fix).
  • yarn typecheck is green.

Task: ARCH-2150

Summary by CodeRabbit

  • New Features

    • Introduced unified stream event listener system for improved real-time data handling across the platform
    • Added comprehensive stream subscription mechanism for monitoring all events on a given stream
  • Refactor

    • Modernized user presence update architecture with streamlined event-driven system

Review Change Stack

ggazzo and others added 2 commits May 14, 2026 16:12
…e to sdk.onAnyStreamEvent

The client `StreamerCentral` / `Streamer` classes in `client/lib/streamer/` had a
single remaining consumer (`app/notifications/client/lib/Presence.ts`) that
needed a wildcard listener over the `stream-user-presence` collection.

Replace the entire legacy infrastructure with a new `sdk.onAnyStreamEvent(name, cb)`
helper backed by `getDdpSdk().client.onCollection` + (when SDK transport is on) a
direct `Meteor.connection._stream` bridge to cover the Meteor-fallback path.
Subscribers register on a per-stream Emitter, so unsubscription is clean (no leak).

Move the side-effect Presence listener into a React hook
(`useUserPresenceListener`) mounted from `UserPresenceProvider`, which already
owns the Presence lifecycle.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Server emits user-presence frames with args = [[username, statusChanged, statusText]]
(tuple nested one level deeper than other streams — see StreamerEvents in
@rocket.chat/ddp-client). The legacy streamerCentral hid this because it
spread fields.args before invoking the listener.

sdk.onAnyStreamEvent passes args through unchanged, so the hook now
destructures the nested tuple explicitly. Without this, username is bound
to the inner array and SystemMessage crashes with
"username.startsWith is not a function".
@dionisio-bot
Copy link
Copy Markdown
Contributor

dionisio-bot Bot commented May 14, 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

@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented May 14, 2026

⚠️ No Changeset found

Latest commit: 59d5666

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
Copy Markdown
Contributor

coderabbitai Bot commented May 14, 2026

Walkthrough

This PR introduces a new SDK-level stream event bridging capability (SDK.onAnyStreamEvent) to replace the legacy client-side streamer implementation. The new method is exposed through ServerContext, consumed via a new useStreamAll hook, and integrated into the user presence listener for observing online status updates.

Changes

Stream Event Bridging Infrastructure

Layer / File(s) Summary
SDK onAnyStreamEvent method
apps/meteor/app/utils/client/lib/SDKClient.ts
SDKClient.ts extends the @rocket.chat/ddp-client SDK interface with onAnyStreamEvent and implements the internal bridge via per-stream Emitter instances, hooking DDP collection changes and optional _stream message events to forward callback updates.
ServerContext and ServerProvider integration
packages/ui-contexts/src/ServerContext.ts, apps/meteor/client/providers/ServerProvider.tsx
ServerContext.ts and ServerProvider.tsx extend the context type and value to include getStreamAll, which wraps sdk.onAnyStreamEvent and returns a typed subscriber function for consuming all events on a given stream.
useStreamAll hook
packages/ui-contexts/src/hooks/useStreamAll.ts, packages/ui-contexts/src/index.ts
Introduces useStreamAll hook that memoizes the getStreamAll subscriber from ServerContext, enabling consumers to subscribe to all events on a named stream with a callback.
User presence listener integration
apps/meteor/client/hooks/useUserPresenceListener.ts, apps/meteor/client/providers/UserPresenceProvider.tsx
Creates useUserPresenceListener hook that subscribes to user-presence stream via useStreamAll, maps status values, and invokes Presence.notify on updates; integrates into UserPresenceProvider render lifecycle.
SDK documentation update
apps/meteor/client/lib/sdk/meteorBackedSdk.ts
Updates comments to clarify that onCollection acts as a bridge for sdk.onAnyStreamEvent during the Meteor-backed SDK transport period.
Test and mock provider updates
apps/meteor/tests/mocks/client/ServerProviderMock.tsx, apps/meteor/client/stories/contexts/ServerContextMock.tsx, packages/mock-providers/src/MockedAppRootBuilder.tsx
Updates ServerContextMock, ServerProviderMock, and MockedAppRootBuilder to include getStreamAll stubs alongside existing mock methods for consistent test consumer access.

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • RocketChat/Rocket.Chat#40445: Refactors meteorBackedSdk and SDKClient stream handling to avoid Tracker.autorun, overlapping at the stream event listener wiring level.
  • RocketChat/Rocket.Chat#40480: Also modifies apps/meteor/client/lib/streamer/streamer.ts and the stream/streamer bridging layer with overlapping _stream typing and handler setup changes.

Suggested labels

type: chore

Suggested reviewers

  • MartinSchoeler
  • tassoevan
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ 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%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ 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 accurately describes the main changes: removing legacy streamerCentral and migrating user-presence to the new sdk.onAnyStreamEvent mechanism, which is the core refactoring objective.
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-2150: 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.

@ggazzo ggazzo added this to the 8.5.0 milestone May 14, 2026
@codecov
Copy link
Copy Markdown

codecov Bot commented May 14, 2026

Codecov Report

❌ Patch coverage is 57.44681% with 20 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.68%. Comparing base (0ae9ab0) to head (59d5666).
⚠️ Report is 11 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #40542      +/-   ##
===========================================
+ Coverage    69.61%   69.68%   +0.07%     
===========================================
  Files         3324     3322       -2     
  Lines       122651   122680      +29     
  Branches     21864    21871       +7     
===========================================
+ Hits         85381    85492     +111     
+ Misses       33939    33839     -100     
- Partials      3331     3349      +18     
Flag Coverage Δ
e2e 59.35% <67.50%> (+0.16%) ⬆️
e2e-api 46.25% <ø> (+0.01%) ⬆️
unit 70.33% <0.00%> (+0.01%) ⬆️

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.

@ggazzo
Copy link
Copy Markdown
Member Author

ggazzo commented May 14, 2026

/jira ARCH-2116

Adds getStreamAll to ServerContextValue and a corresponding useStreamAll
hook. Wires it in ServerProvider through sdk.onAnyStreamEvent so
consumers reach the unified sdk via context (matching the useStream /
useEndpoint pattern) instead of importing the singleton directly.

useUserPresenceListener now consumes useStreamAll('user-presence'),
keeping the temporary wildcard listener for the Meteor → SDK transport
rollout consistent with how the rest of the client subscribes to streams.
@ggazzo ggazzo force-pushed the refactor/remove-client-streamer-central branch from 0db3f9f to 59d5666 Compare May 14, 2026 23:54
@ggazzo ggazzo marked this pull request as ready for review May 14, 2026 23:59
@ggazzo ggazzo requested a review from a team as a code owner May 14, 2026 23:59
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.

Actionable comments posted: 1

🧹 Nitpick comments (2)
apps/meteor/app/utils/client/lib/SDKClient.ts (1)

356-372: ⚡ Quick win

Remove inline implementation commentary from the stream bridge block.

Please move this rationale to PR description/ADR/docs and keep implementation code free of explanatory comment blocks.

As per coding guidelines "Avoid code comments in implementation".

Also applies to: 390-402

🤖 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/app/utils/client/lib/SDKClient.ts` around lines 356 - 372, Remove
the large explanatory comment block above the stream bridge implementation and
replace it with a minimal one-line summary; leave any detailed rationale in the
PR description/ADR/docs as requested. Specifically, delete the multi-line
commentary that describes the two bridge sources and lifecycle around
onAnyStreamEvent, getDdpSdk().client.onCollection, meteorBackedSdk.onCollection
and the Meteor.connection._stream fallback (and the note referencing
apps/meteor/client/lib/presence.ts), and keep only a single short comment that
states the purpose (e.g., "Per-stream bridge for onAnyStreamEvent; details in
PR/ADR"). Ensure you also remove the duplicated explanatory block at the other
location (around lines referencing the same behavior) so implementation files
contain no lengthy rationale.
apps/meteor/client/lib/sdk/meteorBackedSdk.ts (1)

118-124: ⚡ Quick win

Drop the inline explanatory block for ddp.onMessage.

Keep implementation minimal and move this explanation to external documentation (PR/ADR).

As per coding guidelines "Avoid code comments in implementation".

🤖 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/lib/sdk/meteorBackedSdk.ts` around lines 118 - 124, Remove
the inline explanatory comment block that describes why ddp.onMessage is not
registered in the Meteor-backed SDK implementation and instead reference an
external ADR/PR; keep the existing implementation logic in meteorBackedSdk.ts
unchanged (do not add or remove listeners), ensuring the code around
ddp.onMessage, onCollection, Meteor.connection._stream and sdk.onAnyStreamEvent
remains intact and only the comment text is deleted or replaced with a
single-line TODO pointing to the external doc.
🤖 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.

Inline comments:
In `@apps/meteor/client/hooks/useUserPresenceListener.ts`:
- Line 15: The call to Presence.notify uses STATUS_MAP[statusChanged as any],
which sidesteps TypeScript and can yield undefined for out-of-range values;
update the handler that receives statusChanged so its type is number (or
explicitly cast to number) and perform bounds checking against STATUS_MAP.length
or the known valid range (e.g., 0-4) before indexing; if statusChanged is
invalid, use a safe fallback status (e.g., a default STATUS_MAP entry or
'offline') and then call Presence.notify({ _id: uid, username, status:
safeStatus, statusText }); ensure you reference the statusChanged variable,
STATUS_MAP, and Presence.notify while implementing the type and runtime checks.

---

Nitpick comments:
In `@apps/meteor/app/utils/client/lib/SDKClient.ts`:
- Around line 356-372: Remove the large explanatory comment block above the
stream bridge implementation and replace it with a minimal one-line summary;
leave any detailed rationale in the PR description/ADR/docs as requested.
Specifically, delete the multi-line commentary that describes the two bridge
sources and lifecycle around onAnyStreamEvent, getDdpSdk().client.onCollection,
meteorBackedSdk.onCollection and the Meteor.connection._stream fallback (and the
note referencing apps/meteor/client/lib/presence.ts), and keep only a single
short comment that states the purpose (e.g., "Per-stream bridge for
onAnyStreamEvent; details in PR/ADR"). Ensure you also remove the duplicated
explanatory block at the other location (around lines referencing the same
behavior) so implementation files contain no lengthy rationale.

In `@apps/meteor/client/lib/sdk/meteorBackedSdk.ts`:
- Around line 118-124: Remove the inline explanatory comment block that
describes why ddp.onMessage is not registered in the Meteor-backed SDK
implementation and instead reference an external ADR/PR; keep the existing
implementation logic in meteorBackedSdk.ts unchanged (do not add or remove
listeners), ensuring the code around ddp.onMessage, onCollection,
Meteor.connection._stream and sdk.onAnyStreamEvent remains intact and only the
comment text is deleted or replaced with a single-line TODO pointing to the
external doc.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6f648ec1-1651-4274-aa34-106c07db2182

📥 Commits

Reviewing files that changed from the base of the PR and between 2d32e52 and 59d5666.

📒 Files selected for processing (19)
  • apps/meteor/app/notifications/client/index.ts
  • apps/meteor/app/notifications/client/lib/Presence.ts
  • apps/meteor/app/utils/client/lib/SDKClient.ts
  • apps/meteor/client/hooks/useUserPresenceListener.ts
  • apps/meteor/client/importPackages.ts
  • apps/meteor/client/lib/sdk/meteorBackedSdk.ts
  • apps/meteor/client/lib/sdk/streamerAdapter.ts
  • apps/meteor/client/lib/streamer/ddp.ts
  • apps/meteor/client/lib/streamer/emitter.ts
  • apps/meteor/client/lib/streamer/index.ts
  • apps/meteor/client/lib/streamer/streamer.ts
  • apps/meteor/client/providers/ServerProvider.tsx
  • apps/meteor/client/providers/UserPresenceProvider.tsx
  • apps/meteor/client/stories/contexts/ServerContextMock.tsx
  • apps/meteor/tests/mocks/client/ServerProviderMock.tsx
  • packages/mock-providers/src/MockedAppRootBuilder.tsx
  • packages/ui-contexts/src/ServerContext.ts
  • packages/ui-contexts/src/hooks/useStreamAll.ts
  • packages/ui-contexts/src/index.ts
💤 Files with no reviewable changes (8)
  • apps/meteor/app/notifications/client/lib/Presence.ts
  • apps/meteor/client/importPackages.ts
  • apps/meteor/client/lib/streamer/ddp.ts
  • apps/meteor/client/lib/sdk/streamerAdapter.ts
  • apps/meteor/client/lib/streamer/index.ts
  • apps/meteor/app/notifications/client/index.ts
  • apps/meteor/client/lib/streamer/streamer.ts
  • apps/meteor/client/lib/streamer/emitter.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: 🔎 Code Check / TypeScript
  • GitHub Check: 🔎 Code Check / Code Lint
  • GitHub Check: 🔨 Test Unit / Unit Tests
  • GitHub Check: 🔨 Test Storybook / Test Storybook
  • GitHub Check: 📦 Meteor Build (coverage)
  • 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:

  • packages/ui-contexts/src/hooks/useStreamAll.ts
  • packages/ui-contexts/src/index.ts
  • apps/meteor/tests/mocks/client/ServerProviderMock.tsx
  • apps/meteor/client/hooks/useUserPresenceListener.ts
  • apps/meteor/client/providers/ServerProvider.tsx
  • packages/ui-contexts/src/ServerContext.ts
  • apps/meteor/client/lib/sdk/meteorBackedSdk.ts
  • apps/meteor/client/providers/UserPresenceProvider.tsx
  • apps/meteor/client/stories/contexts/ServerContextMock.tsx
  • packages/mock-providers/src/MockedAppRootBuilder.tsx
  • apps/meteor/app/utils/client/lib/SDKClient.ts
🧠 Learnings (8)
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.

Applied to files:

  • packages/ui-contexts/src/hooks/useStreamAll.ts
  • packages/ui-contexts/src/index.ts
  • apps/meteor/client/hooks/useUserPresenceListener.ts
  • packages/ui-contexts/src/ServerContext.ts
  • apps/meteor/client/lib/sdk/meteorBackedSdk.ts
  • apps/meteor/app/utils/client/lib/SDKClient.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.

Applied to files:

  • packages/ui-contexts/src/hooks/useStreamAll.ts
  • packages/ui-contexts/src/index.ts
  • apps/meteor/client/hooks/useUserPresenceListener.ts
  • packages/ui-contexts/src/ServerContext.ts
  • apps/meteor/client/lib/sdk/meteorBackedSdk.ts
  • apps/meteor/app/utils/client/lib/SDKClient.ts
📚 Learning: 2026-03-04T14:16:40.911Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39304
File: packages/ui-contexts/src/ActionManagerContext.ts:26-26
Timestamp: 2026-03-04T14:16:40.911Z
Learning: In TypeScript files where you document accepted union constituents that ultimately resolve to the same primitive, consider using an explicit union type like UiKit.ModalView['id'] | UiKit.BannerView['viewId'] | UiKit.ContextualBarView['id'] to communicate the accepted values. Include a deliberate inline eslint-disable-next-line typescript-eslint/no-duplicate-type-constituents comment if needed to prevent false positives, and do not remove it. This pattern improves readability and intent without changing runtime behavior; apply this guidance to all relevant files under packages/ui-contexts/src/**/*.ts where such unions document input types.

Applied to files:

  • packages/ui-contexts/src/hooks/useStreamAll.ts
  • packages/ui-contexts/src/index.ts
  • packages/ui-contexts/src/ServerContext.ts
📚 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:

  • packages/ui-contexts/src/hooks/useStreamAll.ts
  • packages/ui-contexts/src/index.ts
  • apps/meteor/tests/mocks/client/ServerProviderMock.tsx
  • apps/meteor/client/hooks/useUserPresenceListener.ts
  • apps/meteor/client/providers/ServerProvider.tsx
  • packages/ui-contexts/src/ServerContext.ts
  • apps/meteor/client/lib/sdk/meteorBackedSdk.ts
  • apps/meteor/client/providers/UserPresenceProvider.tsx
  • apps/meteor/client/stories/contexts/ServerContextMock.tsx
  • packages/mock-providers/src/MockedAppRootBuilder.tsx
  • apps/meteor/app/utils/client/lib/SDKClient.ts
📚 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/tests/mocks/client/ServerProviderMock.tsx
  • apps/meteor/client/providers/ServerProvider.tsx
  • apps/meteor/client/providers/UserPresenceProvider.tsx
  • apps/meteor/client/stories/contexts/ServerContextMock.tsx
  • packages/mock-providers/src/MockedAppRootBuilder.tsx
📚 Learning: 2026-02-10T16:32:42.586Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 38528
File: apps/meteor/client/startup/roles.ts:14-14
Timestamp: 2026-02-10T16:32:42.586Z
Learning: In Rocket.Chat's Meteor client code, DDP streams use EJSON and Date fields arrive as Date objects; do not manually construct new Date() in stream handlers (for example, in sdk.stream()). Only REST API responses return plain JSON where dates are strings, so implement explicit conversion there if needed. Apply this guidance to all TypeScript files under apps/meteor/client to ensure consistent date handling in DDP streams and REST responses.

Applied to files:

  • apps/meteor/client/hooks/useUserPresenceListener.ts
  • apps/meteor/client/lib/sdk/meteorBackedSdk.ts
📚 Learning: 2026-05-11T20:30:35.265Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 40480
File: apps/meteor/client/meteor/startup/accounts.ts:59-61
Timestamp: 2026-05-11T20:30:35.265Z
Learning: In Rocket.Chat’s Meteor client code, when calling `dispatchToastMessage` with `{ type: 'error' }`, pass the raw caught error object as `message` without manual normalization. `dispatchToastMessage` is designed to accept `message: unknown` for error toasts, so avoid converting errors to strings (e.g., `String(error)`) or extracting `error.message` before passing them.

Applied to files:

  • apps/meteor/client/hooks/useUserPresenceListener.ts
  • apps/meteor/client/lib/sdk/meteorBackedSdk.ts
📚 Learning: 2026-04-14T21:10:31.855Z
Learnt from: dougfabris
Repo: RocketChat/Rocket.Chat PR: 36292
File: apps/meteor/client/hooks/useHasValidLocationHash.ts:7-12
Timestamp: 2026-04-14T21:10:31.855Z
Learning: When reviewing files in apps/meteor/client/hooks/, do not treat JSDoc-style comments on React hooks (especially exported hooks) as a violation of any “avoid code comments in implementation” guideline. It’s acceptable to use JSDoc to document the public API of exported hooks (e.g., parameter/return types, intended usage), as long as it documents behavior/contracts rather than adding narrative implementation comments.

Applied to files:

  • apps/meteor/client/hooks/useUserPresenceListener.ts
🔇 Additional comments (11)
packages/ui-contexts/src/ServerContext.ts (1)

9-10: LGTM!

Also applies to: 53-55, 74-74

apps/meteor/client/providers/ServerProvider.tsx (1)

7-8: LGTM!

Also applies to: 79-83, 169-169

packages/ui-contexts/src/hooks/useStreamAll.ts (1)

1-13: LGTM!

packages/ui-contexts/src/index.ts (1)

85-85: LGTM!

apps/meteor/tests/mocks/client/ServerProviderMock.tsx (1)

59-59: LGTM!

Also applies to: 75-75

apps/meteor/client/stories/contexts/ServerContextMock.tsx (1)

180-180: LGTM!

packages/mock-providers/src/MockedAppRootBuilder.tsx (1)

119-119: LGTM!

apps/meteor/app/utils/client/lib/SDKClient.ts (1)

19-20: LGTM!

Also applies to: 373-389, 393-427, 432-432, 452-452

apps/meteor/client/hooks/useUserPresenceListener.ts (2)

1-11: LGTM!


12-18: LGTM!

apps/meteor/client/providers/UserPresenceProvider.tsx (1)

6-6: LGTM!

Also applies to: 19-20

useEffect(
() =>
subscribe((uid, [[username, statusChanged, statusText]]) => {
Presence.notify({ _id: uid, username, status: STATUS_MAP[statusChanged as any], statusText });
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Replace as any with proper typing and add bounds checking.

The as any type assertion bypasses TypeScript's type safety, and accessing STATUS_MAP[statusChanged] without validation could return undefined if the server sends an unexpected index value outside 0-4.

🛡️ Proposed fix with type safety and bounds validation
-				Presence.notify({ _id: uid, username, status: STATUS_MAP[statusChanged as any], statusText });
+				const statusIndex = typeof statusChanged === 'number' ? statusChanged : -1;
+				const status = statusIndex >= 0 && statusIndex < STATUS_MAP.length ? STATUS_MAP[statusIndex] : UserStatus.OFFLINE;
+				Presence.notify({ _id: uid, username, status, statusText });

Alternatively, if you're confident the server always sends valid indices, at minimum replace as any with as number:

-				Presence.notify({ _id: uid, username, status: STATUS_MAP[statusChanged as any], statusText });
+				Presence.notify({ _id: uid, username, status: STATUS_MAP[statusChanged as number], statusText });
📝 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
Presence.notify({ _id: uid, username, status: STATUS_MAP[statusChanged as any], statusText });
const statusIndex = typeof statusChanged === 'number' ? statusChanged : -1;
const status = statusIndex >= 0 && statusIndex < STATUS_MAP.length ? STATUS_MAP[statusIndex] : UserStatus.OFFLINE;
Presence.notify({ _id: uid, username, status, statusText });
🤖 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/hooks/useUserPresenceListener.ts` at line 15, The call to
Presence.notify uses STATUS_MAP[statusChanged as any], which sidesteps
TypeScript and can yield undefined for out-of-range values; update the handler
that receives statusChanged so its type is number (or explicitly cast to number)
and perform bounds checking against STATUS_MAP.length or the known valid range
(e.g., 0-4) before indexing; if statusChanged is invalid, use a safe fallback
status (e.g., a default STATUS_MAP entry or 'offline') and then call
Presence.notify({ _id: uid, username, status: safeStatus, statusText }); ensure
you reference the statusChanged variable, STATUS_MAP, and Presence.notify while
implementing the type and runtime checks.

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