Skip to content

Add reflex, the API browser code reaches Reflex through - #7949

Draft
FarhanAliRaza wants to merge 7 commits into
mainfrom
farhan/focused-darwin-dx76ek-env
Draft

FarhanAliRaza wants to merge 7 commits into
mainfrom
farhan/focused-darwin-dx76ek-env

Conversation

@FarhanAliRaza

@FarhanAliRaza FarhanAliRaza commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Type of change

  • New feature (non-breaking change which adds functionality)
  • This change requires a documentation update

Description

First of a stacked series for ENG-9127 (safer script evaluation).

Problem. Code run by rx.call_script sees every export of utils/state.js, plus socket, navigate, params and token. Apps and Reflex itself come to depend on frontend internals by accident, and none of them can move.

Change. This PR adds one defined object, reflex (utils/reflex.js), and its Python mirror on rx.js:

JavaScript Python (rx.js) What it does
reflex.ref(id) rx.js.ref(id) The ref of the component with that id. Its current is the element.
reflex.addEvents(events) rx.js.add_events(*events) Dispatches events, as event triggers do.
reflex.event(name, payload) (none) Builds an event for addEvents.
reflex.library(name) rx.js.library(name) Returns a promise of an npm library bundled for dynamic components.
rx.button("Focus", on_click=rx.call_script("reflex.ref('search').current.focus()"))


class SearchState(rx.State):
    @rx.event
    def clear_later(self):
        return rx.run_script(rx.js.add_events(SearchState.clear))

Why the name reflex. Comparable frameworks name their browser API after the framework: Shiny's Shiny, htmx's htmx, Livewire's $wire, Dash's dash_clientside. A generic name collides with an app's own names. An earlier draft called it env, which shadowed the env from env.json that rx.get_upload_url renders (getBackendURL(env.UPLOAD)). That made upload URLs in backend scripts silently wrong. Scripts now see both names: env (the config, as in v0.11) and reflex.

Errors. Each one states the problem, its cause and the fix:

  • rx.js.add_events with a handler that needs arguments fails at definition time. The message says which handler failed and how to pass the arguments.
  • reflex.library rejects Reflex internals ($/...), a library the app does not bundle (the message says to call bundle_library(...)), and calls made before the app has mounted (the message says to call it from an event such as on_mount).

Out of scope.

  • reflex exposes no state and no queueEvents; those need a concrete use first.
  • ref_<id> registry keys stay private.
  • Restricting what a script can see is a later PR. This one changes no name a script could already reach.

Tests

  • vitest tests/reflex.test.js: each member, with exact values and error texts; late binding; the object is frozen; load order across the import cycle with state.js.
  • vitest run_script.test.js: the names a backend script sees, plus a regression test for getBackendURL(env.UPLOAD) → …/_upload/a.png.
  • tests/units/reflex_base/test_js.py: the rendered expressions and imports, and the exact error for a handler that needs arguments.
  • Playwright test_call_script.py::test_reflex_api: reflex from a string script; rx.js from an event trigger and from a backend handler; ref read from the backend; library from on_mount.
  • Coverage: 100% of the added Python lines and JS statements. ruff, pyright and npm run check are clean.

https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf

Code run by rx.call_script sees every export of utils/state.js, so apps and
Reflex itself depend on frontend internals by accident, and none of them can
move. This adds one defined object instead, utils/script_env.js:

  env.ref(id)        the ref of a component, named as format_ref names it
  env.refs           the ref registry
  env.addEvents(...) dispatch through the event loop mounted at call time
  env.event(...)     build an event for addEvents
  env.library(name)  a bundled library, loaded first when loading is lazy

Script code sees it as `env`. On the Python side rx.js.env (reflex_base.js)
builds the same calls as vars; it renders under the alias __reflexEnv, which
runScript also passes in, so one expression works compiled into a page and
sent from the backend, and cannot collide with the `env` pages import from
env.json. Every member reads the runtime at call time, so the module loads in
either order despite its import cycle with utils/state.js.

Nothing existing changes: scripts keep every name they saw before.

Part of ENG-9127.

Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
@greptile-apps

greptile-apps Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The PR reaches browser scripts and Python event code in Reflex apps.

The stack needs caller updates before merging because both dependent PRs still use the removed API.

Findings

  1. P1 Dependent apps cannot build ▶

Summary

Adds reflex as the browser API and exposes matching calls through rx.js.

  • Browser scripts and Python calls now share a Reflex API.

Reviews (4) · Last reviewed commit: "Document reflex and rx.js usage-first" · Reviewed by Greptile

@codspeed

codspeed Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

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

✅ 146 untouched benchmarks
⏩ 8 skipped benchmarks1


Comparing farhan/focused-darwin-dx76ek-env (2557adf) 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. ↩

`env` inside scripts shadowed the `env` that `rx.get_upload_url` compiles
to (`getBackendURL(env.UPLOAD)`), so a backend script linking to an upload
opened `.../ping/a.png`; since the Function-constructor runScript it was a
ReferenceError. The API is now `reflex`, exported from utils/reflex.js,
and runScript passes `env` (the app's env.json) as the direct eval did in
0.11.0.

The API is narrowed to what is documented: `refs` is gone (`ref(id)`
covers it and keeps the registry key format private), `addEvents` takes
only the events, and `library` rejects `$/` frontend modules. Each
`library` error names the library, the cause and the fix, including a
call made before the app root registered its libraries.

Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
`rx.js.env.ref(...)` becomes `rx.js.ref(...)`, and likewise for
`add_events` and `library`; each renders as a call on `reflex`, which a
page imports from `$/utils/reflex` and runScript passes to backend
scripts, so the `__reflexEnv` alias and the public `ScriptEnvVar` class
are gone, as is `refs`. `rx.js.ref(id).current` is typed, so
`rx.js.ref("search").current.value` reads the element's value.

`add_events` now builds each event through `call_event_handler`, so a
handler that still needs arguments fails when the var is built, with a
message naming the handler and the fix, instead of dispatching an empty
payload at runtime.

Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
Covers `reflex.ref` from a string script, `rx.js.add_events` from a
trigger and from the backend, `rx.js.ref` read by the backend,
`reflex.library` from on_mount, and an `rx.get_upload_url` script sent
from the backend resolving to the upload endpoint.

Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
Rename "The Script Environment" to "Reaching Reflex from JavaScript": a
runnable demo from a script, a JavaScript module, rx.js from Python, the
rule to prefer `reflex` over other names in scope, and each error with
its fix. News fragments follow the rename, and the unreleased script
scope fragment lists `env` again.

Claude-Session: https://claude.ai/code/session_01LwJUCVxPh3ihrnaFn6CWnf
@FarhanAliRaza FarhanAliRaza changed the title Add env, the API scripts reach Reflex through Add reflex, the API browser code reaches Reflex through Nov 21, 2026
*/
const refName = (id) => `ref_${String(id).replace(/[^\p{L}\p{N}_]+/gu, "_")}`;

export const reflex = Object.freeze({

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.

P1 Dependent apps cannot build

PRs #7950 and #7951 still write a page_script.js that imports env from $/utils/script_env and calls env.addEvents. This rename removes that module, so their test app cannot bundle.

Both PRs also retain environment.py, which reads the removed Dirs.SCRIPT_ENV_PATH and builds calls to __reflexEnv, which runScript no longer provides. Update those dependent callers and exports to the new API before merging the stack.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. #7950 and #7951 are being rebased onto this change now: page_script.js will import { reflex } from $/utils/reflex, and environment.py, Dirs.SCRIPT_ENV_PATH and __reflexEnv are being removed from them. I'll resolve this thread once both PRs are pushed with the new API.


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