Repository navigation
Await the results of browser scripts from background handlers - #7955
FarhanAliRaza wants to merge 49 commits into
Conversation
A background event handler can now `await rx.call_script(...)`,
`rx.call_function(...)` or `rx.run_script(...)` and get the script's
result back, instead of passing a callback that the browser evals.
- Event gains an optional `rid`, sent only when the backend awaits the
event, so ordinary events serialize as before. Clients cannot set it.
- The browser runs the script and answers on a new `result` socket event
with `{rid, json}` or `{rid, error}`. It does not await the script in
the event queue, so a script waiting on the user holds up nothing.
- BrowserCalls keeps the pending calls per token. A result settles a
call only for the token it was sent to. A disconnect starts a grace
period (browser_call_grace_period); a reconnect within it keeps the
calls, since socket.io buffers the result emit.
- Awaiting under the state lock (a foreground handler, `async with
self`) raises EventHandlerTypeError, as does passing a callback too.
- Timeouts default to browser_call_timeout, overridable with timeout=.
- Errors raise BrowserScriptError, BrowserResultSerializationError,
BrowserDisconnectedError or TimeoutError.
Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
add_args binds extra arguments to the event's signature parameters, so the new keyword-only timeout absorbed one. The signature the event reports now leaves it out. runEventScript declares the late-bound addEvents alias itself, as every function that runs user code must. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
[Medium impact] The PR appears safe to merge, with no new actionable issues found. SummaryAdds awaited browser-script results for background handlers, with timeouts, browser errors, and a reconnect grace period.
Reviews (23) · Last reviewed commit: "Name the polling test transport's pendin..." · Reviewed by Greptile |
String() throws on an object without a prototype, so a script rejecting with one sent no result and its call waited for the timeout. Error fields now fall back to Object.prototype.toString. The new tests also import the exceptions at the top of their modules. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
Merging this PR will improve performance by 21.71%2 warnings
Performance Changes
Tip Curious why performance improved? Comment Comparing Footnotes
|
The rid field on Event cost every Event one more frozen field write (CodSpeed: -7% on from_event_type). Only _call_script and _call_function ever carry a request id, so it now goes in their payload and no other event pays for it; the Event serializer and the _EVENT_FIELDS change are gone with the field. The script event signature is also computed once instead of on every call, which made console_log 8% slower. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
|
CodSpeed on 53e4424 reports
The two regressions earlier runs found ( Generated by Claude Code |
Pass name, message and stack to Exception.__init__ so the error survives pickling, and format it in __str__; an error the backend found itself has no JavaScript name and prints its message alone. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
A call's own timeout=None already waits without a limit; the config setting can now say the same. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
The timeout only matters to the backend task that awaits the call, so it is kept on the spec (_BrowserCallSpec) instead of in the event args: a trigger or a yielded script no longer sends an unused timeout to the browser. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
A thrown value whose name or message getter throws, or a revoked Proxy, made describeScriptError throw, so the backend never got a reply and waited for its timeout. It now gets a generic error instead. The error for a function or symbol result also says what to return instead. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
A reloaded page reconnected under its sessionStorage token within the grace period, which kept calls whose script had died with the old page: they waited for their timeout, forever with timeout=None. The frontend now sends a random page id with every connect; a connect from another page load under the token fails the token's pending calls at once, while a reconnect of the same page keeps them. A call made between a socket's disconnect and the cleanup of its token passed the connected check and registered without a grace timer. The namespace now drops the page of a socket in on_disconnect itself, and a token whose socket has no page is not connected. Results settle their call by request id alone, so a tab that was given a new token on reconnect still delivers them. A result Python cannot parse (nested too deeply, or malformed) always fails its call instead of leaving it pending. The error messages say what happened, why, and what to change. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
The CallScript app drops its socket and reconnects within the grace period (the result still arrives), past it (BrowserDisconnectedError), and reloads the page (BrowserDisconnectedError at once). A vitest covers a script dispatching events through the late-bound addEvents. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
The Awaiting Results section now lists the rules, then each error with its exact message and fix, and says a reload fails the call at once. The configuration page shows the settings in rxconfig.py and that browser_call_timeout may be None. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
with_args rebuilt the spec from four named fields, so a copy of an awaited call lost its timeout. It now copies every field. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
Each loaded app sends its own page id, so the size-check test now replaces it with a placeholder before comparing frames; the id has a fixed length, so the measured sizes are unchanged. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
EventSpec.with_args used dataclasses.replace, which passes fn to CallableEventSpec's constructor along with the fields it already derives from fn, so copying clear_selected_files raised TypeError. EventSpec keeps its explicit constructor call; _BrowserCallSpec overrides with_args to keep its timeout. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
A 100,000-deep payload exhausts the JSON parser on some interpreters and not on others (CI's Python 3.14 and 3.15 parse it), so the test now makes the parser raise RecursionError the way it does at that depth. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
String() already throws on an object without a prototype, so the outer fallback describes it as it does a throwing getter or a revoked Proxy; the separate toText fallback and the kind parameter go. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
EventContext.call_frontend only checked for a missing frontend before calling call_frontend_impl, for its single caller _await_browser_call, which now does both. EventProcessor._on_connect only forwarded to BrowserCalls.connect; the socket's connect handler calls that directly, as its result handler already calls BrowserCalls.resolve. The processor and app tests no longer repeat the reconnect and reload sequences test_browser_calls pins, nor the not-connected check test_page_of_only_for_a_live_socket_on_this_instance pins. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
A call cancels its tab's grace timer as it ends, so close() only cancels the futures. Merge the two zero-grace-period tests into one. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
The hooked and Var scripts exercise call_script's existing branches, not the timeout; and CallableEventSpec.with_args is unchanged by this branch. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
Checking a script's result for DOM nodes read its `nodeType` and `window`, so a getter of the result ran an extra time before serializing it ran it again. A window is now told by its tag and a node by Node's own nodeType getter, reached only when the value has a nodeType property, so the result's own getters run once. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
The window check called Object.prototype.toString, which runs a result's Symbol.toStringTag getter: a tag getter with side effects changed the result, and one that threw failed the call. A window is now this page's or one of its frames', compared by identity; any other window refers to itself, so serializing it fails as before. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
… event is built rx.call_script, rx.call_function and rx.run_script accepted timeout=0, a negative number, inf, nan or True: the script still ran in the browser and the awaited call failed at once. The call's timeout now follows the rule of browser_call_timeout, through one helper the config shares, and raises EventHandlerValueError as the event is built. Config._post_init checks both browser call settings in one method, so it is no more complex than before the awaited calls.
…e_event_inline execute_event_inline grew a branch for script events. The script spec now awaits its call itself, and both share the check for a client's context, so an awaited script fails outside an event handler as before.
A result whose JSON exceeded REFLEX_SOCKET_MAX_HTTP_BUFFER_SIZE made the server drop the socket, so the call waited out its timeout and blamed an unsettled promise, or hung with timeout=None. The browser now measures the result against the frame limit the server announced, on the connection that carries it, and reports a larger one as a BrowserResultSerializationError that says how to fix it. The JSON travels as a binary attachment instead of a string inside the socket.io message, so its quotes are no longer escaped a second time: a quote-heavy result that fits as JSON now fits as a result.
A tab whose old socket stayed half-open reconnects while the server still links its token to that socket, so the connect is given a new token. Its calls stayed filed under the old token, and when the old socket's pings timed out, about 150 seconds later, its disconnect failed them although the tab was connected. A connect from the same page load given a new token now moves the page's calls to that token; a duplicated tab, from another page load, still leaves them with the tab that runs them.
With several backend workers, a tab that dropped its socket and reconnected to another worker within browser_call_grace_period sent its result there, where no call waits for it. The call failed when the grace period ended, saying the tab did not reconnect, although it had. The error now says the tab did not reconnect to this worker, names the other worker as a cause, and points to sticky sessions; the docs say a reconnect delivers the result only on the same worker, and that a reconnect or reload onto another worker fails the call when the grace period ends.
There was a problem hiding this comment.
2 issues found across 13 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="reflex/app.py">
<violation number="1" location="reflex/app.py:2786">
P2: A reload can be misclassified as a duplicate tab during the old token's asynchronous cleanup. In that window `connecting` receives `new_token`, leaves the old page's calls waiting, and `connected(new_token)` cannot find them, so the reload reports a grace-period disconnect error instead of failing immediately as a page replacement; distinguish a still-live old socket from a stale token link before passing the replacement token.</violation>
</file>
<file name="packages/reflex-frontend/src/utils/state.js">
<violation number="1" location="packages/reflex-frontend/src/utils/state.js:731">
P2: The polling check budgets only the base64 attachment, not the Socket.IO event envelope and Engine.IO separator sent with it. Near the limit, the server can reject an accepted result and leave the backend call waiting until timeout; calculate the size of the complete encoded payload before emitting.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
|
The The same line also fails Generated by Claude Code |
…old socket is unlinked A disconnect unlinks the token from its socket in a task, so a reload that connected before the task finished was given a new token and taken for a duplicated tab: its page's calls kept waiting, and failed when the grace period ended with an error saying the tab did not reconnect. A connect from another page load given a new token now fails the calls as a replaced page when the tab's socket already disconnected; a duplicated tab, whose original is still connected, leaves them waiting as before. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
…o it Over polling, engine.io-client posts the socket.io message and its binary attachment in one request body when they are queued together, as while an earlier request is in flight. The size check counted only the attachment's "b" marker and base64, so a result just under that budget made a body over REFLEX_SOCKET_MAX_HTTP_BUFFER_SIZE: python-engineio answered 400, the socket dropped and the result was lost. The check now also counts the encoded message, its Engine.IO type and the separator. A websocket sends the two as separate frames, so its budget is unchanged. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
…in-dx76ek-await-results
…in-dx76ek-await-results # Conflicts: # packages/reflex-base/src/reflex_base/event/processor/event_processor.py # packages/reflex-frontend/src/utils/state.js # reflex/app.py # tests/units/reflex_base/event/processor/test_event_processor.py # tests/units/test_app.py
A thrown error's name, message and stack went to the backend in full, so a long one exceeded the socket's frame limit and the server dropped the connection instead of raising BrowserScriptError. Each is now cut to 4000 characters.
There was a problem hiding this comment.
All reported issues were addressed across 2 files (changes from recent commits).
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
The drop_connection button reconnected with socket.connect(), which resends the query of the socket's last connect through the frontend. Since main's session-bound tokens (#7361), a new tab connects with an empty token and the backend issues one by new_token, so that query still carries the empty token: the backend issued yet another token on the reconnect. The awaited call stayed filed under the old token, which no socket linked any more, so neither its result nor its BrowserDisconnectedError reached the page. Reconnect through socket.reconnect(), the frontend's own path after a dropped connection, which connects with the tab's current token and the session cookie that authorizes it. The two reconnect tests now also check that the tab comes back with the token it had, which failed before this change. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
Both sides appended tests to tests/units/reflex_base/event/test_init.py; the merge keeps both sets and their imports. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ESN8Dip5DMdnmAVDXcoyyV
|
Merged
Generated by Claude Code |
…mits A frontend built before awaited browser calls ignores the request id and never sends a result, so the call times out; the TimeoutError now says so and how to rebuild. The docs said a reloaded page fails its calls as soon as it connects. That holds only when the backend already saw the old connection close: while it still looks open, the connect is indistinguishable from a duplicated tab, and the call fails on its timeout or with the grace period message once the old connection times out. The multi-worker note also says that after a reconnect that moved the tab to a new token, the handler's later state changes go to the old token. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
checkResultSize reads engine._maxPayload, the packet encoder and engine.transport.name, private socket.io-client fields the existing tests only fake. Connect a real socket.io-client over in-memory websocket and polling transports and check the budget it computes, so an upgrade that moves any of them fails here instead of dropping the connection in an app. Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
|
Thanks @masenf. Addressed in afdf4b1 and e6c4ba1:
Generated by Claude Code |
There was a problem hiding this comment.
All reported issues were addressed across 7 files (changes from recent commits).
Tip: Review your code locally with the cubic CLI to iterate faster.
View guided diff | Turn on auto-fix | Re-trigger cubic
…ethods; state when a reload's call reaches the grace period message Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
All Submissions:
Type of change
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
awaitthe script itself:This works for
rx.call_script,rx.call_functionandrx.run_script. If the script returns a promise, the handler gets the value the promise resolves to.Rules.
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.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.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.Errors. Each message states the problem, its cause and the fix, and a test compares the full text:
BrowserScriptErrorname,messageandstack(each cut to 4000 characters, so the reply fits in one message), and is picklable.BrowserResultSerializationErrorwindow, 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.TimeoutErrorBrowserDisconnectedError(aConnectionError)Design.
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.RecursionError.Out of scope.
_call_js, a separate stacked PR).New Feature Submission:
Changes To Core Features:
Tests:
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.Docs: "Awaiting Results" in
docs/api-reference/browser_javascript.md, with each rule and every error's exact message and fix. Both settings are indocs/advanced_onboarding/configuration.md.https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf