diff --git a/apps/app/src/components/dialogs/ProjectPathDialog.test.tsx b/apps/app/src/components/dialogs/ProjectPathDialog.test.tsx index 96a17ae80c2..66f2923aaf2 100644 --- a/apps/app/src/components/dialogs/ProjectPathDialog.test.tsx +++ b/apps/app/src/components/dialogs/ProjectPathDialog.test.tsx @@ -92,7 +92,7 @@ describe("ProjectPathDialog machine selection", () => { ); }); - it("preserves the direct single-machine folder flow", () => { + it("preserves the direct single-machine folder flow", async () => { const onSubmit = vi.fn(); render( { expect(screen.queryByRole("button", { name: "Machine" })).toBeNull(); fireEvent.click( - screen.getByRole("button", { name: "Choose folder on host_atum" }), + await screen.findByRole("button", { name: "Choose folder on host_atum" }), ); fireEvent.click(screen.getByRole("button", { name: "Add project" })); diff --git a/apps/app/src/components/secondary-panel/FilePreview.test.tsx b/apps/app/src/components/secondary-panel/FilePreview.test.tsx index 8ee33f828f5..c0e91981150 100644 --- a/apps/app/src/components/secondary-panel/FilePreview.test.tsx +++ b/apps/app/src/components/secondary-panel/FilePreview.test.tsx @@ -1074,7 +1074,7 @@ describe("FilePreview", () => { expect(screen.getByRole("alert").textContent).toBe("Failed to load file"); }); - it("renders .htm files with the existing Preview and Raw controls", () => { + it("renders .htm files with the existing Preview and Raw controls", async () => { const path = "reports/report.HTM"; const url = "/preview/reports/report.HTM"; const view = render( @@ -1104,6 +1104,7 @@ describe("FilePreview", () => { expect( screen.getByRole("button", { name: "Raw" }).getAttribute("aria-pressed"), ).toBe("true"); + await settleLazyModules(); expect( view.container.querySelector("diffs-container")?.shadowRoot?.textContent, ).toBe("

Report

"); diff --git a/apps/app/src/lib/define-split.test.tsx b/apps/app/src/lib/define-split.test.tsx index f705ecf475c..7156f9ff9f1 100644 --- a/apps/app/src/lib/define-split.test.tsx +++ b/apps/app/src/lib/define-split.test.tsx @@ -12,6 +12,9 @@ import { afterEach, expect, it, vi } from "vitest"; import { downloadSplit } from "./split-prefetch"; import { defineSplit } from "./define-split"; +vi.unmock("react"); +vi.unmock("./define-split"); + afterEach(() => { cleanup(); vi.restoreAllMocks(); diff --git a/apps/app/src/test/lazy-modules.test.tsx b/apps/app/src/test/lazy-modules.test.tsx index e35d5b78aa9..b87faa01336 100644 --- a/apps/app/src/test/lazy-modules.test.tsx +++ b/apps/app/src/test/lazy-modules.test.tsx @@ -2,7 +2,8 @@ import { cleanup, render, screen } from "@testing-library/react"; import { lazy, Suspense, type ComponentType } from "react"; -import { afterEach, expect, it, vi } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { defineSplit } from "@/lib/define-split"; import { settleLazyModules } from "./lazy-modules"; afterEach(cleanup); @@ -80,3 +81,63 @@ it("lets findBy wait for an import that starts a microtask after render and outl expect(await screen.findByText("Slow")).toBeTruthy(); }); + +const CachedSplit = defineSplit<{ label: string }>({ + id: "lazy-modules-test-cached", + load: () => + trackedImport(({ label }: { label: string }) =>

{label}

, "./Cached"), + loading: () =>

Loading cached

, + tier: "intent", +}); + +const PreparedSplit = defineSplit<{ label: string }>({ + id: "lazy-modules-test-prepared", + load: () => + trackedImport( + ({ label }: { label: string }) =>

{label}

, + "./Prepared", + ), + loading: () =>

Loading prepared

, + tier: "intent", +}); + +const CachedLazy = lazy(() => + trackedImport({ default: () =>

Lazy ready

}, "./CachedLazy"), +); + +await PreparedSplit.preload(); + +describe("modules loaded before the current test", { shuffle: false }, () => { + it("loads a split and a lazy component in one test", async () => { + render(); + render( + Loading lazy

}> + +
, + ); + expect(await screen.findByText("First")).toBeTruthy(); + expect(await screen.findByText("Lazy ready")).toBeTruthy(); + render(); + expect(screen.getByText("Same test")).toBeTruthy(); + }); + + it("holds an already-loaded split and lazy component until this test settles", async () => { + render(); + render( + Loading lazy

}> + +
, + ); + expect(screen.getByText("Loading cached")).toBeTruthy(); + expect(screen.getByText("Loading lazy")).toBeTruthy(); + + await settleLazyModules(); + expect(screen.getByText("Second")).toBeTruthy(); + expect(screen.getByText("Lazy ready")).toBeTruthy(); + }); + + it("renders a split the file preloaded during collection immediately", () => { + render(); + expect(screen.getByText("Prepared")).toBeTruthy(); + }); +}); diff --git a/apps/app/src/test/lazy-modules.ts b/apps/app/src/test/lazy-modules.ts index 602d3328fc3..e0502385215 100644 --- a/apps/app/src/test/lazy-modules.ts +++ b/apps/app/src/test/lazy-modules.ts @@ -1,4 +1,7 @@ import { setImmediate as realSetImmediate } from "node:timers"; +import type * as React from "react"; +import type { ComponentType } from "react"; +import { afterEach, beforeEach } from "vitest"; interface HeldImport { specifier: string; @@ -10,6 +13,11 @@ interface LazyImportState { held: HeldImport[]; inFlight: Map, string>; unsettled: string[]; + started: number; + generation: number; + collecting: boolean; + prepared: Set; + renderGates: Map; } const SETTLING_WRAPPER = Symbol.for("bb.settleLazyModulesBeforeWaiting"); @@ -28,12 +36,18 @@ function lazyImportState(): LazyImportState { held: [], inFlight: new Map(), unsettled: [], + started: 0, + generation: 0, + collecting: true, + prepared: new Set(), + renderGates: new Map(), }; return globalThis.__bbLazyImportState; } function trackLazyImport(load: Promise, specifier: string): Promise { const state = lazyImportState(); + state.started += 1; let loaded = load; if (state.holding) { let release = () => {}; @@ -52,6 +66,44 @@ function trackLazyImport(load: Promise, specifier: string): Promise { return loaded; } +function lazyModuleGeneration(): number { + return lazyImportState().generation; +} + +function gatedLazyComponent

( + key: unknown, + specifier: string, + loadedGeneration: number, + View: ComponentType

, + lazy: typeof React.lazy, +): React.ElementType

{ + const state = lazyImportState(); + const existing = state.renderGates.get(key); + if (existing !== undefined) return existing as React.ElementType

; + const chosen: React.ElementType

= + state.holding && + loadedGeneration < state.generation && + !state.prepared.has(key) + ? (() => { + const gate = trackLazyImport(Promise.resolve(), specifier); + return lazy(() => gate.then(() => ({ default: View }))); + })() + : View; + state.renderGates.set(key, chosen as React.ElementType); + return chosen; +} + +function beginLazyModuleTestFile(): void { + const state = lazyImportState(); + state.collecting = true; + state.prepared.clear(); +} + +export function prepareLazyModuleForFile(key: string): void { + const state = lazyImportState(); + if (state.collecting) state.prepared.add(key); +} + function releaseHeldImports(state: LazyImportState): void { for (const held of state.held.splice(0)) held.release(); } @@ -66,12 +118,15 @@ async function reactAct(run: () => Promise): Promise { } async function settleTrackedImports(state: LazyImportState): Promise { + let started: number; do { + started = state.started; await reactAct(async () => { await Promise.all([...state.inFlight.keys()]); await nextMacrotask(); }); - } while (state.inFlight.size > 0); + await nextMacrotask(); + } while (state.inFlight.size > 0 || state.started !== started); } async function whileImportsFlow(run: () => Promise): Promise { @@ -103,11 +158,11 @@ export async function settleLazyModules( }); } -export function installLazyImportTracking(): void { +function installLazyImportTracking(): void { globalThis.__bbTrackLazyImport = trackLazyImport; } -export async function settleLazyModulesBeforeWaiting(): Promise { +async function settleLazyModulesBeforeWaiting(): Promise { const { configure, getConfig } = await import("@testing-library/react"); const { asyncWrapper } = getConfig(); if (Reflect.get(asyncWrapper, SETTLING_WRAPPER) === true) return; @@ -121,10 +176,13 @@ export async function settleLazyModulesBeforeWaiting(): Promise { configure({ asyncWrapper: settlingWrapper }); } -export function holdLazyImports(): void { +function holdLazyImports(): void { const state = lazyImportState(); state.unsettled = []; state.inFlight.clear(); + state.renderGates.clear(); + state.generation += 1; + state.collecting = false; state.holding = true; } @@ -138,14 +196,91 @@ function describeUnsettled(state: LazyImportState): string[] { ]; } -export function releaseLazyImports(): void { +function releaseLazyImports(): void { const state = lazyImportState(); state.holding = false; state.unsettled = describeUnsettled(state); releaseHeldImports(state); } -export function unsettledLazyImports(): readonly string[] { +function unsettledLazyImports(): readonly string[] { const state = lazyImportState(); return state.holding ? describeUnsettled(state) : state.unsettled; } + +let reactModule: typeof React | undefined; + +function loadedReact(): typeof React { + if (reactModule === undefined) { + throw new Error( + "gateLoadedComponent rendered before installLazyModuleHold() loaded React", + ); + } + return reactModule; +} + +const UNSETTLED_HINT = + "A lazy import resolves when the test awaits settleLazyModules() from @/test/lazy-modules or a Testing Library findBy/waitFor; synchronous assertions after the render or interaction that starts it see the loading state."; + +export function installLazyModuleHold(): void { + installLazyImportTracking(); + beginLazyModuleTestFile(); + beforeEach(async (context) => { + reactModule ??= await import("react"); + await settleLazyModulesBeforeWaiting(); + holdLazyImports(); + context.onTestFailed(({ task }) => { + const unsettled = unsettledLazyImports(); + const [error] = task.result?.errors ?? []; + if (unsettled.length === 0 || error === undefined) return; + error.message += `\n\nLazy imports had not settled when this test failed: ${unsettled.join(", ")}. ${UNSETTLED_HINT}`; + }); + }); + afterEach(() => { + releaseLazyImports(); + }); +} + +export function gateLoadedComponent

( + key: string, + View: ComponentType

, +): ComponentType

{ + const loadedIn = lazyModuleGeneration(); + function GatedLoadedComponent(props: P) { + const react = loadedReact(); + const Gated = gatedLazyComponent(key, key, loadedIn, View, react.lazy); + return react.createElement(Gated, props); + } + return GatedLoadedComponent; +} + +export function gateReactLazy(react: R): R { + reactModule = react; + const lazy: typeof react.lazy = (load) => { + let resolvedIn: number | null = null; + const Inner: React.ElementType = react.lazy(() => + load().then((module) => { + resolvedIn ??= lazyModuleGeneration(); + return module; + }), + ); + function LazyContent(props: object) { + return react.createElement(Inner, props); + } + function GatedLazy(props: object) { + const View = + resolvedIn === null + ? LazyContent + : gatedLazyComponent( + load, + "React.lazy", + resolvedIn, + LazyContent, + react.lazy, + ); + return react.createElement(View, props); + } + return GatedLazy as never; + }; + return { ...react, lazy, default: { ...react, lazy } }; +} diff --git a/apps/app/src/test/setup.ts b/apps/app/src/test/setup.ts index a68017bec5e..d62a2ee8214 100644 --- a/apps/app/src/test/setup.ts +++ b/apps/app/src/test/setup.ts @@ -1,30 +1,45 @@ /// import "@bb/shared-ui/icon-extended"; -import { afterEach, beforeEach } from "vitest"; -import { - holdLazyImports, - installLazyImportTracking, - releaseLazyImports, - settleLazyModulesBeforeWaiting, - unsettledLazyImports, -} from "./lazy-modules"; - -installLazyImportTracking(); - -beforeEach(async (context) => { - await settleLazyModulesBeforeWaiting(); - holdLazyImports(); - context.onTestFailed(({ task }) => { - const unsettled = unsettledLazyImports(); - const [error] = task.result?.errors ?? []; - if (unsettled.length === 0 || error === undefined) return; - error.message += `\n\nLazy imports had not settled when this test failed: ${unsettled.join(", ")}. In app tests a lazy import resolves when the test awaits settleLazyModules() from @/test/lazy-modules or a Testing Library findBy/waitFor; synchronous assertions after the render or interaction that starts it see the loading state.`; - }); +import type { ComponentType } from "react"; +import { vi } from "vitest"; +import { installLazyModuleHold } from "./lazy-modules"; + +installLazyModuleHold(); + +vi.mock("react", async (importOriginal) => { + const { gateReactLazy } = await import("./lazy-modules"); + return gateReactLazy(await importOriginal()); }); -afterEach(() => { - releaseLazyImports(); +vi.mock("@/lib/define-split", async (importOriginal) => { + const actual = await importOriginal(); + const { gateLoadedComponent, prepareLazyModuleForFile } = + await import("./lazy-modules"); + const defineSplit: typeof actual.defineSplit = (options) => { + const key = `split:${options.id}`; + const split = actual.defineSplit({ + ...options, + load: () => + options + .load() + .then( + (View) => + gateLoadedComponent( + key, + View as ComponentType, + ) as typeof View, + ), + }); + const preload = split.preload; + return Object.assign(split, { + preload: async () => { + await preload(); + prepareLazyModuleForFile(key); + }, + }); + }; + return { ...actual, defineSplit }; }); if (typeof globalThis.navigator === "undefined") { diff --git a/apps/app/src/views/thread-detail/ThreadDetailSecondaryContent.test.tsx b/apps/app/src/views/thread-detail/ThreadDetailSecondaryContent.test.tsx index 39d60c80a8d..857fed1f22c 100644 --- a/apps/app/src/views/thread-detail/ThreadDetailSecondaryContent.test.tsx +++ b/apps/app/src/views/thread-detail/ThreadDetailSecondaryContent.test.tsx @@ -2,7 +2,7 @@ import { useMemo, type ComponentProps, type ReactNode } from "react"; import { act, cleanup, render, screen } from "@testing-library/react"; -import { afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { MemoryRouter } from "react-router-dom"; import { CompactViewportOverrideProvider } from "@bb/shared-ui/hooks/use-compact-viewport"; import { TooltipProvider } from "@bb/shared-ui/tooltip"; @@ -18,7 +18,6 @@ import { usePromptDraftStorage, } from "@/hooks/usePromptDraftStorage"; import { ThreadDetailSecondaryContent } from "./ThreadDetailSecondaryContent"; -import { LazyThreadSecondaryPanel } from "@/components/secondary-panel/lazySecondaryPanelComponents"; import { DefaultPaneContextProvider, PaneContext, @@ -337,10 +336,6 @@ function renderThreadDetail( ); } -beforeAll(async () => { - await LazyThreadSecondaryPanel.preload(); -}); - afterEach(() => { cleanup(); publishedHostedPanel = null; @@ -390,22 +385,14 @@ describe("ThreadDetailSecondaryContent", () => { ); expect( - await screen.findByRole( - "button", - { name: "Hide right panel" }, - { timeout: 5_000 }, - ), + await screen.findByRole("button", { name: "Hide right panel" }), ).not.toBeNull(); }); it("keeps the thread header inside the timeline column beside the panel", async () => { renderThreadDetail(false); - const sidePanel = await screen.findByTestId( - "inline-secondary-panel", - {}, - { timeout: 5_000 }, - ); + const sidePanel = await screen.findByTestId("inline-secondary-panel"); const timelinePanel = screen.getByTestId("panel"); const panelGroup = screen.getByTestId("panel-group"); expect(timelinePanel.contains(screen.getByTestId("header"))).toBe(true); @@ -492,11 +479,7 @@ describe("ThreadDetailSecondaryContent", () => { , ); - const sidePanel = await screen.findByTestId( - "inline-secondary-panel", - {}, - { timeout: 5_000 }, - ); + const sidePanel = await screen.findByTestId("inline-secondary-panel"); const panelGroup = screen.getByTestId("panel-group"); const nextProps = createProps(); @@ -601,7 +584,7 @@ describe("ThreadDetailSecondaryContent", () => { , ); - await screen.findByTestId("inline-secondary-panel", {}, { timeout: 5_000 }); + await screen.findByTestId("inline-secondary-panel"); expect(screen.getByTestId("footer-composer-draft").textContent).toBe(""); const paneRendersAfterMount = timelinePaneRenders.mock.calls.length; diff --git a/docs/ui-code-splitting.md b/docs/ui-code-splitting.md index f568fb4fd45..f383a5cf968 100644 --- a/docs/ui-code-splitting.md +++ b/docs/ui-code-splitting.md @@ -246,8 +246,13 @@ real content. Do not add artificial production delays for screenshots. In `@bb/app` tests, every dynamic `import()` in app source stays pending until the test settles it. `vite-test-lazy-imports.ts` wraps each call and -`src/test/setup.ts` holds the result for the duration of each test. A test -therefore never depends on how fast a chunk transforms on the runner: +`src/test/setup.ts` holds the result for the duration of each test. A module +already loaded before the current test is held too: the setup mocks +`defineSplit` and React's `lazy` so that a split or lazy component an earlier +test or file loaded renders its loading state on its first render in each later +test. A module loaded earlier in the same test renders at once. A test therefore +never depends on how fast a chunk transforms on the runner or on a sibling test +having loaded it first: - Testing Library `findBy*` and `waitFor` settle pending imports before they poll, let imports flow while polling, and settle again before returning. @@ -259,11 +264,16 @@ therefore never depends on how fast a chunk transforms on the runner: - To assert a loading state, render and assert synchronously or poll with `vi.waitFor`, which does not settle. The hold replaces deferred promises in `vi.mock` factories. Keep a factory gate only to make an import fail. -- Collection-time `await Split.preload()` remains the way to keep a heavy - module's first transform out of every test in a suite. - -A test that fails while an import is pending reports the held or loading -specifiers in its error. +- Collection-time `await Split.preload()` keeps a heavy module's first + transform out of every test in a suite and marks the split as prepared for + that file, so its tests render it at once. +- A test of Suspense or `defineSplit` mechanics itself calls + `vi.unmock("react")` and `vi.unmock("@/lib/define-split")`, as + `define-split.test.tsx` does. + +A test that fails while an import or gated module is pending reports the held +or loading specifiers in its error, for example `split:remote-path-browser +(held)`. ## Choosing a policy