perf(ui): prefetch only the lazy views a window is likely to open (#5464)

After start-up, the workbench window loaded the code of every lazy view in the background, one chunk at a time, whether or not the user ever opened it: 122 extra chunks, +2.1 MB of JS and +3.0 MB of JS heap, plus ~300 ms of task time in the main window. `lazyComponent` / `lazyWhen` now take `{ prefetch: true }`, and `prefetchLazyComponents` loads only the components that set it. Everything else loads when it is first rendered, as it always could. Only the main workbench window prefetches (`mountWindowRoot(..., { prefetchLazy: true })`); auxiliary windows never did.
Opted in (what most sessions open early, where a blank first frame would show): Terminal tool window, Agents tool window + task and new-task editors, Commit and Git tool windows, the Settings dialog shell (not its pages), Search Everywhere / Find in Files / Recent files / File structure overlays, the markdown preview editor, the project switcher popup. Left on demand: all database, debugger, plugins, notebook, logcat, remote/deployment, github, python-console, web, build-tools, templates views, all settings pages (they already preload on page reveal via `preloadBuiltinPage`), edit-configurations, merge/compare/local-history editors, Run and Find tool windows (their stripes only appear on use, so the view mounts as it appears).

Co-authored-by: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com>
This commit is contained in:
Mr0Bread
2026-11-24 01:37:47 +08:00
committed by GitHub
parent 518a62ea6c
commit 92d94a7ac4
9 changed files with 108 additions and 23 deletions
+3 -3
View File
@@ -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);
+14 -6
View File
@@ -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 }),
@@ -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),
);
+1 -1
View File
@@ -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: [
+2 -2
View File
@@ -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({
+3 -1
View File
@@ -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,
}),
+1 -1
View File
@@ -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([
{
+59
View File
@@ -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 =>
() => <p>{name}</p>;
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(<Cold />);
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(<Warm />);
expect(screen.getByText("warm")).toBeInTheDocument();
expect(load).toHaveBeenCalledTimes(1);
});
});
+24 -8
View File
@@ -1,6 +1,17 @@
import { useEffect, useState, type ComponentType } from "react";
const loaders: Array<() => Promise<unknown>> = [];
/** Loaders of the components that opted into `prefetch`, in registration order. */
const prefetched: Array<() => Promise<unknown>> = [];
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<P extends object = Record<string, never>> = ComponentType<P> & {
preload(): Promise<ComponentType<P>>;
@@ -12,7 +23,10 @@ export type LazyComponent<P extends object = Record<string, never>> = 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<P extends object>(load: () => Promise<ComponentType<P>>): LazyComponent<P> {
export function lazyComponent<P extends object>(
load: () => Promise<ComponentType<P>>,
{ prefetch = false }: LazyOptions = {},
): LazyComponent<P> {
let loaded: ComponentType<P> | null = null;
let pending: Promise<ComponentType<P>> | null = null;
const get = () =>
@@ -23,7 +37,7 @@ export function lazyComponent<P extends object>(load: () => Promise<ComponentTyp
throw e;
},
));
loaders.push(get);
if (prefetch) prefetched.push(get);
function LazyComponent(props: P) {
const [Component, setComponent] = useState<ComponentType<P> | null>(() => loaded);
@@ -52,8 +66,9 @@ export function lazyComponent<P extends object>(load: () => Promise<ComponentTyp
export function lazyWhen<P extends object>(
useShown: () => boolean,
load: () => Promise<ComponentType<P>>,
options?: LazyOptions,
): ComponentType<P> {
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<P extends object>(
}
/**
* 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));
};