Skip to content

chore: migrate DDP callers to REST endpoints (used methods with REST replacement)#40659

Merged
ggazzo merged 11 commits into
developfrom
chore/ddp-migrate-used-with-rest
May 26, 2026
Merged

chore: migrate DDP callers to REST endpoints (used methods with REST replacement)#40659
ggazzo merged 11 commits into
developfrom
chore/ddp-migrate-used-with-rest

Conversation

@ggazzo
Copy link
Copy Markdown
Member

@ggazzo ggazzo commented May 22, 2026

Summary

Replaces runtime DDP callers in apps/meteor/client with their REST equivalents for methods that already have a working /v1 endpoint. DDP method registrations stay on the server — they remain reachable for external SDK/mobile clients until 9.0.0 removes them.

Status

Method Caller Status
personalAccessTokens:generateToken AddToken.tsx ✅ migrated
personalAccessTokens:regenerateToken AccountTokensTable.tsx ✅ migrated
personalAccessTokens:removeToken AccountTokensTable.tsx ✅ migrated
autoTranslate.getSupportedLanguages app/autotranslate/client/lib/autotranslate.ts ✅ migrated
autoTranslate.translateMessage useTranslateAction.ts, useViewOriginalTranslationAction.ts ✅ migrated
cloud:syncWorkspace RegisteredWorkspaceModal.tsx ✅ migrated
createDirectMessage useOpenRoom.ts + slashcommand ✅ migrated
createPrivateGroup GameCenterInvitePlayersModal.tsx ✅ migrated
e2e.getUsersOfRoomWithoutKey client/lib/e2ee/rocketchat.e2e.room.ts ✅ migrated
e2e.setRoomKeyID client/lib/e2ee/rocketchat.e2e.room.ts ✅ migrated
executeSlashCommandPreview ComposerBoxPopupPreview.tsx ✅ migrated
getRoomById useGoToRoom.ts ✅ migrated (mapper handles room wrapper + Date→string)
getSingleMessage client/lib/chats/data.ts ✅ migrated
getSlashCommandPreviews ComposerPopupProvider.tsx ✅ migrated
getThreadMessages useThreadMessagesQuery.ts ✅ migrated; read-marker side effect restored via separate readThreads DDP call
listCustomUserStatus useStatusItems.tsx ✅ migrated (mapCustomUserStatusFromApi)
saveRoomSettings app/slashcommands-topic/client/topic.ts ✅ migrated
setUserStatus app/slashcommands-status/client/status.ts ✅ migrated
getReadReceipts (EE) ReadReceiptsModal.tsx ⏳ deferred — REST migration triggered timing issues with optimistic message reconciliation; plan in docs/ddp-migration-sendMessage-getReadReceipts-plan.md, follow-up #40675
sendMessage 8 callers ⏳ deferred — same timing issue (quote-attachment e2e fails); plan documented, follow-up #40675
registerUser ComposerAnonymous.tsx + SetupWizardProvider.tsx ⏳ pending
requestDataDownload PreferencesMyDataSection.tsx ⏳ pending
setAvatarFromService useUpdateAvatar.ts ⏳ pending (REST takes multipart image or avatarUrl; no service param)
subscriptions/get client/lib/cachedStores/CachedStore.ts ⏳ pending (template-literal call ${this.name}/get; whole CachedStore abstraction needs review)

Mappers

REST responses serialize Date to ISO strings while DDP returns Date. Three mappers added under client/lib/utils/ keep call-sites typed against the domain shape:

  • mapMessageFromApi (existed)
  • mapCustomUserStatusFromApi
  • mapReadReceiptFromApi

Reverted

sendMessage + getReadReceipts were migrated in an earlier revision and reverted in this branch — both broke optimistic UI reconciliation and read-receipt timing in e2e (quote-attachment.spec.ts, omnichannel-livechat-read-receipts.spec.ts). Follow-up #40675 carries the deeper fix (server-side await + client reconcile via Messages.state.update(mapMessageFromApi(saved))).

Test plan

  • Account tokens: add, regenerate, remove
  • Auto-translate toggle + per-message translate/original
  • Workspace sync from admin
  • Create DM via /dm + room open from search
  • Game Center invite (private group create + opening welcome message)
  • E2EE room: enable encryption, exchange keys, post message
  • Slash-command preview popup (/giphy, /topic previews)
  • Go-to-room by id (links, deeplinks)
  • Thread message list + read-marker
  • Custom user statuses dropdown
  • /topic, /status slash commands

Task: ARCH-2159

Summary by CodeRabbit

  • Refactor
    • Switched many client actions to use standardized REST endpoints (translations, slash commands, direct messages, status/topic updates, thread and room retrieval, tokens, workspace sync, group creation, E2E key ops), improving backend consistency without changing user flows.
  • New Utilities
    • Added utilities to map custom user statuses and read receipts from API responses.

Review Change Stack

@dionisio-bot
Copy link
Copy Markdown
Contributor

dionisio-bot Bot commented May 22, 2026

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

@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented May 22, 2026

⚠️ No Changeset found

Latest commit: 617ef50

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 22, 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: 875db95e-5873-4f28-b333-0be525767e00

📥 Commits

Reviewing files that changed from the base of the PR and between e13bf8b and 617ef50.

📒 Files selected for processing (3)
  • apps/meteor/client/apps/gameCenter/GameCenterInvitePlayersModal.tsx
  • apps/meteor/client/views/admin/workspace/VersionCard/modals/RegisteredWorkspaceModal.tsx
  • apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
📜 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). (5)
  • GitHub Check: ⚙️ Variables Setup
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: CodeQL-Build
  • GitHub Check: Hacktron Security Check
  • 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/views/admin/workspace/VersionCard/modals/RegisteredWorkspaceModal.tsx
  • apps/meteor/client/apps/gameCenter/GameCenterInvitePlayersModal.tsx
  • apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
🧠 Learnings (6)
📚 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/views/admin/workspace/VersionCard/modals/RegisteredWorkspaceModal.tsx
  • apps/meteor/client/apps/gameCenter/GameCenterInvitePlayersModal.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/views/admin/workspace/VersionCard/modals/RegisteredWorkspaceModal.tsx
  • apps/meteor/client/apps/gameCenter/GameCenterInvitePlayersModal.tsx
  • apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
📚 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/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.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/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.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 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:

  • apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.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:

  • apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
🧬 Code graph analysis (1)
apps/meteor/client/apps/gameCenter/GameCenterInvitePlayersModal.tsx (1)
apps/meteor/client/lib/utils/callWithErrorHandling.ts (1)
  • callWithErrorHandling (6-16)
🔇 Additional comments (3)
apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts (1)

114-114: LGTM!

apps/meteor/client/views/admin/workspace/VersionCard/modals/RegisteredWorkspaceModal.tsx (1)

47-48: LGTM!

apps/meteor/client/apps/gameCenter/GameCenterInvitePlayersModal.tsx (1)

38-44: Invite sending is still gated by an impossible condition.

openedRoom is read before groups.create runs, so it still cannot equal the freshly created group._id. This means the new callWithErrorHandling('sendMessage', ...) path remains unreachable for the invite flow.


Walkthrough

Client code migrated from DDP/method calls and useMethod hooks to REST endpoints and useEndpoint hooks across translation, room navigation, message fetching, tokens, slash commands, E2EE, composer previews, user status, and tests; response shapes and mappers were added or adjusted.

Changes

DDP-to-REST API Migration

Layer / File(s) Summary
Translation system migration
apps/meteor/app/autotranslate/client/lib/autotranslate.ts, apps/meteor/client/components/message/toolbar/useTranslateAction.ts, apps/meteor/client/components/message/toolbar/useViewOriginalTranslationAction.ts
AutoTranslate init and translate/view-original hooks now call REST endpoints (e.g., /v1/autotranslate.getSupportedLanguages, /v1/autotranslate.translateMessage) and use object payloads { messageId, targetLanguage }.
Slash command handler migrations
apps/meteor/app/slashcommands-open/client/client.ts, apps/meteor/app/slashcommands-status/client/status.ts, apps/meteor/app/slashcommands-topic/client/topic.ts
Slash commands use REST endpoints (/v1/im.create, /v1/users.setStatus, /v1/rooms.saveRoomSettings) instead of SDK method calls; payload shapes adjusted.
Room info and navigation endpoints
apps/meteor/client/views/room/hooks/useGoToRoom.ts, apps/meteor/client/views/room/hooks/useOpenRoom.ts
Room info and DM creation replaced useMethod calls with useEndpoint for /v1/rooms.info and /v1/im.create, added explicit missing-room error handling, and navigate using returned room IDs.
Message data, threads, and mappers
apps/meteor/client/lib/chats/data.ts, apps/meteor/client/lib/utils/mapReadReceiptFromApi.ts, apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
Single-message fallback and thread queries use REST endpoints; added mappers (mapMessageFromApi, mapReadReceiptFromApi) to convert serialized dates; message permission reads adjusted.
User status and custom statuses
apps/meteor/client/lib/utils/mapCustomUserStatusFromApi.ts, apps/meteor/client/navbar/NavBarSettingsToolbar/UserMenu/hooks/useStatusItems.tsx
Added mapper to convert _updatedAt to Date; useStatusItems pages /v1/custom-user-status.list, accumulates pages, and maps items.
Personal access token management
apps/meteor/client/views/account/tokens/AccountTokensTable/*
Token create/regenerate/remove use POST endpoints under /v1/users.* via useEndpoint; handlers now destructure { token } from responses.
Composer and command preview UI
apps/meteor/client/views/room/composer/ComposerBoxPopupPreview.tsx, apps/meteor/client/views/room/providers/ComposerPopupProvider.tsx
Slash-command preview execution switched to /v1/commands.preview endpoint with consolidated request payloads; preview extraction uses preview.i18nTitle and preview.items.
Game center and notification updates
apps/meteor/client/apps/gameCenter/GameCenterInvitePlayersModal.tsx, apps/meteor/client/hooks/notification/useNotification.ts
Game center group creation now uses sdk.rest.post('/v1/groups.create'); notification avatar URL retrieval removed an explicit type assertion.
E2EE group key operations
apps/meteor/client/lib/e2ee/rocketchat.e2e.room.ts
E2E key import/publish and user lookup use REST endpoints (/v1/e2e.setRoomKeyID, /v1/e2e.getUsersOfRoomWithoutKey) and remove non-null assertions when parsing/using keys.
Workspace sync endpoint
apps/meteor/client/views/admin/workspace/VersionCard/modals/RegisteredWorkspaceModal.tsx
Workspace sync uses POST /v1/cloud.syncWorkspace via useEndpoint and validates { success } in the response, adjusting error toast derivation.
Test mock updates
apps/meteor/client/views/room/MessageList/hooks/useLoadSurroundingMessages.spec.ts
Tests mock /v1/rooms.info responses instead of DDP getRoomById method stubs.

Sequence Diagram

sequenceDiagram
  participant UI as Client UI
  participant SDK as client sdk.rest
  participant Server
  UI->>SDK: POST /v1/im.create { usernames }
  SDK->>Server: HTTP POST /v1/im.create
  Server-->>SDK: { room: { _id, t, name } }
  SDK-->>UI: { room }
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • tassoevan
  • ricardogarim
  • sampaiodiego
🚥 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 clearly summarizes the main change: migration of DDP method callers to REST endpoints. It accurately reflects the primary purpose of the pull request across all modified files.
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-2159: 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.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 22, 2026

Codecov Report

❌ Patch coverage is 65.78947% with 26 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.65%. Comparing base (10266c1) to head (617ef50).

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #40659      +/-   ##
===========================================
- Coverage    69.68%   69.65%   -0.03%     
===========================================
  Files         3338     3339       +1     
  Lines       123248   123269      +21     
  Branches     21947    21972      +25     
===========================================
- Hits         85881    85859      -22     
- Misses       34013    34051      +38     
- Partials      3354     3359       +5     
Flag Coverage Δ
e2e 59.21% <59.67%> (+<0.01%) ⬆️
e2e-api 45.97% <ø> (-0.03%) ⬇️
unit 70.46% <60.00%> (-0.06%) ⬇️

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 added a commit that referenced this pull request May 22, 2026
The deprecation logger throws in TEST_MODE
(apps/meteor/app/lib/server/lib/deprecationWarningLogger.ts:118), so a
deprecation log on a method that's still invoked by integration or
unit tests turns those tests into failures with messages like:

    Error: The method "addUsersToRoom" is deprecated and will be
    removed on version 9.0.0

That's the intended dev-loop guard rail, but it means this PR can
only carry deprecation calls on methods with **no callers**.

Removes the 83 logger calls (and their now-unused imports) that
targeted methods listed in audit.used. They will be revisited as part
of the caller-migration PR #40659 — once each callsite moves to the
matching REST endpoint, the DDP method can either get a deprecation
log here or be removed outright in #40656.

What remains in this PR: 71 deprecation calls, all on orphan methods
without a REST replacement.
@ggazzo ggazzo changed the title chore: migrate DDP callers to REST endpoints chore: migrate DDP callers to REST endpoints (used methods with REST replacement) May 22, 2026
@rc-layne
Copy link
Copy Markdown

rc-layne Bot commented May 25, 2026

Layne — scan passed

No security issues found on latest push.

Comment thread scripts/strip-empty-replacement-loggers.mjs Outdated
@ggazzo ggazzo force-pushed the chore/ddp-migrate-used-with-rest branch from 9c237e2 to 533f925 Compare May 25, 2026 19:00
@ggazzo ggazzo added this to the 8.6.0 milestone May 25, 2026
@ggazzo
Copy link
Copy Markdown
Member Author

ggazzo commented May 25, 2026

/jira ARCH-2156

ggazzo added 9 commits May 25, 2026 17:50
Replaces `useMethod('personalAccessTokens:generateToken' |
'personalAccessTokens:regenerateToken' | 'personalAccessTokens:removeToken')`
in the account-tokens table with `useEndpoint('POST',
'/v1/users.${verb}PersonalAccessToken')`. Destructures the new
`{ token }` response wrapper instead of treating the token as the bare
return value.

Both methods remain registered server-side for external DDP clients —
the deprecation log on develop will warn callers that they're scheduled
for removal in 9.0.0.
Swaps useMethod / sdk.call for useEndpoint / sdk.rest in the
following client modules where the REST endpoint is a faithful
drop-in (after destructuring the response wrapper):

  - RegisteredWorkspaceModal.tsx
      cloud:syncWorkspace -> POST /v1/cloud.syncWorkspace
      (returns { success } now; threw on failure previously, still does)

  - PreferencesMyDataSection.tsx
      (skipped - REST drops url + pendingOperationsBeforeMyRequest)

  - ReadReceiptsModal.tsx
      getReadReceipts -> GET /v1/chat.getMessageReadReceipts
      (REST wraps as { receipts }; destructured in queryFn)

  - ComposerPopupProvider.tsx
      getSlashCommandPreviews -> GET /v1/commands.preview
      (params reshape: { cmd, params, msg: { rid, tmid } } ->
       { command, params, roomId }; tmid no longer forwarded - REST
       GET schema doesn't accept it)

  - useTranslateAction.ts + useViewOriginalTranslationAction.ts
      autoTranslate.translateMessage -> POST /v1/autotranslate.translateMessage
      (REST takes { messageId, targetLanguage }; result was already discarded)

  - apps/autotranslate/client/lib/autotranslate.ts
      autoTranslate.getSupportedLanguages -> GET /v1/autotranslate.getSupportedLanguages
      (REST wraps as { languages })

  - slashcommands-status/client/status.ts
      setUserStatus -> POST /v1/users.setStatus
      ({ message: params } - status defaults to undefined like before)

  - slashcommands-topic/client/topic.ts
      saveRoomSettings -> POST /v1/rooms.saveRoomSettings
      ({ rid, roomTopic: params })

  - lib/chats/data.ts
      getSingleMessage -> GET /v1/chat.getMessage
      (destructure response.message)

  - lib/e2ee/rocketchat.e2e.room.ts
      e2e.setRoomKeyID -> POST /v1/e2e.setRoomKeyID
      e2e.getUsersOfRoomWithoutKey -> GET /v1/e2e.getUsersOfRoomWithoutKey

  - GameCenterInvitePlayersModal.tsx
      createPrivateGroup -> POST /v1/groups.create
      (REST returns { group }; group.t / group._id replace .t / .rid)

Skipped in this pass (need follow-up):
  - requestDataDownload: REST drops url + pendingOperationsBeforeMyRequest
  - registerUser: REST returns { user } while anonymous DDP path
    returns a stamped login token used for auto-login
  - executeSlashCommandPreview: REST POST requires triggerId which the
    caller does not currently produce
Six methods from docs/ddp-complex-migration-analysis.md that were
classified as 'pure caller refactor':

  - getRoomById -> GET /v1/rooms.info
      useGoToRoom destructures { room } and throws on null. Accepts the
      extra team/parent lookups REST does (rare path - only when the
      Subscriptions.state miss path is taken).

  - createDirectMessage -> POST /v1/im.create
      useOpenRoom passes { usernames: reference } instead of the
      variadic ...split(', ') and reads room._id from the new { room }
      wrapper. slashcommand /open passes { username: room } for the
      single-user case.

  - listCustomUserStatus -> GET /v1/custom-user-status.list
      useStatusItems wraps the paginated endpoint in a loop that walks
      offset->total to reproduce the 'give me everything' contract the
      DDP method had. Bounded in practice (few dozen entries on a
      typical workspace).

  - getThreadMessages -> GET /v1/chat.getThreadMessages
      useThreadMessagesQuery destructures { messages } from the
      paginated response and fires POST /v1/subscriptions.read with
      { tmid } as a fire-and-forget side effect to preserve the
      read-marker behavior the DDP method had server-side.

  - executeSlashCommandPreview -> POST /v1/commands.preview
      ComposerBoxPopupPreview reshapes args from
      { cmd, params, msg: { rid, tmid } } + previewItem to
      { command, params, roomId, tmid?, triggerId, previewItem } and
      mints a triggerId via Random.id() (the preview popup did not
      previously produce one - the slash-command runtime did).

  - sendMessage -> POST /v1/chat.sendMessage (8 callsites)
      Wraps the message in { message, previewUrls? }. Callers updated:
        - client/lib/chats/flows/sendMessage.ts (primary send path)
        - client/hooks/notification/useNotification.ts (reply from
          desktop notification)
        - client/apps/gameCenter/GameCenterInvitePlayersModal.tsx
          (drops callWithErrorHandling - sdk.rest already throws on
          non-2xx)
        - all five asciiart slash commands
          (lenny, tableflip, unflip, gimme, shrug)

Server-side DDP method registrations stay alive for external SDK and
mobile clients. They will be picked up by the deprecation log on the
next pass once tests are no longer the gating factor.
REST endpoint typings serialize dates as strings, so the migrated
callers need explicit casts when feeding the results into APIs that
expect IMessage / IReadReceiptWithUser / ICustomUserStatus (which use
Date). Five files touched:

  - client/lib/chats/data.ts: cast chat.getMessage response.message
    to IMessage when feeding findMessageByID's IMessage|null contract.
  - client/views/room/modals/ReadReceiptsModal/ReadReceiptsModal.tsx:
    annotate the queryFn return type as IReadReceiptWithUser[] so the
    ReadReceiptRow props line up.
  - client/navbar/.../useStatusItems.tsx: declare the
    listCustomUserStatus loop as ICustomUserStatus[] so UserStatusLister
    is satisfied.
  - client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts:
    drop the explicit subscriptions.read call - the REST endpoint
    doesn't accept tmid; the per-thread read marker no longer fires
    here. Comment notes the gap.
  - client/views/admin/workspace/VersionCard/modals/RegisteredWorkspaceModal.tsx:
    POST /v1/cloud.syncWorkspace takes no body; call syncWorkspace()
    without an argument.
Audit showed the four `as unknown as T` casts I added earlier were
hiding real serialization differences - REST returns
`Serialized<T>` (ISO date strings) while callers consume the same
identifier expecting `T` (Date objects). At runtime any code reaching
for `.getTime()` on `ts` / `_updatedAt` would crash.

Replaces each cast with a proper mapper:

  - client/lib/chats/data.ts: chat.getMessage response goes through
    `mapMessageFromApi` (already existed) before satisfying the
    `IMessage | null` contract findMessageByID promises.

  - client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts:
    each message from chat.getThreadMessages goes through
    `mapMessageFromApi` so the IThreadMessage type predicate sees a
    real Date in `msg.ts`.

  - client/views/room/modals/ReadReceiptsModal/ReadReceiptsModal.tsx:
    chat.getMessageReadReceipts response is mapped through the new
    `mapReadReceiptFromApi` (revives `ts` and `_updatedAt`).

  - client/navbar/.../useStatusItems.tsx: custom-user-status.list
    response is mapped through the new `mapCustomUserStatusFromApi`
    (revives `_updatedAt` which the UserStatuses store uses for
    ordering and conflict detection).

Two new helpers added under apps/meteor/client/lib/utils/. Pattern
mirrors the existing `mapMessageFromApi`.
Dropping the readThread side effect from useThreadMessagesQuery broke
two e2e tests:
  - read-receipts-thread / should show read receipt as viewed in
    thread when both users have the thread open
  - omnichannel-livechat-read-receipts (cascading from the same gap)

REST has no per-thread read-marker endpoint — `/v1/subscriptions.read`
marks the whole room. Until one exists, fall back to the existing
`readThreads` DDP method (which is on the used-without-rest list and
will stay registered through 9.x) and fire it as a side effect from
the query function.
After deep debug, the two persistent UI test failures
(quote-attachment + omnichannel-livechat-read-receipts) trace back to
behavior differences between DDP and REST for these two methods:

  - sendMessage: DDP path triggers Minimongo-driven reactive updates
    that the composer/optimistic-message flow depends on for
    visual reset; REST returns the wrapped message but the client
    does not get the same reactive replacement. Quote-attachment's
    composer stays in preview state because the optimistic temp
    message is not reconciled.

  - getReadReceipts: REST single GET races with the visitor's
    self-receipt insertion that the DDP method, going through the
    Meteor call queue, happens to wait behind. Livechat read-receipts
    test reads only one receipt instead of two.

Both server endpoints exist and are otherwise correct, but the client
plumbing assumes DDP semantics in subtle ways. Migrating these two
methods needs a deeper refactor of the composer state machine and the
read-receipt timing — out of scope here.

Reverted callsites:
  - apps/meteor/client/lib/chats/flows/sendMessage.ts
  - apps/meteor/client/hooks/notification/useNotification.ts
  - apps/meteor/client/apps/gameCenter/GameCenterInvitePlayersModal.tsx
  - apps/meteor/app/slashcommand-asciiarts/client/{lenny,tableflip,unflip,gimme,shrug}.ts
  - apps/meteor/client/views/room/modals/ReadReceiptsModal/ReadReceiptsModal.tsx

The mapReadReceiptFromApi helper is left in place — harmless and
useful for the next attempt.
Captures the two regressions that forced the revert in this PR and
the work needed to reattempt the migration cleanly. Sequenced as four
small PRs: server-side livechat-receipt sync + client invalidation
for getReadReceipts, optimistic reconciliation + 8-callsite swap for
sendMessage.
@ggazzo ggazzo force-pushed the chore/ddp-migrate-used-with-rest branch from 533f925 to d55b95d Compare May 25, 2026 20:51
@ggazzo ggazzo marked this pull request as ready for review May 25, 2026 20:55
@ggazzo ggazzo requested a review from a team as a code owner May 25, 2026 20:55
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.

1 issue found across 22 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread apps/meteor/client/apps/gameCenter/GameCenterInvitePlayersModal.tsx Outdated
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: 3

🧹 Nitpick comments (4)
apps/meteor/client/views/room/providers/ComposerPopupProvider.tsx (1)

374-385: 💤 Low value

Consider adding optional chaining on items for defensive handling.

If the API ever returns a preview object without an items array, preview?.items.map() would throw a TypeError. Adding preview?.items?.map() provides safer fallback.

Suggested defensive improvement
 return (
-    preview?.items.map((item) => ({
+    preview?.items?.map((item) => ({
         _id: item.id,
         value: item.value,
         type: item.type,
     })) ?? []
 );
🤖 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/views/room/providers/ComposerPopupProvider.tsx` around
lines 374 - 385, The getItemsFromLocal handler can throw if preview exists but
preview.items is undefined; update the mapping to defensively handle missing
items by using optional chaining and a safe fallback (e.g., change
preview?.items.map(...) to preview?.items?.map(...) ?? [] or ensure you default
preview.items to an empty array before mapping) inside the getItemsFromLocal
function that calls call(...) and sets setPreviewTitle(...), so the function
always returns an array even when preview.items is absent.
apps/meteor/client/navbar/NavBarSettingsToolbar/UserMenu/hooks/useStatusItems.tsx (1)

31-31: ⚡ Quick win

Remove the inline implementation comment

Line 31 adds an implementation comment in TSX code, which this repo guideline disallows.

Suggested change
-		// REST endpoint is paginated; loop until total reached.

As per coding guidelines: **/*.{ts,tsx,js} — “Avoid code comments in the 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/navbar/NavBarSettingsToolbar/UserMenu/hooks/useStatusItems.tsx`
at line 31, Remove the inline implementation comment "// REST endpoint is
paginated; loop until total reached." from the useStatusItems hook in
useStatusItems.tsx; locate the comment inside the useStatusItems function (or
its surrounding hook logic) and delete the comment so the file complies with the
repository guideline that implementation comments are disallowed in .ts/.tsx
files.
apps/meteor/client/apps/gameCenter/GameCenterInvitePlayersModal.tsx (1)

27-27: 💤 Low value

Unused hook if condition is removed.

If the condition on line 37 is removed as suggested above, openedRoom becomes unused and this line can be deleted along with the useOpenedRoom import.

🤖 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/apps/gameCenter/GameCenterInvitePlayersModal.tsx` at line
27, Remove the now-unused hook and variable: delete the useOpenedRoom import and
the const openedRoom = useOpenedRoom(); declaration (references: useOpenedRoom,
openedRoom) since the conditional that used openedRoom was removed and these are
no longer needed.
apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts (1)

