Await the results of browser scripts from background handlers
FA
4d ago+3494+3494+0123456789012345678901234567890123456789-130-130-012345678901234567890123456789
All Submissions:
- Have you followed the guidelines stated in CONTRIBUTING.md file?
- Have you checked to ensure there aren't any other open Pull Requests for the desired changed?
Type of change
- New feature (non-breaking change which adds functionality)
- This change requires a documentation update
Description
Part of ENG-9127.
Problem. Getting a value out of the browser today means passing a callback. The browser evals that callback string, and the code that asks for the value ends up split from the code that uses it.
Change. A background handler can now await the script itself:
@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']}"
This works for rx.call_script, rx.call_function and rx.run_script. If the script returns a promise, the handler gets the value the promise resolves to.
Rules.
- Await outside the state lock: in a background handler, outside
async with self. Under the lock, every other event of the tab would wait for the browser, so that raisesEventHandlerTypeError. So does passingcallback=and awaiting. - Timeout:
browser_call_timeout(30 s by default;Nonemeans no limit), ortimeout=on a single call. A per-call value must be positive, finite seconds orNone, as for the config, and a bad one raisesEventHandlerValueErrorwhen the event is built. The timeout stays on the backend and is never sent to the browser. - Disconnects:
- A tab that reconnects to the same backend worker within
browser_call_grace_period(5 s) still delivers its result, also under a new token. A reconnect to another worker cannot pass the result on, so the call fails when the grace period ends, with a message that names that cause and sticky sessions. - A tab that reloads or navigates away fails the call as soon as the new page connects. It doesn't wait out the timeout.
- A tab that doesn't come back fails the call when the grace period ends.
- A tab that reconnects to the same backend worker within
Errors. Each message states the problem, its cause and the fix, and a test compares the full text:
| Exception | Raised when |
|---|---|
BrowserScriptError | The script throws or its promise rejects. Carries the JS name, message and stack (each cut to 4000 characters, so the reply fits in one message), and is picklable. |
BrowserResultSerializationError | The result cannot be sent as JSON: a DOM node, window, a function, a value nested too deep, a result larger than one socket message (REFLEX_SOCKET_MAX_HTTP_BUFFER_SIZE), or a frontend from another Reflex version. |
TimeoutError | No result arrived in time. The message names both ways to raise the limit. |
BrowserDisconnectedError (a ConnectionError) | The tab isn't connected to this worker, was reloaded, never came back, or the app runs without a frontend. |
Design.
- The backend puts a request id (
rid, a uuid4) in the event payload. The browser runs the script and replies on a newresultsocket event with{rid, json}or{rid, error}. The JSON travels as UTF-8 bytes in a binary attachment, so it is not escaped a second time, and the browser checks its size against the server's frame limit before it sends. It sends that reply without blocking its event queue, so a script that waits on the user holds up no other event. BrowserCallssettles a call by itsridalone. The id is unguessable, so a tab that reconnects under a new token still delivers its result: when the same page connects under a new token, its calls move to that token, so the old socket's disconnect does not end them. A per-token index exists only for disconnects and grace timers.- Each page load sends a random page id with every connect. When the same token connects with a new page id, the old page is gone, so its calls fail at once.
- A reply is always sent, even when the thrown value can't be read (getters that throw, revoked proxies). The backend side catches every parse failure, including
RecursionError.
Out of scope.
- Routing a call, or its result, between workers. A call to a tab connected to another worker fails immediately, and a result sent after a reconnect to another worker is lost when the grace period ends; both messages say to use sticky sessions. Forwarding results over the existing redis lost+found channel is a possible follow-up.
- Awaiting JS module functions (
_call_js, a separate stacked PR).
New Feature Submission:
- Does your submission pass the tests?
- Have you linted your code locally prior to submission?
Changes To Core Features:
- Have you added an explanation of what your changes do and why you'd like us to include them?
- Have you written new tests for your core changes, as applicable?
- Have you successfully ran tests with your changes locally?
Tests:
- Unit: the registry (resolve, timeout, grace period, reload, new token, cancellation, deep nesting), the processor wiring, the real app socket handlers with a real processor, and the config.
- vitest: serialization, every thrown-value case, and ordering.
- Playwright
test_call_script.py: values, errors, timeouts, the lock rules, a socket drop inside and past the grace period, and a page reload. The grace period is set to 2 s for the test. - Coverage: 100% of the added Python lines and branches, and of the JS statements and branches.
Docs: "Awaiting Results" in docs/api-reference/browser_javascript.md, with each rule and every error's exact message and fix. Both settings are in docs/advanced_onboarding/configuration.md.