Skip to content

Conversation

@harshjdhv
Copy link
Contributor

@harshjdhv harshjdhv commented Jan 1, 2026

Proposed changes (including videos or screenshots)

This PR fixes a critical variable shadowing bug in the POST /api/v1/livechat/messages endpoint that prevented new visitors (those without an existing token) from sending messages.

The Bug:
In apps/meteor/app/livechat/server/api/v1/message.ts, the logic for handling new visitors was inside an else block where a new const visitor was declared. This declaration shadowed the outer visitor variable. As a result, when the code exits the else block, the outer visitor variable remained undefined, causing the subsequent check if (!guest) to fail and throw an error-invalid-token.

The Fix:

  • Changed the outer const visitor to let visitor.
  • Removed the const declaration inside the else block to ensure the newly registered visitor is assigned to the outer variable.

Issue(s)

Closes #38039

Steps to test or reproduce

  1. Ensure Livechat is enabled.
  2. Make a POST request to /api/v1/livechat/messages with a brand new visitor token (one that does not exist in the database yet).
curl -X POST "http://localhost:3000/api/v1/livechat/messages" \
  -H "Content-Type: application/json" \
  -H "X-Auth-Token: YOUR_AUTH_TOKEN" \
  -H "X-User-Id: YOUR_USER_ID" \
  -d '{
    "visitor": {"token": "unique-new-token-12345"},
    "messages": [{"msg": "Hello, this is a test"}]
  }'

Before Fix:
Returns {"success": false, "error": "error-invalid-token"}

After Fix:
Returns {"success": true, "messages": [...]}

Further comments

This is a straightforward scope fix. No logical changes were made to the registration process itself, just ensuring the variable is correctly accessible in the outer scope.

Summary by CodeRabbit

  • Refactor
    • Internal improvements to live chat visitor handling to fix a registration edge-case; no user-facing behavior changes.
  • Chores
    • Patch version bump recorded for the Meteor package to include the fix.

✏️ Tip: You can customize this high-level summary in your review settings.

Copilot AI review requested due to automatic review settings January 1, 2026 14:14
@harshjdhv harshjdhv requested a review from a team as a code owner January 1, 2026 14:14
@changeset-bot
Copy link

changeset-bot bot commented Jan 1, 2026

🦋 Changeset detected

Latest commit: 481a23e

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 40 packages
Name Type
@rocket.chat/meteor Patch
@rocket.chat/core-typings Patch
@rocket.chat/rest-typings Patch
@rocket.chat/uikit-playground Patch
@rocket.chat/api-client Patch
@rocket.chat/apps Patch
@rocket.chat/core-services Patch
@rocket.chat/cron Patch
@rocket.chat/ddp-client Patch
@rocket.chat/fuselage-ui-kit Patch
@rocket.chat/gazzodown Patch
@rocket.chat/http-router Patch
@rocket.chat/livechat Patch
@rocket.chat/model-typings Patch
@rocket.chat/ui-avatar Patch
@rocket.chat/ui-client Patch
@rocket.chat/ui-contexts Patch
@rocket.chat/ui-voip Patch
@rocket.chat/web-ui-registration Patch
@rocket.chat/account-service Patch
@rocket.chat/authorization-service Patch
@rocket.chat/ddp-streamer Patch
@rocket.chat/omnichannel-transcript Patch
@rocket.chat/presence-service Patch
@rocket.chat/queue-worker Patch
@rocket.chat/abac Patch
@rocket.chat/federation-matrix Patch
@rocket.chat/license Patch
@rocket.chat/media-calls Patch
@rocket.chat/omnichannel-services Patch
@rocket.chat/pdf-worker Patch
@rocket.chat/presence Patch
rocketchat-services Patch
@rocket.chat/models Patch
@rocket.chat/network-broker Patch
@rocket.chat/omni-core-ee Patch
@rocket.chat/mock-providers Patch
@rocket.chat/ui-video-conf Patch
@rocket.chat/instance-status Patch
@rocket.chat/omni-core Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@dionisio-bot
Copy link
Contributor

dionisio-bot bot commented Jan 1, 2026

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

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 1, 2026

Walkthrough

Changed a shadowed visitor binding by making the outer declaration mutable so the POST handler can assign either an existing visitor or a newly registered guest to the same variable.

Changes

Cohort / File(s) Summary
Livechat visitor binding fix
apps/meteor/app/livechat/server/api/v1/message.ts
Replaced const visitor with let visitor and removed the inner const visitor shadowing in the else branch so the outer visitor is correctly assigned when registering a new guest.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Suggested reviewers

  • ggazzo
  • tassoevan

Poem

🐰 I hopped in code, a tiny fix I made,
No more shadows where a token strayed.
Let visitor stay, both old and new,
One binding holds them — tidy and true! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the primary change: fixing variable shadowing that prevented new visitor registration in the livechat messages API.
Linked Issues check ✅ Passed The code changes directly address the variable shadowing bug described in issue #38039 by converting const to let and removing inner redeclaration.
Out of Scope Changes check ✅ Passed All changes are strictly scoped to fixing the variable shadowing bug; no unrelated modifications are present.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Jira integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between ea966f5 and ea9685c.

📒 Files selected for processing (1)
  • .changeset/mean-eagles-complain.md
🔇 Additional comments (2)
.changeset/mean-eagles-complain.md (2)

1-3: LGTM! Changeset header is correctly formatted.

The changeset follows the standard format, and the patch version bump is appropriate for a bug fix.


5-5: LGTM! Clear and accurate description.

The description concisely documents the fix for the variable shadowing bug and its impact on new visitor registration.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Copy link
Contributor

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

Choose a reason for hiding this comment

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

No issues found across 1 file

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
apps/meteor/app/livechat/server/api/v1/message.ts (1)

281-284: Consider simplifying redundant visitor check.

The check at lines 281-284 appears redundant since:

  • If visitor exists at line 258, it's used directly
  • If not, it's registered at line 275 and already validated at lines 276-278

That said, this defensive check is harmless and may provide value if the registration logic changes in the future.

Optional simplification
-const guest = visitor;
-if (!guest) {
-  throw new Error('error-invalid-token');
-}
+const guest = visitor; // visitor is guaranteed to exist at this point
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Jira integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d3511ea and ea966f5.

📒 Files selected for processing (1)
  • apps/meteor/app/livechat/server/api/v1/message.ts
🧰 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/app/livechat/server/api/v1/message.ts
🧠 Learnings (1)
📚 Learning: 2025-11-19T18:20:37.116Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 37419
File: apps/meteor/server/services/media-call/service.ts:141-141
Timestamp: 2025-11-19T18:20:37.116Z
Learning: In apps/meteor/server/services/media-call/service.ts, the sendHistoryMessage method should use call.caller.id or call.createdBy?.id as the message author, not call.transferredBy?.id. Even for transferred calls, the message should appear in the DM between the two users who are calling each other, not sent by the person who transferred the call.

Applied to files:

  • apps/meteor/app/livechat/server/api/v1/message.ts
🧬 Code graph analysis (1)
apps/meteor/app/livechat/server/api/v1/message.ts (2)
packages/ddp-client/src/livechat/LivechatClientImpl.ts (1)
  • visitor (151-159)
packages/models/src/index.ts (1)
  • LivechatVisitors (170-170)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: CodeQL analysis (javascript-typescript)
🔇 Additional comments (2)
apps/meteor/app/livechat/server/api/v1/message.ts (2)

256-256: Variable shadowing fix: Correctly enables visitor reassignment.

The change from const to let is necessary and correct. This allows the newly registered guest to be assigned to the same visitor variable in the else block (line 275), fixing the bug where new visitors couldn't register successfully.


275-275: Correct assignment to outer scope variable.

The assignment to the outer visitor variable (without redeclaring) properly fixes the shadowing bug. Combined with the let declaration at line 256, this ensures newly registered guests flow through the same code path as existing visitors.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

@harshjdhv
Copy link
Contributor Author

@Dnouv can you please review this

@codecov
Copy link

codecov bot commented Jan 12, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 70.63%. Comparing base (c5f7dcb) to head (481a23e).
⚠️ Report is 1 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #38040      +/-   ##
===========================================
- Coverage    70.65%   70.63%   -0.02%     
===========================================
  Files         3148     3148              
  Lines       108850   108850              
  Branches     19543    19606      +63     
===========================================
- Hits         76906    76890      -16     
- Misses       29933    29955      +22     
+ Partials      2011     2005       -6     
Flag Coverage Δ
e2e 60.22% <ø> (+0.04%) ⬆️
e2e-api 47.32% <ø> (-1.13%) ⬇️
unit 71.74% <ø> (-0.02%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@KevLehman KevLehman added this to the 8.1.0 milestone Jan 12, 2026
@KevLehman KevLehman added the stat: QA assured Means it has been tested and approved by a company insider label Jan 12, 2026
@dionisio-bot dionisio-bot bot added the stat: ready to merge PR tested and approved waiting for merge label Jan 12, 2026
@kodiakhq kodiakhq bot merged commit 0bd848c into RocketChat:develop Jan 13, 2026
42 checks passed
@harshjdhv harshjdhv deleted the fix/livechat-messages-visitor-shadowing branch January 15, 2026 19:18
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.

Variable shadowing preventing new visitor registration in livechat messages API

2 participants