From 46c04135a51e9f4d41d2807129f632bc448f4834 Mon Sep 17 00:00:00 2001 From: will Date: Fri, 16 Oct 2026 19:41:36 -0400 Subject: [PATCH 1/2] fix(web): share the app registry with managed auth cleanup --- apps/web/src/AppRoot.tsx | 5 +- apps/web/src/main.auth.test.tsx | 128 ++++++++++++++++++++++++++++++++ apps/web/src/main.tsx | 14 ++-- 3 files changed, 139 insertions(+), 8 deletions(-) create mode 100644 apps/web/src/main.auth.test.tsx diff --git a/apps/web/src/AppRoot.tsx b/apps/web/src/AppRoot.tsx index df610d8e1ab8f..a89764939c51c 100644 --- a/apps/web/src/AppRoot.tsx +++ b/apps/web/src/AppRoot.tsx @@ -3,7 +3,6 @@ import { RouterProvider } from "@tanstack/react-router"; import { BrowserProfileReporter } from "./browser/BrowserProfileReporter"; import { ElectronBrowserHost } from "./browser/ElectronBrowserHost"; import { QuitHoldOverlay } from "./components/QuitHoldOverlay"; -import { AppAtomRegistryProvider } from "./rpc/atomRegistry"; import type { AppRouter } from "./router"; /** @@ -13,11 +12,11 @@ import type { AppRouter } from "./router"; */ export function AppRoot({ router }: { readonly router: AppRouter }) { return ( - + <> - + ); } diff --git a/apps/web/src/main.auth.test.tsx b/apps/web/src/main.auth.test.tsx new file mode 100644 index 0000000000000..f2b485449d343 --- /dev/null +++ b/apps/web/src/main.auth.test.tsx @@ -0,0 +1,128 @@ +// @vitest-environment jsdom + +import { useAtomValue } from "@effect/atom-react"; +import { act, createElement, type PropsWithChildren, useState } from "react"; +import { afterEach, expect, it, vi } from "vite-plus/test"; + +import { environmentCatalog } from "./connection/catalog"; + +const fixture = vi.hoisted(() => { + let completeCleanup = () => {}; + const cleanupFinished = new Promise((resolve) => { + completeCleanup = resolve; + }); + return { signOut: () => {}, cleanupFinished, completeCleanup }; +}); + +vi.mock("@clerk/react", async () => { + const { createContext, useContext } = await import("react"); + const AuthContext = createContext({ isSignedIn: false }); + const getToken = async () => null; + return { + ClerkProvider: ({ children }: PropsWithChildren) => { + const [isSignedIn, setSignedIn] = useState(true); + fixture.signOut = () => setSignedIn(false); + return createElement(AuthContext.Provider, { value: { isSignedIn } }, children); + }, + useAuth: () => { + const { isSignedIn } = useContext(AuthContext); + return { isLoaded: true, isSignedIn, userId: isSignedIn ? "demo-account" : null, getToken }; + }, + }; +}); + +vi.mock("./connection/catalog", async () => { + const { Atom, AsyncResult } = await import("effect/reactivity"); + const catalogValueAtom = Atom.make({ + entries: new Map([ + ["relay-demo", true], + ["independent-direct", false], + ]), + }); + return { + environmentCatalog: { + catalogValueAtom, + // Keep registry selection real. This in-memory catalog isolates bootstrap + // ownership from network and persistence; registry.test covers route removal. + removeRelayEnvironments: { + label: "test:remove-relay-environments", + run: async (registry: import("effect/reactivity/AtomRegistry").AtomRegistry) => { + registry.set(catalogValueAtom, { + entries: new Map( + [...registry.get(catalogValueAtom).entries].filter(([, relay]) => !relay), + ), + }); + fixture.completeCleanup(); + return AsyncResult.success(undefined); + }, + }, + }, + }; +}); + +function CatalogView() { + const { entries } = useAtomValue(environmentCatalog.catalogValueAtom); + return createElement("div", null, [...entries.keys()].join(", ")); +} + +vi.mock("@tanstack/react-router", async (importOriginal) => ({ + ...(await importOriginal()), + RouterProvider: () => createElement(CatalogView), +})); +vi.mock("./router", () => ({ getRouter: () => ({ load: async () => {} }) })); +vi.mock("./env", () => ({ isElectron: false })); +vi.mock("./providerAuthDelivery", () => ({ prepareProviderAuthDelivery: () => {} })); +vi.mock("./cloud/publicConfig", () => ({ + hasCloudPublicConfig: () => true, + resolveRelayClerkTokenOptions: () => ({}), +})); +vi.mock("./lib/runtime", () => ({ + runtime: { runPromiseExit: async () => ({ _tag: "Success", value: undefined }) }, +})); +vi.mock("./browser/BrowserProfileReporter", () => ({ BrowserProfileReporter: () => null })); +vi.mock("./browser/ElectronBrowserHost", () => ({ ElectronBrowserHost: () => null })); +vi.mock("./components/QuitHoldOverlay", () => ({ QuitHoldOverlay: () => null })); + +// Retain the actual renderer while capturing its root for teardown. +let unmount: (() => void) | undefined; +vi.mock("react-dom/client", async (importOriginal) => { + const actual = await importOriginal(); + const createRoot: typeof actual.createRoot = (...args) => { + const root = actual.createRoot(...args); + unmount = () => root.unmount(); + return root; + }; + return { ...actual, default: { ...actual, createRoot }, createRoot }; +}); + +afterEach(async () => { + await act(() => unmount?.()); + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + document.body.replaceChildren(); +}); + +it("sign-out removes Relay environments from the catalog rendered by the app", async () => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", "pk_test_synthetic"); + const container = document.createElement("div"); + container.id = "root"; + document.body.append(container); + + // Run the real entry point, lazy auth shell, ManagedRelayAuthProvider, AppRoot, + // RegistryContext and useAtomCommand. Neither registry nor command hook is mocked. + await act(async () => { + const { startup } = await import("./main"); + await startup; + }); + expect(container.textContent).toContain("relay-demo"); + expect(container.textContent).toContain("independent-direct"); + + await act(() => fixture.signOut()); + await act(async () => { + await fixture.cleanupFinished; + }); + + expect(container.textContent).not.toContain("relay-demo"); + expect(container.textContent).toContain("independent-direct"); +}); diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index e2dfab60d81a0..fa410a1b57939 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -13,6 +13,7 @@ import { syncDocumentWindowControlsOverlayClass, } from "./lib/windowControlsOverlay"; import { AppRoot } from "./AppRoot"; +import { AppAtomRegistryProvider } from "./rpc/atomRegistry"; import { clearChunkReloadGuard, reloadOnceForChunkLoadError } from "./lib/chunkReloadGuard"; prepareProviderAuthDelivery(); @@ -62,13 +63,16 @@ export const startup = Promise.all([ // the lazy component and surfaces through the route error boundary. if (reloadScheduled) return; if (!chunkLoadFailed) clearChunkReloadGuard(); + // Auth cleanup must update the same connection registry as the routed UI. ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( - {ManagedAuthShell && clerkPublishableKey ? ( - {app} - ) : ( - app - )} + + {ManagedAuthShell && clerkPublishableKey ? ( + {app} + ) : ( + app + )} + , ); }) From f6d7d750b3e656e58888b0df046f7ab17028df82 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 08:56:18 +0000 Subject: [PATCH 2/2] fix(web): share the app registry with managed auth cleanup --- apps/web/src/cloud/managedAuth.test.ts | 122 ++++++++++++++++++++--- apps/web/src/main.auth.test.tsx | 128 ------------------------- apps/web/src/main.tsx | 1 - 3 files changed, 110 insertions(+), 141 deletions(-) delete mode 100644 apps/web/src/main.auth.test.tsx diff --git a/apps/web/src/cloud/managedAuth.test.ts b/apps/web/src/cloud/managedAuth.test.ts index 63001bdb184da..b77ef69746d65 100644 --- a/apps/web/src/cloud/managedAuth.test.ts +++ b/apps/web/src/cloud/managedAuth.test.ts @@ -1,31 +1,105 @@ +// @vitest-environment jsdom + +import { useAtomValue } from "@effect/atom-react"; import { managedRelaySessionAtom, setManagedRelaySession } from "@t3tools/client-runtime/relay"; import * as Effect from "effect/Effect"; +import { act, createElement, type PropsWithChildren, useState } from "react"; +import ReactDOM, { type Root } from "react-dom/client"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; +import { environmentCatalog } from "../connection/catalog"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { activateManagedRelayAuthentication, deactivateManagedRelayAuthentication, } from "./managedAuth"; -vi.mock("@clerk/react", () => ({ - useAuth: vi.fn(), -})); +const fixture = vi.hoisted(() => { + let completeCleanup = () => {}; + const cleanupFinished = new Promise((resolve) => { + completeCleanup = resolve; + }); + return { signOut: () => {}, cleanupFinished, completeCleanup }; +}); + +vi.mock("@clerk/react", async () => { + const { createContext, useContext } = await import("react"); + const AuthContext = createContext({ isSignedIn: false }); + const getToken = async () => null; + return { + ClerkProvider: ({ children }: PropsWithChildren) => { + const [isSignedIn, setSignedIn] = useState(true); + fixture.signOut = () => setSignedIn(false); + return createElement(AuthContext.Provider, { value: { isSignedIn } }, children); + }, + useAuth: () => { + const { isSignedIn } = useContext(AuthContext); + return { isLoaded: true, isSignedIn, userId: isSignedIn ? "demo-account" : null, getToken }; + }, + }; +}); + +vi.mock("../connection/catalog", async () => { + const { Atom, AsyncResult } = await import("effect/reactivity"); + const catalogValueAtom = Atom.make({ + entries: new Map([ + ["relay-demo", true], + ["independent-direct", false], + ]), + }); + return { + environmentCatalog: { + catalogValueAtom, + // Each real registry owns its catalog state; registry.test covers route-removal policy. + removeRelayEnvironments: { + label: "test:remove-relay-environments", + run: async (registry: import("effect/reactivity/AtomRegistry").AtomRegistry) => { + registry.set(catalogValueAtom, { + entries: new Map( + [...registry.get(catalogValueAtom).entries].filter(([, relay]) => !relay), + ), + }); + fixture.completeCleanup(); + return AsyncResult.success(undefined); + }, + }, + }, + }; +}); + +function CatalogView() { + const { entries } = useAtomValue(environmentCatalog.catalogValueAtom); + return createElement("div", null, [...entries.keys()].join(", ")); +} +vi.mock("@tanstack/react-router", async (importOriginal) => ({ + ...(await importOriginal()), + RouterProvider: () => createElement(CatalogView), +})); +vi.mock("../router", () => ({ getRouter: () => ({ load: async () => {} }) })); +vi.mock("../env", () => ({ isElectron: false })); +vi.mock("../providerAuthDelivery", () => ({ prepareProviderAuthDelivery: () => {} })); +vi.mock("./publicConfig", () => ({ + hasCloudPublicConfig: () => true, + resolveRelayClerkTokenOptions: () => ({}), +})); vi.mock("../lib/runtime", () => ({ - runtime: { - runPromiseExit: vi.fn(), - }, + runtime: { runPromiseExit: async () => ({ _tag: "Success", value: undefined }) }, })); +vi.mock("../browser/BrowserProfileReporter", () => ({ BrowserProfileReporter: () => null })); +vi.mock("../browser/ElectronBrowserHost", () => ({ ElectronBrowserHost: () => null })); +vi.mock("../components/QuitHoldOverlay", () => ({ QuitHoldOverlay: () => null })); -vi.mock("../connection/catalog", () => ({ - environmentCatalog: { - removeRelayEnvironments: {}, - }, -})); +let root: Root | undefined; -afterEach(() => { +afterEach(async () => { + await act(() => root?.unmount()); + root = undefined; deactivateManagedRelayAuthentication(); + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + document.body.replaceChildren(); }); describe("managed relay authentication", () => { @@ -55,4 +129,28 @@ describe("managed relay authentication", () => { expect(appAtomRegistry.get(managedRelaySessionAtom)?.accountId).toBe("account-2"); }); + + it("sign-out removes Relay environments from the catalog rendered by the app", async () => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", "pk_test_synthetic"); + const container = document.createElement("div"); + container.id = "root"; + document.body.append(container); + + const createRoot = ReactDOM.createRoot; + vi.spyOn(ReactDOM, "createRoot").mockImplementation((...args) => (root = createRoot(...args))); + // Boot the production provider tree so auth and routed UI must select the same registry. + await act(async () => { + const { startup } = await import("../main"); + await startup; + }); + expect(container.textContent).toBe("relay-demo, independent-direct"); + + await act(() => fixture.signOut()); + await act(async () => { + await fixture.cleanupFinished; + }); + + expect(container.textContent).toBe("independent-direct"); + }); }); diff --git a/apps/web/src/main.auth.test.tsx b/apps/web/src/main.auth.test.tsx deleted file mode 100644 index f2b485449d343..0000000000000 --- a/apps/web/src/main.auth.test.tsx +++ /dev/null @@ -1,128 +0,0 @@ -// @vitest-environment jsdom - -import { useAtomValue } from "@effect/atom-react"; -import { act, createElement, type PropsWithChildren, useState } from "react"; -import { afterEach, expect, it, vi } from "vite-plus/test"; - -import { environmentCatalog } from "./connection/catalog"; - -const fixture = vi.hoisted(() => { - let completeCleanup = () => {}; - const cleanupFinished = new Promise((resolve) => { - completeCleanup = resolve; - }); - return { signOut: () => {}, cleanupFinished, completeCleanup }; -}); - -vi.mock("@clerk/react", async () => { - const { createContext, useContext } = await import("react"); - const AuthContext = createContext({ isSignedIn: false }); - const getToken = async () => null; - return { - ClerkProvider: ({ children }: PropsWithChildren) => { - const [isSignedIn, setSignedIn] = useState(true); - fixture.signOut = () => setSignedIn(false); - return createElement(AuthContext.Provider, { value: { isSignedIn } }, children); - }, - useAuth: () => { - const { isSignedIn } = useContext(AuthContext); - return { isLoaded: true, isSignedIn, userId: isSignedIn ? "demo-account" : null, getToken }; - }, - }; -}); - -vi.mock("./connection/catalog", async () => { - const { Atom, AsyncResult } = await import("effect/reactivity"); - const catalogValueAtom = Atom.make({ - entries: new Map([ - ["relay-demo", true], - ["independent-direct", false], - ]), - }); - return { - environmentCatalog: { - catalogValueAtom, - // Keep registry selection real. This in-memory catalog isolates bootstrap - // ownership from network and persistence; registry.test covers route removal. - removeRelayEnvironments: { - label: "test:remove-relay-environments", - run: async (registry: import("effect/reactivity/AtomRegistry").AtomRegistry) => { - registry.set(catalogValueAtom, { - entries: new Map( - [...registry.get(catalogValueAtom).entries].filter(([, relay]) => !relay), - ), - }); - fixture.completeCleanup(); - return AsyncResult.success(undefined); - }, - }, - }, - }; -}); - -function CatalogView() { - const { entries } = useAtomValue(environmentCatalog.catalogValueAtom); - return createElement("div", null, [...entries.keys()].join(", ")); -} - -vi.mock("@tanstack/react-router", async (importOriginal) => ({ - ...(await importOriginal()), - RouterProvider: () => createElement(CatalogView), -})); -vi.mock("./router", () => ({ getRouter: () => ({ load: async () => {} }) })); -vi.mock("./env", () => ({ isElectron: false })); -vi.mock("./providerAuthDelivery", () => ({ prepareProviderAuthDelivery: () => {} })); -vi.mock("./cloud/publicConfig", () => ({ - hasCloudPublicConfig: () => true, - resolveRelayClerkTokenOptions: () => ({}), -})); -vi.mock("./lib/runtime", () => ({ - runtime: { runPromiseExit: async () => ({ _tag: "Success", value: undefined }) }, -})); -vi.mock("./browser/BrowserProfileReporter", () => ({ BrowserProfileReporter: () => null })); -vi.mock("./browser/ElectronBrowserHost", () => ({ ElectronBrowserHost: () => null })); -vi.mock("./components/QuitHoldOverlay", () => ({ QuitHoldOverlay: () => null })); - -// Retain the actual renderer while capturing its root for teardown. -let unmount: (() => void) | undefined; -vi.mock("react-dom/client", async (importOriginal) => { - const actual = await importOriginal(); - const createRoot: typeof actual.createRoot = (...args) => { - const root = actual.createRoot(...args); - unmount = () => root.unmount(); - return root; - }; - return { ...actual, default: { ...actual, createRoot }, createRoot }; -}); - -afterEach(async () => { - await act(() => unmount?.()); - vi.unstubAllEnvs(); - vi.unstubAllGlobals(); - document.body.replaceChildren(); -}); - -it("sign-out removes Relay environments from the catalog rendered by the app", async () => { - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); - vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", "pk_test_synthetic"); - const container = document.createElement("div"); - container.id = "root"; - document.body.append(container); - - // Run the real entry point, lazy auth shell, ManagedRelayAuthProvider, AppRoot, - // RegistryContext and useAtomCommand. Neither registry nor command hook is mocked. - await act(async () => { - const { startup } = await import("./main"); - await startup; - }); - expect(container.textContent).toContain("relay-demo"); - expect(container.textContent).toContain("independent-direct"); - - await act(() => fixture.signOut()); - await act(async () => { - await fixture.cleanupFinished; - }); - - expect(container.textContent).not.toContain("relay-demo"); - expect(container.textContent).toContain("independent-direct"); -}); diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index fa410a1b57939..2d2184a0873dc 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -63,7 +63,6 @@ export const startup = Promise.all([ // the lazy component and surfaces through the route error boundary. if (reloadScheduled) return; if (!chunkLoadFailed) clearChunkReloadGuard(); - // Auth cleanup must update the same connection registry as the routed UI. ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(