diff --git a/src/features/agents/index.ts b/src/features/agents/index.ts index aecb694ac..6254e5585 100644 --- a/src/features/agents/index.ts +++ b/src/features/agents/index.ts @@ -117,7 +117,7 @@ export function activate(): () => void { icon: "toolwindow-agents", anchor: "right", order: 0.5, - component: lazyComponent(() => import("./AgentsView").then((m) => m.AgentsView)), + component: lazyComponent(() => import("./AgentsView").then((m) => m.AgentsView), { prefetch: true }), headerMenu: useAgentsHeaderMenu, plainTitle: true, headerActions: lazyComponent(() => import("./AgentsView").then((m) => m.AgentsHeaderActions)), @@ -137,7 +137,7 @@ export function activate(): () => void { }), registerEditorKind({ kind: SESSION_KIND, - component: lazyComponent(() => import("./SessionEditor").then((m) => m.SessionEditor)), + component: lazyComponent(() => import("./SessionEditor").then((m) => m.SessionEditor), { prefetch: true }), title: (input) => { const data = input.data as { task: string; title?: string }; return useAgents.getState().tasks.get(data.task)?.title ?? data.title ?? "Agent Task"; @@ -166,7 +166,7 @@ export function activate(): () => void { }), registerEditorKind({ kind: HOME_KIND, - component: lazyComponent(() => import("./HomeEditor").then((m) => m.HomeEditor)), + component: lazyComponent(() => import("./HomeEditor").then((m) => m.HomeEditor), { prefetch: true }), title: () => "New Agent Task", icon: (input) => { const task = useAgents.getState().tasks.get((input.data as { task: string }).task); diff --git a/src/features/search/index.ts b/src/features/search/index.ts index 187052748..04fda8c97 100644 --- a/src/features/search/index.ts +++ b/src/features/search/index.ts @@ -168,23 +168,31 @@ export function activate(): void | (() => void) { registerOverlay({ id: "search.everywhere", - component: lazyWhen(useEverywhereOpen, () => - import("./everywhere/SearchEverywhere").then((m) => m.SearchEverywhereOverlay), + component: lazyWhen( + useEverywhereOpen, + () => import("./everywhere/SearchEverywhere").then((m) => m.SearchEverywhereOverlay), + { prefetch: true }, ), }), registerOverlay({ id: "search.recent", - component: lazyWhen(useRecentOpen, () => import("./recent/RecentPopups").then((m) => m.RecentPopupsOverlay)), + component: lazyWhen(useRecentOpen, () => import("./recent/RecentPopups").then((m) => m.RecentPopupsOverlay), { + prefetch: true, + }), }), registerOverlay({ id: "search.findInFiles", - component: lazyWhen(useFindOpen, () => import("./find/FindInFiles").then((m) => m.FindInFilesOverlay)), + component: lazyWhen(useFindOpen, () => import("./find/FindInFiles").then((m) => m.FindInFilesOverlay), { + prefetch: true, + }), }), registerOverlay({ id: "search.scopes", component: ScopesDialogOverlay }), registerOverlay({ id: "search.fileStructure", - component: lazyWhen(useFileStructureOpen, () => - import("./structure/StructureView").then((m) => m.FileStructureOverlay), + component: lazyWhen( + useFileStructureOpen, + () => import("./structure/StructureView").then((m) => m.FileStructureOverlay), + { prefetch: true }, ), }), registerOverlay({ id: "search.bookmarks", component: BookmarkPopupsOverlay }), diff --git a/src/features/settings/dialog/LazySettingsDialog.tsx b/src/features/settings/dialog/LazySettingsDialog.tsx index 44e03ba5c..af07dfd22 100644 --- a/src/features/settings/dialog/LazySettingsDialog.tsx +++ b/src/features/settings/dialog/LazySettingsDialog.tsx @@ -31,7 +31,7 @@ export function unloadBuiltinPages() { void loaded?.then((dispose) => dispose()); } -const Dialog = lazyComponent(() => import("./SettingsDialog").then((m) => m.SettingsDialog)); +const Dialog = lazyComponent(() => import("./SettingsDialog").then((m) => m.SettingsDialog), { prefetch: true }); const ProjectStructure = lazyComponent(() => import("../languages/ProjectStructurePage").then((m) => m.ProjectStructureDialog), ); diff --git a/src/features/terminal/index.ts b/src/features/terminal/index.ts index 720dd24fd..f064d532f 100644 --- a/src/features/terminal/index.ts +++ b/src/features/terminal/index.ts @@ -122,7 +122,7 @@ export function activate(): () => void { icon: "toolwindow-terminal", anchor: "bottom", order: 10, - component: lazyComponent(() => loadTerminalRuntime().then((rt) => rt.TerminalView)), + component: lazyComponent(() => loadTerminalRuntime().then((rt) => rt.TerminalView), { prefetch: true }), headerContent: lazyComponent(() => loadTerminalRuntime().then((rt) => rt.TerminalTabs)), plainTitle: true, headerMenu: [ diff --git a/src/features/vcs/index.ts b/src/features/vcs/index.ts index ef922ab09..8d1d89bd0 100644 --- a/src/features/vcs/index.ts +++ b/src/features/vcs/index.ts @@ -146,7 +146,7 @@ function trackCommitWindow(): () => void { icon: "toolwindow-commit", anchor: "left", order: 1, - component: lazyComponent(() => import("./CommitView").then((m) => m.CommitToolWindow)), + component: lazyComponent(() => import("./CommitView").then((m) => m.CommitToolWindow), { prefetch: true }), headerContent: lazyComponent(() => import("./CommitView").then((m) => m.CommitTabs)), tabsReplaceTitle: true, useBadge: () => { @@ -284,7 +284,7 @@ export function activate(): () => void { icon: "toolwindow-git", anchor: "bottom", order: 5, - component: lazyComponent(() => import("./GitLog").then((m) => m.GitToolWindow)), + component: lazyComponent(() => import("./GitLog").then((m) => m.GitToolWindow), { prefetch: true }), headerContent: lazyComponent(() => import("./GitLog").then((m) => m.GitTabs)), }), registerEditorKind({ diff --git a/src/features/viewers/index.ts b/src/features/viewers/index.ts index a256eb37d..67906c6d0 100644 --- a/src/features/viewers/index.ts +++ b/src/features/viewers/index.ts @@ -125,7 +125,9 @@ export function activate(): () => void { registerTextEditorWrapper({ id: "viewers.markdown", matches: isMarkdownPath, - component: lazyComponent(() => import("./markdown/MarkdownEditor").then((m) => m.MarkdownEditor)), + component: lazyComponent(() => import("./markdown/MarkdownEditor").then((m) => m.MarkdownEditor), { + prefetch: true, + }), tabActions: MarkdownLayoutActions, useSourceHidden: useMarkdownSourceHidden, }), diff --git a/src/features/welcome/index.ts b/src/features/welcome/index.ts index c51386770..d62840ab3 100644 --- a/src/features/welcome/index.ts +++ b/src/features/welcome/index.ts @@ -13,7 +13,7 @@ export function activate(): () => void { trackSession(), onIdeEvent("windowGroupsChanged", () => void loadRecent()), provideWelcomeView(WelcomeView), - provideProjectPopup(lazyComponent(() => import("./ProjectPopup").then((m) => m.ProjectPopup))), + provideProjectPopup(lazyComponent(() => import("./ProjectPopup").then((m) => m.ProjectPopup), { prefetch: true })), registerOverlay({ id: "welcome.recentProjects", component: RecentProjectsPopup }), registerActions([ { diff --git a/src/ui/lazy.test.tsx b/src/ui/lazy.test.tsx new file mode 100644 index 000000000..8f488b3d4 --- /dev/null +++ b/src/ui/lazy.test.tsx @@ -0,0 +1,59 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, cleanup, render, screen } from "@testing-library/react"; +import type { ComponentType } from "react"; + +// The prefetch list is module state, so every test starts from a fresh module. +async function setup() { + vi.resetModules(); + return import("./lazy"); +} + +const view = + (name: string): ComponentType => + () =>

{name}

; + +describe("prefetchLazyComponents", () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => { + cleanup(); + vi.useRealTimers(); + }); + + it("loads only the components that opted in, and the rest still load when first rendered", async () => { + const { lazyComponent, lazyWhen, prefetchLazyComponents } = await setup(); + const warm = vi.fn(async () => view("warm")); + const warmWhen = vi.fn(async () => view("warm when")); + const cold = vi.fn(async () => view("cold")); + const coldWhen = vi.fn(async () => view("cold when")); + lazyComponent(warm, { prefetch: true }); + lazyWhen(() => false, warmWhen, { prefetch: true }); + const Cold = lazyComponent(cold); + lazyWhen(() => true, coldWhen); + + prefetchLazyComponents(); + await vi.advanceTimersByTimeAsync(60_000); + + expect(warm).toHaveBeenCalledTimes(1); + expect(warmWhen).toHaveBeenCalledTimes(1); + expect(cold).not.toHaveBeenCalled(); + expect(coldWhen).not.toHaveBeenCalled(); + + render(); + await act(async () => {}); + expect(screen.getByText("cold")).toBeInTheDocument(); + expect(cold).toHaveBeenCalledTimes(1); + }); + + it("does not load a prefetched component again when it is first rendered", async () => { + const { lazyComponent, prefetchLazyComponents } = await setup(); + const load = vi.fn(async () => view("warm")); + const Warm = lazyComponent(load, { prefetch: true }); + + prefetchLazyComponents(); + await vi.advanceTimersByTimeAsync(60_000); + render(); + + expect(screen.getByText("warm")).toBeInTheDocument(); + expect(load).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/ui/lazy.tsx b/src/ui/lazy.tsx index 5a0e05a2b..a6620c7a2 100644 --- a/src/ui/lazy.tsx +++ b/src/ui/lazy.tsx @@ -1,6 +1,17 @@ import { useEffect, useState, type ComponentType } from "react"; -const loaders: Array<() => Promise> = []; +/** Loaders of the components that opted into `prefetch`, in registration order. */ +const prefetched: Array<() => Promise> = []; + +type LazyOptions = { + /** + * Load this component's code in the background after start-up (see + * `prefetchLazyComponents`). Set it only for views most users open early, where + * a blank first frame would be noticeable; every prefetched chunk costs + * download, parse and heap in every window, opened or not. + */ + prefetch?: boolean; +}; export type LazyComponent

> = ComponentType

& { preload(): Promise>; @@ -12,7 +23,10 @@ export type LazyComponent

> = ComponentT * not `React.lazy`: a suspended boundary is revealed ~300 ms late (React's * fallback throttling), even when the chunk is already there. */ -export function lazyComponent

(load: () => Promise>): LazyComponent

{ +export function lazyComponent

( + load: () => Promise>, + { prefetch = false }: LazyOptions = {}, +): LazyComponent

{ let loaded: ComponentType

| null = null; let pending: Promise> | null = null; const get = () => @@ -23,7 +37,7 @@ export function lazyComponent

(load: () => Promise | null>(() => loaded); @@ -52,8 +66,9 @@ export function lazyComponent

(load: () => Promise( useShown: () => boolean, load: () => Promise>, + options?: LazyOptions, ): ComponentType

{ - const Lazy = lazyComponent(load); + const Lazy = lazyComponent(load, options); let shown = false; return function LazyWhen(props: P) { const now = useShown(); @@ -63,8 +78,9 @@ export function lazyWhen

( } /** - * Loads every lazy component's code one at a time while the app is idle, so a - * view opened later shows at once. Call after start-up. + * Loads the code of the lazy components marked `prefetch` one at a time while the + * app is idle, so those views show at once when first opened. The others load + * when first rendered. Call after start-up. */ export function prefetchLazyComponents(): () => void { let cancelled = false; @@ -72,8 +88,8 @@ export function prefetchLazyComponents(): () => void { const idle = (f: () => void) => typeof requestIdleCallback === "function" ? requestIdleCallback(f, { timeout: 10_000 }) : setTimeout(f, 200); const step = () => { - if (cancelled || next >= loaders.length) return; - void loaders[next++]!() + if (cancelled || next >= prefetched.length) return; + void prefetched[next++]!() .catch(() => {}) .finally(() => idle(step)); };