Repository navigation
Hold app lazy imports until tests settle them - #7736
Merged
Merged
Conversation
ymichael
force-pushed
the
bb/lazy-module-settled-signal
branch
from
November 17, 2026 20:54
563d2df to
0fbac35
Compare
ymichael
added a commit
that referenced
this pull request
Nov 18, 2026
…s in tests #7713 owns the Connect Set up change and #7736 the plugin-boot test preload. Keep only a shared test helper that clicks Set up after the status call has been answered and flushed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
App tests waited for lazy modules with per-file copies: module-specific imports inside act, deferred gates in vi.mock factories, findBy deadlines, counted macrotask loops, vi.dynamicImportSettled, and per-test timeouts. A cold transform on a slow runner beat each copy's deadline, and tests passed only after a sibling had warmed the module. A test-only Vite transform tracks every dynamic import in app source. The app test setup holds each import until the test settles it, so a test that asserts lazy content without waiting fails deterministically and names the pending module. settleLazyModules() is the one signal; Testing Library findBy and waitFor settle before polling. Move every caller onto it and delete the copies. Co-Authored-By: Claude Opus 5.5 <[email protected]>
defineSplit starts its import() one microtask after render, so a waitFor or findBy that follows fireEvent saw no pending imports, skipped settling, and raced its 1 s deadline again. Always settle before and after the wait. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Escape restores focus to the prompt editor through TipTap's focus command, which focuses one animation frame later and dismisses any open plugin popup. The test reopened the popup inside that frame and passed only because it asserted before the frame fired; with Testing Library waits now settling first, the stray refocus closes the popup. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
force-pushed
the
bb/lazy-module-settled-signal
branch
from
November 18, 2026 00:30
0fbac35 to
0e40879
Compare
This was referenced Nov 18, 2026
ymichael
added a commit
that referenced
this pull request
Nov 18, 2026
## Human comments ## What was wrong Boot JavaScript grew from 349.6 KB to 419.8 KB brotli between #6076 (dae54bd) and f1c5304, measured per module with the same build. Most of the growth came from features, but the largest piece was a leak. #6579 had the sidebar updates badge (`useUpdateInventory`) import `pluginHasUpdateSurfaces` from `PluginUpdatesCard.tsx`. That one helper put the plugin-management UI, the shared-ui resource list and `@radix-ui/react-scroll-area` on boot: 19.7 KB brotli. A second leak came with #6756: `thread-action-registry` imports `useBbNavigate` from `plugin-navigation-hooks.ts`, which also defined the plugin-only file-open hook, so the local open-target hooks loaded before first paint. While splitting dialogs I also found a bug in `vite-journey-chunks.ts`. Vite adds `\0vite/preload-helper.js` to `importedIds` for any module with a dynamic `import()`, with no matching import declaration in the code. The counts disagreed, so `moduleEdges` fell back to following every name of every import. Once `ThreadActionsProvider` gained a split, that pulled the `@bb/client-core` and `@bb/thread-view` timeline code into the plugin runtime chunk (PluginFrontend +18.5 KB, NewThreadPage +15 KB). Boot brotli growth, #6076 → f1c5304 (per-module attribution, brotli share of each boot chunk): | Commit / module cluster | Brotli bytes | |---|---| | #6579 Settings → Updates: plugin management UI, shared-ui resource list, `@radix-ui/react-scroll-area` via `pluginHasUpdateSurfaces` | +19,727 | | #7133 dependency update: `react-dom` 19.2.4 → 19.3.1 (+ `react`, `scheduler`) | +7,329 | | #6002 keyed thread store: `query-tags` keyed store, `thread-entity-store`, `thread-panel-queries` | +5,824 | | #6013 / #6519 core tab and message-metadata registrations through the plugin collector (`plugin-app-registration-collector`, validators) | +5,249 | | #7213 single update button: `@radix-ui/react-hover-card`, badge model | +3,148 | | #6756 open-target hooks via `plugin-navigation-hooks` | +2,381 | | #6763 shared rename path: `inline-rename`, rename dialogs | +1,830 | | #7176 setup-guide telemetry: `onboarding-model` | +1,733 | | Radix version bumps (`react-collection` and others, excluding scroll-area and hover-card) | +~3,900 | | React Compiler memo caches (Nov 15 budget entry) and other app/shared-ui feature growth | remainder (~19,000) | | **Total** | **+70,214** | Shared packages: `@bb/shared-ui` +15.3 KB (mostly the resource list above), `@get-bb/plugin-sdk` +5.2 KB (the collector), `@bb/server-contract` +2.0 KB, `@bb/sdk` +1.2 KB, `@bb/domain` +0.1 KB. Zod was already on boot at #6076 and is unchanged. ## What changed - `pluginHasUpdateSurfaces` moved from `PluginUpdatesCard.tsx` to `plugin-status.ts`. The plugin-management UI now loads with Settings and Tools (−19.7 KB). - `usePluginCanOpenFileExternally` moved from `plugin-navigation-hooks.ts` to a new `plugin-file-open-hooks.ts`, still re-exported by `plugin-sdk-hooks.ts`. The open-target hooks now load with the thread and compose pages, which already use them (−2.4 KB). - An earlier version also set `treeshake.manualPureFunctions: ["z"]` to drop unused zod schemas (−3.6 KB). It is removed. Rolldown matches that name in every module, minified dependencies included, and also inside function bodies. In the built app it deleted sonner's `setSwiping(true)`/`setSwiping(false)` calls (toasts no longer follow a swipe on touch screens), cmdk's result-sort call, and two `push` calls in d3-scale's log ticks. - The project path, project rename and delete, and thread delete and archive dialogs load behind `defineSplit` preload-tier wrappers that mount when opened and stay mounted, following `ApplicationUrlDialog` (−3.1 KB). Nothing in them is visible at first paint. - `vite-journey-chunks.ts` ignores the preload helper id. The regression test fails before the fix and passes after. - `bundle-budget.json`: `splitBoundaries` boot guards for `PluginUpdatesCard`, `UpdatePluginDialog`, `useLocalOpenTargets` and the five dialogs. `@radix-ui/react-scroll-area` is added to `forbiddenBootPackages`, plus a dated `$comment` entry. Against main's build, the new budget reports all nine guards. - Limits are unchanged. Boot now measures 402,655 bytes against 429,151, which is 6.2% headroom. 10% over the new measurement (442,921) would be a raise, so lowering the limit would leave less than 10%. Not reached: 10% headroom needs about 12.3 KB more. The remaining boot code that isn't first-paint UI is small and spread out. The command-palette placeholder is kept on boot deliberately so Cmd+K opens instantly. The updates hover-card body is ~2 KB and splitting it would risk an empty card on an early hover. The plugin collector (5.2 KB) is how core registers its own Info tab and message time, per the rule that core uses the plugin API path. Each of these would cost something visible or break that rule. ## How you verified Bundle sizes from real builds of main (3678415, same sizes as f1c5304) and this branch rebased on main (`.br` files, as `check-bundle-budget.mjs` counts them): | Closure | main raw / brotli | branch raw / brotli | brotli Δ | |---|---|---|---| | boot | 1,717,479 / 428,928 | 1,597,774 / 402,655 | −26,273 (−6.1%) | | ThreadPage | 1,909,102 / 504,492 | 1,918,632 / 506,727 | +2,235 | | NewThreadPage | 1,007,979 / 270,590 | 1,025,094 / 274,769 | +4,179 | | PluginFrontend | 832,313 / 220,554 | 846,772 / 223,750 | +3,196 | | boot + ThreadPage | 933,420 | 909,382 | −24,038 | | boot + NewThreadPage | 699,518 | 677,424 | −22,094 | | boot + PluginFrontend | 649,482 | 626,405 | −23,077 | Journey growth is the open-target hooks (~3.9 KB) that those pages use, plus small dialog dependencies. First content on a real server (measured with the earlier version that still had the `z` hint, so about 3.6 KB more JS was removed than now): one `pnpm start:worktree` server with real data (a real agent thread plus fixtures). Main's and this branch's builds were served by swapping `index.html` in `apps/app/dist`, so server and data were identical. Each run used headless Chrome on a fresh navigation with the HTTP cache cleared and disabled, 4× CPU throttle, 1.6 Mbps / 150 ms RTT. Median of 6 alternating runs; ranges did not overlap for any metric: | Page | Metric | main | branch | Δ | |---|---|---|---|---| | New thread `/` | FCP | 3,594 ms | 3,430 ms | −164 | | | composer painted | 6,862 ms | 6,731 ms | −131 | | Thread `/threads/<id>` | FCP | 3,606 ms | 3,432 ms | −174 | | | timeline painted | 8,942 ms | 8,756 ms | −187 | | Plugin page `/plugins/automations/automations` | FCP | 3,572 ms | 3,422 ms | −150 | | | content painted | 7,496 ms | 7,353 ms | −144 | | | JS downloaded before content (new / thread / plugin) | 745,687 / 979,589 / 732,738 B | 719,291 / 951,279 / 706,155 B | −26.4 / −28.3 / −26.6 KB | Manual checks on the branch build: - Cold load, sidebar and composer: no console errors. - Updates badge hover card: lists the provider CLI updates. - Thread page renders its timeline. - New thread submitted from the composer. - Thread delete dialog: confirmed, thread deleted. - Archive on a parent with a child: dialog shows the child count; both threads archived. - "New project" path-entry fallback dialog: path submitted, project created. - Settings → Updates and the Plugins page render. - Project rename and delete dialogs opened through the real `ProjectActionsProvider` in a throwaway test, because their only menu sits in a header that the current routes don't render. - A 409 on `GET /threads/<new>/thread-storage/location` right after submit also happens on main. Commands: - `pnpm exec turbo run typecheck lint --filter=@bb/app` - `pnpm exec turbo run test --filter=@bb/app -- <63 related test files>`: 63 passed - `src/vite-journey-chunks.test.ts`: fails before the fix, passes after - `node scripts/check-bundle-budget.mjs`: OK - `oxfmt --check` - Rebased on main (includes #7736); `pnpm exec turbo run build typecheck lint --filter=@bb/app` and `check-bundle-budget.mjs` pass, and the 40 app test files that touch the changed providers, dialogs, layout and hooks pass on the merge. - The built sonner and cmdk code again contains the swipe setter and sort calls that the `z` hint had removed. > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 18, 2026
## Human comments ## What was wrong #7736 holds each dynamic `import()` in `@bb/app` tests until the test settles it, but only the call itself. Once a `defineSplit` split or a `React.lazy` component has loaded in a worker, later tests render it synchronously, so the hold never applies to them. A test that asserts lazy content without waiting therefore passes only when an earlier test or file loaded the module first. `ProjectPathDialog.test.tsx` on main shows this. In default order it passes: test 1 awaits `findByRole`, which loads `RemotePathBrowser`, and test 2 then reads it synchronously. Run alone (`-t "preserves the direct single-machine folder flow"`) it fails, and with `--sequence.shuffle` seeds 1, 3 and 8 fail (seed 1 is the nightly app-3 failure). ## What changed **Per-test gate for already-loaded modules (`apps/app/src/test/lazy-modules.ts`, `setup.ts`).** The app test setup now mocks two lazy helpers: - It wraps `defineSplit`'s loaded view with `gateLoadedComponent`. - It replaces React's `lazy` with `gateReactLazy`. No production code changes. In each test, a split or lazy component that loaded before that test renders its real loading state on its first render, until the test settles (`settleLazyModules()`, `findBy` or `waitFor`). A failing test names it, for example `split:remote-path-browser (held)`. Two cases render at once: - **Loaded in the same test.** A production preload that warms a module counts as legitimate. - **Preloaded by the file during collection.** A top-level `await Split.preload()` exempts that split for the file's tests. That is explicit, order-independent fixture preparation. `settleLazyModules()` also loops until no new import starts during a pass. This covers an import started in a microtask after render, which could outlast `findBy`'s deadline. **Tests moved onto the signal.** - **ProjectPathDialog:** test 2 awaits the folder browser. - **FilePreview:** the `.htm` case settles before reading the source view. - **ThreadDetailSecondaryContent:** drops its four 5 s `findBy` timeouts and its `beforeAll` preload. - **`define-split.test.tsx`:** tests `defineSplit`'s own Suspense and preload mechanics, so it unmocks `react` and `./define-split`. **Docs:** `docs/ui-code-splitting.md` ("Test lazy boundaries") describes the gate, the collection-time preload exemption and the unmock for mechanism tests. **Scope.** An earlier revision moved the hold into `@get-bb/plugin-sdk` as six `experimental_` exports for plugins and `@bb/shared-ui`. That move is dropped, so this PR has no SDK, plugin, shared-ui or version changes. In-repo plugins have no lazy UI that their tests exercise: - Composer has one `import()`, already covered by `vi.dynamicImportSettled()`. - Monaco's tests mock its loader. The hold can move into the SDK when a plugin needs it. ## How you verified - **Repro on main:** ProjectPathDialog passes in default order, fails when the test runs alone, and fails with shuffle seeds 1, 3 and 8. - **Fix on this branch:** it passes alone, in default order and with seeds 1–8. - **Gate catches it deterministically:** main's unfixed `ProjectPathDialog.test.tsx` fails under this branch's gate in default order, with `Lazy imports had not settled when this test failed: split:remote-path-browser (held)`. - **Mechanism tests (`apps/app/src/test/lazy-modules.test.tsx`)** cover: - an already-loaded split and `React.lazy` held until the test settles; - a same-test load rendering at once; - a collection-time preload rendering at once; - a microtask-after-render import. - **Local checks:** `pnpm exec turbo run typecheck lint lint:type-aware test --filter=@bb/app` passes (689 test files). > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human comments
What was wrong
App tests had no shared way to wait for a lazy module. Each test that rendered a
defineSplit,React.lazyor dynamic-import loader made up its own wait:await import("./X")insideact, deferred gates invi.mockfactories, afindBywith its 1 s deadline, countedsetTimeout(0)loops,vi.dynamicImportSettled(), a{ timeout: 5_000 }bump, or a collection-time raw import. On a cold runner the transform beat whichever deadline the copy had. Tests also passed only because a sibling test had already loaded the module. Each flake was fixed again in the file where it appeared.Past fixes for this root cause:
findByText's 1 s deadline (lazy plugin renderers).Each was a per-file patch. None stops the next test from making the same mistake.
What changed
Guard (
apps/app/vite-test-lazy-imports.ts,src/test/setup.ts). A test-only Vite transform wraps every dynamicimport()in app source. Production code is unchanged. During each test the setup holds every such import until the test settles it. A test that asserts lazy content without waiting now fails deterministically, on every machine and in every order. Its error names the held or loading module:One signal (
src/test/lazy-modules.ts).await settleLazyModules()resolves once every import has loaded, including imports that loading starts, and React has committed.await settleLazyModules(operation)covers tests that await a production promise whose chain loads code, such asbootPluginFrontends().findBy*andwaitForsettle pending imports before they poll, so the ordinary idiom is correct for lazy content without per-test code.vi.waitFordoes not settle, so cold-load tests use it to poll while an import is still pending.Copies deleted.
await import()waits in VoiceInputButton, SelectableMessageProse (×2), FilePreview and thread search.beforeAll/top-level preloads in CommandPalette, PromptBoxInternal paste and ServerMoveOverlay.ready/loaded/releasedeferred gates in the CommandPalette and ModelReasoningPicker cold-open tests, KaTeX loader, cold HTML, lazy plugin renderers, CodeHosts cold-load, sidebar retry and queued messages. The hold now does their job.vi.importActualpreloads in lazy-plugin-renderers (Load the real SDK adapters before timing the cold-load renderer test #6938) andvi.dynamicImportSettled()in useCodeRendererPreloads.flushLoad(setTimeout(0)inact) helper in ThreadDetailWorkerPoolProvider.{ timeout: 5_000 }waits in AppFileExternalNavigationHost.await act(async () => { await opened })wait in the terminal clipboard fixture.Migrated callers. The guard also found tests that passed only by order or timing: timeline row isolation, sender metadata and plugin-slot render counts, which asserted before a lazy row view committed. It also found the new
plugin-frontend-boot-catch-up.test.tsfrom #7615, which awaited a held import.Kept. Collection-time
await Split.preload()stays where a whole suite renders a heavy split. That is fixture preparation through the production API; it races no deadline. The two plugin-frontend boot tests now load./plugin-frontendat collection time, because that real import takes about 8.5 s on main too.docs/ui-code-splitting.mdgains a "Test lazy boundaries" section describing the contract.No per-test timeouts, counts or other tuned numbers were added; two 5 s overrides were removed. No production code, plugin SDK or wire changes.
How you verified
@bb/appsuite failed 44 files / ~70 tests. That includes every file patched by Wait for the real code renderer in the FilePreview refresh test #6851, Stabilize lazy UI tests by awaiting module completion #7673, Prepare functional UI dependencies and await real lazy-load completion #7678 and Remove timing and shared-state assumptions from UI test fixtures #7684, failing in their current, patched form, because each waits on a module-specific import rather than the app's own load.src/test/lazy-modules.test.tsxchecks four things: hold until settle, synchronous assertions after settle,findBywithout a module wait, and imports started inside an awaited operation. Re-introducing the deadlock I hit (holding imports while awaiting an operation) fails the last case.pnpm exec turbo run lint typecheck test --filter=@bb/appafter rebasing on 77e45fa: 689 files, 7136 tests passed. One failure,plugin-frontend-boot-catch-upfrom Start plugin boot from the served shell and skip plugin teardown on unload #7615, was migrated above; that file and its sibling now pass.--sequence.shuffle --sequence.seed=8821): 685 of 686 files passed.SplitThreadArea.test.tsx › carries maximization…timed out once at its 1 swaitForwith no lazy imports pending. It passed 3 of 3 times alone with the same seed, so I count it as CPU contention, not this change.Follow-up: imports that start just after a wait begins
defineSplitstarts itsimport()one microtask after render. InfireEvent.click(...)followed bywaitFor(...), the wait looked for pending imports before that import started, found none, skipped settling, and raced its 1 s deadline again.AppFileExternalNavigationHost.test.tsx, whose 5 s timeout this PR removed, failed 2 of 3 local runs on its own.waitFor/findBynow always settle before and after polling.lazy-modules.test.tsxgains a case for an import that starts a microtask after render and outlastsfindBy's deadline. It fails without the change.Always settling exposed
PromptBoxInternal.test.tsx › defers compact content…. Escape restores focus to the prompt editor through TipTap'sfocuscommand, which runs one animation frame later and dismisses any open plugin popup. The test reopened the popup inside that frame. On main it passed only because it asserted before the frame fired; the popup closed right after. It now lets that frame pass before reopening.Verified with every app lazy import's result delayed 1.5 s: the 9 touched files that failed 6 tests on main pass 216/216.
🤖 Generated with Claude Code