Skip to content

Await the results of browser scripts from background handlers - #7955

Draft
FarhanAliRaza wants to merge 6 commits into
mainfrom
farhan/focused-darwin-dx76ek-await-results
Draft

FarhanAliRaza wants to merge 6 commits into
mainfrom
farhan/focused-darwin-dx76ek-await-results

Conversation

@FarhanAliRaza

@FarhanAliRaza FarhanAliRaza commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

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. Instead of passing a callback that the browser evals, the browser now sends a script's return value back to the backend, so a background handler can await it:

@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']}"

Works for rx.call_script, rx.call_function and rx.run_script. A script returning a promise is awaited in the browser, and the handler gets the resolved value.

Rules

  • Only awaitable outside the state lock (a background handler, outside async with self). Awaiting in a foreground handler or under the lock raises EventHandlerTypeError, because every other event of the tab would wait for the browser. Passing callback= and awaiting raises too.
  • Timeout: browser_call_timeout config (30s by default), overridable per call with timeout= (None = no limit). Raises TimeoutError.
  • Disconnects: pending calls survive browser_call_grace_period (5s). socket.io buffers the browser's result emit, so a tab reconnecting in time still delivers it. Otherwise the call raises BrowserDisconnectedError, which is also what you get when calling a tab that is not connected.
  • Errors: a script that throws or rejects raises BrowserScriptError (with the JS name, message and stack). A value JSON cannot carry raises BrowserResultSerializationError. That includes DOM nodes and window, which would otherwise arrive as {}, and BigInt.

Wire

  • An awaited _call_script / _call_function event carries a request id in its payload (rid). No other event changes shape or cost: the Event dataclass is untouched.
  • The browser answers on a new result socket event with {rid, json} or {rid, error: {name, message, stack, kind?}}. BrowserCalls (one per event processor) resolves a call only for the token it was sent to, so a client cannot answer another tab's call.
  • The frontend runs the script synchronously, then sends its result without awaiting it in the event queue. A script waiting on the user holds up nothing; a Playwright test covers this.
  • The script events' signature (without timeout) is computed once instead of on every call, so creating a script event is cheaper than before.

Out of scope / follow-ups

  • Multi-worker (Redis) routing: a call only reaches tabs connected to the same worker, otherwise BrowserDisconnectedError. This is documented.
  • A tab that reloads reconnects with its token but loses the running script, so the call ends at its timeout. This is documented.
  • Deprecating callback=, and the browser awaiting the backend (env.call).

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 run locally:

  • Unit tests pass, except tests/units/reflex_cli/v2, which fails identically on main in this environment.
  • vitest: 214 tests (14 new), plus the reflex-frontend lint and typecheck.
  • Playwright: test_call_script.py (2 new end-to-end tests).
  • pyright reflex tests, ruff and pre-commit.

Docs: "Awaiting Results" in docs/api-reference/browser_javascript.md, and both settings in docs/advanced_onboarding/configuration.md.

https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf

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
@linear-code

linear-code Bot commented Nov 21, 2026

Copy link
Copy Markdown

ENG-9127

@greptile-apps

greptile-apps Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with no new actionable findings.

Summary

Background handlers can await browser scripts and receive their values or errors, with configurable timeouts and reconnect grace periods.

  • Background handlers can use browser script results directly.
  • Pending browser calls survive a brief tab reconnect.

Reviews (4) · Last reviewed commit: "Import the exceptions at the top of the ..." · 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
@codspeed

codspeed Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Merging this PR will regress 1 benchmark

2 warnings

⚠️ 15 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

⚠️ 2 benchmarks with a significant change ran in a different software environment

Their base and head results were measured with a different OS or toolchain, such as compiler, runtime or library versions, so the changes might come from this difference rather than from the code. Open an affected benchmark to see what changed.

See affected benchmarks

⚡ 1 improved benchmark
❌ 1 regressed benchmark
✅ 144 untouched benchmarks
⏩ 8 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_proxy_list_mutation 9.3 ms 9.7 ms -4.81%
⚡ test_console_log 658.1 µs 522 µs +26.08%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing farhan/focused-darwin-dx76ek-await-results (53e4424) with main (df7f157)

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

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

Copy link
Copy Markdown
Contributor Author

CodSpeed on 53e4424 reports test_proxy_list_mutation at -4.81%. This is not caused by this PR:

  • 53e4424 differs from b33c046 only in tests/integration/tests_playwright/test_call_script.py, which no benchmark runs. On b33c046, CodSpeed listed test_proxy_list_mutation as untouched.
  • The PR does not change the state proxy or anything under reflex/istate.

The two regressions earlier runs found (test_console_log, test_from_event_type[event_spec]) were real; b33c046 fixed them. test_console_log is now 26% faster than main.


Generated by Claude Code

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant