Skip to content

regression: login hangs on loading when "Forget User Session on Window Close" is enabled#40676

Open
cardoso wants to merge 10 commits into
release-8.5.0from
fix/CORE-2236
Open

regression: login hangs on loading when "Forget User Session on Window Close" is enabled#40676
cardoso wants to merge 10 commits into
release-8.5.0from
fix/CORE-2236

Conversation

@cardoso
Copy link
Copy Markdown
Member

@cardoso cardoso commented May 25, 2026

Proposed changes (including videos or screenshots)

Reintroduces the behavior of switching from localStorage to sessionStorage when the Accounts_ForgetUserSessionOnWindowClose setting is enabled.

Unskips the test.

This fixes the workspace client being broken after enabling the setting, but it's probably not the whole story.

Issue(s)

CORE-2236

Steps to test or reproduce

  1. Go to Workspace → Settings → Account

  2. enable Accounts_ForgetUserSessionOnWindowClose

  3. Save the setting

  4. Go to a channel

  5. Refresh the page or open a new tab

Expected Behavior

If refreshing, the user should stay logged in

If opening in a new tab, the user should be able to log back in

Actual Behavior

The user can’t log in; it gets stuck on the loading page

on a new tab and had the same issue, only started working again once I disabled the setting

Further comments

Root cause: #40479

Summary by CodeRabbit

  • New Features

    • Configurable storage backend to choose between persistent (local) and session storage for user session data.
    • Session handling now follows that setting so sessions can be retained or cleared on window close.
    • Client-side custom scripts are recomputed and reapplied automatically when related script settings change.
  • Tests

    • E2E tests updated to verify session persistence and cross-tab behavior under the updated setting.

Review Change Stack

@cardoso cardoso added this to the 8.5.0 milestone May 25, 2026
@dionisio-bot
Copy link
Copy Markdown
Contributor

dionisio-bot Bot commented May 25, 2026

Looks like this PR is not ready to merge, because of the following issues:

  • This PR is missing the 'stat: QA assured' label

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented May 25, 2026

⚠️ No Changeset found

Latest commit: 06f1ee9

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 25, 2026

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

Walkthrough

Client storage now supports switching between localStorage and sessionStorage with migration of login keys; Meteor Accounts is configured to match the selected backend on startup and when the setting changes. Server-side injected migration was removed and E2E tests updated to assert session persistence when the setting is enabled.

Changes

Session Storage Backend and Accounts Configuration

Layer / File(s) Summary
Storage backend abstraction and key migration
apps/meteor/client/lib/sdk/storage.ts
getStorageForBackend added; getStorage() is backend-aware; exports setStorageBackend() which uses moveLoginKeys() to migrate Rocket.Chat login/session keys between localStorage and sessionStorage.
Accounts startup configuration and sync
apps/meteor/client/meteor/startup/accounts.ts
Reads Accounts_ForgetUserSessionOnWindowClose, selects 'session' or 'local', calls setStorageBackend(), and invokes Accounts.config(); re-applies on setting or readiness/user changes.

Server Cleanup and Test Validation

Layer / File(s) Summary
Remove server-side script injection logic
apps/meteor/app/ui-master/server/scripts.ts
Removes injected load-event handler and localStorage→sessionStorage migration from getContent(); script injection driven only by Custom_Script_Logged_Out, Custom_Script_Logged_In, and Custom_Script_On_Logout.
E2E test coverage for session persistence
apps/meteor/tests/e2e/account-forgetSessionOnWindowClose.spec.ts
Unskips and updates the "Setting on" tests to assert session persists across reload and in a new tab.

Sequence Diagram(s)

sequenceDiagram
  participant ClientStartup as Client Startup
  participant PublicSetting as PublicSettingsCachedStore
  participant setStorageBackend as setStorageBackend()
  participant moveLoginKeys as moveLoginKeys()
  participant Storage as localStorage/sessionStorage
  participant AccountsConfig as Accounts.config()

  ClientStartup->>PublicSetting: read Accounts_ForgetUserSessionOnWindowClose
  PublicSetting-->>ClientStartup: desired backend ('session'|'local')
  ClientStartup->>setStorageBackend: request backend change
  setStorageBackend->>moveLoginKeys: migrate login keys
  moveLoginKeys->>Storage: read keys from source storage
  moveLoginKeys->>Storage: write keys to target storage
  moveLoginKeys->>Storage: remove keys from source storage
  setStorageBackend->>AccountsConfig: ensure Accounts configured with backend
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • RocketChat/Rocket.Chat#40482: Affects getStoredItem(STORAGE_KEYS.LOGIN_TOKEN) calls used by login persistence and relates to migrating tokens between storages.

Suggested labels

area: authentication

Suggested reviewers

  • tassoevan
🚥 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 directly addresses the main regression being fixed: login hanging when the 'Forget User Session on Window Close' setting is enabled, which is the core problem solved across all modified files.
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.

✏️ 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)
  • CORE-2236: 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 25, 2026

Codecov Report

❌ Patch coverage is 32.60870% with 93 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (release-8.5.0@ed9e2c0). Learn more about missing BASE report.

Additional details and impacted files

Impacted file tree graph

@@               Coverage Diff                @@
##             release-8.5.0   #40676   +/-   ##
================================================
  Coverage                 ?   69.90%           
================================================
  Files                    ?     3327           
  Lines                    ?   126722           
  Branches                 ?    22007           
================================================
  Hits                     ?    88580           
  Misses                   ?    34851           
  Partials                 ?     3291           
Flag Coverage Δ
unit 70.01% <32.60%> (?)

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.

@cardoso cardoso marked this pull request as ready for review May 25, 2026 20:22
@cardoso cardoso requested a review from a team as a code owner May 25, 2026 20:22
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.

2 issues found across 4 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="apps/meteor/client/lib/sdk/storage.ts">

<violation number="1" location="apps/meteor/client/lib/sdk/storage.ts:58">
P1: `moveLoginKeys` performs unguarded `localStorage`/`sessionStorage` reads and writes, which can throw and break startup login flow. Wrap migration access in a `try/catch` (consistent with `getStorage`) so unavailable storage does not crash initialization.</violation>
</file>

<file name="apps/meteor/client/meteor/startup/accounts.ts">

<violation number="1" location="apps/meteor/client/meteor/startup/accounts.ts:73">
P1: `Accounts.config({ clientStorage })` is invoked from reactive subscriptions, so toggling the setting can reconfigure Accounts at runtime and trigger Meteor’s “Can’t set … more than once” error.</violation>
</file>

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

Re-trigger cubic

Comment thread apps/meteor/client/lib/sdk/storage.ts Outdated
Comment thread apps/meteor/client/meteor/startup/accounts.ts 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: 1

Caution

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

⚠️ Outside diff range comments (1)
apps/meteor/tests/e2e/account-forgetSessionOnWindowClose.spec.ts (1)

22-22: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Replace page.locator('role=...') with semantic locators.

The tests use page.locator('role=heading[name="Welcome to Rocket.Chat"]') instead of the preferred semantic locator page.getByRole(). As per coding guidelines, always prefer semantic locators like page.getByRole(), page.getByLabel(), page.getByText(), or page.getByTitle() over page.locator() in Playwright tests.

♻️ Proposed fix

Replace all instances of:

-await expect(page.locator('role=heading[name="Welcome to Rocket.Chat"]')).toBeVisible();
+await expect(page.getByRole('heading', { name: 'Welcome to Rocket.Chat' })).toBeVisible();

And:

-await expect(newPage.locator('role=heading[name="Welcome to Rocket.Chat"]')).toBeVisible();
+await expect(newPage.getByRole('heading', { name: 'Welcome to Rocket.Chat' })).toBeVisible();

Apply this pattern to lines 22, 27, 43, 47, 53, and 61.

As per coding guidelines: Avoid using page.locator() in Playwright tests - always prefer semantic locators.

Also applies to: 27-27, 43-43, 47-47, 53-53, 61-61

🤖 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/tests/e2e/account-forgetSessionOnWindowClose.spec.ts` at line 22,
Replace the non-semantic Playwright locators that use the "role=..." string with
semantic locators: change any usage of page.locator that targets a role to
page.getByRole and supply the role (e.g., "heading") and the name option
("Welcome to Rocket.Chat"); apply the same pattern for the other occurrences
flagged (replace role-based page.locator calls with the appropriate semantic
getByRole/getByLabel/getByText/getByTitle variants) so all role locators become
semantic locators.
🤖 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/sdk/storage.ts`:
- Around line 44-69: moveLoginKeys currently dereferences
window.localStorage/sessionStorage directly and can throw; update it to use the
same guarded access as getStorage(): obtain source and target via the safe
accessor (or replicate its checks) so that if Web Storage is unavailable you
treat it as a no-op, and wrap setItem/getItem/removeItem operations in try/catch
to avoid throwing and leaving setStorageBackend half-applied; reference
moveLoginKeys, getStorage, setStorageBackend and STORAGE_KEYS when locating and
modifying the code.

---

Outside diff comments:
In `@apps/meteor/tests/e2e/account-forgetSessionOnWindowClose.spec.ts`:
- Line 22: Replace the non-semantic Playwright locators that use the "role=..."
string with semantic locators: change any usage of page.locator that targets a
role to page.getByRole and supply the role (e.g., "heading") and the name option
("Welcome to Rocket.Chat"); apply the same pattern for the other occurrences
flagged (replace role-based page.locator calls with the appropriate semantic
getByRole/getByLabel/getByText/getByTitle variants) so all role locators become
semantic locators.
🪄 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: a4ec1a5b-1b6f-40b9-b3d9-98fe8a66b6e6

📥 Commits

Reviewing files that changed from the base of the PR and between 6fb88e1 and 62b79b1.

📒 Files selected for processing (4)
  • apps/meteor/app/ui-master/server/scripts.ts
  • apps/meteor/client/lib/sdk/storage.ts
  • apps/meteor/client/meteor/startup/accounts.ts
  • apps/meteor/tests/e2e/account-forgetSessionOnWindowClose.spec.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Hacktron Security Check
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{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/tests/e2e/account-forgetSessionOnWindowClose.spec.ts
  • apps/meteor/client/lib/sdk/storage.ts
  • apps/meteor/app/ui-master/server/scripts.ts
  • apps/meteor/client/meteor/startup/accounts.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/tests/e2e/account-forgetSessionOnWindowClose.spec.ts
apps/meteor/tests/e2e/**/*.spec.ts

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

apps/meteor/tests/e2e/**/*.spec.ts: All test files must be created in apps/meteor/tests/e2e/ directory
Avoid using page.locator() in Playwright tests - always prefer semantic locators such as page.getByRole(), page.getByLabel(), page.getByText(), or page.getByTitle()
Use test.beforeAll() and test.afterAll() for setup/teardown in Playwright tests
Use test.step() for complex test scenarios to improve organization in Playwright tests
Group related tests in the same file
Utilize Playwright fixtures (test, page, expect) for consistency in test files
Prefer web-first assertions (toBeVisible, toHaveText, etc.) in Playwright tests
Use expect matchers for assertions (toEqual, toContain, toBeTruthy, toHaveLength, etc.) instead of assert statements in Playwright tests
Use page.waitFor() with specific conditions instead of hardcoded timeouts in Playwright tests
Implement proper wait strategies for dynamic content in Playwright tests
Maintain test isolation between test cases in Playwright tests
Ensure clean state for each test execution in Playwright tests
Ensure tests run reliably in parallel without shared state conflicts

Files:

  • apps/meteor/tests/e2e/account-forgetSessionOnWindowClose.spec.ts
apps/meteor/tests/e2e/**/*.{ts,spec.ts}

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

apps/meteor/tests/e2e/**/*.{ts,spec.ts}: Store commonly used locators in variables/constants for reuse
Follow Page Object Model pattern consistently in Playwright tests

Files:

  • apps/meteor/tests/e2e/account-forgetSessionOnWindowClose.spec.ts
🧠 Learnings (8)
📚 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/tests/e2e/account-forgetSessionOnWindowClose.spec.ts
📚 Learning: 2026-02-24T19:39:42.247Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 38493
File: apps/meteor/tests/e2e/page-objects/fragments/message.ts:7-7
Timestamp: 2026-02-24T19:39:42.247Z
Learning: In RocketChat e2e tests, avoid using data-qa attributes to locate elements. Prefer semantic locators such as getByRole, getByLabel, getByText, getByTitle and ARIA-based selectors. Apply this rule to all TypeScript files under apps/meteor/tests/e2e to improve test reliability, accessibility, and maintainability.

Applied to files:

  • apps/meteor/tests/e2e/account-forgetSessionOnWindowClose.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/tests/e2e/account-forgetSessionOnWindowClose.spec.ts
  • apps/meteor/client/lib/sdk/storage.ts
  • apps/meteor/app/ui-master/server/scripts.ts
  • apps/meteor/client/meteor/startup/accounts.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/tests/e2e/account-forgetSessionOnWindowClose.spec.ts
  • apps/meteor/client/lib/sdk/storage.ts
  • apps/meteor/app/ui-master/server/scripts.ts
  • apps/meteor/client/meteor/startup/accounts.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/tests/e2e/account-forgetSessionOnWindowClose.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/tests/e2e/account-forgetSessionOnWindowClose.spec.ts
  • apps/meteor/client/lib/sdk/storage.ts
  • apps/meteor/app/ui-master/server/scripts.ts
  • apps/meteor/client/meteor/startup/accounts.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/sdk/storage.ts
  • apps/meteor/client/meteor/startup/accounts.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/sdk/storage.ts
  • apps/meteor/client/meteor/startup/accounts.ts
🧬 Code graph analysis (4)
apps/meteor/tests/e2e/account-forgetSessionOnWindowClose.spec.ts (2)
apps/meteor/tests/e2e/page-objects/auth.ts (1)
  • Login (48-76)
apps/meteor/tests/e2e/utils/test.ts (1)
  • test (134-134)
apps/meteor/client/lib/sdk/storage.ts (2)
apps/meteor/client/lib/sdk/ddpSdk.ts (2)
  • ensureConnectedAndAuthenticated (75-154)
  • readStoredLoginToken (71-71)
apps/meteor/client/meteor/startup/accounts.ts (1)
  • applyForgetSessionOnWindowClose (65-75)
apps/meteor/app/ui-master/server/scripts.ts (1)
apps/meteor/app/ui-master/server/inject.ts (1)
  • addScript (78-94)
apps/meteor/client/meteor/startup/accounts.ts (1)
apps/meteor/client/lib/sdk/storage.ts (1)
  • setStorageBackend (39-42)
🔇 Additional comments (4)
apps/meteor/app/ui-master/server/scripts.ts (1)

37-40: LGTM!

apps/meteor/tests/e2e/account-forgetSessionOnWindowClose.spec.ts (2)

40-48: LGTM!


50-62: LGTM!

apps/meteor/client/meteor/startup/accounts.ts (1)

1-8: LGTM!

Also applies to: 53-80

Comment thread apps/meteor/client/lib/sdk/storage.ts Outdated
Comment thread apps/meteor/client/lib/sdk/storage.ts 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.

🧹 Nitpick comments (1)
apps/meteor/client/lib/sdk/storage.ts (1)

2-3: 💤 Low value

Module comment references only localStorage but code now supports sessionStorage.

The header comment states reads/writes use window.localStorage under the hood, but the implementation now supports both localStorage and sessionStorage via storageBackend.

📝 Suggested update
 // Single point of access to the client-side persistent storage that
-// Rocket.Chat shares with Meteor's accounts-base. Reads and writes use
-// window.localStorage under the hood; the keys mirror the names Meteor
+// Rocket.Chat shares with Meteor's accounts-base. Reads and writes use either
+// window.localStorage or window.sessionStorage; the keys mirror the names Meteor
 // originally wrote so sessions persist across the Meteor → SDK migration.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/meteor/client/lib/sdk/storage.ts` around lines 2 - 3, Update the module
header comment to reflect that reads/writes may use either window.localStorage
or window.sessionStorage via the storageBackend abstraction (e.g., the
storageBackend variable/parameter used by getItem/setItem/removeItem functions),
so replace the line that claims only window.localStorage is used with a short
note that the implementation supports both localStorage and sessionStorage
through storageBackend.
🤖 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.

Nitpick comments:
In `@apps/meteor/client/lib/sdk/storage.ts`:
- Around line 2-3: Update the module header comment to reflect that reads/writes
may use either window.localStorage or window.sessionStorage via the
storageBackend abstraction (e.g., the storageBackend variable/parameter used by
getItem/setItem/removeItem functions), so replace the line that claims only
window.localStorage is used with a short note that the implementation supports
both localStorage and sessionStorage through storageBackend.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7b8d48ac-14af-44d2-a688-cc75cb0b1dd5

📥 Commits

Reviewing files that changed from the base of the PR and between ad37a00 and 6e91a97.

📒 Files selected for processing (1)
  • apps/meteor/client/lib/sdk/storage.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: CodeQL-Build
  • 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/lib/sdk/storage.ts
🧠 Learnings (5)
📚 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/sdk/storage.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/sdk/storage.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/sdk/storage.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/sdk/storage.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/sdk/storage.ts
🔇 Additional comments (2)
apps/meteor/client/lib/sdk/storage.ts (2)

17-31: LGTM!


61-66: LGTM!

Also applies to: 69-74, 80-85

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 1 file (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment thread apps/meteor/client/lib/sdk/storage.ts
gabriellsh
gabriellsh previously approved these changes May 27, 2026
@ggazzo ggazzo self-requested a review May 27, 2026 23:56
Comment on lines -39 to 48
window.addEventListener('load', function() {
if (window.localStorage) {
Object.keys(window.localStorage).forEach(function(key) {
window.sessionStorage.setItem(key, window.localStorage.getItem(key));
});
window.localStorage.clear();
Meteor._localStorage = window.sessionStorage;
Accounts.config({ clientStorage: 'session' });
}
settings.watchMultiple(['Custom_Script_Logged_Out', 'Custom_Script_Logged_In', 'Custom_Script_On_Logout'], () => {
const content = getContent();
addScript('scripts', content);
});
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

this was the first thing to happen after a page load. do we no longer need this behavior? Or are we creating a regression/chance for a race condition? Do we need all these modifications?

Comment thread apps/meteor/client/meteor/startup/accounts.ts Outdated
Comment on lines +19 to +29
const getStorageForBackend = (backend: StorageBackend): Storage | undefined => {
if (typeof window === 'undefined') {
return undefined;
}

try {
return backend === 'session' ? window.sessionStorage : window.localStorage;
} catch {
return undefined;
}
};
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

that's what I was expecting from this fix.

Comment on lines +43 to +54
export const setStorageBackend = (backend: StorageBackend): boolean => {
if (backend === storageBackend) {
return true;
}

if (!moveLoginKeys(backend)) {
return false;
}

storageBackend = backend;
return true;
};
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is all this is to fix the regression or some improvement you've seen? I think it should go to 8.6.0.

@ggazzo ggazzo dismissed gabriellsh’s stale review May 28, 2026 00:03

check again

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.

3 issues found across 5 files (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment thread apps/meteor/client/lib/sdk/storage.ts
Comment thread apps/meteor/client/lib/sdk/meteorBackedSdk.ts Outdated
Comment thread apps/meteor/client/meteor/startup/accounts.ts Outdated
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 1 file (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment thread apps/meteor/client/meteor/startup/accounts.ts
cardoso and others added 10 commits May 29, 2026 17:17
Co-authored-by: gabriellsh <40830821+gabriellsh@users.noreply.github.com>
DDPSDK.create can return a sealed instance, making the storage hook
assignment throw at boot. Accounts.config also throws when called twice
with a conflicting value. Both failures aborted client bootstrap during
E2EE login, leaving public_key absent in localStorage and crashing the
page mid-test.
Default configuredStorageBackend to 'local' so the startup pass is a
no-op when the setting is off — matches the in-memory storageBackend
default. Coerce peek/window fallback to a boolean so an undefined cache
no longer routes through the changeStorageBackend side effects, and guard
the SDK call in case the storage hook failed to attach. Restores E2EE
key writes to localStorage when the setting is disabled.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants