Skip to content

Move the frontend javascript into its own package, reflex-frontend - #7794

Merged
FarhanAliRaza merged 22 commits into
mainfrom
claude/js-package-extraction-testing-obmwr4
Nov 12, 2026
Merged

FarhanAliRaza merged 22 commits into
mainfrom
claude/js-package-extraction-testing-obmwr4

Conversation

@FarhanAliRaza

@FarhanAliRaza FarhanAliRaza commented Nov 10, 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

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)

What this does

The javascript every Reflex app runs on lived inside the reflex-base python package, at .templates/web, with its tests in a separate harness (tests/js) that could not install the modules' real dependencies. utils/state.js, the largest module, could not be imported from a test at all.

It is now a javascript package of its own, reflex-frontend, at packages/reflex-frontend/:

  • src/ is the old .templates/web tree. tests/ runs under vitest + jsdom against the real socket.io-client, react-router, mergician and universal-cookie, pinned to the versions an app installs.
  • The package is private and is not published to npm. reflex-frontend is a placeholder name.
  • The reflex-base wheel embeds src/ as reflex_base/.templates/web when it is built, through a build hook (packages/reflex-base/hatch_build.py). The move itself changes nothing in an installed Reflex: after the first two commits the wheel carries the same 26 files as main, byte for byte. The later commits change the source, as described below.
  • In a checkout there is no embedded copy: Templates.Dirs.WEB_TEMPLATE resolves to packages/reflex-frontend/src, so the next reflex init picks up an edit without a rebuild. An editable install embeds nothing.

The commits, in order

Commit What
76e7e0c, 804887e The move, and everything it needed around it. No change to shipped files.
bd55640 Bug 1: generateUUID variant.
d81bb8e Bug 2: IPv6 wildcard backend.
3d37da2 Bugs 3 and 4: queue drains spinning on a dropped connection.
725b494 Bug 5: unmounted event loop reconnecting on tab visibility.
e08cae4 Lint and type-check gates, their behaviour-preserving fixes in the source, and the export contract test.
fec30c8 Bug 6: a failed connection attempt looping through the error handler; floating-promise lint rule.

What had to change around the move

  • uv workspace / CI discovery: it is the one directory under packages/ without a pyproject.toml, so the workspace excludes it and build_packages.yml skips directories that have none.
  • reflex-release: paths are mapped to packages by directory, so a frontend change would no longer count as a change to reflex-base. New setting [tool.reflex-release] extra-source-dirs names directories outside a package that it also ships; this repository lists packages/reflex-frontend/src under reflex-base.
  • Pins: a unit test fails when packages/reflex-frontend/package.json drifts from PackageJson.DEPENDENCIES. Bumping an npm pin is now two edits plus the lockfile.
  • Python tests that read a frontend file go through Templates.Dirs.WEB_TEMPLATE rather than a path.

Bugs the new tests found, fixed here

Six, all in utils/state.js. Each is described in a comment below before its fix, and has a regression test that failed first and its own bugfix fragment:

  1. generateUUID set a reserved variant on about half its ids, so those session tokens were not valid version 4 UUIDs.
  2. getBackendURL never treated an IPv6 wildcard backend as same-domain: URL.hostname returns "[::]", which the list's entries could never match.
  3. The socket's connect handler could spin forever draining the queue if the connection dropped while an awaited frontend event was pending with a state event behind it. Nothing but microtasks ran again: the tab froze.
  4. The event loop's effect had the same loop, with the same result.
  5. An unmounted event loop reconnected when the tab became visible: its visibilitychange listener was never removed, and treated the cleared socket as "not connected yet".
  6. A connection that could not be attempted looped through the error handler: with site storage blocked, an un-awaited promise rejected, the rejection handler reported it by trying to connect again, and the page raised about 12,000 unhandled rejections a second (measured in Chromium) without ever showing a connection error.

Found and reported, not changed: debounce/throttle state shared between components that fire the same handler; window.onerror being assigned rather than listened to; the eval scope contract that keeps state.js one module.

Quality gates added (npm run check, run by the js-unit-tests job)

  • Lint: biome, configured in lint.biome.jsonc, with each exception explained next to it. Its findings are fixed: strict equality, Array.isArray, a parseInt radix, Number.isNaN, a scoped case declaration, one accumulating spread. No behaviour change intended; the diff is mechanical. noFloatingPromises is on for src: a promise nothing awaits is either marked void or a finding.
  • Type check: tsc over the JSDoc with checkJs, nothing emitted, so there is still no compile step. types/globals.d.ts declares every global the runtime reads implicitly (window.__reflex*, $/env.json, import.meta.hot).
  • Export contract: tests/public_api.test.js pins the names each module exports, and imports each one in node, where production builds prerender.
  • npm pack on every run, so the manifest stays publishable.

Testing

  • JS: 143 tests in the package (29 moved, 114 new); lint and type check clean.
  • Python: 13,825 unit tests passed on the move. After the later commits I re-ran the suites that read or execute the frontend source, not the whole suite. ruff and pyright clean.
  • Real browser: a small app run from the checkout and driven through Chromium after the last commit: state events, an awaited rx.call_script with a state event queued behind it, a valid v4 session token, no console errors; and the same app with sessionStorage blocked, which raised 45,128 unhandled rejections in four seconds before fec30c8 and none after.
  • Builds (on the move commits): reflex-base as sdist and wheel, wheel-from-sdist equal to the direct wheel, and the sdist installed into a clean venv outside the repository embeds all 26 files.
  • Not run locally: tests/units/reflex_cli and tests/units/reflex_bench (sandbox limits), the Playwright integration tests, the Docker init test, Windows.

Not in this PR

  • The older node-driven tests under tests/units (*.mjs, about 1,900 lines) still load state.js through a source-rewriting harness; only their paths changed.
  • JS owned by other python packages (otel.js, GradientProfile.js, bench_page.js, the site-shared assets) stays where it is.
  • Splitting state.js. Event code is eval'd inside it and resolves names from its module scope, so moving functions out needs an integration test for that contract first.
  • Publishing. $/... imports and the per-app $/env.json only resolve inside an app's .web, and npm leaves src/.gitignore out of the tarball; the package README lists what is missing.

https://claude.ai/code/session_01LwJUCSZCLWw5meAowrx3Qt

The javascript every Reflex app runs on lived inside the reflex-base python
package, at `.templates/web`, with its tests in a separate harness that could
not install the modules' real dependencies. `utils/state.js`, the largest
module, was not importable from a test at all.

It is now a javascript package, `reflex-frontend`, at
`packages/reflex-base/frontend`: `src/` is what ships, `tests/` runs under
vitest against socket.io-client, react-router, mergician and universal-cookie
at the versions an app installs. The package is private and not published.

The reflex-base wheel embeds `src/` as `reflex_base/.templates/web` when it is
built, so an installed Reflex is unchanged: the wheel carries the same 26 files,
byte for byte. A checkout has no embedded copy, and
`Templates.Dirs.WEB_TEMPLATE` resolves to `frontend/src` there.

`frontend/src` counts as reflex-base source for the changelog check, and CI
tests and packs the package in the existing `js-unit-tests` job.

The new suites cover the helpers and the exports of `state.js` that compiled
code calls. Two of them record bugs they found, as expected failures:
`generateUUID` sets a reserved variant on about half its ids, and
`getBackendURL` never matches an IPv6 wildcard host.

Claude-Session: https://claude.ai/code/session_01LwJUCSZCLWw5meAowrx3Qt
The javascript package sat inside reflex-base's own directory. It now has a
directory of its own beside the python packages.

That puts it outside the reflex-base project root, so a static force-include
can no longer embed it: a wheel built from the sdist would look for a sibling
directory that is not there. A build hook does it instead. From the repository
it adds the frontend's `src` to the sdist (inside `reflex_base`) or to the
wheel; from an sdist it has nothing to do, and it refuses to build when
neither copy exists. An editable install embeds nothing, which also drops the
unused copy the static config left in site-packages. The wheel still carries
the same 26 files, byte for byte.

It is the one directory under packages/ without a pyproject.toml, so the uv
workspace excludes it and the build workflow's discovery skips it.

reflex-release maps changed paths to packages by directory, and would no
longer count a frontend change as a change to reflex-base: no fragment would
be required, and nothing would mark reflex-base as having something to
release. `[tool.reflex-release] extra-source-dirs` names directories outside a
package that it also ships, and this repository lists the frontend's `src`
under reflex-base.

Claude-Session: https://claude.ai/code/session_01LwJUCSZCLWw5meAowrx3Qt
@FarhanAliRaza
FarhanAliRaza requested a review from a team as a code owner November 10, 2026 22:28

Copy link
Copy Markdown
Contributor Author

Bug 1: generateUUID does not produce valid version 4 UUIDs

packages/reflex-frontend/src/utils/state.js, in generateUUID:

return (c == "x" ? r : (r & 0x7) | 0x8).toString(16);

The y digit of xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx carries the UUID variant, which RFC 9562 fixes to the bits 10, i.e. one of 8, 9, a, b. (r & 0x7) | 0x8 keeps three random bits instead of two, so the digit ranges over 8–f and about half the ids come out with a reserved variant (c–f). Example from a test run: 25a808f0-f35f-4345-c67a-032dc95b6c8f.

The Stack Overflow answer the comment credits uses (r & 0x3) | 0x8; this looks like a transcription slip.

Impact: low. The id is the session token, and the backend treats it as an opaque string, so nothing breaks today. It matters to anything that validates the token as a UUID (a strict parser, a database column of type uuid with variant checks, a proxy rule).

Found by: generateUUID sets the RFC 9562 variant in packages/reflex-frontend/tests/state.test.js, currently recorded with test.fails.

Fix (next commit): mask with 0x3. Uniqueness and the token's length and shape are unchanged; existing tokens in session storage keep working, since nothing reads the variant.


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Bug 2: getBackendURL never treats an IPv6 wildcard backend as same-domain

packages/reflex-frontend/src/utils/state.js:

const SAME_DOMAIN_HOSTNAMES = ["localhost", "0.0.0.0", "::", "0:0:0:0:0:0:0:0"];
...
SAME_DOMAIN_HOSTNAMES.includes(endpoint.hostname)

When the backend URL names a wildcard bind address, the browser cannot connect to it, so getBackendURL swaps in the page's own hostname (and, on an https page, upgrades the protocol and drops the port). That works for 0.0.0.0. It never happens for IPv6: URL.hostname returns an IPv6 address in brackets and in its shortest form, so both spellings come back as "[::]":

new URL("ws://[::]:8000/_event").hostname            // "[::]"
new URL("http://[0:0:0:0:0:0:0:0]:8000/ping").hostname // "[::]"

Checked in Node and in Chromium. The list holds "::" and "0:0:0:0:0:0:0:0", neither of which can ever equal "[::]", so those two entries are dead.

Impact: an app whose api_url is http://[::]:8000 (or the long spelling) hands the browser ws://[::]:8000/_event unchanged, and the websocket, the ping and uploads fail to connect. The same app with 0.0.0.0 works. Narrow, since api_url defaults to localhost, but the list shows the case was meant to work.

Found by: getBackendURL treats the IPv6 wildcard like 0.0.0.0 in packages/reflex-frontend/tests/state.test.js, currently recorded with test.fails.

Fix (next commit): replace the two dead entries with "[::]", which is what both spellings normalize to. Behavior for localhost, 0.0.0.0 and any real hostname is unchanged.


Generated by Claude Code

generateUUID masked the variant digit with 0x7 where RFC 9562 allows two
random bits, 0x3. About half the session tokens it produced carried a reserved
variant (c-f in the digit after the third dash) and were not valid version 4
uuids.

The backend treats the token as an opaque string, so nothing failed. A strict
uuid parser would have rejected those tokens.

Found by the frontend package's new test suite, which recorded it as an
expected failure until now.

Claude-Session: https://claude.ai/code/session_01LwJUCSZCLWw5meAowrx3Qt
getBackendURL swaps the page's own hostname into a backend URL that names a
wildcard bind address, which a browser cannot connect to. It compares
URL.hostname against a list that held "::" and "0:0:0:0:0:0:0:0", but
URL.hostname gives an IPv6 address in brackets and in its shortest form, so
both spellings arrive as "[::]" and neither entry could ever match.

An app whose api_url is http://[::]:8000 handed the browser that address
unchanged, and the websocket, the ping and uploads could not connect. The same
app with 0.0.0.0 worked.

The list now holds "[::]". Other hosts, IPv6 or not, are compared as before.

Found by the frontend package's new test suite, which recorded it as an
expected failure until now.

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

greptile-apps Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no new actionable issues were found.

Summary

Moves the shipped JavaScript into reflex-frontend while keeping the installed template location unchanged.

  • Reflex’s frontend source now lives in a private JavaScript package.
  • Queued events wait for a connection, and unmounted loops stop reconnecting.
  • Session tokens now use valid version 4 UUID variants.
  • IPv6 wildcard backends now use the page’s host.
  • Failed connection attempts now show as connection errors.
  • Release rules can track source folders outside a package.

Reviews (11) · Last reviewed commit: "Merge branch 'main' into claude/js-packa..." · Reviewed by Greptile

@cubic-dev-ai cubic-dev-ai Bot left a comment •

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.

1 issue found and verified against the latest diff

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="packages/reflex-release/src/reflex_release/config.py">

<violation number="1" location="packages/reflex-release/src/reflex_release/config.py:445">
P2: Extra source directories bypass the news/CHANGELOG exclusion. If an extra directory is another package's whole directory, that package's release commits and fragments make this package look changed, so it is required to add its own fragment. Exclude every package's `news/` and changelog paths, not only the checked package's own.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread packages/reflex-frontend/README.md Resolved
Comment thread packages/reflex-frontend/README.md Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

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.

1 issue found across 71 files

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="tests/units/test_build_config.py">

<violation number="1" location="tests/units/test_build_config.py:393">
P2: This test fails on the supported Python 3.11 runtime because `TarFile.extractall` has no `filter` parameter there. Remove the keyword for this generated, trusted archive or guard it by Python version.</violation>
</file>

Requires human review: Auto-approval blocked because this review re-detected 2 unresolved issues already reported by Cubic.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread tests/units/test_build_config.py Resolved
@codspeed

codspeed Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

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

✅ 151 untouched benchmarks


Comparing claude/js-package-extraction-testing-obmwr4 (2168a32) with main (cb44da7)

Open in CodSpeed

Copy link
Copy Markdown
Contributor Author

Three more bugs, from an audit of the module-level state in utils/state.js

state.js keeps its event queue, token and socket bookkeeping in module scope, shared by every mounted event loop and every drain. These three come from code that assumes that state only changes between its own steps. Each is reproduced by a test in packages/reflex-frontend/tests/state_connection.test.js that fails on the current branch; fixes follow in the next commits.

Bug 3 and 4: a connection dropped mid-drain freezes the tab

Two places drain the queue with the same loop shape:

// the socket's "connect" handler
while (event_queue.length > 0) {
  await processEvent(socket.current, navigate, params);
}

// the "main event loop" effect in useEventLoop
while (event_queue.length > 0) {
  await ensureSocketConnected();
  await processEvent(socket.current, navigate, params);
}

processEvent returns at once, without taking anything off the queue, when the socket is disconnected and a stateful event is waiting. So if the socket drops while one of these loops is suspended, the loop resumes with a non-empty queue it can no longer shrink and spins. Every iteration only awaits already-settled promises, so the browser never gets back to a macrotask: no reconnect, no timers, no rendering, no input. The tab is frozen until it is closed.

The window for it is any frontend event the queue awaits: an rx.call_script / rx.call_function with a callback whose JavaScript returns a promise (a fetch, a permission prompt, a file picker), with a state event queued behind it, and the connection lost before the promise settles (a deploy, a dev-mode backend reload, a network drop).

Fix: one processEvent call. It already drains recursively until the queue is empty or holds a stateful event the socket cannot send, so the while adds nothing except the spin. What stays queued is sent by the connect handler once the socket is back (also covered by a test).

Bug 5: an unmounted event loop reconnects when the tab becomes visible

connect() registers checkVisibility on document and nothing ever removes it. The event loop's cleanup disconnects the socket and sets socket.current = null, and that is exactly the state checkVisibility treats as "not connected yet":

