Skip to content

PERF: Lazy-load frontend screens so startup loads only the shell and Home - #4423

Open
Fazeel Usmani (FazeelUsmani) wants to merge 15 commits into
microsoft:mainfrom
FazeelUsmani:perf/frontend-route-lazy-loading
Open

Fazeel Usmani (FazeelUsmani) wants to merge 15 commits into
microsoft:mainfrom
FazeelUsmani:perf/frontend-route-lazy-loading

Conversation

@FazeelUsmani

@FazeelUsmani Fazeel Usmani (FazeelUsmani) commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Description

Part of #4056. The app loaded every screen at startup. This makes each screen load when it's first opened, so startup only loads the app shell and Home.

  • Screens are loaded with React.lazy, with a loading spinner while a screen downloads
  • Switching to a screen that hasn't loaded yet shows the spinner right away, so the current view always matches the URL. Otherwise the onboarding tour's Back button could go to the wrong screen while a screen was loading
  • After a redeploy, an open tab still asks for the old chunk file names. The backend answers those with index.html, so the import fails. The screen then shows a Reload page button with a note that reloading discards unsaved work, instead of reloading on its own (the same error happens while the server is briefly unreachable, and chat drafts only live in memory)
  • A screen, Registry tab or the Feedback dialog that fails to load is contained by its own error boundary, so the sidebar and tab bar keep working
  • The first time Feedback opens, a small dialog with a spinner and Cancel shows while the form downloads
  • The Registry tabs have their own Suspense, so the tab bar stays visible while a registry tab loads
  • Removed the per-folder manualChunks rules from vite.config.ts. The shell imports a few shared modules from those folders, so each folder chunk became a startup dependency. With the rules kept, startup is still 2,472 kB

Startup JS, production build of current main vs this branch:

main this PR
Startup JS 2,780 kB 1,652 kB
Gzipped 774 kB 461 kB

Screenshots (production build, chunk request blocked or held in the browser):

A screen that fails to load shows the error and a Reload page button inside the app shell; the sidebar keeps working

The Feedback dialog failing to load shows an alert dialog with Reload page and Close

Opening Feedback for the first time shows a loading dialog with Cancel while the form downloads

Julio César Suástegui (@juliosuas), would you review this? Roman Lutz (@romanlutz) suggested you in #4056.

…Home

App.tsx imported every screen eagerly, and vite.config.ts grouped each
component folder into one chunk, so index.html preloaded all chunks: the
first load fetched all 2,652 kB (738 kB gzip) of JavaScript.

Screens now load on first visit through React.lazy behind a Suspense
fallback, and the folder grouping is removed (it pulled whole folders
into startup through small helper imports). Vendor grouping is kept.
Startup JavaScript drops to 1,628 kB (452 kB gzip).

- RegistryLayout wraps its outlet in Suspense so the tab list stays in
  place while a tab loads.
- After a redeploy an open tab asks for old chunk names, and the backend
  answers unknown paths with index.html, so the import fails.
  installChunkReloadHandler reloads once on vite:preloadError, and leaves
  a repeat failure within 10 s to the error boundary.
- The Suspense around the routes is keyed by view, so switching to a screen that is still
  loading shows the fallback at once. Otherwise React keeps the old screen during the
  transition and currentView lags the URL, which sent the onboarding tour's Back to the
  wrong screen.
- App tests wait for lazily loaded screens with findBy.
Copilot AI balanced review requested due to automatic review settings November 19, 2026 08:11

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Automatic chunk recovery can enter an indefinite reload loop, discard unsaved drafts, and leave rejected lazy imports stuck because the error boundary’s retry action does not retry loading.

3 open issues
What changed in this PR

This PR implements the on-demand loading portion of #4056, reducing PyRIT frontend startup downloads by keeping Home and the app shell eager while deferring other screens.

Changes:

  • Lazy-load screens and Feedback, with loading indicators and a separate Registry tab boundary.
  • Add automatic recovery for failed chunk loads, guarded by a ten-second reload window.
  • Remove feature-folder chunk rules and adapt tests for asynchronous rendering.
File Description
frontend/​vite.config.ts Removes feature-folder chunk grouping that pulled deferred code into startup.
frontend/​src/​utils/​chunkReload.ts Adds reload handling for failed chunk imports.
frontend/​src/​utils/​chunkReload.test.ts Tests reload timing, storage failures, and listener cleanup.
frontend/​src/​main.tsx Installs the chunk-error handler before rendering.
frontend/​src/​components/​Registry/​RegistryLayout.tsx Keeps Registry tabs visible while tab content loads.
frontend/​src/​components/​Registry/​RegistryLayout.test.tsx Tests tab visibility during lazy loading.
frontend/​src/​App.tsx Introduces lazy screen imports and loading boundaries.
frontend/​src/​App.test.tsx Updates assertions to wait for deferred screens.

Review effort: Balanced

Comment thread frontend/src/utils/chunkReload.ts Resolved
Comment thread frontend/src/App.tsx Resolved
Comment thread frontend/src/utils/chunkReload.ts Resolved
The reload guard used a 10 s window, so a chunk that keeps failing on a
slow load could reload again and again. Each failed chunk now gets one
reload per tab; a new deploy has new chunk names, so it still gets its
reload.

React.lazy keeps a failed import, so the error boundary's Try again
could not recover from a chunk that failed to load. For chunk errors it
now offers Reload page instead.
These tests queried a screen right after rendering or navigating, so
they passed only when an earlier test in the file had already loaded
that screen. They now wait for it with findBy.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Invalid await usage prevents App.test.tsx from compiling, and shared recovery keys for URL-less import errors suppress needed reloads for later chunk failures and deployments.

3 open issues
2 resolved since last review

Review effort: Balanced

Comment thread frontend/src/App.test.tsx Resolved
Comment thread frontend/src/utils/chunkReload.ts Resolved
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
findByTestId is async, so it cannot be awaited inside the synchronous
waitFor callback, and the file did not compile. waitFor already retries
getByTestId until the element appears.
Some browsers report a failed import without the chunk URL, so every
such error got the same key and only the first one in a tab could
reload. Those errors are now keyed by the entry script's hashed name,
which changes with each deploy, so every build still gets one reload.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Unchanged loading-boundary keys retain stale screen and registry-tab content during cold navigation, while synchronous tests fail in isolation because they do not await lazy imports.

1 open issue
3 previously missed issues

In code that hasn't changed since last review

Medium severity Await lazy content in isolated App tests

frontend/​src/​App.tsx:73

Some remaining synchronous App tests now depend on earlier tests having resolved these module-scoped lazy components. When run in isolation, “switches to chat view” (App.test.tsx:1249) and “sets conversationId from chat window” (App.test.tsx:1283) query chat content before the first import resolves, so those queries fail. Make these cases and the remaining synchronous registry cases async, awaiting the destination content before interacting with or asserting on it.

Medium severity Key the route boundary by screen identity

frontend/​src/​App.tsx:1055

currentView identifies a feature, not a screen: Chat and Attack History both use chat, Scanner Launch/History/Detail all use scenarios, and both dataset screens use datasets. On a first navigation between those screens, the key stays unchanged, so the router's transition retains the previous screen until the new chunk resolves rather than showing the loading fallback. Reset the boundary by screen identity, while preserving ChatWindow across conversation-only URL changes, and cover a cold intra-feature navigation.

Medium severity Key the registry boundary by selected tab

frontend/​src/​components/​Registry/​RegistryLayout.tsx:67

After a registry tab has rendered, switching to an unloaded tab leaves this boundary and the outer registry key unchanged. The router transition therefore retains the old tab content and selection until the import completes, rather than showing the spinner. Key this inner boundary by selectedTab so the requested tab and its loading state can appear immediately while the tab bar stays mounted.

2 resolved since last review

Review effort: Balanced

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks Fazeel Usmani (@FazeelUsmani), this looks good. I rebuilt main and this branch and got the same numbers: startup JS goes from 2,662 to 1,629 kB (741 → 453 kB gzip). All 7 touched jest suites pass locally.

What I checked:

  • React.lazy / Suspense: every screen in the shell is now lazy, and the static imports left in App.tsx are only the layout, Home and small helpers. Keying the outer Suspense with screenKey() is the right call. A new boundary inside a router transition shows its fallback instead of holding the old screen. And because SCREEN_PATHS matches on the route pattern, moving between attacks, conversations or runs doesn't remount Chat or ScenarioRunPage. I checked the route table and found no param route that's missing from the list (/datasets/detail is static).
  • Registry tabs: the inner Suspense key={selectedTab} keeps the TabList mounted, and the new RegistryLayout test covers it.
  • Stale-chunk reload: one reload per failed asset per tab, URL-less errors keyed by the entry script hash, and no reload when sessionStorage throws. That resolves both earlier loop concerns, and the "Reload page" button for chunk errors is the correct fix for lazy() caching the rejection.
  • manualChunks removal: agreed. The shell imported shared modules from those folders, so the folder chunks were startup dependencies. Vendor splitting is unchanged.

One thing I'd fix (not blocking):

  1. Brief generic error before the reload. When the handler calls preventDefault(), Vite's helper returns undefined instead of throwing (baseModule().catch(handlePreloadError)). React.lazy then resolves to undefined, React throws its "expected the result of a dynamic import()" error, and the app-wide ErrorBoundary renders the generic "Try again" fallback and logs it through onError until location.reload() navigates. A small wrapper avoids this:
    const lazyScreen = <T,>(load: () => Promise<{ default: T }>) =>
      lazy(async () => (await load()) ?? new Promise<never>(() => {})) // reload already in flight
    A test can cover it: reject the import, have the listener prevent default, and assert that only the spinner shows (no fallback, no onError).

Nits / follow-ups:
2. The PR description still says "not again within 10 seconds", but the code now does one reload per failed chunk per tab. Please update it so the squash message is accurate.
3. A regression test for the reason behind the screenKey change would help: navigate to a screen whose import is still pending, then assert that the spinner shows and the sidebar's current item (or the tour's Back target) already follows the URL.
4. FeedbackDialog sits under the app-wide ErrorBoundary, so if its chunk fails, the whole app is replaced by the fallback. A local boundary, or skipping the dialog when the chunk fails, would contain the failure (low priority).
5. Draft loss on the auto-reload: agreed it's fine as a follow-up. It's limited to the redeploy case.

As agreed on #4056, I'll take the bounded idle prefetch once this lands. Prefetching ChatWindow first would hide the spinner on the most common first navigation. Tirth Patel (@tirth6851) has the browser coverage.

Comment thread frontend/src/utils/chunkReload.ts Resolved
Comment thread frontend/src/utils/chunkReload.ts Resolved
Comment thread frontend/src/App.tsx Resolved
Comment thread frontend/src/App.tsx Resolved
Comment thread frontend/src/App.tsx Resolved
@juliosuas

Copy link
Copy Markdown
Contributor

Hi Fazeel Usmani (@FazeelUsmani), this now conflicts with main after #4135 added the prompt-generation pages. I resolved it locally by merging main (no rebase). The only conflict is the import block in frontend/src/App.tsx. I dropped main's eager imports and added PromptGenerationsPage, NewPromptGenerationPage and PromptGenerationPage to your lazy() list, keeping promptGenerationRoutes as a static import. Type-check, lint and the full Jest suite (5,558 tests) pass, and vite build emits the three pages as separate chunks. Here is the resolved frontend/src/App.tsx if it saves you time: https://gist.github.com/juliosuas/1c773b87f85146985f92df08706205c8 (run git merge main, then replace frontend/src/App.tsx with this file and git add it). Feel free to just redo it on your side.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Reloading on its own discarded unsaved chat drafts, and also fired when the
server was briefly unreachable. Failed screens now stay inside the app shell
with a Reload page button that warns about unsaved work, and a failed Feedback
chunk shows a closable dialog. The error message wraps on narrow windows.

Adds tests that a screen still loading shows the spinner and moves the current
view right away, and that a failed screen keeps the shell.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Main enabled exactOptionalPropertyTypes; pass resetKeys only when set and allow an undefined onDismiss on the fallback.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@richlundeen

Richard Lundeen (richlundeen) commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

conversation:7135764966

Merged main (no rebase, now up to fc6de0d) and resolved frontend/src/App.tsx: the three prompt-generation pages are lazy like the other screens, and NEW_PROMPT_GENERATION_PATH and PROMPT_GENERATION_ROUTE are in SCREEN_PATHS, with new listed first so it doesn't match :generationId. Thanks for the gist; it was missing the SCREEN_PATHS entry, so moving between generations would have remounted the page. This is unchanged in a504c8aa.

review:5995326390

Thanks for the review. 1: the import no longer resolves to undefined, because the app no longer reloads on its own. 2: the description is updated. 3: added the pending-screen test. 4: screens and Feedback have local error boundaries. 5: rather than defer draft loss, the app now leaves the reload to the user, since the same event fires during a brief outage, not only after a redeploy. Pre-commit could not run locally for this push because the internal package mirror does not have pyyaml==6.0.4, types-pyyaml==6.0.12.20261122 or av==18.1.1 yet, so all pre-commit hooks (including ruff, ty-check and check-yaml) were skipped here and are left to CI. The frontend was checked locally with tsc and eslint.

Correction: this reply first said jest also passed on 1d23cbf5. It did not. The full jest run there had six failing tests in App.drafts, App.labels and App.targets: two hit the 15-second test timeout, and four failed waiting for an element or saw an old value. Rerun, they passed except one, which failed again and passed only in a later run. The lazy screens moved their module loading into the first timed test of those files, which made those tests slower under load.

a504c8aa imports the lazy screens at the top of those test files, keeping the 15-second timeout, and the full jest suite now passes locally (239 suites, 5589 tests). It also shows a small loading dialog with Cancel the first time Feedback opens, instead of nothing; the description is updated to match. Pre-commit hooks were skipped for that push for the same mirror reason.

review:5971469781

The remaining draft-loss item is fixed: the app no longer reloads on its own and offers Reload page with a note that reloading discards unsaved work. This is unchanged in a504c8aa.

Verified on published commit a504c8aa54634a78b5b8d66bad53cda4fb27e4c9.

…pp tests

The first Feedback open rendered nothing while its chunk downloaded; show a
small dialog with a spinner and Cancel instead.

Under ts-jest each lazy screen import ran inside the first timed test of
App.drafts, App.labels and App.targets; import the screens with the test
file so the 15 s limit measures the test, not module loading.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-checked at a504c8a, since my approval was on 8fcee2e. The changes since then answer all five points from my review:

  • With no automatic reload, the "undefined module" path is gone. The Reload page button with the draft-loss warning is the right trade-off, since the same error shows up during a short outage.
  • The local boundaries on screens, Registry tabs and Feedback keep the shell usable, and the RegistryLayout test covers the tabs.
  • The pending-screen test pins the screenKey behavior, which is the tour Back regression.

One small suggestion: test-utils/preloadLazyScreens.ts says "keep this list in step with the lazy imports in App.tsx", but nothing checks that. In the prefetch follow-up I'm moving the loaders into one screenLoaders module that both React.lazy and the prefetch use, with a test that compares the two lists. So this can wait for that PR if you prefer.

Still 👍 from me.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
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.

4 participants