Repository navigation
Lazy-load KaTeX in MarkdownPreview and guard on-demand packages in the bundle budget (A9) - #1891
Merged
SawyerHood merged 2 commits intoAug 19, 2026
Conversation
SawyerHood
force-pushed
the
bb/mobile-perf/katex-lazy
branch
from
August 19, 2026 07:42
9b629a7 to
279fe03
Compare
SawyerHood
force-pushed
the
bb/mobile-perf/katex-lazy
branch
from
August 19, 2026 07:50
279fe03 to
06f520d
Compare
SawyerHood
marked this pull request as ready for review
August 19, 2026 08:04
SawyerHood
force-pushed
the
bb/mobile-perf/katex-lazy
branch
from
August 19, 2026 15:59
06f520d to
c44a607
Compare
markdown-preview.tsx imported rehype-katex and katex.min.css statically, so the 259 KB raw / 64 KB brotli katex chunk (plus its CSS and font references) was a static edge of the thread route closure. Every thread paid for the math renderer before first paint even though almost no message contains $$ math. Keep remark-math static so parsing does not change. Move rehype-katex and the stylesheet into markdown-katex.ts, a module reached only through a cached dynamic import() in markdown-katex-loader.ts. MarkdownPreview checks the body for the `$$` delimiter (the only way to produce a math node with singleDollarTextMath off), kicks off the import when present, and re-renders with the plugin appended to the rehype chain once it resolves. Until then the math stays as the remark-math code wrappers. Co-Authored-By: Claude <[email protected]>
check-bundle-budget only saw the boot closure, so nothing would notice if KaTeX became a static import of markdown-preview again: it would sit in the thread route closure, invisible to forbiddenBootPackages. bundle-stats.json now records every JS chunk with its static imports and facade module. bundle-budget.json gains onDemandPackages, mapping a package to the source module its dynamic import() resolves to; the check fails when any chunk outside that gate's static closure reaches the package, or when the gate chunk is missing. The script accepts an optional budget directory so tests can point it at fixture stats. Co-Authored-By: Claude <[email protected]>
SawyerHood
force-pushed
the
bb/mobile-perf/katex-lazy
branch
from
August 19, 2026 16:13
c44a607 to
f06b12e
Compare
SawyerHood
added a commit
that referenced
this pull request
Aug 19, 2026
…te preload + skeleton (A6, A8, A10, A13, A15, J1) (#1890) ## What was wrong - The browser SDK attached the `guide` area, so ~112 KB of generated guide markdown sat in the boot chunk although no browser code calls it (A8). - `@bb/domain`, `@bb/server-contract` and other leaf contract packages had no `sideEffects: false`, so barrel-reachable modules could not be dropped from the boot path (A13). - No font preload: the Inter latin woff2 request started only after the JS rendered text. `--font-mono` named the unshipped "Fira Code" (A15). - The pre-paint script never added the `dark` class or the cached palette CSS, so dark/themed sessions painted the light default palette until main.tsx ran (J1). - The `*` route chunk was fetched only on first React render and sat behind `fallback={null}`; the views then showed a bare "Loading…" paragraph (A6). - 24 desktop-app icon PNGs were base64-inlined into a route chunk (~35 KB br) for a menu that needs a local host daemon (A10). ## What changed - `createBbSdk` takes the guide area as an explicit argument. The Node factory passes `createGuideArea()` and returns `BbSdk`; the browser factory returns `BrowserBbSdk` (all server-backed areas, no `guide`). The public-types test pins the browser key set. Plugin SDK bundled d.ts regenerated. - `sideEffects: false` on `@bb/domain`, `@bb/server-contract`, `@bb/hono-typed-routes`, `@bb/host-daemon-contract`, `@bb/fuzzy-match`. - New build-only Vite plugin `bb:font-preload` (`apps/app/vite-font-preload.ts`) injects `<link rel="preload" as="font" type="font/woff2" crossorigin>` for the emitted `inter-latin-wght-normal` asset. `--font-mono` is now the system monospace stack. - `index.html`: the head script adds `dark` per `bb.theme` / `prefers-color-scheme`; a body-end script injects `bb.appThemeCss` into `<style id="bb-app-theme">` after the app stylesheet. `applyCachedAppThemeCss` adopts that element and re-appends it only when something was inserted after it (dev-mode style tags). - `App.tsx` starts `import("./views/SplitWorkspaceRoute")` at module scope and reuses the promise in `lazy()`. New `RouteLoadingSkeleton` (48 px header row + composer footprint) is the Suspense fallback for the `*` route and replaces the "Loading…" branches in `RootComposeView` and `ThreadDetailView`. - `build.assetsInlineLimit` excludes `/workspace-open-target-icons/`. - `bundle-budget.json` ratcheted to 3% above the new measurement. - A12 (chunk minSize) not applied: rolldown 1.0.0 only supports `minSize` for manual `codeSplitting.groups`; verified with a build that it has no effect on automatic boot chunks. ## How you verified - `pnpm exec turbo run build --filter=@bb/app` then `node apps/app/scripts/check-bundle-budget.mjs`: boot payload 1538.4 KB raw / 415.5 KB brotli, 41 chunks (before: budget 1671 / 456.4). `dist/index.html` contains the font preload link; `root-compose-create-preference-*.js` is 4,253 B; the entry chunk references the SplitWorkspaceRoute chunk statically. - `pnpm exec turbo run typecheck --filter=@bb/sdk --filter=@bb/app --filter=@bb/cli --filter=@bb/server --filter=bb-app --filter=@get-bb/plugin-sdk`: pass. - `pnpm exec turbo run lint --filter=@bb/app --filter=@bb/sdk`: 0 errors (147 pre-existing warnings, none in touched files). - New tests: `apps/app/src/index-html-pre-paint.test.ts` (7 tests: runs the real index.html inline scripts under jsdom; dark class from stored/system preference; palette style injected as last head child; adoption by applyCachedAppThemeCss) and `apps/app/src/vite-font-preload.test.ts` (3 tests). Also ran theme.test.ts, App.* route tests, RootComposeView/SplitWorkspaceRoute/SplitThreadArea tests, full @bb/sdk suite (94 tests), CLI guide tests: all pass. Fixes: part of the mobile / iOS Safari performance program (verified sweep report in the bb thread; no single issue). ## Stack context Layer 11 of 22 in the `bb/mobile-perf/*` stack (bottom → top: quick wins first, big rocks last). - Prerequisite (layer below): `bb/mobile-perf/http-caching-and-hub-gating` (#1889). - Next layer: `bb/mobile-perf/katex-lazy` (#1891). - Audit findings addressed: see title IDs. Review: approved-with-fixes; 1 review fix commit(s). - Deliberately not done here: A12: rolldown 1.0.0 (Vite 8.0.12) exposes codeSplitting.minSize only as a fallback for manual groups, not as a minimum for automatic chunks; verified by build t - Reviewer notes / follow-ups: A12 (chunk minSize) intentionally skipped by the implementer; rolldown's codeSplitting.minSize is a fallback-group setting and did not change the boot graph. Not a defect, just uni | Minor, not fixed: the font <link rel=preload> is injected with injectTo:"head" so it lands as the last head child, after ~40 modulepreload links and the stylesheet. Preload scanner | Pre-existing, not a regression: the root "@bb/sdk" export maps the browser condition to dist/browser.js while its "types" point at node.ts (BbSdk with guide). apps/app only type-im - Wire/contract: None. No server<->daemon payloads, host RPC, or WebSocket messages changed; HOST_DAEMON_PROTOCOL_VERSION not bumped. Type-level contract change only: @bb/sdk BbSdk is now BbSdkAreas + guide; createBrowserBbSdk() returns BrowserBbSdk (no guide). No browser caller used sdk.guide. bundled-types/bb-plugin-sdk.d.ts regenerated. > AGENT GENERATED: by Claude Code (claude-mangosteen-eap) --------- Co-authored-by: Claude <[email protected]>
SawyerHood
added a commit
that referenced
this pull request
Aug 19, 2026
…(A14) (#1892) ## What was wrong The shared `Icon` component kept one string-keyed map of 146 hugeicons entries in `packages/shared-ui/src/components/ui/icon.tsx`. The app shell imports it, so all ~100 KB raw (~20 KB brotli) of glyph arrays sat in the boot chunk of every page load. The shell paints only ~45 of those glyphs before a route renders. `ICON_NAMES` (used by `PluginIcon` to validate manifest icon hints) was derived from the map, which forced the whole map onto the boot path. Ten entries had no references anywhere in the repo. (Audit finding A14.) ## What changed - `icon.tsx` keeps only the core map (sidebar rows and controls, header, toasts, menus, plugin chrome). `IconName` is `CoreIconName | ExtendedIconName`; `ICON_NAMES` is built from the core keys plus a names-only list, so validation does not load artwork. - New `icon-extended.tsx` holds the other 90 glyphs and registers them into new `icon-registry.ts` (names list + tiny subscribe/get store) when it evaluates. - Each lazy route module (`SettingsView`, `ToolsView`, `MachineSettingsView`, `ProjectSettingsView`, `SplitWorkspaceRoute`) imports `@bb/shared-ui/icon-extended` statically. Rolldown places the extended artwork in one shared chunk that Vite preloads with the route chunk, so route icons never flash. - Anywhere else (dialogs mounted from the shell, storybook, plugin bundles) `Icon` renders a same-size empty svg with `data-icon-pending`, calls `preloadExtendedIcons()` (idempotent `import()`, retried on failure) and re-renders through `useSyncExternalStore` once the registry lands. Core icons take no hook and do not re-render. - Pruned ten unreferenced names: AudioLines, BubbleChatQuestion, CalendarSync, ChatFeedback, CircleDashed, Container, FileX2, Idea, LightbulbOff, Rows3 (and their stale story captions). - `packages/plugin-registry/scripts/build-registry.mjs` now follows dynamic `import()` edges so a vendored `@bb/icon` keeps `icon-extended`/`icon-registry`; `r/*.json` and `packages/templates` starter files are regenerated. - `apps/app/src/test/setup.ts` preloads the extended registry so component tests see the same synchronous icons a mounted route does. - `apps/app/bundle-budget.json` ratcheted to 3% above the new measurement. Boot payload measured on the app build: 1655.6 KB -> 1584.1 KB raw, 448.8 KB -> 435.3 KB brotli. The extended chunk is 66.6 KB raw / 14.5 KB brotli and loads with the first route. ## How you verified - New `apps/app/src/components/ui/icon.test.tsx` (4 tests, fresh module graph per test): a core glyph renders synchronously with the registry still null; an extended glyph renders a 24x24 empty placeholder with `data-icon-pending`, then fills in after `preloadExtendedIcons()`; `ICON_NAMES` is the disjoint union of the core keys and the extended map keys and every extended name has artwork; `icon.tsx` reaches `./icon-extended` only through `import()` and `icon-registry.ts` imports no artwork. The placeholder and static-graph tests fail on the old single-map module. - `pnpm exec turbo run typecheck --filter='...@bb/shared-ui'` (16 packages incl. @bb/app, @bb/templates with generator --check, @bb/plugin-registry, all plugins): pass. - `pnpm exec turbo run test --filter=@bb/app --force`: 364 files, 2891 passed, 3 skipped. `--filter=@bb/templates --filter=@bb/plugin-registry`: pass. `--filter=@bb/cli -- plugin-build.test.ts plugin-scaffold-dependencies.test.ts` (scaffold builds through esbuild with the dynamic import): pass. `--filter=bb-plugin-tasks --filter=bb-plugin-side-chat --filter=@bb/plugin-build`: pass, no act warnings. - `pnpm exec turbo run lint --filter=@bb/app`: 0 errors, 147 pre-existing warnings (same count as main). - `pnpm exec turbo run build --filter=@bb/app --force` then `node apps/app/scripts/check-bundle-budget.mjs`: boot 1584.1 KB raw / 435.3 KB brotli, 41 chunks, budget OK with the lowered ratchet. Fixes: part of the mobile / iOS Safari performance program (verified sweep report in the bb thread; no single issue). ## Stack context Layer 13 of 22 in the `bb/mobile-perf/*` stack (bottom → top: quick wins first, big rocks last). - Prerequisite (layer below): `bb/mobile-perf/katex-lazy` (#1891). - Next layer: `bb/mobile-perf/sidebar-defer-realize` (#1893). - Audit findings addressed: see title IDs. Review: approved-with-fixes; 1 review fix commit(s). - Reviewer notes / follow-ups: Follow-up (not blocking): plugin bundles built with esbuild (no code splitting) inline `import("./icon-extended")` as `Promise.resolve().then(init_icon_extended)`, so inside a plug | Follow-up (not blocking): the route preload relies on bare side-effect imports of `@bb/shared-ui/icon-extended`; if anyone later adds `sideEffects: false` to @bb/shared-ui (as A13 | Follow-up (not blocking): the on-demand loader retries on every render after a failed chunk fetch (same retry-on-failure pattern as plugin-frontend-lazy.ts, but triggered from rend - Wire/contract: None. No server<->daemon wire, protocol, route or command changes; HOST_DAEMON_PROTOCOL_VERSION untouched. Internal-only additions: @bb/shared-ui gains "./icon-extended" and "./icon-registry" export entries and Icon exports preloadExtendedIcons(); shared-ui is private and not part of the plugin SDK surface, so no experimental_ prefix or api_to_audit entry applies. Third-party plugins that pass one > AGENT GENERATED: by Claude Code (claude-mangosteen-eap) --------- Co-authored-by: Claude <[email protected]>
SawyerHood
added a commit
that referenced
this pull request
Aug 21, 2026
## What was wrong Issue #1072 (report: https://get-bb.github.io/reports/issues/1072.html) tracks heavy packages that sit in the static import closure of the lazy thread route (`SplitWorkspaceRoute`), so every thread open downloads and parses them before the timeline paints. Since the report was written, main already cut three of the five edges it names: `FilePreview -> @pierre/diffs` and the secondary-panel surfaces (#1894), `markdown-preview -> rehype-katex` (#1891), and Handlebars (#2080). The budget check in CI now ratchets that closure. One edge was still open: `useThreadStorageBrowser.ts` imported `@pierre/trees/react` statically, and `ThreadDetailView` calls that hook on every thread page (it has to, so the tree model survives the Info-tab/file-tab toggle). That put the tree model, its renderer and preact (~250 KB raw / ~62 KB brotli emitted) in the route closure, although only the "Thread storage" browser in the Info tab renders a tree, and the storage file list itself is only fetched once the panel opens. `node scripts/why-eager.mjs --from=views/SplitWorkspaceRoute.tsx node_modules/@pierre/trees` on main: ``` 0. apps/app/src/views/SplitWorkspaceRoute.tsx 1. apps/app/src/views/thread-detail/SplitThreadArea.tsx 2. apps/app/src/views/thread-detail/ThreadDetailView.tsx 3. apps/app/src/components/secondary-panel/useThreadStorageBrowser.ts 4. node_modules/@pierre/trees/dist/react/index.js ``` ## What changed All in `apps/app`. - `src/components/secondary-panel/ThreadStorageFileTree.tsx` (new): the only runtime importer of `@pierre/trees`. Exports `createThreadStorageTreeModel(onSelectionChange)` (the `new FileTree(...)` that `useFileTree` wrapped) and the `ThreadStorageFileTree` render component with the host style that used to live in `ThreadStorageBrowser.tsx`. - `useThreadStorageBrowser.ts`: no static tree import. When a thread has storage files, an effect imports the gate module (through `createRetryingModuleLoader`, the same helper the pierre worker pool uses) and builds the model; `model` is `null` until then, the `resetPaths`/selection sync effects wait for it, and cleanup calls `model.cleanUp()` and ignores a load that resolves after unmount. A failed chunk fetch logs a warning and the next mount retries. - `ThreadStorageBrowser.tsx`: renders the tree through `LazyThreadStorageFileTree` (new wrapper in `lazySecondaryPanelComponents.tsx`) and shows the existing "Loading files..." state while `model` is `null`. - `bundle-budget.json`: `@pierre/trees` added to the `SplitWorkspaceRoute` forbidden list and to `onDemandPackages` (gate: `ThreadStorageFileTree.tsx`, so no chunk outside that gate may reach it); route budget ratcheted to 10% above the new measurement (2,268,430 raw / 605,332 brotli, from 2,533,484 / 671,561). Route closure, `node scripts/check-bundle-budget.mjs`: before 2260.4 KB raw / 599.1 KB brotli, after 2013.9 KB raw / 537.4 KB brotli (-11% raw, -10% brotli). The tree now ships as `ThreadStorageFileTree-*.js` (253,881 B raw / 64,341 B brotli) fetched when the storage browser first has files. Not in this PR: the composer (`PromptBoxInternal -> tiptap/prosemirror`, ~600 KB raw in the shared `workspace-checkout-display` chunk). It is visible on every thread page, `PromptBoxInternal.tsx` owns the `useEditor` instance across 3,600 lines, and a first-focus handoff has to keep draft restore, autofocus, the mention menu and iOS keyboard-on-tap working. #1894 deliberately left it allowed in the route budget for that reason; it needs its own design. A previous agent's WIP on this branch (a null-rendering "tree model host" component returned from the hook as a ReactNode) was discarded in favour of the imperative model factory above. ## How you verified - New `useThreadStorageBrowser.test.tsx` (real `@pierre/trees` in jsdom, `vi.mock` factories only record when the library is first evaluated): - "loads the tree library only once there are files to show" fails on main's source files with `AssertionError: expected "vi.fn()" to not be called at all, but actually been called 1 times ... "@pierre/trees/react"` and passes on this branch. - "syncs files and selection into the model once it arrives, then destroys it on unmount": the files and `selectedPath` that arrived before the chunk are applied to the model; reconciling selection does not echo through `onSelectPath`; unmount calls `cleanUp()` once. - `node scripts/check-bundle-budget.mjs` with the new `bundle-budget.json` against main's build: `@pierre/trees is in the SplitWorkspaceRoute closure (assets/SplitWorkspaceRoute-9lmZmaba.js). It must load on demand`, exit 1. After rebuilding on this branch: `Bundle budget OK` (including the new on-demand gate check). - `pnpm exec turbo run typecheck --filter=@bb/app --force`, `pnpm exec turbo run lint --filter=@bb/app --force`, `pnpm exec turbo run build --filter=@bb/app`: pass. (The first push of this PR had two TS2322 errors in the new test file: `renderHook(..., { initialProps: { files: undefined } })` inferred the props type as `{ files: undefined }`, so the later `rerender({ files: [] })` calls did not compile and the CI bundle-budget step never ran. The test now declares `initialProps` with an explicit `{ files: readonly WorkspaceFile[] | undefined }` type; the forced typecheck is clean and the fail-before/pass-after result above was re-run with the typed test.) - `pnpm exec turbo run test --filter=@bb/app --force`: all files pass. - Manual, own dev instance + headless Chrome: opened a codex thread with two seeded storage files (`docs/notes.md`, `main.ts`); thread painted; opened the right panel, the "Thread storage" tree rendered `docs` and `main.ts`; clicking `main.ts` opened the file preview tab; switching back to Info showed the same tree (model survived the tab toggle). Fixes #1072 > AGENT GENERATED: by Claude Opus 5 ## Independent verification Round 2, by an independent verifier on a fresh worktree checked out at `3cf9d8d10` (rebased on `origin/main` `2c0b747a5`; `git merge-base --is-ancestor origin/main HEAD` true, `mergeable: MERGEABLE`). Commands run: - `pnpm install --frozen-lockfile --prefer-offline && pnpm exec turbo run build` (18/18 tasks). - `cd apps/app && node scripts/check-bundle-budget.mjs` → `SplitWorkspaceRoute closure: 2013.9 KB raw / 537.4 KB brotli` (budget 2215.3 / 591.1), `Bundle budget OK.` `node scripts/why-eager.mjs --from=views/SplitWorkspaceRoute.tsx node_modules/@pierre/trees` → `0 eagerly reachable module(s) ... only reachable behind a dynamic import (56 modules)`. The tree is emitted as `ThreadStorageFileTree-BVIqkJpc.js` (253,881 B). - `pnpm exec turbo run typecheck --filter=@bb/app --force` → `Tasks: 3 successful, 3 total`, no `error TS` (the round-1 TS2322 errors in the test file are gone). - `pnpm exec turbo run lint --filter=@bb/app --force` → `Tasks: 1 successful, 1 total`. - `pnpm exec turbo run test --filter=@bb/app --force` → `Test Files 415 passed (415)`, `Tests 3191 passed | 3 skipped`. Fail-before / pass-after (`apps/app`, `pnpm exec vitest run src/components/secondary-panel/useThreadStorageBrowser.test.tsx`): - With `bundle-budget.json`, `ThreadStorageBrowser.tsx`, `lazySecondaryPanelComponents.tsx`, `useThreadStorageBrowser.ts` checked out from `origin/main` and `ThreadStorageFileTree.tsx` removed: `1 failed | 1 passed` — `AssertionError: expected "vi.fn()" to not be called at all, but actually been called 1 times` with `1st vi.fn() call: ["@pierre/trees/react"]` at `useThreadStorageBrowser.test.tsx:45:38`. - Restored to the PR tree: `Tests 2 passed (2)`. Repro on the fixed branch (own dev instance, production `apps/app/dist` served on a private port with `/api` proxied, headless Chrome, `performance.getEntriesByType("resource")` with an enlarged buffer; codex thread `thr_52anzhhcu7` seeded with `docs/notes.md` and `main.ts` in its thread-storage dir): - Right panel closed: thread painted; `SplitWorkspaceRoute-BX4iePCW.js` (267,669 B) and `workspace-checkout-display-BuOjOA0-.js` (1,074,222 B) fetched at ~290 ms; no `/thread-storage/files` request and no `ThreadStorageFileTree` chunk at all. - Right panel open on the Info tab: `/thread-storage/files` at 1087 ms, then `ThreadStorageFileTree-BVIqkJpc.js` at 1207 ms; the "Thread storage" tree rendered `docs` and `main.ts`. CI on `3cf9d8d10`: all checks pass (Checks incl. `check-bundle-budget.mjs`, Tests app-1/2/3, integration, packages, server, Package Smoke ubuntu/macos). Residual risks / notes for the maintainer: - The composer edge (`PromptBoxInternal -> @tiptap/*` / `prosemirror-*`, ~600 KB raw inside `workspace-checkout-display`) is still a static import of the thread route; it is named in the issue title and is the largest remaining item behind "no editor parsing on first paint". `bundle-budget.json` allows it by design (#1894). If you want #1072 to keep tracking that edge, change `Fixes #1072` to `Refs #1072` or open a follow-up issue before merging; otherwise this PR closes it. - Behavior change is limited to the storage browser: one extra chunk fetch (and the existing "Loading files..." state) the first time a thread shows storage files; a failed chunk fetch leaves that state, logs a `console.warn`, and retries on the next mount. The model is now created per "files non-empty" span instead of once per `ThreadDetailView` mount, so it is rebuilt after the file list empties and refills; `resetPaths` re-applies expansion from the current search state in both designs, so no visible difference. > AGENT GENERATED: by Claude Opus 5 Co-authored-by: Claude <[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.
What was wrong
apps/app/src/components/ui/markdown-preview.tsximportedrehype-katexandkatex/dist/katex.min.cssstatically. Thekatex-*.jschunk (259,230 B raw / 64,287 B brotli) plus its CSS was a static edge of the thread route closure. Every thread downloaded and parsed the math renderer before first paint. Almost no message contains$$math. Nothing in CI could catch a regression:check-bundle-budget.mjsonly inspects the boot closure, and the thread route is a lazy chunk.What changed
markdown-katex.ts(new): the only module that importsrehype-katexand the KaTeX stylesheet.markdown-katex-loader.ts(new): cachedimport("./markdown-katex.js"), auseSyncExternalStorehook that returns the plugin once loaded, andmarkdownMayContainMath(content.includes("$$"); withsingleDollarTextMath: falsethis is the only way to produce a math node).markdown-preview.tsx:remark-mathstays static. The rehype chain is[rehypeRaw, rehypeSanitize]or[], withrehypeKatexappended only after the chunk resolves. Ordering (KaTeX after sanitize) is unchanged.vite-bundle-stats.ts: also writeschunks[](every JS chunk with staticimports,packages, andfacademodule) alongsidebootChunks.bundle-budget.json+scripts/check-bundle-budget.mjs:onDemandPackagesmapskatexandrehype-katextosrc/components/ui/markdown-katex.ts. The check fails when any chunk outside that gate's static closure reaches the package, or when the gate chunk is missing. The script takes an optional budget directory argument for tests.How you verified
pnpm exec turbo run test --filter=@bb/app -- src/check-bundle-budget.test.ts src/components/ui/markdown-katex-loader.test.tsx src/components/ui/markdown-preview.test.tsx: 20 passed.markdown-katex-loader.test.tsx: content without$$never triggers the chunk import; two mounted previews with math load the chunk once and both re-render with.katex; a later preview gets it synchronously.check-bundle-budget.test.ts: fixture graph passes when katex is only behind the gate; fails namingroute.js, markdown-preview.jswhen markdown-preview imports the katex chunk statically; fails when the gate module is absent.markdown-preview.test.tsxnowwaitForthe lazy chunk.pnpm exec turbo run build --filter=@bb/appthennode apps/app/scripts/check-bundle-budget.mjs: "Bundle budget OK" (boot 1655.6 KB raw / 448.8 KB br). Graph inspection:SplitWorkspaceRouteclosure no longer containskatex;markdown-katex-*.js(15.7 KB, facadesrc/components/ui/markdown-katex.ts) statically importskatex-*.js; the KaTeX CSS is now its ownmarkdown-katex-*.csschunk.pnpm exec turbo run typecheck lint --filter=@bb/app: pass (pre-existing React Compiler warnings only, none in touched files).Fixes: part of the mobile / iOS Safari performance program (verified sweep report in the bb thread; no single issue).
Stack context
Layer 12 of 22 in the
bb/mobile-perf/*stack (bottom → top: quick wins first, big rocks last).bb/mobile-perf/boot-shell-quickwins(Boot payload quick wins: SDK guide, font preload, dark pre-paint, route preload + skeleton (A6, A8, A10, A13, A15, J1) #1890).bb/mobile-perf/icon-core-map(Split the icon map into a core boot map and a lazy extended registry (A14) #1892).$$math, the display-math block flashes as aMATHfenced-code block (header + copy button) until the | Nit: apps/app/src/check-bundle-budget.test.ts leaves its mkdtemp directories in os.tmpdir() (no cleanup). Harmless.chunksarray; bundle-budget.json gainsonDemandPackages; check-bundle-budget.mjs accepts an optional second argv (budget/stats directory) — additive, CI invocation unchanged.