if (!socket.current) {
  connect(socket, dispatch, transports, ...);

socket.current is only ever null there after a cleanup, since the listener is registered after the socket is created. So the next time the tab becomes visible, the torn-down loop opens a fresh socket with its stale dispatch, hydrates against the backend, and registers one more listener. It bypasses the mounted guard ensureSocketConnected has for the same situation.

Reachable in embed mode when the host page unmounts the widget, and in dev on every hot reload of the provider.

Fix: checkVisibility removes itself when its socket is gone, and only ever reconnects a socket that still exists.

Found but not changed here (design-level, and wider than a bug fix):

  • debounce and throttle state is keyed by event name and delay only, so two components firing the same handler with different arguments share it. Typing in input A and then input B inside the debounce window cancels A's pending event.
  • window.onerror and window.onunhandledrejection are assigned, not added as listeners, and never restored: in embed mode this replaces the host page's handlers.
  • eval'd event code resolves names from state.js's module scope (queueEvents, processEvent, refs, and whatever else it references), which is why the file cannot safely be split into smaller modules without an integration test for that contract.

Generated by Claude Code

Two places drained the queue with `while (event_queue.length > 0)` around
`await processEvent(...)`: the socket's connect handler and the event loop's
effect. processEvent returns at once, taking nothing off the queue, when the
socket is disconnected and a stateful event is waiting. A socket that dropped
while either loop was suspended left it with a queue it could not shrink, and
it spun. Each turn awaited only settled promises, so the browser never reached
another macrotask: no reconnect, no timers, no rendering. The tab was frozen.

It took a frontend event the queue awaits (a call_script or call_function with
a callback whose JavaScript returns a promise), a state event queued behind
it, and the connection lost before the promise settled.

processEvent already drains recursively, until the queue is empty or holds a
stateful event the socket cannot send. One call is the whole drain, and what
it leaves is sent by the connect handler when the socket is back.

The tests drive a fake socket that breaks such a loop and records that it had
to: a real spin would hang the run instead of failing a test.

Claude-Session: https://claude.ai/code/session_01LwJUCSZCLWw5meAowrx3Qt
connect() registers a visibilitychange listener on the document and nothing
removed it. The event loop's cleanup disconnects its socket and clears the
ref, which is the one state the listener answered by calling connect() again:
the ref is only ever empty there after a cleanup, since the listener is
registered once the socket exists. So the next time the tab became visible, a
torn-down loop opened a new socket with its stale dispatch, hydrated against
the backend and registered another listener, past the `mounted` guard that
ensureSocketConnected has for the same case.

It happened to an embedded app the host page unmounted, and in dev to every
hot-reloaded copy of the provider.

The listener now removes itself when its socket is gone, and only reconnects
a socket that still exists.

Claude-Session: https://claude.ai/code/session_01LwJUCSZCLWw5meAowrx3Qt

@cubic-dev-ai cubic-dev-ai Bot left a comment •

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.

All reported issues were addressed across 4 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 package had tests but nothing that reads the code the way a reviewer
does. Three gates now run in CI beside them (`npm run check`):

- biome lint, configured in lint.biome.jsonc. Its findings in the source are
  fixed: strict equality throughout, `Array.isArray`, a radix for `parseInt`,
  `Number.isNaN` in place of self-comparison, a scoped `case` declaration, and
  an `Object.assign` where a reduce copied its accumulator on every event.
  None of it changes behaviour.
- tsc over the JSDoc (`checkJs`), with nothing emitted, so there is still no
  compile step between the package and an app. types/globals.d.ts declares
  what the runtime reads that no module defines: the hooks other code puts on
  `window`, the per-app env.json, Vite's `import.meta.hot`. An undeclared
  global now fails the check.
- tests/public_api.test.js lists the names each module exports, since compiled
  pages and separately released component packages import them by name, and
  imports every module in node, where a production build prerenders pages.

state.js evaluates event code with `eval`, which resolves names from the
scopes around it. The linter's unused-variable rules are off for that file
for this reason, with the reason written next to the setting, and the README
gains a section on this and the rest of the state that does not appear in
function signatures.

The config is not named biome.jsonc: the repository's format hook runs biome
from the root without a configuration and stops when it finds a nested one.

Claude-Session: https://claude.ai/code/session_01LwJUCSZCLWw5meAowrx3Qt

@cubic-dev-ai cubic-dev-ai Bot left a comment •

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.

All reported issues were addressed across 20 files (changes from recent commits).

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread packages/reflex-frontend/README.md Resolved
Comment thread packages/reflex-frontend/tsconfig.json Resolved

Copy link
Copy Markdown
Contributor Author

Bug 6: a connection that cannot be attempted loops through the error handler forever

Found by checking utils/state.js against the "no floating promises" rule in Cloudflare's Workers Best Practices guide (a promise nothing awaits or catches fails silently, or somewhere unexpected). biome's noFloatingPromises finds ten of them in src. Nine are deliberate fire-and-forget. One closes a loop:

// useEventLoop
const addEvents = useCallback((events, args, event_actions) => {
  ...
  ensureSocketConnected();   // not awaited, not caught
  ...
});

window.onunhandledrejection = function (event) {
  addEvents([ReflexEvent(`${app.exception_state_name}.handle_frontend_exception`, ...)]);
};

ensureSocketConnected rejects when the connection cannot even be attempted, for instance when the browser blocks site storage: connect() calls getToken(), and window.sessionStorage throws a SecurityError. The rejection is unhandled, so it reaches window.onunhandledrejection, which reports it with addEvents, which calls ensureSocketConnected() again, which rejects again.

Measured in Chromium against a running app, with window.sessionStorage made to throw the way it does when a site may not store data:

seconds after load unhandled rejections so far
1 8,502
2 20,382
3 32,206
4 45,128

No socket to the backend is ever opened, each turn queues one more exception event that can never be sent, and the page shows no connection error: it renders as if it were working.

Fix: ensureSocketConnected catches a failure to connect and records it with setConnectErrors, which is where every other connection failure goes and what the connection banner reads. It can then no longer reject, so nothing reaches the rejection handler. The other nine floating promises are marked void with the lint rule turned on, so the next un-awaited promise is a decision somebody made.


Generated by Claude Code

FarhanAliRaza and others added 2 commits November 10, 2026 22:55
ensureSocketConnected is called without being awaited, by addEvents and by
the mount effect. When the connection could not even be attempted it rejected,
and nothing caught that: with site storage blocked, connect() throws a
SecurityError reading the token from sessionStorage. The unhandled rejection
reached window.onunhandledrejection, which reports errors with addEvents,
which called ensureSocketConnected again, which rejected again.

In Chromium, with sessionStorage made to throw, a running app raised about
12,000 unhandled rejections a second and went on doing so (45,128 after four
seconds), opened no socket, queued one unsendable exception event per turn,
and showed no connection error. With this change the same page raises none.

The failure is now caught and added to the connection errors, where every
other connection failure goes.

The call was one of ten promises in `src` that nothing awaited. The other
nine are deliberate, and are marked `void`. biome's noFloatingPromises is on
for what ships, so the next one is a decision rather than an accident. The
rule comes from Cloudflare's Workers best practices, where a floating promise
is dropped work; in a browser it is an error that surfaces somewhere else.

Claude-Session: https://claude.ai/code/session_01LwJUCSZCLWw5meAowrx3Qt
Preserve the frontend template move and React Compiler test imports. Add the new useRegisteredRef export to the frontend public API contract.
@linear-code

linear-code Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

ENG-13451

ENG-13448

docs/app/tests/frontend_quality.test.mjs reads `components/shiki/code.js` and
`utils/state.js` from the old `.templates/web` location, so the reflex-docs
job failed on three of its five tests with ENOENT once the files moved.

Claude-Session: https://claude.ai/code/session_01LwJUCSZCLWw5meAowrx3Qt
Three gaps in the new setting, each found in review:

- A directory was matched against changed paths as written. `./assets` or
  `packages/../assets` named a real directory, passed validation, and never
  matched a path git reports, so a change there required no fragment and
  triggered no release. Directories are now normalized when loaded, and one
  that is absolute, the repository root, or outside it is rejected.
- A root package listed in internal-packages with no root-source-dirs is
  rejected, because its auto-release trigger would have nothing to fire on.
  Its extra-source-dirs made the list of prefixes non-empty and let it
  through, with a trigger that covered only the extras.
- The mapping made the frozen Config unhashable. It is left out of the hash.

Claude-Session: https://claude.ai/code/session_01LwJUCSZCLWw5meAowrx3Qt
The listener removed itself the next time the page's visibility changed and
found its socket gone. A page that stayed visible kept it, and the event loop
it closes over, until then, and every remount added another.

connect() now hands the socket a `stopWatchingVisibility`, and the event
loop's cleanup calls it with the rest of the teardown. The self-removal stays
for a socket released some other way.

The connection tests release the sockets they connect without an event loop,
so a listener from one test does not answer an event from the next.

Claude-Session: https://claude.ai/code/session_01LwJUCSZCLWw5meAowrx3Qt
The type check covered `src/utils` and `src/components` only. It now takes in
the build files at the top of `src` as well, which found two JSDoc types that
did not exist: a generic `ServerResponse` and a `connect` import. What is
still unchecked is listed in tsconfig.json with the reason for each.

The README said tooling stays outside `src`, which holds the build tooling an
app runs; described `@react-router/dev` as optional and left out
`@react-router/fs-routes`; and said all import-time work is skipped without a
`window`, when the cookie reader is always created and the client state store
depends on `document`.

Claude-Session: https://claude.ai/code/session_01LwJUCSZCLWw5meAowrx3Qt

@cubic-dev-ai cubic-dev-ai Bot left a comment •

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.

All reported issues were addressed across 12 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

Comment thread packages/reflex-frontend/tsconfig.json Resolved
Extending the type check to the build files turned node's types on for the
whole program, so `process` or `Buffer` in a module that runs in a browser
passed the check and would have failed at runtime.

The browser modules are checked with no node types, as before. The build
files get a program of their own, with node's types and without the DOM's, so
each rejects the other's globals. `npm run typecheck` runs both.

Claude-Session: https://claude.ai/code/session_01LwJUCSZCLWw5meAowrx3Qt
main added tests/js/set.test.js beside a change to the set helpers. The
directory it was added to has moved, so the test goes to
packages/reflex-frontend/tests, where the package's suite runs it.

Claude-Session: https://claude.ai/code/session_01LwJUCSZCLWw5meAowrx3Qt
main now publishes `refs` on `globalThis` for code written against 0.10. The
README's account of the state outside function signatures covered only the
globals the runtime reads.

Claude-Session: https://claude.ai/code/session_01LwJUCSZCLWw5meAowrx3Qt
The README said the type check would reject a module that used `refs` without
importing it. It does not: state.js now assigns `globalThis.refs`, which
TypeScript takes as declaring a global, so a bare `refs` type-checks in every
module of the package.

biome's noUndeclaredVariables is turned on for what ships, where it finds
nothing today and rejects exactly that case. The README is corrected to say
which check does the work.

Claude-Session: https://claude.ai/code/session_01LwJUCSZCLWw5meAowrx3Qt
main now requires a test to compare an error message or produced output in
full, never a fragment of it. Three assertions added here matched part of an
error message, and the two build tests checked that some paths were in the
wheel and the sdist rather than what the archives hold.

The release-config and scaffold tests compare the complete message, the
build-hook test derives its message from the path it removed, and the wheel
and sdist tests compare the complete file list.

Claude-Session: https://claude.ai/code/session_01LwJUCSZCLWw5meAowrx3Qt

@masenf masenf left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

i think this is a good transitionary step, and i hesitate to suggest any changes that would make this PR even bigger 😁.

so i will mark approve, and we should bring this in.


ultimately i want to get rid of the duplication between installer.py and package.json -- we should just be installing reflex-frontend as a package, including the dependencies that it carries. eventually this will allow us to stop blowing away .web just because the reflex version changed. only changes in reflex-frontend will require a fast in-place package upgrade. i recognize that we'll need to shim the $/utils/* imports for downstream apps while we deprecate that style of import -- in the meantime, it can just reimport the function from reflex-frontend, wherever we move it to.

i'm also thinking that we need a kind of first class integration for bringing js code snippets into the app. because a lot of what we're shipping in reflex-frontend right now, i would say belongs next to the specific components that it enhances (radix, shiki, dataeditor, etc). flexgen is sort of using rx.asset for that, but it's not ideal because it skips minification and throws warnings on the console about importing through /public. not sure exacly what that looks like, but it would be nice to support files in addition to inline code for short snippets.

you can already sort of do this for simple stuff:

@rx.memo
def double(x: rx.Var) -> rx.Var:
    return rx.Var("x * 2")
export const double_5ea530bf = ((x) => x * 2);
...
  return jsx(
    RadixThemesHeading,
    { size: "9" },
    "Welcome to Reflex! " + double_5ea530bf(2),
  )

and you can do it for components by overriding add_custom_code and defining whatever you want at module level, then wrapping that definition in the same python class

class ExampleDrawing(rx.Component):
    tag = "ExampleDrawing"

    def add_imports(self) -> dict[str, list[str]]:
        return {"react": ["useEffect", "useRef"]}

    def add_custom_code(self) -> list[str]:
        return [
            """
function ExampleDrawing(props) {
  const canvasRef = useRef(null);
  useEffect(() => {
    const canvas = canvasRef.current;
    if (canvas) {
      const ctx = canvas.getContext("2d");
      // Draw a pentagram
      ctx.beginPath();
      for (let i = 0; i < 5; i++) {
        const angle = (i * 4 * Math.PI) / 5 - Math.PI / 2;
        const x = 100 + 50 * Math.cos(angle);
        const y = 100 + 50 * Math.sin(angle);
        if (i === 0) {
          ctx.moveTo(x, y);
        } else {
          ctx.lineTo(x, y);
        }
      }
      ctx.closePath();
      ctx.stroke();
    }
  }, []);

  return <canvas ref={canvasRef} {...props}></canvas>

}"""
        ]

it's a little weird, but it gets the job done.

i just wonder if there's a nicer API that we're overlooking, because most of the time it really is nicer to define the js in a separate JS file and get proper LSP support, syntax highlighting, linting, etc.


finally, the next direction for this work is to untangle #6208 and figure out the best way to safely eval scripts. we'll need a controlled environment that exposes a limited and well defined API that scripts can access (with the ability to poke through additional libraries, like the mechanism dynamic components is using). We should expose that object to the frontend python code with a typed helper to make calling the APIs more reliable as we move the actual js code around. once we have the safe eval environment (and the "legacy" / dangerous eval environment based on the current state.js imports), then we can start deconstructing state.js and really cleaning up the frontend code.

@FarhanAliRaza
FarhanAliRaza merged commit 8f1856f into main Nov 12, 2026
180 of 202 checks passed
@FarhanAliRaza
FarhanAliRaza deleted the claude/js-package-extraction-testing-obmwr4 branch November 12, 2026 17:43
FarhanAliRaza added a commit that referenced this pull request Nov 13, 2026
Resolutions:
- The frontend moved to packages/reflex-frontend (#7794): event_results.js
  lives in src/utils, its vitest suite in tests, and the state.js harnesses
  load it from there. The thenable ResultStream carries a biome-ignore for
  noThenProperty, and main's debounce test asserts the shared stream.
- Stateless handlers were reverted (#7770): their execution path and the
  stateless result test go; the cancelled-while-sending test uses a
  background handler returning outside `async with self` instead.
- _is_result builds on main's _is_invalid_result, so yields and returns
  share its rules for mistaken events (self.handler, an uncalled
  rx.redirect); the foreground path keeps main's flush on failure (#7696).
- EventContext keeps both request_id/emit_result_impl and main's middleware.
- The dropped-result warning (#7796) now applies only to an event sent
  without a request id; the chaining docs say where the value goes instead.
- The awaitable-handlers news fragments were released with 0.11.0.
- reflex now needs reflex-base >= 0.11.1.dev0 for the request id API.

Claude-Session: https://claude.ai/code/session_01LwJUCSPGJ9cvdFM2KLFHoH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

on deck PRs lined up to review / merge next

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants