diff --git a/packages/reflex-base/hatch_build.py b/packages/reflex-base/hatch_build.py index ea2c9279161..139ba46ddf3 100644 --- a/packages/reflex-base/hatch_build.py +++ b/packages/reflex-base/hatch_build.py @@ -38,7 +38,7 @@ def initialize(self, version: str, build_data: dict[str, Any]) -> None: if frontend.is_dir(): prefix = "src/" if self.target_name == "sdist" else "" build_data["force_include"][str(frontend)] = prefix + WEB_TEMPLATE - elif not (root / "src" / WEB_TEMPLATE).is_dir(): + elif not (root / "src" / WEB_TEMPLATE / "utils" / "state.js").is_file(): msg = ( f"No frontend to embed: neither {frontend} nor an sdist's copy exists." ) diff --git a/packages/reflex-base/news/+frontend-template-storage-followups.bugfix.md b/packages/reflex-base/news/+frontend-template-storage-followups.bugfix.md new file mode 100644 index 00000000000..3b3ec8437cc --- /dev/null +++ b/packages/reflex-base/news/+frontend-template-storage-followups.bugfix.md @@ -0,0 +1 @@ +Prefer `packages/reflex-frontend/src` over a leftover or stale `.templates/web` directory in source checkouts, and report a dedicated `storage_blocked` connection error when browser site storage is blocked. diff --git a/packages/reflex-base/src/reflex_base/constants/base.py b/packages/reflex-base/src/reflex_base/constants/base.py index 5add4115098..1cef8df96f5 100644 --- a/packages/reflex-base/src/reflex_base/constants/base.py +++ b/packages/reflex-base/src/reflex_base/constants/base.py @@ -128,9 +128,9 @@ class ReflexHostingCLI(SimpleNamespace): def _web_template_dir(root_dir: Path) -> Path: """Locate the frontend package that is copied into a project's web directory. - A built distribution embeds it under ``.templates/web``. A source checkout - has nothing there and reads ``packages/reflex-frontend/src`` in place, so - an edit to the frontend is never shadowed by a stale copy. + A source checkout reads ``packages/reflex-frontend/src`` in place, so an + edit to the frontend is never shadowed by a leftover ``.templates/web`` + directory. A built distribution embeds it under ``.templates/web``. Args: root_dir: The root directory of the reflex_base package. @@ -138,10 +138,13 @@ def _web_template_dir(root_dir: Path) -> Path: Returns: The directory holding the frontend files. """ + checkout = root_dir.parents[2] / "reflex-frontend" / "src" + if (checkout / "utils" / "state.js").is_file(): + return checkout embedded = root_dir / ".templates" / "web" - if embedded.is_dir(): + if (embedded / "utils" / "state.js").is_file(): return embedded - return root_dir.parents[2] / "reflex-frontend" / "src" + return checkout class Templates(SimpleNamespace): diff --git a/packages/reflex-base/src/reflex_base/constants/event.py b/packages/reflex-base/src/reflex_base/constants/event.py index 9c0cf2bd3e5..b120d642ca9 100644 --- a/packages/reflex-base/src/reflex_base/constants/event.py +++ b/packages/reflex-base/src/reflex_base/constants/event.py @@ -74,6 +74,7 @@ class ClientErrorType(SimpleNamespace): DISPATCH_MISSING = "dispatch_function_missing" STATE_UPDATE = "state_update_processing_error" HYDRATION_PAYLOAD_TOO_LARGE = "hydration_payload_too_large" + STORAGE_BLOCKED = "storage_blocked" class EventTriggers(SimpleNamespace): diff --git a/packages/reflex-components-core/news/+storage-blocked-banner.bugfix.md b/packages/reflex-components-core/news/+storage-blocked-banner.bugfix.md new file mode 100644 index 00000000000..3a756907aa1 --- /dev/null +++ b/packages/reflex-components-core/news/+storage-blocked-banner.bugfix.md @@ -0,0 +1 @@ +Show the browser storage error message immediately in `ConnectionToaster`, `ConnectionBanner`, and `ConnectionModal` when site storage is blocked instead of reporting that the server is unreachable. diff --git a/packages/reflex-components-core/src/reflex_components_core/core/banner.py b/packages/reflex-components-core/src/reflex_components_core/core/banner.py index 6cf4e97a58b..1c90dcaf3ac 100644 --- a/packages/reflex-components-core/src/reflex_components_core/core/banner.py +++ b/packages/reflex-components-core/src/reflex_components_core/core/banner.py @@ -7,7 +7,11 @@ from reflex_base import constants from reflex_base.components.component import Component from reflex_base.constants import Dirs, Hooks, Imports -from reflex_base.constants.compiler import CompileVars +from reflex_base.constants.compiler import ( + CompileVars, + MemoizationDisposition, + MemoizationMode, +) from reflex_base.environment import environment from reflex_base.utils.imports import ImportVar from reflex_base.vars import VarData @@ -54,6 +58,14 @@ _var_data=connect_error_var_data, ).to(BooleanVar) +has_storage_blocked_error = Var( + _js_expr=( + "((connectErrors.length > 0) && " + f"(connectErrors[connectErrors.length - 1].code === '{constants.ClientErrorType.STORAGE_BLOCKED}'))" + ), + _var_data=connect_error_var_data, +).to(BooleanVar) + class WebsocketTargetURL(Var): """A component that renders the websocket target URL.""" @@ -84,10 +96,16 @@ def default_connection_error() -> list[str | Var | Component]: The default connection error message. """ return [ - "Cannot connect to server: ", - connection_error, - ". Check if server is reachable at ", - WebsocketTargetURL.create(), + cond( + has_storage_blocked_error | has_hydration_payload_error, + connection_error, + Fragment.create( + "Cannot connect to server: ", + connection_error, + ". Check if server is reachable at ", + WebsocketTargetURL.create(), + ), + ), ] @@ -103,6 +121,7 @@ def add_hooks(self) -> list[str | Var]: toast_id = "websocket-error" # Its own id, so a pending dismiss of the connection toast cannot remove it. hydration_toast_id = "hydration-payload-error" + storage_blocked_toast_id = "storage-blocked-error" target_url = WebsocketTargetURL.create() props = ToastProps( description=LiteralVar.create( @@ -168,11 +187,16 @@ def add_hooks(self) -> list[str | Var]: () => {{ if ({has_hydration_payload_error!s}) {{ toast?.error({connection_error!s}, {{id: "{hydration_toast_id}", closeButton: true, duration: Infinity}}); + }} else if ({has_storage_blocked_error!s}) {{ + toast?.dismiss("{toast_id}"); + toast?.error({connection_error!s}, {{id: "{storage_blocked_toast_id}", closeButton: true, duration: Infinity}}); }} else if ({has_too_many_connection_errors!s}) {{ + toast?.dismiss("{storage_blocked_toast_id}"); if (!userDismissed) {{ {toast_var!s} }} }} else {{ + toast?.dismiss("{storage_blocked_toast_id}"); toast?.dismiss("{toast_id}"); setUserDismissed(false); // after reconnection reset dismissed state }} @@ -248,15 +272,59 @@ def create(cls, comp: Component | None = None) -> Component: """ if not comp: comp = el.span(*default_connection_error()) - return cond( - has_too_many_connection_errors, - el.dialog( - el.h2("Connection Error"), - comp, - open=has_too_many_connection_errors, - z_index=9999, + has_modal_error = ( + has_too_many_connection_errors + | has_storage_blocked_error + | has_hydration_payload_error + ) + modal_dismissed_var_data = VarData.merge( + has_modal_error._get_all_var_data(), + VarData( + imports={"react": ("useEffect", "useState")}, + hooks={ + "const [modalDismissed, setModalDismissed] = useState(false);": None, + f"useEffect(() => {{ if (!({has_modal_error!s})) {{ setModalDismissed(false); }} }}, [connectErrors]);": None, + }, ), ) + modal_dismissed = Var( + "modalDismissed", + _var_type=bool, + _var_data=modal_dismissed_var_data, + ).to(BooleanVar) + show_modal = has_modal_error & ~modal_dismissed + close_button = el.button( + "Close", + type="button", + custom_attrs={ + "on_click": Var( + _js_expr="() => setModalDismissed(true)", + _var_data=modal_dismissed_var_data, + ), + }, + ) + close_row = el.div(close_button, margin_top="0.75rem") + dialog = el.dialog( + el.h2("Connection Error"), + comp, + close_row, + open=show_modal, + z_index=9999, + ) + modal = cond(show_modal, dialog) + # Keep the modal chrome in one component scope without suppressing auto-memoization + # of caller-supplied `comp`, so custom `on_mount`/`on_unmount` stay scoped to `comp`. + modal_cond = modal.children[0] + true_branch = ( + modal_cond.children[0] + if isinstance(modal_cond, Component) and modal_cond.children + else None + ) + unmemoized = MemoizationMode(disposition=MemoizationDisposition.NEVER) + for chrome in (modal, modal_cond, true_branch, dialog, close_row, close_button): + if isinstance(chrome, Component): + chrome._memoization_mode = unmemoized + return modal class WifiOffPulse(Icon): diff --git a/packages/reflex-frontend/src/utils/state.js b/packages/reflex-frontend/src/utils/state.js index afce90ccda9..52a8a842539 100644 --- a/packages/reflex-frontend/src/utils/state.js +++ b/packages/reflex-frontend/src/utils/state.js @@ -52,6 +52,7 @@ const STATE_MISMATCH_WINDOW_EVENT = "reflex:state-mismatch"; const ERROR_TYPE_DISPATCH_MISSING = "dispatch_function_missing"; const ERROR_TYPE_STATE_UPDATE = "state_update_processing_error"; const ERROR_TYPE_HYDRATION_PAYLOAD_TOO_LARGE = "hydration_payload_too_large"; +const ERROR_TYPE_STORAGE_BLOCKED = "storage_blocked"; // These hostnames indicate that the backend and frontend are reachable via the same domain. // They are compared with URL.hostname, which gives an IPv6 address in brackets @@ -145,6 +146,21 @@ export const generateUUID = () => { }); }; +/** + * Build the connection error reported when the browser blocks site storage. + * @param {unknown} cause The underlying storage error thrown by the browser. + * @returns {Error & { code?: string }} The tagged error. + */ +const storageBlockedError = (cause) => { + /** @type {Error & { code?: string }} */ + const error = new Error( + "Site storage is blocked by the browser. Allow cookies and site data for this site and reload.", + { cause }, + ); + error.code = ERROR_TYPE_STORAGE_BLOCKED; + return error; +}; + /** * Get the token for the current session. * @returns The token. @@ -154,10 +170,15 @@ export const getToken = () => { return token; } if (typeof window !== "undefined") { - token = - window.sessionStorage.getItem(clientTokenStorageKey()) || - window.sessionStorage.getItem(LEGACY_TOKEN_STORAGE_KEY) || - ""; + const key = clientTokenStorageKey(); + try { + token = + window.sessionStorage.getItem(key) || + window.sessionStorage.getItem(LEGACY_TOKEN_STORAGE_KEY) || + ""; + } catch (error) { + throw storageBlockedError(error); + } } return token || ""; }; @@ -208,7 +229,15 @@ const sessionRefreshStorageKey = () => `${sessionStorageKey()}:expires_at`; /** Store only the non-secret tab routing token in JavaScript-accessible storage. */ const setToken = (value) => { token = value; - window.sessionStorage.setItem(clientTokenStorageKey(), value); + const key = clientTokenStorageKey(); + try { + window.sessionStorage.setItem(key, value); + } catch (error) { + if (error?.name === "SecurityError") { + throw storageBlockedError(error); + } + throw error; + } }; /** Wait until credentialed HTTP calls can use the initial session cookie. */ @@ -1167,6 +1196,7 @@ const handleStateMismatch = (info) => { * @param client_storage The client storage object from context.js * @param navigate The navigate function from React Router * @param params The params object from React Router + * @returns {Promise<(() => void) | undefined>} Cleanup function to stop watching visibility, if registered. */ export const connect = async ( socket, @@ -1196,7 +1226,18 @@ export const connect = async ( // the state schema goes along on every (re)connect, since a reconnect can // land on another backend version. const bootAuth = (first) => (callback) => { - const boot_event = withRouterData(app.initialEvents(first)[0], params); + let boot_event; + try { + boot_event = withRouterData(app.initialEvents(first)[0], params); + } catch (error) { + // Blocked storage during hydration cannot build the CONNECT auth payload: + // report it and abort this pending attempt without scheduling a retry. + releaseBootstrap(); + currentSocket.wait_connect = false; + setConnectErrors((errors) => [...errors.slice(-9), error]); + currentSocket.disconnect(); + return; + } bootRoute = currentRouteKey(); recordSentStorageValues(boot_event); // Instrumentation hook (installed by reflex-otel): may add a traceparent. @@ -1245,10 +1286,16 @@ export const connect = async ( }; // Ask for a new credential once the wait has passed. A browser runs a timer // over 2**31 - 1 ms with no delay, so the wait is capped. - const scheduleSessionRefresh = ( - wait = Number(window.localStorage.getItem(sessionRefreshStorageKey())) - - Date.now(), - ) => { + const scheduleSessionRefresh = (wait) => { + if (wait === undefined) { + try { + wait = + Number(window.localStorage.getItem(sessionRefreshStorageKey())) - + Date.now(); + } catch { + wait = 0; + } + } window.clearTimeout(sessionTimer); if (wait > 0) { sessionTimer = window.setTimeout( @@ -1344,13 +1391,15 @@ export const connect = async ( current.connect(); }; const key = sessionStorageKey(); - if ( - window.navigator?.locks && - !( + let refreshDue = false; + try { + refreshDue = Number(window.localStorage.getItem(sessionRefreshStorageKey())) > - Date.now() - ) - ) { + Date.now(); + } catch { + // The refresh time is only a hint; fall back to acquiring the lock. + } + if (window.navigator?.locks && !refreshDue) { // Only cold tabs wait. The first socket hydrates while its in-band // credential becomes a cookie; the next tab then shares that cookie. window.navigator.locks @@ -1372,12 +1421,6 @@ export const connect = async ( }; function checkVisibility() { - if (!socket.current) { - // The socket was released without stopWatchingVisibility being called. - // Connecting here would open a socket nothing listens to any more. - document.removeEventListener("visibilitychange", checkVisibility); - return; - } if (document.visibilityState === "visible") { if (!socket.current.connected) { console.log("Socket is disconnected, attempting to reconnect "); @@ -1578,7 +1621,11 @@ export const connect = async ( } }); socket.current.on("new_token", async (new_token) => { - setToken(new_token); + try { + setToken(new_token); + } catch (error) { + setConnectErrors((errors) => [...errors.slice(-9), error]); + } }); socket.current.on(SESSION_REFRESH_EVENT, requestSessionRefresh); socket.current.on("session_token", async (sessionCredential) => { @@ -1626,7 +1673,11 @@ export const connect = async ( } } catch (error) { if (sessionController !== controller) return; - window.localStorage.removeItem(sessionRefreshStorageKey()); + try { + window.localStorage.removeItem(sessionRefreshStorageKey()); + } catch { + // Local storage may be blocked too; keep reporting the error below. + } if (error.status === 403) { // The backend does not trust this page's origin, so a retry gets the // same answer. The socket works without the cookie: release HTTP calls. @@ -1656,12 +1707,15 @@ export const connect = async ( socket.current.on(STATE_MISMATCH_EVENT, handleStateMismatch); + await socket.current.reconnect(); + if (socket.current !== currentSocket) { + return; + } document.addEventListener("visibilitychange", checkVisibility); - // Called by whoever releases the socket: the listener lives on the document, - // so it would otherwise outlive the socket and everything it closes over. - socket.current.stopWatchingVisibility = () => + // Returned to whoever owns the socket ref: the listener lives on the + // document, so it must be removed before the ref is cleared. + return () => document.removeEventListener("visibilitychange", checkVisibility); - await socket.current.reconnect(); }; /** @@ -1757,25 +1811,33 @@ export const hydrateClientStorage = (client_storage) => { } } if (client_storage.local_storage && typeof window !== "undefined") { - for (const state_key in client_storage.local_storage) { - const options = client_storage.local_storage[state_key]; - const local_storage_value = localStorage.getItem( - options.name || state_key, - ); - if (local_storage_value !== null) { - client_storage_values[state_key] = local_storage_value; + try { + for (const state_key in client_storage.local_storage) { + const options = client_storage.local_storage[state_key]; + const local_storage_value = localStorage.getItem( + options.name || state_key, + ); + if (local_storage_value !== null) { + client_storage_values[state_key] = local_storage_value; + } } + } catch (error) { + throw storageBlockedError(error); } } if (client_storage.session_storage && typeof window !== "undefined") { - for (const state_key in client_storage.session_storage) { - const session_options = client_storage.session_storage[state_key]; - const session_storage_value = sessionStorage.getItem( - session_options.name || state_key, - ); - if (session_storage_value != null) { - client_storage_values[state_key] = session_storage_value; + try { + for (const state_key in client_storage.session_storage) { + const session_options = client_storage.session_storage[state_key]; + const session_storage_value = sessionStorage.getItem( + session_options.name || state_key, + ); + if (session_storage_value != null) { + client_storage_values[state_key] = session_storage_value; + } } + } catch (error) { + throw storageBlockedError(error); } } if ( @@ -1911,6 +1973,7 @@ export const useEventLoop = ( client_storage = {}, ) => { const socket = useRef(null); + const stopWatchingVisibility = useRef(null); const location = useLocation(); const navigate = useNavigate(); const paramsR = useParams(); @@ -1950,7 +2013,7 @@ export const useEventLoop = ( !socket.current?.connected ) { // Initialize the websocket connection. - await connect( + const connecting = connect( socket, dispatch, [env.TRANSPORT], @@ -1959,6 +2022,15 @@ export const useEventLoop = ( navigate, params, ); + const currentSocket = socket.current; + const stop = await connecting; + if (stop) { + if (mounted.current && socket.current === currentSocket) { + stopWatchingVisibility.current = stop; + } else { + stop(); + } + } } } catch (error) { // A connection that cannot even be attempted (the browser blocks the @@ -2048,11 +2120,12 @@ export const useEventLoop = ( // Cleanup function. return () => { mounted.current = false; + stopWatchingVisibility.current?.(); + stopWatchingVisibility.current = null; if (socket.current) { socket.current.releaseSessionBootstrap?.(); socket.current.disconnect(); socket.current.off(); - socket.current.stopWatchingVisibility(); socket.current = null; } }; diff --git a/packages/reflex-frontend/tests/state.test.js b/packages/reflex-frontend/tests/state.test.js index 3cd3440e5cf..3112787859d 100644 --- a/packages/reflex-frontend/tests/state.test.js +++ b/packages/reflex-frontend/tests/state.test.js @@ -400,6 +400,31 @@ describe("session", () => { expect(sessionStorage.getItem("token")).toBeNull(); }); + test("getToken labels blocked sessionStorage with storage_blocked", () => { + const denied = new DOMException("blocked", "SecurityError"); + const spy = vi + .spyOn(Storage.prototype, "getItem") + .mockImplementation(() => { + throw denied; + }); + try { + let caught; + try { + getToken(); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(Error); + expect(caught.code).toBe("storage_blocked"); + expect(caught.cause).toBe(denied); + expect(caught.message).toBe( + "Site storage is blocked by the browser. Allow cookies and site data for this site and reload.", + ); + } finally { + spy.mockRestore(); + } + }); + test("isBackendDisabled reads the backend-enabled cookie", () => { expect(isBackendDisabled()).toBe(false); document.cookie = "other=1"; @@ -463,6 +488,31 @@ describe("client storage", () => { test("hydrateClientStorage sends nothing for an app without client storage", () => { expect(hydrateClientStorage({})).toEqual({}); }); + + test("hydrateClientStorage labels blocked localStorage with storage_blocked", () => { + const denied = new DOMException("blocked", "SecurityError"); + const spy = vi + .spyOn(Storage.prototype, "getItem") + .mockImplementation(() => { + throw denied; + }); + try { + let caught; + try { + hydrateClientStorage({ local_storage: { "state.local": {} } }); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(Error); + expect(caught.code).toBe("storage_blocked"); + expect(caught.cause).toBe(denied); + expect(caught.message).toBe( + "Site storage is blocked by the browser. Allow cookies and site data for this site and reload.", + ); + } finally { + spy.mockRestore(); + } + }); }); describe("applyDelta", () => { diff --git a/packages/reflex-frontend/tests/state_connection.test.js b/packages/reflex-frontend/tests/state_connection.test.js index b8d40202803..15b04b233ec 100644 --- a/packages/reflex-frontend/tests/state_connection.test.js +++ b/packages/reflex-frontend/tests/state_connection.test.js @@ -114,8 +114,8 @@ beforeEach(async () => { afterEach(() => { // Release what a mounted loop's cleanup would, so no listener of this test // answers an event dispatched by the next. - for (const socketRef of looseSockets) { - socketRef.current?.stopWatchingVisibility(); + for (const { socketRef, stopWatchingVisibility } of looseSockets) { + stopWatchingVisibility?.(); socketRef.current = null; } vi.restoreAllMocks(); @@ -125,7 +125,7 @@ afterEach(() => { /** Connect a socket the way the mounted event loop does. */ const connectSocket = async () => { const socketRef = { current: null }; - await state.connect( + const stopWatchingVisibility = await state.connect( socketRef, {}, ["websocket"], @@ -134,7 +134,7 @@ const connectSocket = async () => { navigate, params, ); - looseSockets.push(socketRef); + looseSockets.push({ socketRef, stopWatchingVisibility }); return socketRef; }; @@ -280,6 +280,7 @@ test("a mounted event loop reconnects its socket when the page becomes visible", expect(socket.connect).toHaveBeenCalledTimes(1); expect(io).toHaveBeenCalledTimes(1); + expect(socket.stopWatchingVisibility).toBeUndefined(); await loop.unmount(); }); @@ -307,6 +308,59 @@ test("a connection that cannot be attempted is a connection error, not a rejecti expect(rejections).toEqual([]); expect(io).not.toHaveBeenCalled(); - expect(loop.connectErrors().at(-1)).toBe(denied); + const error = loop.connectErrors().at(-1); + expect(error.code).toBe("storage_blocked"); + expect(error.cause).toBe(denied); + expect(error.message).toBe( + "Site storage is blocked by the browser. Allow cookies and site data for this site and reload.", + ); + await loop.unmount(); +}); + +test("an unmounted loop during connect does not leave a visibility listener", async () => { + const added = vi.spyOn(document, "addEventListener"); + const dispatch = {}; + const Probe = () => { + state.useEventLoop(dispatch); + return null; + }; + const container = document.body.appendChild(document.createElement("div")); + const root = createRoot(container); + act(() => { + root.render(createElement(MemoryRouter, null, createElement(Probe))); + }); + act(() => { + root.unmount(); + }); + await Promise.resolve(); + + expect( + added.mock.calls.filter(([type]) => type === "visibilitychange"), + ).toEqual([]); +}); + +test("blocked sessionStorage during new_token records storage_blocked instead of rejecting", async () => { + const loop = await mountEventLoop(); + const denied = new DOMException("blocked", "SecurityError"); + vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { + throw denied; + }); + + const rejections = []; + const record = (reason) => rejections.push(reason); + process.on("unhandledRejection", record); + + await act(async () => { + await loop.socket.trigger("new_token", "next-token"); + }); + process.off("unhandledRejection", record); + + expect(rejections).toEqual([]); + const error = loop.connectErrors().at(-1); + expect(error.code).toBe("storage_blocked"); + expect(error.cause).toBe(denied); + expect(error.message).toBe( + "Site storage is blocked by the browser. Allow cookies and site data for this site and reload.", + ); await loop.unmount(); }); diff --git a/pyi_hashes.json b/pyi_hashes.json index fec0b8f2474..84dc709c31a 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -14,7 +14,7 @@ "packages/reflex-components-core/src/reflex_components_core/base/strict_mode.pyi": "135dd395a27f01be303b3879ece179c1", "packages/reflex-components-core/src/reflex_components_core/core/__init__.pyi": "931b222daf3755f67281b6c4d7155f85", "packages/reflex-components-core/src/reflex_components_core/core/auto_scroll.pyi": "2d83dc211884423496c31d372d3f3734", - "packages/reflex-components-core/src/reflex_components_core/core/banner.pyi": "85ff5f20fc7a59de5544858cfc364cf1", + "packages/reflex-components-core/src/reflex_components_core/core/banner.pyi": "4ce3092a9b14cc2e7080c3069e167091", "packages/reflex-components-core/src/reflex_components_core/core/clipboard.pyi": "21d51b69ab11279e864f7aca9307462f", "packages/reflex-components-core/src/reflex_components_core/core/debounce.pyi": "86b2bea0aeec5334dbb64b3addae91df", "packages/reflex-components-core/src/reflex_components_core/core/helmet.pyi": "a43533eba05dec1ece2602bd64ca0f01", diff --git a/tests/units/compiler/state_js.test.mjs b/tests/units/compiler/state_js.test.mjs index 2b4fdd40757..51e3df46f29 100644 --- a/tests/units/compiler/state_js.test.mjs +++ b/tests/units/compiler/state_js.test.mjs @@ -140,9 +140,14 @@ async function setup({ } this.finishNamespaceConnect = () => { if (typeof this.auth === "function") { + let resolved = false; this.auth((auth) => { + resolved = true; this.auth = auth; }); + if (!resolved) { + return; + } } // Like Manager._packet: encode the auth callback's resolved payload. const frames = this.io.encoder.encode({ @@ -272,6 +277,7 @@ async function setup({ window, localStorage, socket, + appRegistry: imports["$/utils/context-registry"].app, updates, consoleErrors, get connectErrors() { @@ -711,12 +717,52 @@ test("hot reload before the microtask runs prevents speculative setup", async () test("blocked session storage does not throw from speculative setup", async () => { const app = await setup(); + const blocked = new Error("storage blocked"); app.window.sessionStorage.getItem = () => { - throw new Error("storage blocked"); + throw blocked; }; app.flush(); assert.equal(app.sockets.length, 0); - await assert.rejects(app.connect(), /storage blocked/); + await assert.rejects( + app.connect(), + (error) => + error.code === "storage_blocked" && + error.cause === blocked && + error.message === + "Site storage is blocked by the browser. Allow cookies and site data for this site and reload.", + ); +}); + +test("blocked localStorage during delayed bootAuth reports storage_blocked without retrying", async () => { + const app = await setup({ deferNamespaceConnect: true }); + app.flush(); + const blocked = new Error("localStorage blocked"); + app.localStorage.getItem = () => { + throw blocked; + }; + const { hydrateClientStorage, ReflexEvent } = app.module.namespace; + app.appRegistry.initialEvents = () => [ + ReflexEvent("root.hydrate_and_load", { + vars: hydrateClientStorage({ local_storage: { "child.value": {} } }), + }), + ]; + await app.connect(); + const socket = app.socket.current; + assert.equal(socket.namespaceConnects, 0); + + socket.finishNamespaceConnect(); + + assert.equal(socket.namespaceConnects, 0); + assert.equal(socket.disconnects, 1); + assert.equal(app.timers.size, 0); + assert.equal(app.connectErrors.length, 1); + const [error] = app.connectErrors; + assert.equal(error.code, "storage_blocked"); + assert.equal(error.cause, blocked); + assert.equal( + error.message, + "Site storage is blocked by the browser. Allow cookies and site data for this site and reload.", + ); }); test("a caller selecting another transport gets its requested configuration", async () => { diff --git a/tests/units/components/core/test_banner.py b/tests/units/components/core/test_banner.py index 8ea73a93775..a38576f92b6 100644 --- a/tests/units/components/core/test_banner.py +++ b/tests/units/components/core/test_banner.py @@ -63,3 +63,303 @@ def test_connection_toaster_shows_hydration_errors_at_once(): assert hydration_check < hooks.index("(connectErrors.length >= 2)") assert 'id: "hydration-payload-error"' in hooks assert "duration: Infinity" in hooks + + +def test_connection_toaster_shows_storage_blocked_errors_at_once(): + hooks = [str(hook) for hook in ConnectionToaster.create()._get_all_hooks()] + assert hooks == [ + "const connectErrors = useContext(EventLoopContext)[1];", + "const toast = refs['__toast'];", + ( + 'const toast_props = ({ ["description"] : ("Check if server is reachable at "' + '+getBackendURL(env.EVENT).href), ["closeButton"] : true, ' + '["duration"] : 120000, ["id"] : "websocket-error" });' + ), + "const [userDismissed, setUserDismissed] = useState(false);", + "const [waitedForBackend, setWaitedForBackend] = useState(false);", + """(useEffect( +() => { + if (connectErrors.some((error) => error.code === 'hydration_payload_too_large')) { + toast?.error(((connectErrors.length > 0) ? connectErrors[connectErrors.length - 1].message : ''), {id: "hydration-payload-error", closeButton: true, duration: Infinity}); + } else if (((connectErrors.length > 0) && (connectErrors[connectErrors.length - 1].code === 'storage_blocked'))) { + toast?.dismiss("websocket-error"); + toast?.error(((connectErrors.length > 0) ? connectErrors[connectErrors.length - 1].message : ''), {id: "storage-blocked-error", closeButton: true, duration: Infinity}); + } else if ((connectErrors.length >= 2)) { + toast?.dismiss("storage-blocked-error"); + if (!userDismissed) { + toast?.error(("Cannot connect to server: "+((connectErrors.length > 0) ? connectErrors[connectErrors.length - 1].message : '')+"."), {...toast_props, onDismiss: () => setUserDismissed(true)},) + } + } else { + toast?.dismiss("storage-blocked-error"); + toast?.dismiss("websocket-error"); + setUserDismissed(false); // after reconnection reset dismissed state + } +} +, [connectErrors, waitedForBackend]))""", + ] + + +def test_connection_banner_and_modal_handle_storage_blocked_errors(): + expected_message = { + "name": "Fragment", + "props": [], + "children": [ + { + "cond_state": ( + "pyOr(((connectErrors.length > 0) && (connectErrors[connectErrors.length - 1].code === 'storage_blocked')), " + "() => (connectErrors.some((error) => error.code === 'hydration_payload_too_large')))" + ), + "true_value": { + "name": "Fragment", + "props": [], + "children": [ + { + "contents": "((connectErrors.length > 0) ? connectErrors[connectErrors.length - 1].message : '')" + } + ], + }, + "false_value": { + "name": "Fragment", + "props": [], + "children": [ + {"contents": '"Cannot connect to server: "'}, + { + "contents": "((connectErrors.length > 0) ? connectErrors[connectErrors.length - 1].message : '')" + }, + {"contents": '". Check if server is reachable at "'}, + {"contents": "getBackendURL(env.EVENT).href"}, + ], + }, + } + ], + } + + assert ConnectionBanner.create().render() == { + "name": "Fragment", + "props": [], + "children": [ + { + "cond_state": "(connectErrors.length > 0)", + "true_value": { + "name": "Fragment", + "props": [], + "children": [ + { + "name": '"div"', + "props": [ + 'css:({ ["display"] : "flex", ["justifyContent"] : "center", ["backgroundColor"] : "crimson", ["width"] : "100vw", ["padding"] : "5px", ["position"] : "fixed" })' + ], + "children": [ + { + "name": '"span"', + "props": [ + 'css:({ ["color"] : "black", ["fontSize"] : "1.125rem" })' + ], + "children": [expected_message], + } + ], + } + ], + }, + "false_value": {"name": "Fragment", "props": [], "children": []}, + } + ], + } + modal = ConnectionModal.create() + expected_modal_cond = ( + "pyAnd(pyOr(pyOr((connectErrors.length >= 2), " + "() => (((connectErrors.length > 0) && (connectErrors[connectErrors.length - 1].code === 'storage_blocked')))), " + "() => (connectErrors.some((error) => error.code === 'hydration_payload_too_large'))), " + "() => (!(modalDismissed)))" + ) + assert [str(hook) for hook in modal._get_all_hooks()] == [ + "const connectErrors = useContext(EventLoopContext)[1];", + "const [modalDismissed, setModalDismissed] = useState(false);", + ( + "useEffect(() => { if (!(pyOr(pyOr((connectErrors.length >= 2), " + "() => (((connectErrors.length > 0) && (connectErrors[connectErrors.length - 1].code === 'storage_blocked')))), " + "() => (connectErrors.some((error) => error.code === 'hydration_payload_too_large'))))) " + "{ setModalDismissed(false); } }, [connectErrors]);" + ), + ] + assert modal.render() == { + "name": "Fragment", + "props": [], + "children": [ + { + "cond_state": expected_modal_cond, + "true_value": { + "name": "Fragment", + "props": [], + "children": [ + { + "name": '"dialog"', + "props": [ + 'css:({ ["zIndex"] : 9999 })', + f"open:{expected_modal_cond}", + ], + "children": [ + { + "name": '"h2"', + "props": [], + "children": [{"contents": '"Connection Error"'}], + }, + { + "name": '"span"', + "props": [], + "children": [expected_message], + }, + { + "name": '"div"', + "props": ['css:({ ["marginTop"] : "0.75rem" })'], + "children": [ + { + "name": '"button"', + "props": [ + "onClick:() => setModalDismissed(true)", + 'type:"button"', + ], + "children": [{"contents": '"Close"'}], + } + ], + }, + ], + } + ], + }, + "false_value": {"name": "Fragment", "props": [], "children": []}, + } + ], + } + + +def test_connection_modal_shares_dismiss_state_under_auto_memoize(): + from reflex_base.event import EventChain + from reflex_base.plugins import CompileContext, CompilerHooks + from reflex_components_core import el + + from reflex.app import UnevaluatedPage + from reflex.compiler import compiler + from reflex.compiler.plugins import default_page_plugins + + def page_default(): + return ConnectionModal.create() + + ctx = CompileContext( + pages=[UnevaluatedPage(route="/page", component=page_default)], + hooks=CompilerHooks(plugins=default_page_plugins(auto_memoize=True)), + ) + with ctx: + compiled = ctx.compile() + memo_files, _ = compiler.compile_memo_components( + tuple(ctx.auto_memo_components.values()) + ) + bare_tag, cond_tag = (tag for tag, _ in ctx.auto_memo_components) + assert len(memo_files) == 2 + expected_page_code = f""" +import {{{bare_tag}}} from "$/utils/components/{bare_tag}" +import {{Fragment,useContext,useEffect,useState}} from "react" +import env from "$/env.json" +import {{getBackendURL,isTrue,pyAnd,pyOr}} from "$/utils/state" +import {{{cond_tag}}} from "$/utils/components/{cond_tag}" +import {{EventLoopContext}} from "$/utils/context" +import {{jsx}} from "@emotion/react" + + + + + +function Component() {{ +const connectErrors = useContext(EventLoopContext)[1]; +const [modalDismissed, setModalDismissed] = useState(false); +useEffect(() => {{ if (!(pyOr(pyOr((connectErrors.length >= 2), () => (((connectErrors.length > 0) && (connectErrors[connectErrors.length - 1].code === 'storage_blocked')))), () => (connectErrors.some((error) => error.code === 'hydration_payload_too_large'))))) {{ setModalDismissed(false); }} }}, [connectErrors]); + + return ( + jsx(Fragment,{{}},jsx(Fragment,{{}},(pyAnd(pyOr(pyOr((connectErrors.length >= 2), () => (((connectErrors.length > 0) && (connectErrors[connectErrors.length - 1].code === 'storage_blocked')))), () => (connectErrors.some((error) => error.code === 'hydration_payload_too_large'))), () => (!(modalDismissed)))?(jsx(Fragment,{{}},jsx("dialog",{{css:({{ ["zIndex"] : 9999 }}),open:pyAnd(pyOr(pyOr((connectErrors.length >= 2), () => (((connectErrors.length > 0) && (connectErrors[connectErrors.length - 1].code === 'storage_blocked')))), () => (connectErrors.some((error) => error.code === 'hydration_payload_too_large'))), () => (!(modalDismissed)))}},jsx("h2",{{}},"Connection Error"),jsx("span",{{}},jsx(Fragment,{{}},jsx({cond_tag},{{}},jsx(Fragment,{{}},jsx({bare_tag},{{}},)),jsx(Fragment,{{}},"Cannot connect to server: ",jsx({bare_tag},{{}},),". Check if server is reachable at ",getBackendURL(env.EVENT).href)))),jsx("div",{{css:({{ ["marginTop"] : "0.75rem" }})}},jsx("button",{{onClick:() => setModalDismissed(true),type:"button"}},"Close"))))):(jsx(Fragment,{{}},)))),jsx("title",{{}}," | Page"),jsx("meta",{{content:"",property:"og:image"}},)) + ) +}} +Component.displayName = "Component(/page)"; + +export default Component; +""".strip() + assert (compiled["/page"].output_code or "").strip() == expected_page_code + + def _no_args() -> list[object]: + return [] + + def page_custom(): + return ConnectionModal.create( + el.div( + "Custom error", + on_mount=EventChain.create(value=_no_args, args_spec=_no_args), + on_unmount=EventChain.create(value=_no_args, args_spec=_no_args), + ) + ) + + custom_ctx = CompileContext( + pages=[UnevaluatedPage(route="/page", component=page_custom)], + hooks=CompilerHooks(plugins=default_page_plugins(auto_memoize=True)), + ) + with custom_ctx: + custom_compiled = custom_ctx.compile() + custom_memo_files, _ = compiler.compile_memo_components( + tuple(custom_ctx.auto_memo_components.values()) + ) + assert len(custom_memo_files) == 1 + custom_tag = next(iter(custom_ctx.auto_memo_components))[0] + expected_custom_page_code = f""" +import {{{custom_tag}}} from "$/utils/components/{custom_tag}" +import {{Fragment,useContext,useEffect,useState}} from "react" +import {{EventLoopContext}} from "$/utils/context" +import {{isTrue,pyAnd,pyOr}} from "$/utils/state" +import {{jsx}} from "@emotion/react" + + + + + +function Component() {{ +const connectErrors = useContext(EventLoopContext)[1]; +const [modalDismissed, setModalDismissed] = useState(false); +useEffect(() => {{ if (!(pyOr(pyOr((connectErrors.length >= 2), () => (((connectErrors.length > 0) && (connectErrors[connectErrors.length - 1].code === 'storage_blocked')))), () => (connectErrors.some((error) => error.code === 'hydration_payload_too_large'))))) {{ setModalDismissed(false); }} }}, [connectErrors]); + + return ( + jsx(Fragment,{{}},jsx(Fragment,{{}},(pyAnd(pyOr(pyOr((connectErrors.length >= 2), () => (((connectErrors.length > 0) && (connectErrors[connectErrors.length - 1].code === 'storage_blocked')))), () => (connectErrors.some((error) => error.code === 'hydration_payload_too_large'))), () => (!(modalDismissed)))?(jsx(Fragment,{{}},jsx("dialog",{{css:({{ ["zIndex"] : 9999 }}),open:pyAnd(pyOr(pyOr((connectErrors.length >= 2), () => (((connectErrors.length > 0) && (connectErrors[connectErrors.length - 1].code === 'storage_blocked')))), () => (connectErrors.some((error) => error.code === 'hydration_payload_too_large'))), () => (!(modalDismissed)))}},jsx("h2",{{}},"Connection Error"),jsx({custom_tag},{{}},"Custom error"),jsx("div",{{css:({{ ["marginTop"] : "0.75rem" }})}},jsx("button",{{onClick:() => setModalDismissed(true),type:"button"}},"Close"))))):(jsx(Fragment,{{}},)))),jsx("title",{{}}," | Page"),jsx("meta",{{content:"",property:"og:image"}},)) + ) +}} +Component.displayName = "Component(/page)"; + +export default Component; +""".strip() + assert ( + custom_compiled["/page"].output_code or "" + ).strip() == expected_custom_page_code + expected_custom_memo_code = f""" +import {{ReflexEvent,applyEventActions,isTrue,mergeSlotProps}} from "$/utils/state" +import {{Fragment,memo,useEffect}} from "react" +import {{addEvents}} from "$/utils/context" +import {{jsx}} from "@emotion/react" + + + + + + +export const {custom_tag} = /*#__PURE__*/ (() => {{ +const {custom_tag} = memo(({{children, ...rest}}) => {{ +{" "} + useEffect(() => {{ + ((...args) => (addEvents([], args, ({{ }}))))() + return () => {{ + ((...args) => (addEvents([], args, ({{ }}))))() + }} + }}, []); + return( + jsx("div",{{...mergeSlotProps(rest, ({{ }}))}},children) + ) +}}); +{custom_tag}.displayName = "Div"; +return {custom_tag}; +}})(); +""".strip() + assert custom_memo_files[0][1].strip() == expected_custom_memo_code diff --git a/tests/units/reflex_base/constants/test_base.py b/tests/units/reflex_base/constants/test_base.py index 51fc15db3e3..be0fa6b77d6 100644 --- a/tests/units/reflex_base/constants/test_base.py +++ b/tests/units/reflex_base/constants/test_base.py @@ -13,11 +13,12 @@ def test_literal_env_matches_env_enum(): assert set(get_args(LITERAL_ENV)) == {env.value for env in Env} -def test_web_template_dir_prefers_the_embedded_copy(tmp_path: Path): +def test_web_template_dir_uses_the_embedded_copy(tmp_path: Path): """A built distribution carries the frontend inside the package.""" root_dir = tmp_path / "site-packages" / "reflex_base" embedded = root_dir / ".templates" / "web" - embedded.mkdir(parents=True) + (embedded / "utils").mkdir(parents=True) + (embedded / "utils" / "state.js").write_text("// state") assert _web_template_dir(root_dir) == embedded @@ -30,6 +31,32 @@ def test_web_template_dir_falls_back_to_the_checkout(tmp_path: Path): ) +def test_web_template_dir_prefers_checkout_over_leftover_embedded(tmp_path: Path): + """A leftover or stale `.templates/web` in a checkout never shadows the package.""" + root_dir = tmp_path / "packages" / "reflex-base" / "src" / "reflex_base" + embedded = root_dir / ".templates" / "web" + (embedded / "utils").mkdir(parents=True) + (embedded / ".DS_Store").write_text("") + (embedded / "utils" / "state.js").write_text("// stale") + + checkout = tmp_path / "packages" / "reflex-frontend" / "src" + (checkout / "utils").mkdir(parents=True) + (checkout / "utils" / "state.js").write_text("// live") + + assert _web_template_dir(root_dir) == checkout + + +def test_web_template_dir_ignores_incomplete_embedded_copy(tmp_path: Path): + """An untracked directory like `.templates/web/.DS_Store` is not treated as embedded.""" + root_dir = tmp_path / "packages" / "reflex-base" / "src" / "reflex_base" + embedded = root_dir / ".templates" / "web" + embedded.mkdir(parents=True) + (embedded / ".DS_Store").write_text("") + assert ( + _web_template_dir(root_dir) == tmp_path / "packages" / "reflex-frontend" / "src" + ) + + def test_web_template_holds_the_frontend(): """Whichever layout is installed, the template resolves to real files.""" assert (Templates.Dirs.WEB_TEMPLATE / "utils" / "state.js").is_file() diff --git a/tests/units/test_app.py b/tests/units/test_app.py index fe7f06a3f4d..da7ed3cc0c5 100644 --- a/tests/units/test_app.py +++ b/tests/units/test_app.py @@ -5636,16 +5636,25 @@ def test_client_error_constants_match_frontend(): Nothing at runtime keeps the two definitions in sync, so pin them here. """ state_js = (Templates.Dirs.WEB_TEMPLATE / "utils/state.js").read_text() + declarations = dict( + re.findall(r'^const ([A-Z0-9_]+) = "([^"\n]+)";$', state_js, re.MULTILINE) + ) + assert declarations["CLIENT_ERROR_EVENT"] == constants.SocketEvent.CLIENT_ERROR + assert ( + declarations["ERROR_TYPE_DISPATCH_MISSING"] + == constants.ClientErrorType.DISPATCH_MISSING + ) assert ( - f'const CLIENT_ERROR_EVENT = "{constants.SocketEvent.CLIENT_ERROR}"' in state_js + declarations["ERROR_TYPE_STATE_UPDATE"] + == constants.ClientErrorType.STATE_UPDATE ) assert ( - f'const ERROR_TYPE_DISPATCH_MISSING = "{constants.ClientErrorType.DISPATCH_MISSING}"' - in state_js + declarations["ERROR_TYPE_HYDRATION_PAYLOAD_TOO_LARGE"] + == constants.ClientErrorType.HYDRATION_PAYLOAD_TOO_LARGE ) assert ( - f'const ERROR_TYPE_STATE_UPDATE = "{constants.ClientErrorType.STATE_UPDATE}"' - in state_js + declarations["ERROR_TYPE_STORAGE_BLOCKED"] + == constants.ClientErrorType.STORAGE_BLOCKED ) diff --git a/tests/units/test_build_config.py b/tests/units/test_build_config.py index cb2ae44c8f3..29fe629b2ac 100644 --- a/tests/units/test_build_config.py +++ b/tests/units/test_build_config.py @@ -463,6 +463,19 @@ def test_reflex_base_refuses_to_build_without_a_frontend( ) +def test_reflex_base_refuses_to_build_with_incomplete_embedded_frontend( + reflex_base_checkout: Path, tmp_path: Path +): + """A leftover `.templates/web/.DS_Store` does not count as an sdist's copy.""" + frontend = reflex_base_checkout.parent / "reflex-frontend" + shutil.rmtree(frontend) + leftover = reflex_base_checkout / "src" / WEB_TEMPLATE + leftover.mkdir(parents=True) + (leftover / ".DS_Store").write_text("") + with pytest.raises(FileNotFoundError): + build_wheel(reflex_base_checkout, tmp_path / "dist") + + def test_frontend_package_is_where_the_build_hook_looks(): """The hook and the checkout fallback both assume this location.""" frontend = REFLEX_BASE.parent / "reflex-frontend"