29-31: ⚡ Quick win

Remove implementation comments from this hook.

Line 29–31 adds inline implementation comments; move this migration rationale to PR/ADR/docs instead.

✂️ Proposed cleanup
-	// REST has no per-thread read-marker endpoint yet; fall back to the
-	// `readThreads` DDP method so the side effect that DDP getThreadMessages
-	// used to do server-side keeps happening for callers.
 	const readThreads = useMethod('readThreads');
As per coding guidelines: `**/*.{ts,tsx,js}` → "Avoid code comments in the 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/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts`
around lines 29 - 31, The inline implementation comment inside the
useThreadMessagesQuery hook (referencing REST lacking a per-thread read-marker
and falling back to the `readThreads` DDP method so the side effect that DDP
`getThreadMessages` used to do server-side keeps happening) should be removed
from the source; edit the `useThreadMessagesQuery` hook to delete those lines
and move the migration rationale to the PR/ADR/docs instead, keeping the hook
implementation and any related calls to `getThreadMessages`/`readThreads`
untouched.
🤖 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/apps/gameCenter/GameCenterInvitePlayersModal.tsx`:
- Around line 37-43: The check using openedRoom (from useOpenedRoom()) prevents
sending the invite to the newly created group because openedRoom cannot equal
the new group._id; remove the conditional and call sdk.call('sendMessage', {
_id: Random.id(), rid: group._id, msg: t('Apps_Game_Center_Play_Game_Together',
{ name }) }) unconditionally after the group is created (or, if conditional
behavior was intended, update the condition to reflect the correct runtime value
instead of openedRoom). Ensure the sendMessage invocation uses Random.id(),
group._id, and the same i18n key t('Apps_Game_Center_Play_Game_Together', { name
}).

In
`@apps/meteor/client/views/admin/workspace/VersionCard/modals/RegisteredWorkspaceModal.tsx`:
- Around line 38-41: The thrown Error from syncWorkspace() is fine but the catch
handler forwards the raw error object to the toast, which can produce
non-readable output; update the catch to pass a plain string (e.g.
error?.message ?? String(error) or (error instanceof Error ? error.message :
String(error))) to the message/toast call so the user sees a readable message;
locate the try/catch around syncWorkspace() in RegisteredWorkspaceModal.tsx and
replace the direct error forwarding with the message string extraction.

In
`@apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts`:
- Line 114: The call to readThreads(tmid) is fired-and-forgotten and can produce
unhandled promise rejections; update the usage in useThreadMessagesQuery to
either await readThreads(tmid) inside the surrounding async function or attach a
rejection handler (e.g., readThreads(tmid).catch(err =>
process/log/handleError(err))). Ensure you reference the readThreads invocation
at the spot where void readThreads(tmid) is called and handle errors
consistently with the component’s error logging/handling utilities.

---

Nitpick comments:
In `@apps/meteor/client/apps/gameCenter/GameCenterInvitePlayersModal.tsx`:
- Line 27: Remove the now-unused hook and variable: delete the useOpenedRoom
import and the const openedRoom = useOpenedRoom(); declaration (references:
useOpenedRoom, openedRoom) since the conditional that used openedRoom was
removed and these are no longer needed.

In
`@apps/meteor/client/navbar/NavBarSettingsToolbar/UserMenu/hooks/useStatusItems.tsx`:
- Line 31: Remove the inline implementation comment "// REST endpoint is
paginated; loop until total reached." from the useStatusItems hook in
useStatusItems.tsx; locate the comment inside the useStatusItems function (or
its surrounding hook logic) and delete the comment so the file complies with the
repository guideline that implementation comments are disallowed in .ts/.tsx
files.

In
`@apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts`:
- Around line 29-31: The inline implementation comment inside the
useThreadMessagesQuery hook (referencing REST lacking a per-thread read-marker
and falling back to the `readThreads` DDP method so the side effect that DDP
`getThreadMessages` used to do server-side keeps happening) should be removed
from the source; edit the `useThreadMessagesQuery` hook to delete those lines
and move the migration rationale to the PR/ADR/docs instead, keeping the hook
implementation and any related calls to `getThreadMessages`/`readThreads`
untouched.

In `@apps/meteor/client/views/room/providers/ComposerPopupProvider.tsx`:
- Around line 374-385: The getItemsFromLocal handler can throw if preview exists
but preview.items is undefined; update the mapping to defensively handle missing
items by using optional chaining and a safe fallback (e.g., change
preview?.items.map(...) to preview?.items?.map(...) ?? [] or ensure you default
preview.items to an empty array before mapping) inside the getItemsFromLocal
function that calls call(...) and sets setPreviewTitle(...), so the function
always returns an array even when preview.items is absent.
🪄 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: 98205e28-0540-4d9b-8b56-c5342229fbe7

📥 Commits

Reviewing files that changed from the base of the PR and between 10266c1 and e13bf8b.

📒 Files selected for processing (22)
  • apps/meteor/app/autotranslate/client/lib/autotranslate.ts
  • apps/meteor/app/slashcommands-open/client/client.ts
  • apps/meteor/app/slashcommands-status/client/status.ts
  • apps/meteor/app/slashcommands-topic/client/topic.ts
  • apps/meteor/client/apps/gameCenter/GameCenterInvitePlayersModal.tsx
  • apps/meteor/client/components/message/toolbar/useTranslateAction.ts
  • apps/meteor/client/components/message/toolbar/useViewOriginalTranslationAction.ts
  • apps/meteor/client/hooks/notification/useNotification.ts
  • apps/meteor/client/lib/chats/data.ts
  • apps/meteor/client/lib/e2ee/rocketchat.e2e.room.ts
  • apps/meteor/client/lib/utils/mapCustomUserStatusFromApi.ts
  • apps/meteor/client/lib/utils/mapReadReceiptFromApi.ts
  • apps/meteor/client/navbar/NavBarSettingsToolbar/UserMenu/hooks/useStatusItems.tsx
  • apps/meteor/client/views/account/tokens/AccountTokensTable/AccountTokensTable.tsx
  • apps/meteor/client/views/account/tokens/AccountTokensTable/AddToken.tsx
  • apps/meteor/client/views/admin/workspace/VersionCard/modals/RegisteredWorkspaceModal.tsx
  • apps/meteor/client/views/room/MessageList/hooks/useLoadSurroundingMessages.spec.ts
  • apps/meteor/client/views/room/composer/ComposerBoxPopupPreview.tsx
  • apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
  • apps/meteor/client/views/room/hooks/useGoToRoom.ts
  • apps/meteor/client/views/room/hooks/useOpenRoom.ts
  • apps/meteor/client/views/room/providers/ComposerPopupProvider.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). (4)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Hacktron Security Check
  • GitHub Check: 📦 Build Packages
  • GitHub Check: CodeQL-Build
🧰 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:

  • apps/meteor/client/lib/utils/mapCustomUserStatusFromApi.ts
  • apps/meteor/app/slashcommands-status/client/status.ts
  • apps/meteor/client/hooks/notification/useNotification.ts
  • apps/meteor/client/lib/utils/mapReadReceiptFromApi.ts
  • apps/meteor/app/slashcommands-topic/client/topic.ts
  • apps/meteor/client/components/message/toolbar/useViewOriginalTranslationAction.ts
  • apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
  • apps/meteor/client/views/account/tokens/AccountTokensTable/AddToken.tsx
  • apps/meteor/client/views/admin/workspace/VersionCard/modals/RegisteredWorkspaceModal.tsx
  • apps/meteor/app/slashcommands-open/client/client.ts
  • apps/meteor/client/navbar/NavBarSettingsToolbar/UserMenu/hooks/useStatusItems.tsx
  • apps/meteor/client/views/account/tokens/AccountTokensTable/AccountTokensTable.tsx
  • apps/meteor/client/views/room/composer/ComposerBoxPopupPreview.tsx
  • apps/meteor/client/views/room/MessageList/hooks/useLoadSurroundingMessages.spec.ts
  • apps/meteor/app/autotranslate/client/lib/autotranslate.ts
  • apps/meteor/client/views/room/providers/ComposerPopupProvider.tsx
  • apps/meteor/client/apps/gameCenter/GameCenterInvitePlayersModal.tsx
  • apps/meteor/client/components/message/toolbar/useTranslateAction.ts
  • apps/meteor/client/lib/chats/data.ts
  • apps/meteor/client/views/room/hooks/useGoToRoom.ts
  • apps/meteor/client/lib/e2ee/rocketchat.e2e.room.ts
  • apps/meteor/client/views/room/hooks/useOpenRoom.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/client/views/room/MessageList/hooks/useLoadSurroundingMessages.spec.ts
🧠 Learnings (9)
📚 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/lib/utils/mapCustomUserStatusFromApi.ts
  • apps/meteor/client/hooks/notification/useNotification.ts
  • apps/meteor/client/lib/utils/mapReadReceiptFromApi.ts
  • apps/meteor/client/components/message/toolbar/useViewOriginalTranslationAction.ts
  • apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
  • apps/meteor/client/views/room/MessageList/hooks/useLoadSurroundingMessages.spec.ts
  • apps/meteor/client/components/message/toolbar/useTranslateAction.ts
  • apps/meteor/client/lib/chats/data.ts
  • apps/meteor/client/views/room/hooks/useGoToRoom.ts
  • apps/meteor/client/lib/e2ee/rocketchat.e2e.room.ts
  • apps/meteor/client/views/room/hooks/useOpenRoom.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/lib/utils/mapCustomUserStatusFromApi.ts
  • apps/meteor/client/hooks/notification/useNotification.ts
  • apps/meteor/client/lib/utils/mapReadReceiptFromApi.ts
  • apps/meteor/client/components/message/toolbar/useViewOriginalTranslationAction.ts
  • apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
  • apps/meteor/client/views/room/MessageList/hooks/useLoadSurroundingMessages.spec.ts
  • apps/meteor/client/components/message/toolbar/useTranslateAction.ts
  • apps/meteor/client/lib/chats/data.ts
  • apps/meteor/client/views/room/hooks/useGoToRoom.ts
  • apps/meteor/client/lib/e2ee/rocketchat.e2e.room.ts
  • apps/meteor/client/views/room/hooks/useOpenRoom.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 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:

  • apps/meteor/client/lib/utils/mapCustomUserStatusFromApi.ts
  • apps/meteor/app/slashcommands-status/client/status.ts
  • apps/meteor/client/hooks/notification/useNotification.ts
  • apps/meteor/client/lib/utils/mapReadReceiptFromApi.ts
  • apps/meteor/app/slashcommands-topic/client/topic.ts
  • apps/meteor/client/components/message/toolbar/useViewOriginalTranslationAction.ts
  • apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
  • apps/meteor/app/slashcommands-open/client/client.ts
  • apps/meteor/client/views/room/MessageList/hooks/useLoadSurroundingMessages.spec.ts
  • apps/meteor/app/autotranslate/client/lib/autotranslate.ts
  • apps/meteor/client/components/message/toolbar/useTranslateAction.ts
  • apps/meteor/client/lib/chats/data.ts
  • apps/meteor/client/views/room/hooks/useGoToRoom.ts
  • apps/meteor/client/lib/e2ee/rocketchat.e2e.room.ts
  • apps/meteor/client/views/room/hooks/useOpenRoom.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:

  • apps/meteor/client/lib/utils/mapCustomUserStatusFromApi.ts
  • apps/meteor/app/slashcommands-status/client/status.ts
  • apps/meteor/client/hooks/notification/useNotification.ts
  • apps/meteor/client/lib/utils/mapReadReceiptFromApi.ts
  • apps/meteor/app/slashcommands-topic/client/topic.ts
  • apps/meteor/client/components/message/toolbar/useViewOriginalTranslationAction.ts
  • apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
  • apps/meteor/app/slashcommands-open/client/client.ts
  • apps/meteor/client/views/room/MessageList/hooks/useLoadSurroundingMessages.spec.ts
  • apps/meteor/app/autotranslate/client/lib/autotranslate.ts
  • apps/meteor/client/components/message/toolbar/useTranslateAction.ts
  • apps/meteor/client/lib/chats/data.ts
  • apps/meteor/client/views/room/hooks/useGoToRoom.ts
  • apps/meteor/client/lib/e2ee/rocketchat.e2e.room.ts
  • apps/meteor/client/views/room/hooks/useOpenRoom.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:

  • apps/meteor/client/lib/utils/mapCustomUserStatusFromApi.ts
  • apps/meteor/app/slashcommands-status/client/status.ts
  • apps/meteor/client/hooks/notification/useNotification.ts
  • apps/meteor/client/lib/utils/mapReadReceiptFromApi.ts
  • apps/meteor/app/slashcommands-topic/client/topic.ts
  • apps/meteor/client/components/message/toolbar/useViewOriginalTranslationAction.ts
  • apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
  • apps/meteor/client/views/account/tokens/AccountTokensTable/AddToken.tsx
  • apps/meteor/client/views/admin/workspace/VersionCard/modals/RegisteredWorkspaceModal.tsx
  • apps/meteor/app/slashcommands-open/client/client.ts
  • apps/meteor/client/navbar/NavBarSettingsToolbar/UserMenu/hooks/useStatusItems.tsx
  • apps/meteor/client/views/account/tokens/AccountTokensTable/AccountTokensTable.tsx
  • apps/meteor/client/views/room/composer/ComposerBoxPopupPreview.tsx
  • apps/meteor/client/views/room/MessageList/hooks/useLoadSurroundingMessages.spec.ts
  • apps/meteor/app/autotranslate/client/lib/autotranslate.ts
  • apps/meteor/client/views/room/providers/ComposerPopupProvider.tsx
  • apps/meteor/client/apps/gameCenter/GameCenterInvitePlayersModal.tsx
  • apps/meteor/client/components/message/toolbar/useTranslateAction.ts
  • apps/meteor/client/lib/chats/data.ts
  • apps/meteor/client/views/room/hooks/useGoToRoom.ts
  • apps/meteor/client/lib/e2ee/rocketchat.e2e.room.ts
  • apps/meteor/client/views/room/hooks/useOpenRoom.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/notification/useNotification.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/client/views/account/tokens/AccountTokensTable/AddToken.tsx
  • apps/meteor/client/views/admin/workspace/VersionCard/modals/RegisteredWorkspaceModal.tsx
  • apps/meteor/client/navbar/NavBarSettingsToolbar/UserMenu/hooks/useStatusItems.tsx
  • apps/meteor/client/views/account/tokens/AccountTokensTable/AccountTokensTable.tsx
  • apps/meteor/client/views/room/composer/ComposerBoxPopupPreview.tsx
  • apps/meteor/client/views/room/providers/ComposerPopupProvider.tsx
  • apps/meteor/client/apps/gameCenter/GameCenterInvitePlayersModal.tsx
📚 Learning: 2026-02-24T19:22:48.358Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 38493
File: apps/meteor/tests/e2e/omnichannel/omnichannel-send-pdf-transcript.spec.ts:66-67
Timestamp: 2026-02-24T19:22:48.358Z
Learning: In Playwright end-to-end tests (e.g., under apps/meteor/tests/e2e/...), prefer locating elements by translated text (getByText) and ARIA roles (getByRole) over data-qa attributes. If translation values change, update the corresponding test locators accordingly. Never use data-qa locators. This guideline applies to all Playwright e2e test specs in the repository and helps keep tests robust to UI text changes and accessible semantics.

Applied to files:

  • apps/meteor/client/views/room/MessageList/hooks/useLoadSurroundingMessages.spec.ts
📚 Learning: 2026-03-06T18:10:15.268Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/code/CodeBlock.spec.tsx:47-68
Timestamp: 2026-03-06T18:10:15.268Z
Learning: In tests (especially those using testing-library/dom/jsdom) for Rocket.Chat components, the HTML <code> element has an implicit ARIA role of 'code'. Therefore, screen.getByRole('code') or screen.findByRole('code') will locate <code> elements even without a role attribute. Do not flag findByRole('code') as invalid in reviews; prefer using the implicit role instead of adding role="code" unless necessary for accessibility.

Applied to files:

  • apps/meteor/client/views/room/MessageList/hooks/useLoadSurroundingMessages.spec.ts
🧬 Code graph analysis (11)
apps/meteor/client/lib/utils/mapCustomUserStatusFromApi.ts (1)
apps/meteor/client/navbar/NavBarSettingsToolbar/UserMenu/hooks/useStatusItems.tsx (1)
  • useStatusItems (19-107)
apps/meteor/client/hooks/notification/useNotification.ts (1)
apps/meteor/app/utils/client/getUserAvatarURL.ts (1)
  • getUserAvatarURL (3-9)
apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts (3)
apps/meteor/client/lib/utils/mapMessageFromApi.ts (1)
  • mapMessageFromApi (5-31)
apps/meteor/app/threads/server/methods/getThreadMessages.ts (1)
  • getThreadMessages (21-60)
apps/meteor/server/methods/readThreads.ts (1)
  • readThreads (20-49)
apps/meteor/client/views/account/tokens/AccountTokensTable/AddToken.tsx (1)
apps/meteor/client/views/account/tokens/AccountTokensTable/AccountTokensTable.tsx (1)
  • AccountTokensTable (23-187)
apps/meteor/app/slashcommands-open/client/client.ts (1)
apps/meteor/client/lib/rooms/roomTypes/direct.ts (1)
  • findRoom (140-147)
apps/meteor/client/navbar/NavBarSettingsToolbar/UserMenu/hooks/useStatusItems.tsx (2)
apps/meteor/client/lib/utils/mapCustomUserStatusFromApi.ts (1)
  • mapCustomUserStatusFromApi (3-6)
apps/meteor/client/navbar/NavBarSettingsToolbar/UserMenu/hooks/useUserMenu.tsx (1)
  • useUserMenu (13-61)
apps/meteor/client/views/room/providers/ComposerPopupProvider.tsx (1)
apps/meteor/app/utils/lib/i18n.ts (1)
  • t (6-6)
apps/meteor/client/lib/chats/data.ts (1)
apps/meteor/client/lib/utils/mapMessageFromApi.ts (1)
  • mapMessageFromApi (5-31)
apps/meteor/client/views/room/hooks/useGoToRoom.ts (2)
apps/meteor/client/views/room/MessageList/hooks/useLoadSurroundingMessages.ts (1)
  • useLoadSurroundingMessages (14-69)
apps/meteor/client/navbar/NavBarPagesGroup/actions/CreateDirectMessage.tsx (1)
  • CreateDirectMessage (24-109)
apps/meteor/client/lib/e2ee/rocketchat.e2e.room.ts (1)
apps/meteor/client/lib/e2ee/rocketchat.e2e.ts (1)
  • E2E (46-875)
apps/meteor/client/views/room/hooks/useOpenRoom.ts (1)
apps/meteor/client/views/room/RoomOpenerEmbedded.tsx (1)
  • RoomOpenerEmbedded (30-96)
🔇 Additional comments (20)
apps/meteor/client/views/admin/workspace/VersionCard/modals/RegisteredWorkspaceModal.tsx (1)

14-14: LGTM!

Also applies to: 32-32

apps/meteor/app/autotranslate/client/lib/autotranslate.ts (1)

88-93: LGTM!

apps/meteor/client/components/message/toolbar/useTranslateAction.ts (1)

2-2: LGTM!

Also applies to: 18-18, 57-57

apps/meteor/client/components/message/toolbar/useViewOriginalTranslationAction.ts (1)

2-2: LGTM!

Also applies to: 18-18, 57-57

apps/meteor/client/views/room/MessageList/hooks/useLoadSurroundingMessages.spec.ts (1)

133-133: LGTM!

Also applies to: 244-244

apps/meteor/client/views/account/tokens/AccountTokensTable/AccountTokensTable.tsx (1)

11-11: LGTM!

Also applies to: 29-30, 72-72

apps/meteor/client/views/account/tokens/AccountTokensTable/AddToken.tsx (1)

4-4: LGTM!

Also applies to: 22-22, 45-45

apps/meteor/client/lib/e2ee/rocketchat.e2e.room.ts (1)

404-404: LGTM!

Also applies to: 426-426, 485-487, 503-503, 509-509

apps/meteor/app/slashcommands-open/client/client.ts (1)

30-42: LGTM!

apps/meteor/app/slashcommands-status/client/status.ts (1)

14-18: LGTM!

apps/meteor/app/slashcommands-topic/client/topic.ts (1)

14-20: LGTM!

apps/meteor/client/views/room/composer/ComposerBoxPopupPreview.tsx (1)

31-31: LGTM!

Also applies to: 67-79

apps/meteor/client/lib/utils/mapCustomUserStatusFromApi.ts (1)

1-6: LGTM!

apps/meteor/client/navbar/NavBarSettingsToolbar/UserMenu/hooks/useStatusItems.tsx (1)

1-1: LGTM!

Also applies to: 5-7, 16-30, 32-39

apps/meteor/client/hooks/notification/useNotification.ts (1)

36-36: LGTM!

apps/meteor/client/views/room/hooks/useGoToRoom.ts (1)

3-3: LGTM!

Also applies to: 15-15, 30-33

apps/meteor/client/views/room/hooks/useOpenRoom.ts (1)

3-3: LGTM!

Also applies to: 21-21, 47-47, 49-49

apps/meteor/client/lib/chats/data.ts (1)

12-12: LGTM!

Also applies to: 38-39, 73-73, 80-80, 211-211, 224-224

apps/meteor/client/lib/utils/mapReadReceiptFromApi.ts (1)

1-7: LGTM!

apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts (1)

2-2: LGTM!

Also applies to: 8-8, 28-28, 32-32, 113-113, 115-117

Comment on lines +37 to 43
if (openedRoom === group._id) {
void sdk.call('sendMessage', {
_id: Random.id(),
rid: result.rid,
rid: group._id,
msg: t('Apps_Game_Center_Play_Game_Together', { name }),
});
}
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 | 🔴 Critical | ⚡ Quick win

Unreachable code: invite message will never be sent.

The condition openedRoom === group._id can never be true. openedRoom is captured from useOpenedRoom() at render time (the room open before the modal), while group._id is the ID of a group that was just created in the preceding line. A newly created group cannot match a previously opened room.

This appears to be a regression—the invite message is now unreachable.

Proposed fix: send the message unconditionally to the new group
 			roomCoordinator.openRouteLink(group.t, { rid: group._id, name: group.name });
 
-			if (openedRoom === group._id) {
-				void sdk.call('sendMessage', {
-					_id: Random.id(),
-					rid: group._id,
-					msg: t('Apps_Game_Center_Play_Game_Together', { name }),
-				});
-			}
+			void sdk.call('sendMessage', {
+				_id: Random.id(),
+				rid: group._id,
+				msg: t('Apps_Game_Center_Play_Game_Together', { name }),
+			});
 			onClose();

If the original intent was conditional sending, please clarify the expected behavior.

🤖 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/apps/gameCenter/GameCenterInvitePlayersModal.tsx` around
lines 37 - 43, The check using openedRoom (from useOpenedRoom()) prevents
sending the invite to the newly created group because openedRoom cannot equal
the new group._id; remove the conditional and call sdk.call('sendMessage', {
_id: Random.id(), rid: group._id, msg: t('Apps_Game_Center_Play_Game_Together',
{ name }) }) unconditionally after the group is created (or, if conditional
behavior was intended, update the condition to reflect the correct runtime value
instead of openedRoom). Ensure the sendMessage invocation uses Random.id(),
group._id, and the same i18n key t('Apps_Game_Center_Play_Game_Together', { name
}).

Copy link
Copy Markdown

@hacktron-app hacktron-app Bot left a comment

Choose a reason for hiding this comment

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

1 issue found across 1 file

Severity Count
🟡 Medium 1

View full scan results

Comment on lines +31 to 34
const executeSlashCommandPreviewEndpoint = useEndpoint('POST', '/v1/commands.preview');

useImperativeHandle(
ref,
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium: DOM-based XSS in ComposerBoxPopupPreview via unvalidated src attributes

The ComposerBoxPopupPreview component renders item.value directly into the src attributes of img, audio, and video tags without validation or sanitization. If an attacker can influence the response from the /v1/commands.preview endpoint, they can inject malicious javascript: URIs. While modern browsers have some protections against javascript: in src attributes, this remains a security risk and a violation of secure coding practices. The application should validate that the provided URI uses an expected, safe protocol (e.g., http, https) before assigning it to a src attribute.

Steps to Reproduce
  1. Intercept the JSON response from the /v1/commands.preview API endpoint.
  2. Modify the value field of an item in the response to contain a malicious payload, such as javascript:alert('XSS').
  3. Trigger the corresponding slash command in the Rocket.Chat composer.
  4. Observe that the component renders the <img> or <source> tag with the malicious src attribute.
Trace
graph TD
    subgraph SG0 ["./Rocket.Chat/apps/meteor/client/views/room/composer/ComposerBoxPopupPreview.tsx"]
        ComposerBoxPopupPreview{{"Component for previewing slash command results in the composer popup."}}
        select["Selects a preview item and executes the associated slash command."]
    end
    style SG0 fill:#2a2a2a,stroke:#444,color:#aaa
    subgraph SG1 ["./Rocket.Chat/apps/meteor/client/views/room/contexts/ChatContext.ts"]
        useChat["React hook to access the Chat context."]
    end
    style SG1 fill:#2a2a2a,stroke:#444,color:#aaa
    ComposerBoxPopupPreview --> useChat
    ComposerBoxPopupPreview --> select
Loading
Fix with AI

Open in Cursor Open in Claude

Fix the following security vulnerability found by Hacktron.

File: apps/meteor/client/views/room/composer/ComposerBoxPopupPreview.tsx
Lines: 31-79
Severity: medium

Vulnerability: DOM-based XSS in ComposerBoxPopupPreview via unvalidated src attributes

Description:
The `ComposerBoxPopupPreview` component renders `item.value` directly into the `src` attributes of `img`, `audio`, and `video` tags without validation or sanitization. If an attacker can influence the response from the `/v1/commands.preview` endpoint, they can inject malicious `javascript:` URIs. While modern browsers have some protections against `javascript:` in `src` attributes, this remains a security risk and a violation of secure coding practices. The application should validate that the provided URI uses an expected, safe protocol (e.g., `http`, `https`) before assigning it to a `src` attribute.

Proof of Concept:
**Steps to Reproduce**

1. Intercept the JSON response from the `/v1/commands.preview` API endpoint.
2. Modify the `value` field of an item in the response to contain a malicious payload, such as `javascript:alert('XSS')`.
3. Trigger the corresponding slash command in the Rocket.Chat composer.
4. Observe that the component renders the `<img>` or `<source>` tag with the malicious `src` attribute.

Affected Code:
{item.type === 'image' && <img src={item.value} alt={item._id} />}
{item.type === 'audio' && (
    <audio controls>
        <track kind='captions' />
        <source src={item.value} />
        Your browser does not support the audio element.
    </audio>
)}
{item.type === 'video' && (
    <video controls className='inline-video'>
        <track kind='captions' />
        <source src={item.value} />
        Your browser does not support the video element.
    </video>
)}

Fix this vulnerability. Only change what's necessary - don't modify unrelated code.

Triage: Reply !fp <reason> (false positive), !valid (confirmed), or !accepted_risk <reason>. Reason is optional but improves future scans — e.g. !fp internal endpoint, not user-facing. Any other reply is saved as a triage note.

View finding in Hacktron

- GameCenterInvitePlayersModal: restore callWithErrorHandling so sendMessage failures surface as toasts (cubic P2)
- useThreadMessagesQuery: catch fire-and-forget readThreads rejection to avoid unhandled promise (coderabbit major)
- RegisteredWorkspaceModal: pass error.message to toast instead of raw Error object (coderabbit minor)
@tassoevan tassoevan added the stat: QA assured Means it has been tested and approved by a company insider label May 26, 2026
@dionisio-bot dionisio-bot Bot added the stat: ready to merge PR tested and approved waiting for merge label May 26, 2026
@ggazzo ggazzo merged commit af676c5 into develop May 26, 2026
48 checks passed
@ggazzo ggazzo deleted the chore/ddp-migrate-used-with-rest branch May 26, 2026 02:27
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.

3 participants