TypeScript
perf(web): halve the cold-start bundle by splitting Clerk and cold routes (#9058)
Wout Stiens80c708a1fa89
diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsxindex a3ba7667968..3d9e0e82e51 100644--- a/apps/web/src/components/AppSidebarLayout.tsx+++ b/apps/web/src/components/AppSidebarLayout.tsx@@ -1,6 +1,8 @@import { useAtomValue } from "@effect/atom-react";import * as Schema from "effect/Schema";import {+ lazy,+ Suspense,useEffect,useState,useSyncExternalStore,@@ -17,7 +19,6 @@ import { primaryServerKeybindingsAtom } from "../state/server";import { useEnvironmentIdentificationMode, useLegacySidebarEnabled } from "../hooks/useSettings";import LegacyThreadSidebar from "./LegacySidebar";import ThreadSidebar from "./Sidebar";-import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";import { SidebarChromeHeader } from "./sidebar/SidebarChrome";import {resolveSidebarStageFocusRingOffsetClass,@@ -43,6 +44,14 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "90px";+// The settings nav (and the Clerk profile surfaces behind it) only renders on+// settings routes; lazy-loading it keeps that subtree out of the startup chunk.+const SettingsSidebarNav = lazy(() =>+ import("./settings/SettingsSidebarNav").then((module) => ({+ default: module.SettingsSidebarNav,+ })),+);+function subscribeToViewportWidth(onChange: () => void): () => void {window.addEventListener("resize", onChange);return () => window.removeEventListener("resize", onChange);@@ -229,7 +238,9 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {{isOnSettings ? (<><SidebarChromeHeader isElectron={isElectron} />- <SettingsSidebarNav pathname={pathname} />+ <Suspense fallback={null}>+ <SettingsSidebarNav pathname={pathname} />+ </Suspense></>) : legacySidebarEnabled ? (<LegacyThreadSidebar />diff --git a/apps/web/src/components/clerk/BrowserManagedAuthShell.tsx b/apps/web/src/components/clerk/BrowserManagedAuthShell.tsxnew file mode 100644index 00000000000..285e9f7c760--- /dev/null+++ b/apps/web/src/components/clerk/BrowserManagedAuthShell.tsx@@ -0,0 +1,25 @@+import { ClerkProvider } from "@clerk/react";+import type { ReactNode } from "react";++import { ManagedRelayAuthProvider } from "../../cloud/managedAuth";+import { clerkAppearance } from "./clerkAppearance";++/**+ * Browser half of the managed-auth boundary, loaded lazily from the entry so+ * cloudless local mode never downloads a Clerk runtime. The browser provider+ * stays small on its own: it hotloads clerk-js at runtime instead of bundling+ * it.+ */+export default function BrowserManagedAuthShell({+ publishableKey,+ children,+}: {+ readonly publishableKey: string;+ readonly children: ReactNode;+}) {+ return (+ <ClerkProvider appearance={clerkAppearance} publishableKey={publishableKey}>+ <ManagedRelayAuthProvider>{children}</ManagedRelayAuthProvider>+ </ClerkProvider>+ );+}diff --git a/apps/web/src/components/clerk/ElectronManagedAuthShell.tsx b/apps/web/src/components/clerk/ElectronManagedAuthShell.tsxnew file mode 100644index 00000000000..3030c2a3955--- /dev/null+++ b/apps/web/src/components/clerk/ElectronManagedAuthShell.tsx@@ -0,0 +1,26 @@+import { passkeys } from "@clerk/electron/passkeys";+import { ClerkProvider } from "@clerk/electron/react";+import type { ReactNode } from "react";++import { ManagedRelayAuthProvider } from "../../cloud/managedAuth";+import { clerkAppearance } from "./clerkAppearance";++/**+ * Electron half of the managed-auth boundary. The Electron provider statically+ * bundles the full clerk-js runtime, so this module must only ever load+ * lazily, and only inside the desktop shell — importing it eagerly would put+ * clerk-js back into every client's startup graph.+ */+export default function ElectronManagedAuthShell({+ publishableKey,+ children,+}: {+ readonly publishableKey: string;+ readonly children: ReactNode;+}) {+ return (+ <ClerkProvider appearance={clerkAppearance} publishableKey={publishableKey} passkeys={passkeys}>+ <ManagedRelayAuthProvider>{children}</ManagedRelayAuthProvider>+ </ClerkProvider>+ );+}diff --git a/apps/web/src/components/settings/ThemeEditorHost.tsx b/apps/web/src/components/settings/ThemeEditorHost.tsxindex faf2d770e90..7eca6a2de52 100644--- a/apps/web/src/components/settings/ThemeEditorHost.tsx+++ b/apps/web/src/components/settings/ThemeEditorHost.tsx@@ -1,11 +1,17 @@-import { useCallback } from "react";+import { lazy, Suspense, useCallback } from "react";import { useTheme } from "../../hooks/useTheme";import { getThemeDefinition, type ThemeAppearance, type ThemeDefinition } from "../../themePalette";import { stackedThreadToast, toastManager } from "../ui/toast";-import { ThemeEditorPanel } from "./ThemeEditorPanel";import { useThemeEditorStore } from "./themeEditorStore";+// The host mounts above the router on every page, but the editor body only+// renders once a session opens; lazy-loading it keeps the editor UI out of+// the startup chunk.+const ThemeEditorPanel = lazy(() =>+ import("./ThemeEditorPanel").then((module) => ({ default: module.ThemeEditorPanel })),+);+/*** Renders the theme editor above the router. The editor paints its draft on* the live app, so it has to outlive the settings route: the point is to walk@@ -97,18 +103,20 @@ export function ThemeEditorHost() {const seedTheme = session.seedThemeId ? (getThemeDefinition(session.seedThemeId) ?? null) : null;return (- <ThemeEditorPanel- editingTheme={editingTheme}- initialAppearance={session.initialAppearance}- key={session.id}- onOpenChange={(open) => {- if (!open) closeThemeEditor();- }}- onSaved={handleSaved}- open- restoreTheme={refreshTheme}- seedName={session.seedName ?? undefined}- seedTheme={seedTheme}- />+ <Suspense fallback={null}>+ <ThemeEditorPanel+ editingTheme={editingTheme}+ initialAppearance={session.initialAppearance}+ key={session.id}+ onOpenChange={(open) => {+ if (!open) closeThemeEditor();+ }}+ onSaved={handleSaved}+ open+ restoreTheme={refreshTheme}+ seedName={session.seedName ?? undefined}+ seedTheme={seedTheme}+ />+ </Suspense>);}diff --git a/apps/web/src/lib/chunkReloadGuard.test.ts b/apps/web/src/lib/chunkReloadGuard.test.tsnew file mode 100644index 00000000000..632e8ec8cf0--- /dev/null+++ b/apps/web/src/lib/chunkReloadGuard.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it, vi } from "vite-plus/test";++import { clearChunkReloadGuard, reloadOnceForChunkLoadError } from "./chunkReloadGuard";++function createStorageStub(): Storage {+ const store = new Map<string, string>();+ return {+ getItem: (key) => store.get(key) ?? null,+ setItem: (key, value) => {+ store.set(key, value);+ },+ removeItem: (key) => {+ store.delete(key);+ },+ clear: () => store.clear(),+ key: (index) => [...store.keys()][index] ?? null,+ get length() {+ return store.size;+ },+ };+}++describe("reloadOnceForChunkLoadError", () => {+ it("reloads on the first failure and lets the second one surface", () => {+ const storage = createStorageStub();+ const reload = vi.fn();++ expect(reloadOnceForChunkLoadError(() => storage, reload)).toBe(true);+ expect(reload).toHaveBeenCalledTimes(1);++ expect(reloadOnceForChunkLoadError(() => storage, reload)).toBe(false);+ expect(reload).toHaveBeenCalledTimes(1);+ });++ it("reloads again after a successful boot cleared the guard", () => {+ const storage = createStorageStub();+ const reload = vi.fn();++ reloadOnceForChunkLoadError(() => storage, reload);+ clearChunkReloadGuard(() => storage);++ expect(reloadOnceForChunkLoadError(() => storage, reload)).toBe(true);+ expect(reload).toHaveBeenCalledTimes(2);+ });++ it("never reloads when storage is blocked, so a persistent failure cannot loop", () => {+ const reload = vi.fn();+ const blocked = () => {+ throw new DOMException("blocked", "SecurityError");+ };++ expect(reloadOnceForChunkLoadError(blocked, reload)).toBe(false);+ expect(reload).not.toHaveBeenCalled();+ expect(() => clearChunkReloadGuard(blocked)).not.toThrow();+ });+});diff --git a/apps/web/src/lib/chunkReloadGuard.ts b/apps/web/src/lib/chunkReloadGuard.tsnew file mode 100644index 00000000000..c31127816b0--- /dev/null+++ b/apps/web/src/lib/chunkReloadGuard.ts@@ -0,0 +1,39 @@+// Split chunks are fetched lazily, so a deploy (or desktop server swap)+// between page load and a later fetch can 404 the old hashed assets. One+// reload picks up the fresh index.html. A sessionStorage flag keeps a+// persistent failure from becoming a reload loop, and a successful boot clears+// it so the next stale deploy gets its own single reload.+const CHUNK_RELOAD_GUARD_KEY = "t3code:chunk-load-reloaded";++/**+ * Called from the `vite:preloadError` listener. Reloads at most once per+ * failure streak and returns whether it did, so the caller knows whether to+ * swallow the event or let the error surface through the normal paths.+ */+export function reloadOnceForChunkLoadError(+ getStorage: () => Storage = () => window.sessionStorage,+ reload: () => void = () => window.location.reload(),+): boolean {+ let alreadyReloaded: boolean;+ try {+ const storage = getStorage();+ alreadyReloaded = storage.getItem(CHUNK_RELOAD_GUARD_KEY) === "1";+ if (!alreadyReloaded) storage.setItem(CHUNK_RELOAD_GUARD_KEY, "1");+ } catch {+ // Without storage the guard cannot survive a reload, so a persistent+ // failure would loop forever. Let the error surface instead.+ return false;+ }+ if (alreadyReloaded) return false;+ reload();+ return true;+}++/** Clears the guard after a successful boot so a later stale deploy can reload again. */+export function clearChunkReloadGuard(getStorage: () => Storage = () => window.sessionStorage) {+ try {+ getStorage().removeItem(CHUNK_RELOAD_GUARD_KEY);+ } catch {+ // Blocked storage never held the flag.+ }+}diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsxindex 3cdc8188b75..78655785020 100644--- a/apps/web/src/main.tsx+++ b/apps/web/src/main.tsx@@ -1,14 +1,10 @@import React from "react";import ReactDOM from "react-dom/client";-import { ClerkProvider } from "@clerk/react";-import { passkeys } from "@clerk/electron/passkeys";-import { ClerkProvider as ElectronClerkProvider } from "@clerk/electron/react";import { createHashHistory, createBrowserHistory } from "@tanstack/react-router";import "./index.css";import { isElectron } from "./env";-import { ManagedRelayAuthProvider } from "./cloud/managedAuth";import { hasCloudPublicConfig } from "./cloud/publicConfig";import { getRouter } from "./router";import {@@ -16,7 +12,7 @@ import {syncDocumentWindowControlsOverlayClass,} from "./lib/windowControlsOverlay";import { AppRoot } from "./AppRoot";-import { clerkAppearance } from "./components/clerk/clerkAppearance";+import { clearChunkReloadGuard, reloadOnceForChunkLoadError } from "./lib/chunkReloadGuard";// Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.const history = isElectron ? createHashHistory() : createBrowserHistory();@@ -30,26 +26,59 @@ if (isElectron) {const clerkPublishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined;+// A failed split-chunk fetch usually means the hashed assets went stale under+// a deploy; one guarded reload picks up the fresh index.html.+let chunkLoadFailed = false;+let reloadScheduled = false;+window.addEventListener("vite:preloadError", (event) => {+ chunkLoadFailed = true;+ if (reloadOnceForChunkLoadError()) {+ reloadScheduled = true;+ event.preventDefault();+ }+});+const app = <AppRoot router={router} />;-ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(- <React.StrictMode>- {clerkPublishableKey && hasCloudPublicConfig() ? (- isElectron ? (- <ElectronClerkProvider- appearance={clerkAppearance}- publishableKey={clerkPublishableKey}- passkeys={passkeys}- >- <ManagedRelayAuthProvider>{app}</ManagedRelayAuthProvider>- </ElectronClerkProvider>- ) : (- <ClerkProvider appearance={clerkAppearance} publishableKey={clerkPublishableKey}>- <ManagedRelayAuthProvider>{app}</ManagedRelayAuthProvider>- </ClerkProvider>- )- ) : (- app- )}- </React.StrictMode>,-);+// Managed auth is cloud-only, and the Electron Clerk provider bundles the full+// clerk-js runtime. Loading only the selected runtime as a split chunk keeps+// every Clerk byte out of the startup graph for local-mode users, and keeps+// the bundled clerk-js out of the browser build entirely.+const managedAuthShellModule =+ clerkPublishableKey && hasCloudPublicConfig()+ ? isElectron+ ? import("./components/clerk/ElectronManagedAuthShell")+ : import("./components/clerk/BrowserManagedAuthShell")+ : null;++// The index.html boot splash lives inside #root, and React's first commit+// clears it. Resolve everything that first commit needs, the selected+// managed-auth runtime and the initial route's split chunks, before+// rendering, so the splash holds until real UI paints instead of dropping to+// a blank window while chunks download.+void Promise.all([managedAuthShellModule?.then((module) => module.default) ?? null, router.load()])+ .then(([ManagedAuthShell]) => {+ // A route chunk failure still resolves router.load(): the error is parked in+ // the lazy component and surfaces through the route error boundary. Skip the+ // paint when a reload is on its way, and only re-arm the guard after a boot+ // that fetched every chunk it asked for.+ if (reloadScheduled) return;+ if (!chunkLoadFailed) clearChunkReloadGuard();+ ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(+ <React.StrictMode>+ {ManagedAuthShell && clerkPublishableKey ? (+ <ManagedAuthShell publishableKey={clerkPublishableKey}>{app}</ManagedAuthShell>+ ) : (+ app+ )}+ </React.StrictMode>,+ );+ })+ .catch((error: unknown) => {+ // The auth shell chunk failed and the guarded reload is spent. Say so+ // instead of leaving the splash up forever.+ if (reloadScheduled) return;+ console.error("T3 Code failed to load its startup chunks.", error);+ const bootShell = document.getElementById("boot-shell");+ if (bootShell) bootShell.textContent = "T3 Code could not load. Reload to try again.";+ });diff --git a/apps/web/src/router.ts b/apps/web/src/router.tsindex 86ba9d69a17..4362dd3d70b 100644--- a/apps/web/src/router.ts+++ b/apps/web/src/router.ts@@ -7,6 +7,10 @@ export function getRouter(history: RouterHistory) {routeTree,history,context: {},+ // Route components are split chunks (autoCodeSplitting in vite.config);+ // fetching them on hover/focus intent hides the load from the first+ // settings or pull-request navigation.+ defaultPreload: "intent",});}diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.tsindex 6ee5de587b9..399f1bee497 100644--- a/apps/web/vite.config.ts+++ b/apps/web/vite.config.ts@@ -156,7 +156,10 @@ export default defineConfig(() => {assetsInclude: ["**/*.wasm"],plugins: [devCompressionPlugin(),- tanstackRouter(),+ // Route components load as split chunks so settings, pull-request, and+ // usage code stay out of the cold-start payload; the router prefetches+ // them on navigation intent (see getRouter's defaultPreload).+ tanstackRouter({ autoCodeSplitting: true }),react(),babel({// We need to be explicit about the parser options after moving to @vitejs/plugin-react v6.0.0