Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
a785b68
Await the results of browser scripts from background handlers
FarhanAliRaza Nov 21, 2026
e285c29
Keep timeout out of script event signatures
FarhanAliRaza Nov 21, 2026
42ba65c
Format the awaited script result tests
FarhanAliRaza Nov 21, 2026
154a894
Report script errors whose value cannot become text
FarhanAliRaza Nov 21, 2026
b33c046
Carry the browser call request id in the script event's payload
FarhanAliRaza Nov 21, 2026
53e4424
Import the exceptions at the top of the CallScript test app
FarhanAliRaza Nov 21, 2026
37feb97
Make BrowserScriptError picklable
FarhanAliRaza Nov 21, 2026
1b647a4
Allow browser_call_timeout=None to wait without a limit
FarhanAliRaza Nov 21, 2026
863c878
Keep the timeout of a browser call off the wire
FarhanAliRaza Nov 21, 2026
717217d
Answer an awaited script even when its thrown value cannot be read
FarhanAliRaza Nov 21, 2026
e5d6617
Fail an awaited browser call at once when its page is gone
FarhanAliRaza Nov 21, 2026
5916a61
Test awaited browser calls across dropped sockets and reloads
FarhanAliRaza Nov 21, 2026
7bd31a0
Document the errors of awaited browser calls and their fixes
FarhanAliRaza Nov 21, 2026
3402e53
Keep the timeout of a browser call when its spec is copied
FarhanAliRaza Nov 21, 2026
de666a7
Compare connect frames of two apps up to their random page id
FarhanAliRaza Nov 21, 2026
3b8ab52
Copy only browser-call specs with dataclasses.replace
FarhanAliRaza Nov 21, 2026
81ecfaa
Test a result too deep to parse without relying on the stack depth
FarhanAliRaza Nov 21, 2026
eaaa193
Describe an unreadable thrown value in one place
FarhanAliRaza Nov 22, 2026
286e56a
Drop the one-caller wrappers around awaited browser calls
FarhanAliRaza Nov 22, 2026
98d7a9e
Let each cancelled browser call cancel its own grace timer
FarhanAliRaza Nov 22, 2026
0aff9c8
Trim the script event timeout tests to the PR's behavior
FarhanAliRaza Nov 22, 2026
f9e1af5
Start every waiting awaited script through one test helper
FarhanAliRaza Nov 22, 2026
02865f8
Keep browser calls waiting for their tab after a refused reconnect
FarhanAliRaza Nov 22, 2026
7766260
Check every interleaving of a tab's browser calls against their invar…
FarhanAliRaza Nov 22, 2026
15fbc40
Test a refused connect with no linked token or no event processor
FarhanAliRaza Nov 22, 2026
b2a623b
Give the client token, page and request id of browser calls distinct …
FarhanAliRaza Nov 22, 2026
50a4438
Run the grace period of browser calls until a connect is accepted
FarhanAliRaza Nov 22, 2026
ed33271
Reject a DOM node or window of an iframe as a browser call result
FarhanAliRaza Nov 22, 2026
3d820f8
Reject a browser call timeout or grace period that is not finite
FarhanAliRaza Nov 22, 2026
3ffae34
Import every browser call exception the docs name
FarhanAliRaza Nov 22, 2026
6a3b98e
Say when a reload fails awaited calls and where to await them
FarhanAliRaza Nov 22, 2026
e83fc0d
Tell a DOM node from data without running the result's getters
FarhanAliRaza Nov 22, 2026
937818c
Tell a window from data without reading the result's Symbol.toStringTag
FarhanAliRaza Nov 22, 2026
8a86e16
Reject a call's browser timeout that is not positive seconds when the…
FarhanAliRaza Nov 24, 2026
777f2bf
Await browser calls from their own spec instead of a branch of execut…
FarhanAliRaza Nov 24, 2026
40c7e87
Fail an awaited script result too large for one message at once
FarhanAliRaza Nov 24, 2026
bf1e8a5
Keep awaited browser calls of a tab that reconnects under a new token
FarhanAliRaza Nov 24, 2026
04ae88a
Say that a tab back on another backend worker loses an awaited result
FarhanAliRaza Nov 24, 2026
989ab83
Fail awaited browser calls at once when a reload connects before its …
FarhanAliRaza Nov 24, 2026
0d86612
Budget a polled script result together with the message that refers t…
FarhanAliRaza Nov 24, 2026
ed02ae5
Merge remote-tracking branch 'upstream/main' into farhan/focused-darw…
FarhanAliRaza Nov 24, 2026
6a51647
Merge remote-tracking branch 'upstream/main' into farhan/focused-darw…
FarhanAliRaza Nov 25, 2026
e142fba
Cut a long error a script throws to fit a message to the backend
FarhanAliRaza Nov 25, 2026
b24ddab
Keep a clipped script error text within MAX_ERROR_TEXT, its ellipsis …
FarhanAliRaza Nov 25, 2026
c2ca742
Reconnect the call_script test tab with its current client token
FarhanAliRaza Nov 25, 2026
94b6527
Merge branch 'main' into farhan/focused-darwin-dx76ek-await-results
claude Nov 26, 2026
afdf4b1
Name a stale frontend in the browser call timeout; document reload li…
FarhanAliRaza Nov 26, 2026
e6c4ba1
Test the result size check against a real socket.io-client
FarhanAliRaza Nov 26, 2026
7c3d533
Name the polling test transport's pending flag apart from engine.io m…
FarhanAliRaza Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions docs/advanced_onboarding/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,23 @@ config = rx.Config(

The setting can also be overridden with `REFLEX_EVENT_LOOP_BLOCKING_THRESHOLD`, for example `REFLEX_EVENT_LOOP_BLOCKING_THRESHOLD=0` to turn detection off.

## Awaited Browser Calls

A background event handler can [await the result of a browser script](/docs/api-reference/browser-javascript/#awaiting-results). Two settings bound how long it waits:

```python
config = rx.Config(
app_name="my_app",
browser_call_timeout=60.0,
browser_call_grace_period=10.0,
)
```

- `browser_call_timeout` (default `30.0`): the seconds, more than 0, an awaited call waits for its result before raising `TimeoutError`, or `None` to wait without a limit. A call can override it with `timeout=`.
- `browser_call_grace_period` (default `5.0`): the seconds an awaited call waits for its tab to reconnect to the same backend worker after a disconnect before raising `BrowserDisconnectedError`; `0` raises it as soon as the tab disconnects. A reloaded page fails its calls as soon as it connects to that worker, if the worker already saw the old page's connection close; see [Awaiting Results](/docs/api-reference/browser-javascript/#awaiting-results) for a connection that dropped without closing.

They can also be set in seconds with `REFLEX_BROWSER_CALL_TIMEOUT` and `REFLEX_BROWSER_CALL_GRACE_PERIOD`. Waiting without a limit is set in `rxconfig.py`. A negative, infinite or NaN value raises `ConfigError` when the app starts.

## Environment Variables

Any config parameter can be overridden by setting an environment variable with the `REFLEX_` prefix and the parameter name in uppercase. Environment variables take precedence over values set in `rxconfig.py`.
Expand Down
116 changes: 116 additions & 0 deletions docs/api-reference/browser_javascript.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,122 @@ The `callback` parameter may be an `EventHandler` with one argument, or a lambda
If the callback is None, then no event is triggered.
```

## Awaiting Results

A [background event handler](/docs/events/background-events/) can `await` `rx.call_script`, `rx.call_function`, or
`rx.run_script` to get the script's result directly, instead of passing a callback. If the script returns a promise, the
handler gets the value the promise resolves to.

```python demo exec
class ViewportState(rx.State):
viewport: str = ""

@rx.event(background=True)
async def measure(self):
size = await rx.call_script("({w: window.innerWidth, h: window.innerHeight})")
async with self:
self.viewport = f"{size['w']} x {size['h']}"


def viewport_demo():
return rx.hstack(
rx.button("Measure Viewport", on_click=ViewportState.measure),
rx.text(ViewportState.viewport),
)
```

The rules:

- Await the call in a background handler, outside `async with self`. While a handler holds the state lock, the tab's
other events would wait for the browser's answer, so a regular handler cannot await a script either.
- Pass either `callback=` or `await` the result, not both.
- The result travels as JSON: objects become `dict`, arrays become `list`, and `undefined` becomes `None`. Return the
data you need from a DOM element, not the element itself.
- A call waits `browser_call_timeout` seconds for its result (30 by default, set in `rxconfig.py`). Pass `timeout=` to
one call to change it, or `timeout=None` to wait without a limit:

```python
answer = await rx.call_script("askTheUser()", timeout=None)
```

Like `browser_call_timeout`, `timeout=` must be a positive, finite number of seconds or `None`; any other value
raises `EventHandlerValueError` when the event is built: ``timeout is 0, but awaited browser calls need a positive,
finite number of seconds to wait for a result. Set timeout to a number of seconds such as 30, or to None to wait
without a limit.``

- The script keeps running while the tab's socket reconnects. A tab that reconnects to the same backend worker within
`browser_call_grace_period` seconds (5 by default) still delivers its result. A tab that is closed, reloaded or
navigated away stops the script, and the call fails.

The exceptions are imported from `reflex.utils.exceptions`:

```python
from reflex.utils.exceptions import (
BrowserDisconnectedError,
BrowserResultSerializationError,
BrowserScriptError,
EventHandlerTypeError,
)
```

Each error below gives its exact message, with the values of an example call, and its fix.

- `BrowserScriptError`: the script throws, or the promise it returns is rejected. It carries the Javascript error's
`name`, `message` and `stack`, and reads like the browser console: ``ReferenceError: missing_function is not
defined``. Fix the script, or catch the error.
- `BrowserResultSerializationError`, a subclass of `BrowserScriptError`: the result cannot reach the backend as JSON.
- ``TypeError: The script returned a DOM node or window, which JSON cannot carry; return the data you need from it
instead.``
- ``TypeError: The script returned a function, which JSON cannot carry; return plain data (objects, arrays, strings,
numbers, booleans or null) instead.`` (also for a symbol)
- ``RangeError: The script returned 1200000 bytes of JSON, more than the 1000000 a message to the backend can carry;
return less data, or raise REFLEX_SOCKET_MAX_HTTP_BUFFER_SIZE on the backend.`` (with the `polling` transport, a
message carries about three quarters of the limit, as base64)
- ``The script returned a value nested too deeply for Python's JSON parser. Return a value with fewer levels of
nested objects and arrays.``
- ``The browser sent a result the backend cannot read (...). The page runs a frontend built for another version of
Reflex: rebuild the frontend (restart `reflex run`, or export the app again) and reload the page.``
- `TimeoutError`: ``The browser did not return a result for `_call_script` within 30.0 seconds. If the script needs
longer, pass a longer `timeout=` to the call (or `timeout=None` to wait without a limit) or raise
`browser_call_timeout` in rxconfig.py; if it returns a promise, make sure the promise settles. A frontend built by an
older version of Reflex never returns a result: rebuild the frontend (restart `reflex run`, or export the app again)
and reload the page.``
- `BrowserDisconnectedError`, a `ConnectionError`: the tab cannot return the result.
- When the call is made: `` `_call_script` cannot run in the browser tab: the tab is not connected to this backend
worker, because it was closed, is reconnecting, or reconnected to another worker. Catch BrowserDisconnectedError
where the tab may be gone; with several backend workers, route each tab to one worker (sticky sessions). ``
- After the grace period: ``The browser tab did not reconnect to this backend worker within
browser_call_grace_period (5.0 seconds), so the script's result is lost: the tab was closed, lost its connection for
longer, or reconnected to another backend worker, which cannot pass the result on. Catch BrowserDisconnectedError
where the user may close the tab, raise `browser_call_grace_period` in rxconfig.py if connections drop for longer,
and with several backend workers route each tab to one worker (sticky sessions).``
- When a reloaded page connects, if the backend already saw the old page's connection close: ``The browser tab
reloaded or left the page before the script returned a result, so the script stopped. Catch
BrowserDisconnectedError where the user may reload or leave the page while the script runs.`` If the old connection
still looks open, for example because the network dropped it without closing it, the backend cannot tell the
reloaded page from a duplicated tab: the call raises `TimeoutError` when its timeout ends, unless the timeout outlasts
the old connection timing out (`REFLEX_SOCKET_INTERVAL` plus `REFLEX_SOCKET_TIMEOUT`, 145 seconds by default) plus
the grace period; then it raises the grace period message.
- Without a frontend, for example in a test: `` `_call_script` cannot run in a browser: the app is running without a
frontend connection (for example in a test, or a process that runs only the backend), so no tab can return a
result. Await browser scripts in handlers triggered from a page of the running app, and catch
BrowserDisconnectedError where no page may be connected. ``
- `EventHandlerTypeError`:
- `` `_call_script` cannot be awaited while the state lock is held, as every other event of this tab would wait for
the browser's answer; await it in a background event handler, outside `async with self`. ``
- `` `_call_script` was given a callback and awaited; pass either callback= or await its result, not both. ``

```md alert info
# Awaiting results with multiple backend workers

The browser sends the result to the backend worker its tab is connected to. With several workers sharing state through
Redis, a background task awaits results only from tabs connected to its own worker. Calls to other tabs raise
`BrowserDisconnectedError`. A tab that reconnects, or reloads, onto another worker while a call waits fails the call
when the grace period ends, and its result is lost. A tab that reconnects to the same worker before the backend saw
its old connection close is given a new client token: the call still returns the result, but the handler's later
`async with self` changes go to the state of the old token and never reach the page.
```

## Using React Hooks

To use React Hooks directly in a Reflex app, you must subclass `rx.Component`,
Expand Down
1 change: 1 addition & 0 deletions news/+await-browser-results.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The backend receives the results of browser scripts that a background event handler awaits (`await rx.call_script(...)`), keeps those calls alive while their tab reconnects, and fails them with `BrowserDisconnectedError` when the reloaded page connects, or when no tab reconnects within `browser_call_grace_period`.
11 changes: 11 additions & 0 deletions packages/reflex-base/news/+await-browser-results.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
A background event handler can now `await` `rx.call_script`, `rx.call_function` and `rx.run_script` outside `async with self` to get the script's result directly, instead of passing a `callback`:

```python
@rx.event(background=True)
async def measure(self):
size = await rx.call_script("({w: window.innerWidth, h: window.innerHeight})")
async with self:
self.width = size["w"]
```

A script error raises `BrowserScriptError`, a missing result `TimeoutError` (`browser_call_timeout` in `rxconfig.py`, or `timeout=` per call), and a tab that is closed, reloaded or away longer than `browser_call_grace_period` raises `BrowserDisconnectedError`. Awaiting inside `async with self` raises `EventHandlerTypeError`. See [Awaiting Results](https://reflex.dev/docs/api-reference/browser-javascript/#awaiting-results).
82 changes: 76 additions & 6 deletions packages/reflex-base/src/reflex_base/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,8 @@ class BaseConfig:
disable_plugins: List of plugin types to disable in the app.
transport: The transport method for client-server communication.
event_loop_blocking_threshold: Minimum event-loop blocking duration in seconds to report in development. Set to 0 to disable detection.
browser_call_timeout: Seconds an awaited browser call, such as `await rx.call_script(...)` in a background event handler, waits for the browser's result before raising TimeoutError, or None to wait without a limit. A call's own `timeout=` overrides it.
browser_call_grace_period: Seconds an awaited browser call survives its tab disconnecting: a reconnect to the same backend worker within it delivers the result, otherwise the call raises BrowserDisconnectedError.
"""

app_name: str
Expand Down Expand Up @@ -309,6 +311,10 @@ class BaseConfig:

event_loop_blocking_threshold: float = 0.2

browser_call_timeout: float | None = 30.0
Comment thread
FarhanAliRaza marked this conversation as resolved.
Resolved

browser_call_grace_period: float = 5.0

# Whether to skip plugin checks.
_skip_plugins_checks: bool = dataclasses.field(default=False, repr=False)

Expand All @@ -320,6 +326,50 @@ class BaseConfig:
]


def _is_seconds(value: object, *, positive: bool) -> bool:
"""Whether a config value is a finite, non-negative number of seconds.

Args:
value: The configured value.
positive: Whether 0 is rejected too.

Returns:
False for a bool, a non-number, a negative number, inf and nan.
"""
return (
not isinstance(value, bool)
and isinstance(value, (int, float))
and (value > 0 if positive else value >= 0)
and value < math.inf
)


def _check_browser_call_timeout(
timeout: object, name: str, where: str, error: type[Exception]
) -> None:
"""Raise unless a browser call timeout is None or a positive, finite number of seconds.

A timeout of 0 would fail the call before the browser can answer.

Args:
timeout: The timeout.
name: The name the timeout is set under.
where: Where it is set, as the error's fix names it after the name.
error: The exception to raise.

Raises:
error: If the timeout is invalid.
"""
if timeout is not None and not _is_seconds(timeout, positive=True):
msg = (
f"{name} is {timeout!r}, but awaited browser calls need a positive, "
"finite number of seconds to wait for a result. Set "
f"{name}{where} to a number of seconds such as 30, or to None to "
"wait without a limit."
)
raise error(msg)


def _is_plain_path_segment(segment: str) -> bool:
"""Whether a URL path segment maps to a single directory name on every platform.

Expand Down Expand Up @@ -379,6 +429,29 @@ class Config(BaseConfig):
# Track whether the app name has already been validated for this Config instance.
_app_name_is_valid: bool = dataclasses.field(default=False, repr=False)

def _check_browser_call_settings(self) -> None:
"""Check the timeout and the grace period of awaited browser calls.

Raises:
ConfigError: If either is not a valid number of seconds.
"""
_check_browser_call_timeout(
self.browser_call_timeout,
"browser_call_timeout",
" in rxconfig.py",
ConfigError,
)
if not _is_seconds(self.browser_call_grace_period, positive=False):
msg = (
f"browser_call_grace_period is {self.browser_call_grace_period!r}, "
"but awaited browser calls need a non-negative, finite number of "
"seconds to wait for a disconnected tab to reconnect. Set "
"browser_call_grace_period in rxconfig.py to a number of seconds "
"such as 5, or to 0 to fail the calls as soon as their tab "
"disconnects."
)
raise ConfigError(msg)

def _post_init(self, **kwargs):
"""Post-initialization method to set up the config.

Expand Down Expand Up @@ -444,15 +517,12 @@ def _post_init(self, **kwargs):
msg = "trusted_proxy_hops must be a non-negative integer."
raise ConfigError(msg)

threshold = self.event_loop_blocking_threshold
if (
isinstance(threshold, bool)
or not isinstance(threshold, (int, float))
or not 0 <= threshold < math.inf
):
if not _is_seconds(self.event_loop_blocking_threshold, positive=False):
msg = "event_loop_blocking_threshold must be a non-negative finite number."
raise ConfigError(msg)

self._check_browser_call_settings()

# Normalize route prefixes to ensure they start with a slash.
self._normalize_paths()

Expand Down
3 changes: 3 additions & 0 deletions packages/reflex-base/src/reflex_base/constants/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ class CompileVars(SimpleNamespace):
# The key of the CONNECT auth packet that carries the hash of the state
# tree the frontend was compiled for; an old frontend sends none.
CONNECT_AUTH_STATE_SCHEMA = "state_schema"
# The key of the CONNECT auth packet that carries the id of the page load,
# which tells a reconnect of the page from a reload.
CONNECT_AUTH_PAGE = "page"
# Payload keys of hydrate_and_load / update_vars_internal; they are passed
# through as handler kwargs, so they must match those parameter names.
PAYLOAD_VARS = "vars"
Expand Down
3 changes: 3 additions & 0 deletions packages/reflex-base/src/reflex_base/constants/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ class SocketEvent(SimpleNamespace):
PING = "ping"
EVENT = "event"
CLIENT_ERROR = "client_error"
# Sent by the browser with the result of a call the backend awaits
# (must match RESULT_EVENT in packages/reflex-frontend/src/utils/state.js).
RESULT = "result"
# Sent on connect when the frontend was compiled for another state tree
# (must match STATE_MISMATCH_EVENT in packages/reflex-frontend/src/utils/state.js).
STATE_MISMATCH = "state_mismatch"
Expand Down
Loading
Loading