fix: restore away status after websocket reconnection - #41585
Conversation
|
Looks like this PR is ready to merge! 🎉 |
🦋 Changeset detectedLatest commit: 7a70790 The changes in this PR will be included in the next version bump. This PR includes changesets to release 3 packages
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 |
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (3)
📜 Recent review details⏰ Context from checks skipped due to timeout. (3)
|
| 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
Possibly related PRs
- RocketChat/Rocket.Chat#41549: Both changes modify
UserPresenceauto-away timing and reconnection behavior.
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.
Comment @coderabbitai help to get the list of available commands.
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
.changeset/wicked-moons-reconnect.mdapps/meteor/client/lib/userPresence.spec.tsapps/meteor/client/lib/userPresence.tspackages/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.tsapps/meteor/client/lib/userPresence.spec.tsapps/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.tsextension 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.tsapps/meteor/client/lib/userPresence.spec.tsapps/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.tsapps/meteor/client/lib/userPresence.spec.tsapps/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.tsapps/meteor/client/lib/userPresence.spec.tsapps/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.tsapps/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.tsapps/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!
Codecov Report❌ Patch coverage is Additional details and impacted files@@ 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
Flags with carried forward coverage won't be shown. Click here to find out more. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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 winDo not assert away after auto-away is disabled.
If a browser user was idle before
enableAutoAwaychanges to false,this.idleremains true. Line 180 then setsawayTimetoundefined.isIdle()falls back tothis.idle, so Line 191 force-appliesAWAYeven 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 valueRemove 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
📒 Files selected for processing (2)
apps/meteor/client/lib/userPresence.spec.tsapps/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
**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
**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
**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
**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
**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.tsapps/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.tsextension 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.tsapps/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.tsapps/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.tsapps/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.tsapps/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.tsapps/meteor/client/lib/userPresence.ts
🔇 Additional comments (1)
apps/meteor/client/lib/userPresence.spec.ts (1)
168-196: LGTM!
fa0ac00 to
f077e53
Compare
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
f077e53 to
7a70790
Compare
Proposed changes (including videos or screenshots)
Auto-away is lost on every websocket reconnection.
Presence.newConnection()registers every new DDP session asonline, 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 (HAProxytimeout tunnel, nginxproxy_read_timeout, ALB/Cloudflare idle timeouts, LB failover, restarts) reproduces this workspace-wide on that cadence.The client now:
lastActivityAtacross drops, so disconnected time counts as inactivity;awayonce the reconnected session is authenticated, instead of assuming online;enableAutoAwayis enabled.It also fixes the countdown being restarted by unrelated user-document updates: the effect now depends on
user?._idinstead of the wholeuserobject, 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.
In Admin → Settings → Accounts → Default User Preferences, enable Enable Auto Away, set Idle Time Limit to 60s, reload.
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.
In A, undock DevTools into a separate window and stop touching A's window. Once the idle limit passes, B shows A as away.
In A's console, trigger a reconnect and leave it alone:
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.
Issues
Further comments
onlineinnewConnectionand broadcasts it, so there is a ~1 round-trip window where clients see the user online before theawaylands.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.checkBackgroundAndSetAway.newConnectionsounds cheaper, but nothing is left to preserve:connection.onClose→removeConnectionalready recomputed the user toofflinebefore the reconnect arrives. It would need new persisted state, a rule keeping bots and API clients defaulting to online, and the client declaringonlineso 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
Summary by CodeRabbit
Summary by CodeRabbit