Skip to content

fix: restore away status after websocket reconnection - #41585

Merged
dionisio-bot[bot] merged 5 commits into
developfrom
claude/rocketchat-websocket-reconnect-status-kclhot
Aug 12, 2026
Merged

fix: restore away status after websocket reconnection#41585
dionisio-bot[bot] merged 5 commits into
developfrom
claude/rocketchat-websocket-reconnect-status-kclhot

Conversation

@rodrigok

@rodrigok rodrigok commented Jul 27, 2026

Copy link
Copy Markdown
Member

Proposed changes (including videos or screenshots)

Auto-away is lost on every websocket reconnection.

Presence.newConnection() registers every new DDP session as online, and the client kept no memory of activity across the drop — it assumed the reconnected session was online and restarted the idle countdown from zero. An idle user came back online on every reconnect and stayed online for a full idle period; on desktop indefinitely, since the OS idle poller only reports state changes. Any infrastructure that recycles long-lived connections on a timer (HAProxy timeout tunnel, nginx proxy_read_timeout, ALB/Cloudflare idle timeouts, LB failover, restarts) reproduces this workspace-wide on that cadence.

The client now:

  • tracks lastActivityAt across drops, so disconnected time counts as inactivity;
  • restates away once the reconnected session is authenticated, instead of assuming online;
  • schedules the idle timer for the remaining time, not a fresh full period;
  • records the idle state at the away entry point, so an idle transition reported by the desktop app while disconnected is no longer dropped;
  • only forces away when enableAutoAway is enabled.

It also fixes the countdown being restarted by unrelated user-document updates: the effect now depends on user?._id instead of the whole user object, which minted a new reference on every store update.

Steps to test or reproduce

Use two accounts — checking A's own UI means moving the pointer into A's window, which resets the idle countdown, so observe from B instead.

  1. In Admin → Settings → Accounts → Default User Preferences, enable Enable Auto Away, set Idle Time Limit to 60s, reload.

  2. Open A (your user) in a normal window and B (another user) in incognito, with B viewing A in a DM so A's status dot is visible.

  3. In A, undock DevTools into a separate window and stop touching A's window. Once the idle limit passes, B shows A as away.

  4. In A's console, trigger a reconnect and leave it alone:

    Meteor.disconnect(); setTimeout(() => Meteor.reconnect(), 5000);
  5. Watch B: A goes offline, then online on reconnect, then back to away within a round trip, with no interaction. Before this PR, A stayed online for a full idle period.

Undocking matters: the client listens for mousemove/mousedown/keydown on the document and focus on the window, so with the console docked, merely moving the pointer across the page to reach it stamps lastActivityAt and legitimately brings A online. Once undocked, stay in the DevTools window.

Issues

Further comments

  • The server still writes online in newConnection and broadcasts it, so there is a ~1 round-trip window where clients see the user online before the away lands.
  • The non-idle branch intentionally does not send UserPresence:online: the session is already online server-side, so it would add a method call plus a presence broadcast per client on every reconnect, doubling presence work on a mass reconnect for no gain.
  • Mobile needs no equivalent change — it already re-asserts away on the resume login via checkBackgroundAndSetAway.
  • Why not server-side. Preserving the previous status in newConnection sounds cheaper, but nothing is left to preserve: connection.onCloseremoveConnection already recomputed the user to offline before the reconnect arrives. It would need new persisted state, a rule keeping bots and API clients defaulting to online, and the client declaring online so nobody gets stuck away — a lot of machinery to close a sub-second window, for something the server cannot observe anyway. Only the client knows whether the user is idle.

https://claude.ai/code/session_01PQu7gFiCHs1nyDtq3Wmufi

Review in cubic

Summary by CodeRabbit

Summary by CodeRabbit

  • Bug Fixes
    • Preserved users’ away status and inactivity progress after websocket reconnections.
    • Restored online status when users interact while disconnected.
    • Improved presence updates during login, reconnection, and connection changes.
    • Ensured desktop and browser activity consistently resets away status.
    • Prevented inactivity timers from restarting unnecessarily after reconnecting.
    • More accurately restored presence based on the user’s latest activity.

@rodrigok
rodrigok requested review from a team as code owners July 27, 2026 14:10
@dionisio-bot

dionisio-bot Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

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

@changeset-bot

changeset-bot Bot commented Jul 27, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 7a70790

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

This PR includes changesets to release 3 packages
Name Type
@rocket.chat/meteor Patch
@rocket.chat/core-typings Patch
@rocket.chat/rest-typings 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

@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1ba2c472-7793-4756-af27-ed24e825c105

📥 Commits

Reviewing files that changed from the base of the PR and between f077e53 and 7a70790.

📒 Files selected for processing (3)
  • .changeset/wicked-moons-reconnect.md
  • apps/meteor/client/lib/userPresence.spec.ts
  • apps/meteor/client/lib/userPresence.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • .changeset/wicked-moons-reconnect.md
  • apps/meteor/client/lib/userPresence.spec.ts
  • apps/meteor/client/lib/userPresence.ts
📜 Recent review details
⏰ Context from checks skipped due to timeout. (3)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build
⚠️ CI failures not shown inline (3)

GitHub Check: Dionisio QA: Some checks did not pass

Conclusion: failure

View job details

**Conclusion:** failure
### Steps
- ✅ **No merge conflicts**
- ❌ **QA assured** — This PR is missing the 'stat: QA assured' label
- ✅ **Mergeable**
- ✅ **Has milestone or project**
- ✅ **Valid PR title**
- ✅ **Correct target version**

GitHub Check: Dionisio QA: Some checks did not pass

Conclusion: failure

View job details

**Conclusion:** failure
### Steps
- ✅ **No merge conflicts**
- ❌ **QA assured** — This PR is missing the 'stat: QA assured' label
- ✅ **Mergeable**
- ✅ **Has milestone or project**
- ✅ **Valid PR title**
- ✅ **Correct target version**

GitHub Check: Dionisio QA: Some checks did not pass

Conclusion: failure

View job details

**Conclusion:** failure
### Steps
- ✅ **No merge conflicts**
- ❌ **QA assured** — This PR is missing the 'stat: QA assured' label
- ✅ **Mergeable**
- ✅ **Has milestone or project**
- ✅ **Valid PR title**
- ✅ **Correct target version**

Walkthrough

UserPresence preserves activity and idle state across websocket reconnections. It restores online status after activity, reapplies away status when idle, and preserves the remaining inactivity countdown.

Changes

Presence reconnection handling

Layer / File(s) Summary
Activity and away-state reconciliation
apps/meteor/client/lib/userPresence.ts
UserPresence tracks the last activity time and idle state, schedules the remaining idle period, and reconciles presence after reconnection.
Connection and activity wiring
apps/meteor/client/lib/userPresence.ts
Browser activity, desktop callbacks, connection changes, preferences, and away timing use the updated presence handlers.
Reconnection behavior coverage
apps/meteor/client/lib/userPresence.spec.ts, .changeset/wicked-moons-reconnect.md
Tests cover idle transitions, reconnection, login, disconnected activity, desktop idle state, disabled auto-away, and later away transitions. The changeset records the patch release.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Browser
  participant UserPresence
  participant AuthenticatedConnection
  participant PresenceServer
  Browser->>UserPresence: registerActivity or setAway
  AuthenticatedConnection->>UserPresence: disconnect or reconnect
  UserPresence->>PresenceServer: assert online or away status
Loading

Possibly related PRs

Suggested labels: type: bug

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes restoring away status after websocket reconnection, which is the main change.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • CORE-2503: 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.

@rodrigok
rodrigok marked this pull request as draft July 27, 2026 14:11

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 2

🤖 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/lib/userPresence.ts`:
- Around line 137-148: Update reassertPresence so the non-idle branch reconciles
status through applyStatus(UserStatus.ONLINE) instead of assigning this.status
directly, preserving the existing timer and return behavior while ensuring the
cached user state is updated through the centralized status flow.
- Around line 91-127: Handle RPC rejections in the status flow around
applyStatus, assertAway, and the goOnline/goAway calls so failures are treated
as unsuccessful attempts rather than escaping as unhandled rejections. Ensure
assertAway continues through its configured retries after goAway rejects, while
preserving its existing cancellation checks and successful early return; also
prevent goOnline failures from propagating out of the debounced setStatus path.
🪄 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 Plus

Run ID: 238ff06b-134f-44d8-aed9-91ee570cf6de

📥 Commits

Reviewing files that changed from the base of the PR and between d281351 and 685dd36.

📒 Files selected for processing (4)
  • .changeset/wicked-moons-reconnect.md
  • apps/meteor/client/lib/userPresence.spec.ts
  • apps/meteor/client/lib/userPresence.ts
  • packages/models/src/models/UsersSessions.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (4)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Hacktron Security Check
  • 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:

  • packages/models/src/models/UsersSessions.ts
  • apps/meteor/client/lib/userPresence.spec.ts
  • apps/meteor/client/lib/userPresence.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/lib/userPresence.spec.ts
🧠 Learnings (9)
📚 Learning: 2026-03-16T21:50:37.589Z
Learnt from: amitb0ra
Repo: RocketChat/Rocket.Chat PR: 39676
File: .changeset/migrate-users-register-openapi.md:3-3
Timestamp: 2026-03-16T21:50:37.589Z
Learning: For changes related to OpenAPI migrations in Rocket.Chat/OpenAPI, when removing endpoint types and validators from rocket.chat/rest-typings (e.g., UserRegisterParamsPOST, /v1/users.register) document this as a minor changeset (not breaking) per RocketChat/Rocket.Chat-Open-API#150 Rule 7. Note that the endpoint type is re-exposed via a module augmentation .d.ts in the consuming package (e.g., packages/web-ui-registration/src/users-register.d.ts). In reviews, ensure the changeset clearly states: this is a non-breaking change, the major version should not be bumped, and the changeset reflects a minor version bump. Do not treat this as a breaking change during OpenAPI migrations.

Applied to files:

  • .changeset/wicked-moons-reconnect.md
📚 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/models/src/models/UsersSessions.ts
  • apps/meteor/client/lib/userPresence.spec.ts
  • apps/meteor/client/lib/userPresence.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/models/src/models/UsersSessions.ts
  • apps/meteor/client/lib/userPresence.spec.ts
  • apps/meteor/client/lib/userPresence.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/models/src/models/UsersSessions.ts
  • apps/meteor/client/lib/userPresence.spec.ts
  • apps/meteor/client/lib/userPresence.ts
📚 Learning: 2026-07-15T01:31:50.632Z
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 41382
File: packages/model-typings/src/models/IPushTokenModel.ts:10-10
Timestamp: 2026-07-15T01:31:50.632Z
Learning: In Rocket.Chat’s push-token model, APNs/GCM standard tokens and PushKit VoIP tokens use distinct, globally-unique token string values. As a result, when deduplicating/looking up tokens, key identity solely on `{ tokenValue, appName }` (e.g., for `findOneByTokenAndAppName`, `removeDuplicateTokens`) and do **not** include `tokenType` in the uniqueness criteria to avoid collisions between standard and VoIP tokens.

Applied to files:

  • packages/models/src/models/UsersSessions.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/lib/userPresence.spec.ts
  • apps/meteor/client/lib/userPresence.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/userPresence.spec.ts
  • apps/meteor/client/lib/userPresence.ts
📚 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/lib/userPresence.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/lib/userPresence.spec.ts
🔇 Additional comments (5)
packages/models/src/models/UsersSessions.ts (1)

17-33: LGTM!

apps/meteor/client/lib/userPresence.ts (2)

12-18: LGTM!

Also applies to: 30-38, 45-75


150-219: LGTM!

apps/meteor/client/lib/userPresence.spec.ts (1)

1-220: LGTM!

.changeset/wicked-moons-reconnect.md (1)

1-7: LGTM!

Comment thread apps/meteor/client/lib/userPresence.ts Outdated
Comment thread apps/meteor/client/lib/userPresence.ts
@codecov

codecov Bot commented Jul 27, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.52941% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 68.63%. Comparing base (e64e2bb) to head (7a70790).
⚠️ Report is 36 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #41585      +/-   ##
===========================================
+ Coverage    68.58%   68.63%   +0.04%     
===========================================
  Files         4162     4162              
  Lines       158813   158924     +111     
  Branches     28161    28154       -7     
===========================================
+ Hits        108928   109072     +144     
+ Misses       44710    44688      -22     
+ Partials      5175     5164      -11     
Flag Coverage Δ
e2e 58.88% <73.80%> (+<0.01%) ⬆️
e2e-api 45.69% <ø> (-0.01%) ⬇️
unit 70.55% <98.52%> (+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.

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

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.

All reported issues were addressed across 4 files

Tip: cubic used a learning from your PR history. Let your coding agent read cubic learnings directly with the cubic MCP.

Re-trigger cubic

Comment thread apps/meteor/client/lib/userPresence.ts
Comment thread apps/meteor/client/lib/userPresence.ts Outdated
Comment thread apps/meteor/client/lib/userPresence.ts
Comment thread apps/meteor/client/lib/userPresence.ts
@ricardogarim ricardogarim self-assigned this Aug 3, 2026
@rodrigok
rodrigok marked this pull request as ready for review August 3, 2026 20:18

@coderabbitai coderabbitai Bot left a comment

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/meteor/client/lib/userPresence.ts (1)

178-191: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Do not assert away after auto-away is disabled.

If a browser user was idle before enableAutoAway changes to false, this.idle remains true. Line 180 then sets awayTime to undefined. isIdle() falls back to this.idle, so Line 191 force-applies AWAY even though auto-away is disabled.

Track whether auto-away is enabled separately, or clear the browser idle state when disabling it. Add a preference-toggle test for this case.

🤖 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/userPresence.ts` around lines 178 - 191, Update the
useEffect flow around reassertPresence so disabling auto-away cannot reassert
AWAY from a stale this.idle value after awayTime becomes undefined. Track the
enabled state separately or clear the browser idle state when auto-away is
disabled, preserve normal presence reassertion when enabled, and add a
preference-toggle test covering an already-idle browser user disabling
auto-away.
🧹 Nitpick comments (1)
apps/meteor/client/lib/userPresence.ts (1)

23-27: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the added implementation comments.

The file guideline prohibits code comments in implementation. Keep the behavior clear through method names and structure.

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

Also applies to: 39-40, 50-52, 64-64, 104-110, 116-116, 179-179

🤖 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/userPresence.ts` around lines 23 - 27, Remove the
implementation comments added throughout the user presence code, including the
comments near lastActivityAt and idle and the referenced sections, while
preserving all existing behavior and method structure.

Source: Coding guidelines

🤖 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.

Outside diff comments:
In `@apps/meteor/client/lib/userPresence.ts`:
- Around line 178-191: Update the useEffect flow around reassertPresence so
disabling auto-away cannot reassert AWAY from a stale this.idle value after
awayTime becomes undefined. Track the enabled state separately or clear the
browser idle state when auto-away is disabled, preserve normal presence
reassertion when enabled, and add a preference-toggle test covering an
already-idle browser user disabling auto-away.

---

Nitpick comments:
In `@apps/meteor/client/lib/userPresence.ts`:
- Around line 23-27: Remove the implementation comments added throughout the
user presence code, including the comments near lastActivityAt and idle and the
referenced sections, while preserving all existing behavior and method
structure.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9e217cb1-4695-4861-9dd9-7afeddca8f3b

📥 Commits

Reviewing files that changed from the base of the PR and between 685dd36 and af8d302.

📒 Files selected for processing (2)
  • apps/meteor/client/lib/userPresence.spec.ts
  • apps/meteor/client/lib/userPresence.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (2)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Hacktron Security Check
⚠️ CI failures not shown inline (5)

GitHub Check: Dionisio QA: Some checks did not pass

Conclusion: failure

View job details

**Conclusion:** failure
### Steps
- ✅ **No merge conflicts**
- ❌ **QA assured** — This PR is missing the 'stat: QA assured' label
- ✅ **Mergeable**
- ❌ **Has milestone or project** — This PR is missing the required milestone or project
- ✅ **Valid PR title**
- ✅ **Correct target version**

GitHub Check: Dionisio QA: Some checks did not pass

Conclusion: failure

View job details

**Conclusion:** failure
### Steps
- ✅ **No merge conflicts**
- ❌ **QA assured** — This PR is missing the 'stat: QA assured' label
- ✅ **Mergeable**
- ❌ **Has milestone or project** — This PR is missing the required milestone or project
- ✅ **Valid PR title**
- ✅ **Correct target version**

GitHub Check: Dionisio QA: Some checks did not pass

Conclusion: failure

View job details

**Conclusion:** failure
### Steps
- ✅ **No merge conflicts**
- ❌ **QA assured** — This PR is missing the 'stat: QA assured' label
- ✅ **Mergeable**
- ❌ **Has milestone or project** — This PR is missing the required milestone or project
- ✅ **Valid PR title**
- ✅ **Correct target version**

GitHub Check: Dionisio QA: Some checks did not pass

Conclusion: failure

View job details

**Conclusion:** failure
### Steps
- ✅ **No merge conflicts**
- ❌ **QA assured** — This PR is missing the 'stat: QA assured' label
- ✅ **Mergeable**
- ❌ **Has milestone or project** — This PR is missing the required milestone or project
- ✅ **Valid PR title**
- ✅ **Correct target version**

GitHub Check: Dionisio QA: Some checks did not pass

Conclusion: failure

View job details

**Conclusion:** failure
### Steps
- ✅ **No merge conflicts**
- ❌ **QA assured** — This PR is missing the 'stat: QA assured' label
- ✅ **Mergeable**
- ❌ **Has milestone or project** — This PR is missing the required milestone or project
- ✅ **Valid PR title**
- ✅ **Correct target version**
🧰 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/userPresence.spec.ts
  • apps/meteor/client/lib/userPresence.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/lib/userPresence.spec.ts
🧠 Learnings (7)
📚 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/userPresence.spec.ts
  • apps/meteor/client/lib/userPresence.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/userPresence.spec.ts
  • apps/meteor/client/lib/userPresence.ts
📚 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/lib/userPresence.spec.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/userPresence.spec.ts
  • apps/meteor/client/lib/userPresence.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/userPresence.spec.ts
  • apps/meteor/client/lib/userPresence.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/lib/userPresence.spec.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/userPresence.spec.ts
  • apps/meteor/client/lib/userPresence.ts
🔇 Additional comments (1)
apps/meteor/client/lib/userPresence.spec.ts (1)

168-196: LGTM!

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

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.

No issues found across 4 files

Re-trigger cubic

@ricardogarim
ricardogarim force-pushed the claude/rocketchat-websocket-reconnect-status-kclhot branch 2 times, most recently from fa0ac00 to f077e53 Compare August 3, 2026 22:31
@ricardogarim
ricardogarim removed the request for review from a team August 3, 2026 22:37
@ricardogarim ricardogarim added this to the 8.8.0 milestone Aug 3, 2026
claude and others added 5 commits August 4, 2026 09:41
Auto-away lives on the DDP session (`usersSessions.connections[].status`),
and `Presence.newConnection` registers every new session as online. So any
reconnection — dropped socket, network change, server restart, resumed
login — recreated the session as online and the client assumed the same,
restarting the idle countdown from scratch. An idle user was shown online
again for a whole idle period without ever touching the UI.

The client now tracks the last UI interaction, and that timestamp survives
connection drops:

- on reconnection, once the session is authenticated again, it restates the
  away status instead of assuming online. The assertion is retried while the
  server reports no connection was updated, since the login method can
  resolve before `Presence.newConnection` has written the session;
- the idle timer is scheduled for the *remaining* idle time, so time spent
  disconnected (or with the tab suspended) counts as inactivity;
- desktop presence detection goes through the same path, so the state
  reported by the desktop app is also restated on reconnection.

`updateConnectionStatusById` now updates every entry matching the connection
id: a login happening twice over the same connection pushes duplicated
entries, and leaving one of them online kept the user online.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PQu7gFiCHs1nyDtq3Wmufi
Drops the away assertion retry loop. It guarded against the client's away
call reaching the server before `Presence.newConnection` had written the
reconnected session, but that write starts before the login result is even
sent to the client, so it always precedes the round trip the away call needs.
Not worth a retry loop, a generation token and the error handling around
them; `goAway()` is awaited directly again, as before.

Records the idle state on the away entry point instead of after the status
update is applied. The update is debounced and skipped while disconnected,
so an idle transition reported by the desktop app during an outage was
dropped and the user came back online on reconnect — the case this change
is about. Activity was already recorded eagerly, so both are now symmetric.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PQu7gFiCHs1nyDtq3Wmufi
`@types/jest` still declares `jest.fn<TReturn, TArgs>()`, not the single
function-type form from `@jest/globals`, so the generic used to type the
desktop presence-detection mock failed the typecheck (TS2743). @swc/jest
strips types without checking them, which is why the test run stayed green.

Captures the `setUserOnline` callback through a plain typed local instead, so
the test doesn't depend on which jest typings are in scope.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PQu7gFiCHs1nyDtq3Wmufi
@ricardogarim
ricardogarim force-pushed the claude/rocketchat-websocket-reconnect-status-kclhot branch from f077e53 to 7a70790 Compare August 4, 2026 12:41
@ricardogarim ricardogarim added the stat: QA assured Means it has been tested and approved by a company insider label Aug 4, 2026
@ricardogarim ricardogarim removed their assignment Aug 4, 2026
@dionisio-bot dionisio-bot Bot added the stat: ready to merge PR tested and approved waiting for merge label Aug 4, 2026
@ricardogarim ricardogarim removed this from the 8.8.0 milestone Aug 12, 2026
@dionisio-bot dionisio-bot Bot removed the stat: ready to merge PR tested and approved waiting for merge label Aug 12, 2026
@ricardogarim ricardogarim added this to the 8.8.0 milestone Aug 12, 2026
@dionisio-bot dionisio-bot Bot added the stat: ready to merge PR tested and approved waiting for merge label Aug 12, 2026
@dionisio-bot
dionisio-bot Bot added this pull request to the merge queue Aug 12, 2026
Merged via the queue into develop with commit 407436b Aug 12, 2026
99 of 101 checks passed
@dionisio-bot
dionisio-bot Bot deleted the claude/rocketchat-websocket-reconnect-status-kclhot branch August 12, 2026 12:58
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 type: bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants