Skip to content

Persist browser sessions without delaying hydration - #7363

Merged
FarhanAliRaza merged 74 commits into
mainfrom
codex/session-frontend
Nov 25, 2026
Merged

FarhanAliRaza merged 74 commits into
mainfrom
codex/session-frontend

Conversation

@masenf

@masenf masenf commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

Let hydration and ordinary events run while the socket-delivered session credential is exchanged for an HttpOnly cookie. Credentials are never written to browser storage; routing-token and freshness keys are scoped to the backend URL. Web Locks coordinate simultaneous cold tabs, and duplicate tabs adopt server-issued replacement tokens.

Idle timers request fresh credentials over the authenticated socket; a connect or a tab that becomes visible requests one only when the saved refresh time passed. Failed HTTP exchanges retry with bounded backoff while readiness stays pending. Success releases waiting uploads and Enterprise HTTP helpers; teardown aborts the exchange and rejects readiness. When an existing cookie replaces the provisional token, readiness waits until the replacement socket connects.

Uploads reserve their cancellation controller before waiting, so cancellation works immediately. Waiting uploads do not block ordinary WebSocket events. Transport warmup for established sessions and CONNECT-packet hydration remain intact.

Depends on #7362; real browser and deployment coverage is in #7364. Enterprise helper compatibility is in reflex-dev/reflex-enterprise#240. Merged with current main, including its reconnect retry and CONNECT auth changes in state.js.

Validation: all 13 frontend runtime/lifecycle wrapper tests pass, including the actual upload helper, idle renewal, retry recovery, cancellation, late responses after teardown, and cookie-replacement reconnects. The new failure/reconnect regressions fail before their fixes. Full assembled stack: 12,147 unit tests passed with 80.15% coverage.

Review fixes:

  • A 403 from the exchange ends it. The client logs the untrusted origin once, stops the retry and releases waiting uploads; the page no longer shows a connection error for a working socket.
  • HTTP calls wait only for an in-band credential, so a failed renewal of an existing cookie does not hold uploads.
  • The refresh timer is capped at 2**31 - 1 ms.
  • getToken() returns a legacy tab token until the server replaces it.
  • An oversized hydrate releases the cold-tab lock.

Second review round:

  • Browser tests read the client token through CLIENT_TOKEN_JS in tests/integration/utils.py: the token is under a sessionStorage key scoped to the backend URL, so tests from main that waited for the token key timed out.
  • An exchange that fails three times in a row stops holding uploads and keeps retrying (a proxy that does not forward /_reflex/session held them forever).
  • A successful exchange clears an earlier 403 denial.

An upload that the server rejects with a 4xx status, for example a 403 when the browser has no valid session cookie, now shows an error toast (an alert when the app has no toast provider). Production says "Your session has expired. Reload the page and try again." for a 403 and "The server rejected the upload." for another 4xx; development shows the status and the server's reason. Before, it only wrote to the browser console. Cancelled uploads, network errors and handler failures are unchanged.

Related to ENG-12919, ENG-9088.

@masenf
masenf added this pull request to stack #7365 September 30, 2026 00:41
@masenf masenf changed the title Persist in-band browser sessions without delaying hydration Persist browser sessions without delaying hydration Sep 30, 2026
@greptile-apps

greptile-apps Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[High impact] No new blocking issue was identified in this PR.

Summary

This PR saves browser sessions in HttpOnly cookies without holding up hydration or ordinary WebSocket events.

  • Browser tabs exchange socket credentials for backend-scoped session cookies.
  • Uploads wait for session readiness and show users when the server rejects them.

No new actionable findings were identified. The supplied previous threads have no comment numbers, so previousFindings is empty.

Reviews (26) · Last reviewed commit: "Merge branch 'pr-7362' into pr-7363" · Reviewed by Greptile

@masenf
masenf force-pushed the codex/session-frontend branch from 12859c9 to d42c9b7 Compare October 5, 2026 21:24
@linear-code

linear-code Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

ENG-9088

ENG-12919

@masenf
masenf force-pushed the codex/session-frontend branch from d42c9b7 to da3a484 Compare October 8, 2026 17:55
@masenf
masenf force-pushed the codex/session-frontend branch from da3a484 to a8786e0 Compare October 8, 2026 18:24
@masenf
masenf force-pushed the codex/session-frontend branch 2 times, most recently from 77997ba to f72f7b7 Compare October 8, 2026 19:03
@masenf
masenf force-pushed the codex/session-frontend branch from f72f7b7 to c8b6820 Compare October 14, 2026 09:35
- A socket that connected with a cookie always renews over HTTP and gets
  no credential. The backend compared against the session as it was at
  connect, so once that copy expired it sent an exchangeable credential to
  page scripts although the browser held a renewed cookie.
- A session past its maximum age is sent to the session endpoint, which
  issues a new session. Before, the socket sent no reply and the page
  stayed on the ended session until a reload.
- The same-host origin rule requires the scheme of the request, and in
  production the exact origin. A plain HTTP page could install a session
  for the HTTPS host.
- link_token_to_sid works without an ambient event context, as on main.
- The compatibility fixtures and the breaking changelog wording move to
  the pull request that changes the default mode.
…on lasting failures

- Browser tests read the client token through a shared helper. The token
  lives under a sessionStorage key scoped to the backend URL, so tests
  that waited for the old "token" key timed out.
- The navigation test polls for its routed socket. A tab without a session
  cookie opens the socket after the page mounts, and a routed socket fires
  no page event.
- An exchange that fails three times in a row stops holding HTTP calls and
  keeps retrying. A proxy that answers 404 held uploads forever.
- A successful exchange clears an earlier denial, so the next refresh is
  scheduled.
The test compares all cookies and all storage keys of the page. The
session adds one HttpOnly cookie and one localStorage key, and the client
token is under a key scoped to the backend URL.

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

2 issues found across 11 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/reflex-frontend/src/utils/state.js">

<violation number="1" location="packages/reflex-frontend/src/utils/state.js:1649">
P2: After the third failure, the scheduled retry can recreate `initialSessionExchange` and hold new uploads again, contrary to the intended lasting-failure release. Gate readiness creation after the threshold or track a separate flag that keeps readiness released while retries continue.</violation>
</file>

<file name="tests/integration/utils.py">

<violation number="1" location="tests/integration/utils.py:18">
P2: These helpers do not actually select the current backend-scoped entry; they select the first matching suffix. A tab that retained storage from an older backend URL can make tests read a stale token or refresh time, causing false assertions or timeouts. Derive the exact current storage key (or require it from the caller) instead of searching by suffix.</violation>
</file>

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

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread tests/integration/utils.py Resolved
link_token_to_sid built its session check from the ambient event context.
A harness that drives the namespace directly, such as the event benchmark,
has none, so its setup failed with LookupError. The check runs directly in
that case.
An upload that the server refuses before the event handler runs, for
example a 403 because the browser has no valid session cookie, only wrote
to the browser console. The page now shows it as a failed event handler
is shown: an error toast with the status and the reason, or an alert when
the app has no toast provider. A cancelled upload, a network error and a
handler failure are unchanged.
The error toast repeated the server's reason to every visitor: "The
session does not authorize this client token." Production now says "Your
session has expired. Reload the page and try again." for a 403 and "The
server rejected the upload." for another 4xx. Development keeps the
status and the server's reason, as the backend error toast does.
The production same-origin rule compared the raw authority of the Origin
with the Host header. A proxy that forwards the Host with the default
port written out, or in another case, made a same-origin exchange fail.
- The backend's refresh notice no longer restarts an exchange that the
  backend denied for this page's origin. The guard moved from the
  scheduler into the request itself.
- After three failed attempts, a later retry does not hold HTTP calls
  again while its request is open.
WebKit does not store a Secure cookie from plain HTTP, also on a loopback
host, so local development in Safari had no session: fresh state on each
reload and rejected uploads. Local development over plain HTTP now sends
the plain SameSite=Lax cookie next to the secure partitioned one, and
each browser keeps the form that it accepts. The middleware reads the
plain cookie only there, and prefers the secure one. HTTPS and production
are unchanged.
The secure partitioned cookie works in a normal tab and in a cross-site
iframe, and WebKit accepts Secure cookies from loopback hosts since
310542@main. The plain fallback cookie is removed.
An event context without an authorized session read and parsed
REFLEX_SESSION_TOKEN_MODE on each creation (1.9 us). The parsed mode is
now cached by the raw environment value (0.36 us), so a change to the
environment still takes effect.
HTTP calls wait whenever the socket delivers a credential, on a first
connection and on a reconnection alike. The flag that exempted later
credentials was never cleared on disconnect, so an upload after a
reconnection with an expired cookie could start before the new cookie.
The benchmarks connect a namespace that has no server and address state
with a plain token. A connection now issues a session over the socket,
so test_on_event_router_data failed at setup. The fixture moves here
from the integration PR.
@codspeed

codspeed Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 4.72%

1 warning

⚠️ 21 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

⚡ 1 improved benchmark
✅ 145 untouched benchmarks
⏩ 8 skipped benchmarks1

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_get_state[memory] 1.1 ms 1.1 ms +4.72%

Tip

Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.


Comparing codex/session-frontend (14f1b38) with codex/session-transport (f34272a)

Open in CodSpeed

Footnotes

  1. 8 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

# Conflicts:
#	packages/reflex-base/src/reflex_base/config.py
#	packages/reflex-base/src/reflex_base/session.py
#	tests/units/reflex_base/test_session.py
Base automatically changed from codex/session-transport to main November 25, 2026 16:49
@FarhanAliRaza
FarhanAliRaza merged commit 9cb22b4 into main Nov 25, 2026
183 of 206 checks passed
@FarhanAliRaza
FarhanAliRaza deleted the codex/session-frontend branch November 25, 2026 16:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement Anything you want improved on deck PRs lined up to review / merge next roadmap https://github.com/reflex-dev/reflex/issues/2727 security

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants