Skip to content

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

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

Fazeel Usmani (FazeelUsmani) wants to merge 8 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 app now reloads once when that happens (and not again within 10 seconds, so a broken chunk can't cause a reload loop)
  • 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,414 kB

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

main this PR
Startup JS 2,652 kB 1,628 kB
Gzipped 738 kB 452 kB

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 Outdated
{/* Keyed by view so a switch to a screen that is still loading shows the spinner
right away. Otherwise React keeps the old screen until the chunk arrives, and
currentView lags behind the URL (the tour reads it to decide where to go). */}
<Suspense key={currentView} fallback={<Spinner label="Loading..." />}>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yeah, lazy() caches the rejected import so try again couldn't work. for chunk errors the button is now "Reload page"

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.

} catch {
return // without storage a reload loop can't be ruled out
}
event.preventDefault()

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.

After preventDefault(), Vite's preload helper resolves the import with undefined instead of rethrowing, so React.lazy errors and the app ErrorBoundary briefly shows "Try again" (and logs through onError) before the reload lands. A lazyScreen wrapper that turns an undefined module into a never-settling promise keeps the spinner up instead. Non-blocking.

if (asset) return asset
// Some browsers leave the URL out. The entry script's hashed name changes with each deploy,
// so keying on it still gives every build one reload.
const build = target.document?.querySelector('script[type="module"][src]')?.getAttribute('src') ?? ''

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.

Nice: keying URL-less errors by the hashed entry script gives each deploy its own reload. Could you add a one-line comment saying dev mode (/src/main.tsx) is intentionally a single key?

Comment thread frontend/src/App.tsx

// Screens with ids in the URL. Matching on the pattern keeps the ids out of the screen key, so
// moving between attacks, conversations or runs doesn't remount the screen.
const SCREEN_PATHS = [

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.

SCREEN_PATHS + matchPath looks right; I checked every param route in the table. Could you add a comment that any new param route must be added here, or it will remount on id changes?

Comment thread frontend/src/App.tsx
{/* Keyed by screen so a switch to a screen that is still loading shows the spinner
right away. Otherwise React keeps the old screen until the chunk arrives, and
currentView lags behind the URL (the tour reads it to decide where to go). */}
<Suspense key={screenKey(location.pathname)} fallback={<Spinner label="Loading..." />}>

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.

👍 keyed boundary. Could you add a test that a pending lazy screen shows the spinner and the sidebar's current item moves immediately? That's the tour Back regression this fixes.

Comment thread frontend/src/App.tsx
</Suspense>
</MainLayout>
{feedbackOpen && (
<Suspense fallback={null}>

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.

Nit: if the FeedbackDialog chunk fails, it takes down the whole app through the top-level ErrorBoundary. Consider a local boundary.

<div className={styles.content}>
<Outlet />
{/* Tabs load on first visit; keep the tab list in place while one does. */}
<Suspense key={selectedTab} fallback={<Spinner label="Loading..." />}>

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.

👍 key={selectedTab} keeps the tabs in place, and the test covers it.

@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.

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