Skip to content

Start plugin boot from the served shell and skip plugin teardown on unload - #7615

Merged
ymichael merged 5 commits into
mainfrom
bb/preload-plugin-bundles-and-skip-pagehide-teardow-thr_ktviefpqiy
Nov 17, 2026
Merged

ymichael merged 5 commits into
mainfrom
bb/preload-plugin-bundles-and-skip-pagehide-teardow-thr_ktviefpqiy

Conversation

@ymichael

@ymichael ymichael commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Cold load (hotspot 7). I measured before changing anything. Adding HTML preload hints for the priority plugin bundles (via a proxy) moved their download from ~730 ms to ~320 ms at RTT 150 over H2, but ready didn't change (1118 vs 1127 ms). Hinting every enabled plugin made ready worse (+60 ms). Request initiator stacks showed the actual chain. The WebSocket's handleConnected invalidates /api/v1/plugins, and plugin boot's fetchQuery landed right after it, so boot waited ~150 ms for a second fetch of the list. Only then did it discover the lazily loaded zod runtime that thread-list needs (one more round trip). Only then did thread-list mount and issue listPreferences. Once boot stopped waiting, two hidden couplings appeared. (a) Non-priority plugins had only stayed off the HTTP/1.1 connections because of that accidental delay. (b) The toaster and thread-row metadata splits now revealed through Suspense before the thread view. React stamps every Suspense visibility toggle and holds the next retry reveal for 300 ms, so the thread view committed ~300 ms late.

Reload / tab close (hotspot 8). A non-persisted pagehide ran disposePluginFrontends. It removed every plugin's slot registrations and CSS, so React synchronously unmounted each plugin tree. A thread-detail effect then forced layout, and ProseMirror tore down its view, all in a document the browser was about to discard.

First-run onboarding (found in review of this PR). Making plugins the page doesn't need wait for the route paint broke onboarding. Only the main app layout sent that signal, and OnboardingGate doesn't render the main app during first run. So onboarding loaded only the priority plugins (3 of 26), and the Devices step showed an empty Connect sign-in panel. Nothing caught it: every browser harness marks onboarding done before it starts, and the load-order tests stub the signal.

What changed

  • Server (apps/server/src/server.ts): the SPA shell now carries the enabled plugin list as inert JSON (<script type="application/json" id="bb-plugin-list">, the same body GET /api/v1/plugins returns, with < escaped). The shell ETag hashes the rendered document, so a validator from before a plugin change never 304s a stale list. The shell is no longer served from the .br sidecar; the compress middleware gzips it (9.5 KB, and it replaces the separate /plugins request on the critical path). The element ID lives in @bb/server-contract.
  • App boot:
    • main.tsx seeds the plugin-list query from the shell, dated performance.timeOrigin so the initial-connect invalidation still replaces it.
    • Initial boot reads the cached list (ensureQueryData) instead of waiting on a refresh. A reconcile requested before boot (e.g. the connect-time plugins-changed) now runs after boot instead of being dropped.
    • The zod/pierre runtime loaders moved to plugin-runtime-groups.ts so the priority prefetch warms them at entry evaluation.
    • Non-priority plugins wait for whenScreenPainted before downloading.
  • Screen paint signal (apps/app/src/lib/screen-paint.ts, components/ScreenPaintSignal.tsx): the route-content paint signal is renamed to a screen paint signal and moved into its own component. The main app routes and the first-run onboarding screen both render it. whenScreenPainted() also resolves 3 s after page start if no screen sends it, so a screen without the signal (the auth callback today, any future full-screen gate) delays plugin loading instead of stranding it. The signal stays inside the main layout rather than at the app root, because from the root it would fire before the lazy Settings/Plugins/Skills pages draw. docs/ui-code-splitting.md documents both.
  • Bundle budget (apps/app/bundle-budget.json): the boot brotli limit rises 512 bytes (428,127 → 428,639). The onboarding paint signal and its fallback add 0.3 KB brotli to the boot payload. That put it at 418.2 KB against a 418.1 KB limit, which the rest of this PR plus main had left 0.2 KB under. The raw limit is unchanged.
  • defineSplit({ suspends: false }): renders loading until the module arrives, then mounts without a Suspense boundary. It's used for the two boot-time background splits, app-toaster and thread-row-metadata-collectors. Documented in docs/ui-code-splitting.md.
  • Unload: pagehide with persisted: false calls discardPluginFrontends. It aborts pending loads and content-script signals and runs content-script cleanups in reverse order, which the SDK promises. It no longer unmounts slot trees, removes CSS, clears statuses or publishes diagnostics. Discard is terminal: a live reconcile after it does nothing. The bfcache path (persisted: true → keep, pageshow → reconcile) is unchanged. The SDK README now says slot components are not unmounted at unload.
  • I didn't add preload <link> hints. Measured on top of this change, they moved bundle downloads earlier but left ready unchanged or slightly worse in every configuration (table below). The duplicated plugin CSS is left to the per-plugin CSS scoping work in a separate thread (hotspot 3), which owns that pipeline.

No wire changes to the daemon protocol.

How you verified

Production builds of origin/main da3e60b81d and this branch, each served by pnpm start:worktree with the same deterministic 500-thread fixture (long timelines 1.2k/2.9k/9.7k items). Headless Chrome 145; HTTP/2 through a local TLS proxy (like bb Connect) or HTTP/1.1 direct; CDP latency/throughput and CPU emulation. Variants alternated run by run, 5 runs each, median. "Ready" = sidebar row + visible timeline row + composer on a 2.9k-item thread. Cold = empty cache; warm = second load in the same profile (returning user).

Config main cold branch cold main warm branch warm
H2, RTT 150 1108 958 812 665
H2, RTT 150, 20 Mbit/s 1444 1330 833 688
H2, RTT 50, 4× CPU 1783 1704 1999 1863
H1, RTT 50 750 685 562 535
H2, RTT 0 430 400 419 435

Ablation (branch + priority preload hints in HTML): 965 / 1351 / 1701 ms cold for the first three rows, i.e. no gain over the branch alone.

Reload and close, median of 6 (pagehide = the trace's pagehide EventDispatch; reload = reload command to ready):

main branch
pagehide, 1× CPU 162 ms (48 ms layout, 31 ms style) 1 ms
pagehide, 4× CPU 762 ms (226 ms layout) 3 ms
reload → ready, 1× 524 ms 358 ms
reload → ready, 4× 2196 ms 1436 ms
tab close/navigate away, 1× / 4× 190 / 738 ms 38 / 57 ms

Behavior checks on both builds: a draft typed right before reload survives; back/forward restores a working composer, sidebar and plugin styles (Chrome reports BrowsingInstanceNotSwapped, so neither build enters bfcache in this harness). No duplicate plugin bundle requests.

Tests (each fails on the old behavior):

  • app-shell-plugin-list.test.ts: boot candidates resolve from the shell's list while the connect refresh is still in flight (hangs with the old fetchQuery path).
  • plugin-frontend-boot-catch-up.test.ts: a reconcile requested before boot re-reads the list after boot (fails if the pre-boot request is dropped).
  • plugin-frontend-reload.test.ts: discarding an unloading page aborts signals and runs cleanups in reverse order, keeps the plugin UI and stylesheet mounted, and stays terminal.
  • plugin-frontend-load-order.test.ts: other plugins' downloads wait for the screen paint.
  • screen-paint.test.ts: with no signal, waiters are released at the 3 s deadline, counted from page start (fails without the deadline).
  • OnboardingGate.test.tsx: the first-run setup guide sends the paint signal even though the app behind it never renders (fails without it).
  • tests/render-invariants/src/idle.test.ts (real browser): with onboarding not done, opening the app requests every enabled plugin bundle. Without the fix, 3 of 6 load and it fails.
  • define-split.test.tsx: a suspends: false background split doesn't delay a sibling route reveal (≈5 ms vs 298 ms with suspends: true).
  • static-shell.test.ts / static-cache.test.ts: the shell embeds the same list as GET /api/v1/plugins, the ETag rotates with the embedded head, the JSON can't break out of its script element, and the shell is still gzipped.

Onboarding, checked live on pnpm start:worktree with onboarding reset: before the fix the Devices step loaded 3 of 26 plugin bundles and the Connect panel was empty. After it, all 26 load and "Sign in to your bb account" shows. Other plugins start downloading at ~440 ms, so the signal drives it, not the 3 s fallback. Thread-page ready (~1350 ms at RTT 150, HTTP/1.1) and pagehide (<1 ms) are unchanged by the fix.

Rebased onto origin/main cb627c8574a. Main had split the render-invariants suite into idle/typing/push files that run in parallel (#7669), so the onboarding case now lives in idle.test.ts, and useRenderFixture exposes its browser for the case's fresh context. Main already carries plugin SDK 0.6.150, so this PR no longer bumps it; the README note isn't SDK surface, and check-plugin-sdk-version.mjs reports the surface unchanged. After the rebase, pnpm exec turbo run typecheck lint test --filter=@bb/app --filter=@bb/server --filter=@bb/server-contract --filter=@bb/render-invariants --filter=@get-bb/plugin-sdk --filter=@bb/provider-parity and test:render-invariants pass (7/7; the idle group still finishes before the push group). The bundle budget check passes at 418.2 KB brotli against the 418.6 KB limit. iOS Simulator Safari wasn't run: the only simulator was booted by another session, and the persisted (bfcache) path that WebKit uses most is unchanged.

The pagehide and reveal invariants live in the unit suites. A "non-persisted pagehide does no layout" case would also fit the real-browser render-invariants suite.

🤖 Generated with Claude Code

AGENT GENERATED

@ymichael
ymichael force-pushed the bb/preload-plugin-bundles-and-skip-pagehide-teardow-thr_ktviefpqiy branch 2 times, most recently from 3e9e2f2 to 0d2ab3d Compare November 17, 2026 18:04
ymichael and others added 5 commits November 17, 2026 10:31
…nload

Cold load: the server embeds the enabled plugin list in index.html and the
app seeds its plugin-list query from it, so priority plugin bundles and the
zod runtime start at entry evaluation instead of after /api/v1/plugins and
the initial-connect refetch. Boot reuses the cached list; a reconcile
requested before boot runs after it. Other plugins wait for the route to
paint, and the toaster and thread-row metadata splits mount after their
chunks load instead of revealing through Suspense, which restarted React's
300 ms reveal throttle for the thread view.

Unload: a non-persisted pagehide now only aborts and cleans up content
scripts. It no longer unmounts every plugin tree and removes plugin CSS,
which cost 160 ms (760 ms at 4x CPU) of forced layout on every reload and
tab close.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e shell template per request

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…onboarding

Plugins the page does not need waited for a paint signal that only the main
app layout sent, so first-run onboarding loaded only the priority plugins and
the Devices step showed an empty Connect sign-in panel.

The signal is now ScreenPaintSignal. The onboarding screen renders it, and
whenScreenPainted() resolves 3 seconds after page start if no screen sends it,
so any other screen delays plugin loading instead of stranding it. A browser
case in the render-invariants suite checks that onboarding loads every plugin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t signal

The signal and its 3-second fallback add 0.3 KB brotli to the boot payload,
which measured 418.2 KB against a 418.1 KB limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/preload-plugin-bundles-and-skip-pagehide-teardow-thr_ktviefpqiy branch from 0d2ab3d to 7c9257f Compare November 17, 2026 18:37
@ymichael
ymichael merged commit 927087c into main Nov 17, 2026
53 checks passed
@ymichael
ymichael deleted the bb/preload-plugin-bundles-and-skip-pagehide-teardow-thr_ktviefpqiy branch November 17, 2026 19:56
ymichael added a commit that referenced this pull request Nov 17, 2026
#7615 changed packages/plugin-sdk/README.md without a version bump, so the
npm version guard fails on main and every PR: 0.6.150 is already published
with the old README.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 17, 2026
#7615 measured its boot cost on an older base. On main it took the boot
payload from 417.6 KB to 418.7 KB brotli, 0.1 KB over the limit. The npm
version guard failed earlier in the same Checks job, so the budget step
never ran on main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 17, 2026
#7615 changed packages/plugin-sdk/README.md without a version bump, so
the npm version guard fails on main: 0.6.150 is already published with
the old README.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 17, 2026
#7615 measured its boot cost on an older base. On main it took the boot
payload from 417.6 KB to 418.7 KB brotli, 0.1 KB over the limit. The npm
version guard failed earlier in the same Checks job, so the budget step
never ran on main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 17, 2026
#7730)

## Human comments

## What was wrong

The Checks job on `main` has been red since #7615 (`927087cdef6`), for
two reasons. The second was hidden behind the first.

1. **npm version guard.** #7615 added a paragraph about page unload to
`packages/plugin-sdk/README.md` but kept `@get-bb/plugin-sdk` at
`0.6.150`, which is already on npm. The publish job never republishes an
existing version, so the guard fails:
   ```
   npm version guard: FAIL
@get-bb/[email protected] is already published, but the package this
checkout would publish differs from it:
     - README.md
   ```
I diffed the published `0.6.150` tarball against `main`: that README
paragraph is the only difference.
2. **Boot bundle budget.** The guard step runs before the budget step
and stopped the job, so the budget never ran on `main`. Once the guard
passes, it fails:
   ```
   Bundle budget failed:
- boot payload is 418.7 KB brotli, over the 418.6 KB budget by 0.1 KB.
   ```
#7615 raised the limit for a boot cost it measured on an older base
(418.2 KB). On `main`, the Checks logs show the boot payload at 417.6 KB
on `7889bd2b5d9`, the commit before #7615, and 418.7 KB after it.

## What changed

- `node scripts/bump-plugin-sdk.mjs --patch`:
`packages/plugin-sdk/package.json` and
`packages/domain/src/plugin-sdk-version.ts` go from `0.6.150` to
`0.6.151`. No other file references the old version.
- `apps/app/bundle-budget.json`: `maxBootBrotliBytes` rises 512 bytes
(428,639 to 429,151), with a dated note. The raw limit is unchanged.

## How you verified

- `node packages/plugin-sdk/scripts/check-npm-version-guard.mjs` on this
branch: `npm version guard: PASS — @get-bb/[email protected] is not on
npm yet.` On `main` it fails with the output above. The first CI run of
this PR confirmed the guard step passes.
- Built `@bb/app` from `main` and ran `node
apps/app/scripts/check-bundle-budget.mjs`: 418.7 KB brotli, failing
against the old limit and `Bundle budget OK.` against the new one.

The first CI run also failed three Windows test jobs on timing. None of
them involves these files, and each passes on recent `main` commits:
- `github-pr-status` `host.test.ts`: 5 s timeout.
- `@bb/web` `oauth.test.ts`: 5 s timeout. This job also failed on `main`
at `4693d1f7e23` and `927087cdef6`.
- `@bb/app` KaTeX `markdown-preview.test.tsx`: the 1 s `waitFor` ran out
while KaTeX loaded lazily.

> 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

App tests had no shared way to wait for a lazy module. Each test that
rendered a `defineSplit`, `React.lazy` or dynamic-import loader made up
its own wait: `await import("./X")` inside `act`, deferred gates in
`vi.mock` factories, a `findBy` with its 1 s deadline, counted
`setTimeout(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:

- #4911: FilePreview and SplitThreadArea assertions relied on sibling
tests warming the lazy renderer and panel.
- #6851: FilePreview asserted before the lazy code renderer loaded.
- #6938: a cold Vite transform counted against `findByText`'s 1 s
deadline (lazy plugin renderers).
- #7673: a 1 s readiness wait raced the real import (voice preferences,
KaTeX clipboard, model picker and palette cold-open).
- #7678: cold transforms raced short deadlines across functional UI
suites (palette, thread search, sidebar retry, KaTeX, cold HTML, queued
messages, terminal clipboard, prompt paste). Its body lists four rounds
of follow-ups in the same PR.
- #7684: the lazy panel preload in ServerMoveOverlay.

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 dynamic `import()` 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:

> Lazy imports had not settled when this test failed:
"./MicrophonePreferences" (held). …

**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 as
`bootPluginFrontends()`.
- Testing Library `findBy*` and `waitFor` settle pending imports before
they poll, so the ordinary idiom is correct for lazy content without
per-test code. `vi.waitFor` does not settle, so cold-load tests use it
to poll while an import is still pending.

**Copies deleted.**
- Module-specific `await import()` waits in VoiceInputButton,
SelectableMessageProse (×2), FilePreview and thread search.
- Raw `beforeAll`/top-level preloads in CommandPalette,
PromptBoxInternal paste and ServerMoveOverlay.
- `ready`/`loaded`/`release` deferred 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.importActual` preloads in lazy-plugin-renderers (#6938) and
`vi.dynamicImportSettled()` in useCodeRendererPreloads.
- The `flushLoad` (`setTimeout(0)` in `act`) helper in
ThreadDetailWorkerPoolProvider.
- The "5 ticks" loops in SplitThreadArea.environment-archive.
- The `{ timeout: 5_000 }` waits in AppFileExternalNavigationHost.
- The `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.ts` from #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-frontend` at collection time, because that real
import takes about 8.5 s on main too. `docs/ui-code-splitting.md` gains
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

- **Guard fails on main for the known cases.** With only the hold
applied to main's tests (no signal, no migration), the full `@bb/app`
suite failed 44 files / ~70 tests. That includes every file patched by
#6851, #7673, #7678 and #7684, failing in their current, patched form,
because each waits on a module-specific import rather than the app's own
load.
- **Signal removes the need for the patches.** I injected a 1.5 s delay
into every real lazy import, as #7678 did. Then I ran the naive,
pre-patch forms of the VoiceInputButton (#7673), SelectableMessageProse
(#7673), FilePreview (#6851) and CommandPalette thread-search (#7678)
tests. With main's behaviour: 6 failed, 187 passed. With the signal: 193
passed. The delay and naive forms were reverted afterwards.
- **Mechanism test.** `src/test/lazy-modules.test.tsx` checks four
things: hold until settle, synchronous assertions after settle, `findBy`
without 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/app` after
rebasing on 77e45fa: 689 files, 7136 tests passed. One failure,
`plugin-frontend-boot-catch-up` from #7615, was migrated above; that
file and its sibling now pass.
- Shuffled (`--sequence.shuffle --sequence.seed=8821`): 685 of 686 files
passed. `SplitThreadArea.test.tsx › carries maximization…` timed out
once at its 1 s `waitFor` with 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

`defineSplit` starts its `import()` one microtask after render. In
`fireEvent.click(...)` followed by `waitFor(...)`, 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`/`findBy` now
always settle before and after polling. `lazy-modules.test.tsx` gains a
case for an import that starts a microtask after render and outlasts
`findBy`'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's
`focus` command, 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.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant