Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

perf(ui): load desktop sections on navigation intent (#263)

Ruben Lütkef416f253543f
diff --git a/jarvis/ui/web/frontend/src/components/layout/MainView.prefetch.test.tsx b/jarvis/ui/web/frontend/src/components/layout/MainView.prefetch.test.tsx
new file mode 100644
index 0000000000..c409b8e916
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/layout/MainView.prefetch.test.tsx
@@ -0,0 +1,98 @@
+import { act, cleanup, render, screen } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, expect, test, vi } from "vitest";
+
+import { MainView } from "./MainView";
+import { useEventStore } from "@/store/events";
+
+const loads = vi.hoisted(() => [] as string[]);
+vi.mock("@/views/ChatsSurface", () => ({ ChatsSurface: () => <div>home</div> }));
+vi.mock("@/views/SettingsHubView", () => {
+ loads.push("settings");
+ return { SettingsHubDialog: () => null };
+});
+vi.mock("@/views/society/SocietyView", () => {
+ loads.push("agents");
+ return { SocietyView: () => <div>agents ready</div> };
+});
+vi.mock("@/views/WikiView", () => {
+ loads.push("memory");
+ return { WikiView: () => null };
+});
+vi.mock("@/views/PluginsDialog", () => {
+ loads.push("plugins");
+ return { PluginsDialog: () => null };
+});
+vi.mock("@/views/AgenticIdeView", () => {
+ loads.push("ide");
+ return { AgenticIdeView: () => null };
+});
+vi.mock("@/views/AutomationsView", () => {
+ loads.push("tasks");
+ return { AutomationsView: () => null };
+});
+vi.mock("@/views/SessionsView", () => {
+ loads.push("sessions");
+ return { SessionsView: () => null };
+});
+vi.mock("@/views/ClisHubView", () => {
+ loads.push("clis");
+ return { ClisHubView: () => null };
+});
+vi.mock("@/views/DocsView", () => {
+ loads.push("docs");
+ return { DocsView: () => null };
+});
+vi.mock("@/views/BoardView", () => {
+ loads.push("board");
+ return { BoardView: () => null };
+});
+vi.mock("@/views/RunInspectorView", () => {
+ loads.push("runs");
+ return { RunInspectorView: () => null };
+});
+vi.mock("@/views/VoiceHubView", () => {
+ loads.push("voice");
+ return { VoiceHubView: () => null };
+});
+vi.mock("@/views/VisualizationView", () => {
+ loads.push("artifacts");
+ return { VisualizationView: () => null };
+});
+vi.mock("@/views/MarketplaceView", () => {
+ loads.push("marketplace");
+ return { MarketplaceView: () => null };
+});
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+test("an idle home window loads no unused sections or speculative data; navigation still loads its view", async () => {
+ vi.useFakeTimers();
+ useEventStore.setState({ activeSection: "chats", solo: false, detachedViews: [] });
+ const client = new QueryClient();
+ const prefetch = vi.spyOn(client, "prefetchQuery").mockResolvedValue(undefined);
+ render(<QueryClientProvider client={client}><MainView /></QueryClientProvider>);
+
+ // Give both idle-callback and timer implementations enough slots to drain
+ // the old blanket warm-up, without measuring wall time on a busy host.
+ for (let i = 0; i < 15; i += 1) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(4_000);
+ await vi.dynamicImportSettled();
+ });
+ }
+ expect(loads).toEqual([]);
+ expect(prefetch).not.toHaveBeenCalled();
+ expect(screen.getByText("home")).toBeDefined();
+
+ await act(async () => {
+ useEventStore.getState().setActiveSection("agents");
+ await vi.dynamicImportSettled();
+ });
+ expect(loads).toEqual(["agents"]);
+ expect(screen.getByText("agents ready")).toBeDefined();
+ client.clear();
+}, 30_000);
diff --git a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
index e87e30807a..4c71a0f531 100644
--- a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
@@ -1,28 +1,19 @@
import {
lazy,
Suspense,
- useContext,
useEffect,
useState,
type ComponentType,
type LazyExoticComponent,
} from "react";
-import { QueryClientContext } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";
-import {
- costDailyQueryOptions,
- costSummaryQueryOptions,
- EMPTY_FILTERS,
-} from "@/hooks/useCosts";
-import { overviewQueryOptions } from "@/hooks/useLocalModels";
-import { readLocalModelsSeed } from "@/lib/localModelsSeed";
-import { useEventStore } from "@/store/events";
+import { useEventStore, type SectionId } from "@/store/events";
+import { sectionPrefetch } from "@/lib/sectionPrefetch";
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { ViewErrorBoundary } from "@/components/ViewErrorBoundary";
import { DetachedViewPlaceholder } from "@/components/layout/DetachedViewPlaceholder";
import { SETTINGS_HUB_IDS } from "@/components/layout/navGroups";
-import { loadTurnTrace } from "@/components/home/TurnSteps";
// Type-only, so the section's chunk stays split out of the entry bundle.
import type { AgenticIdeViewProps } from "@/views/AgenticIdeView";
// The default section is the one view that must be on screen the moment React
@@ -33,38 +24,18 @@ import type { AgenticIdeViewProps } from "@/views/AgenticIdeView";
import { ChatsSurface } from "@/views/ChatsSurface";
/**
- * Section views are CODE-SPLIT, then prefetched while the app is idle.
- *
- * Why (measured 2026-07-26): importing all 21 views statically linked every
- * section — plus the terminal emulator and the charting library — into a single
- * 2.83 MB entry chunk. A WebView must download, parse AND execute all of it
- * before React paints, which is the "the app feels sluggish on start" report.
- * The boot splash in index.html only hid that wait.
- *
- * Splitting alone would move the cost rather than remove it: the first visit to
- * a section would then pay for its chunk. `useIdleViewPrefetch` closes that gap
- * by pulling the remaining chunks in during idle time after the first paint, so
- * switching sections stays instant while startup only pays for what it shows.
+ * Keep unused views out of every window's startup work. Navigation loads its
+ * view through React.lazy; a deliberate sidebar hover/focus warms only that
+ * destination. Blanket idle imports used to execute all 14 views per window.
*/
type ViewModule = { default: ComponentType };
type ViewLoader = () => Promise<ViewModule>;
-/**
- * Loaders for every split view, in the order the idle prefetch warms them.
- *
- * Typed as returning `unknown` because warming a chunk only cares that the
- * import RAN — the module's shape is the caller's business, and pinning the
- * props-free shape here would keep `lazyPropView` out of the warm-up.
- */
-const prefetchQueue: (() => Promise<unknown>)[] = [];
-
-// First in line: the turn-trace renderer of the front page's voice stage. It
-// is split out of the entry (see TurnSteps) but belongs to the screen that is
-// already open, so it is warmed before any other section.
-prefetchQueue.push(loadTurnTrace);
-
-function lazyView(loader: ViewLoader): LazyExoticComponent<ComponentType> {
- prefetchQueue.push(loader);
+function lazyView(
+ sections: readonly SectionId[],
+ loader: ViewLoader,
+): LazyExoticComponent<ComponentType> {
+ sectionPrefetch.register(sections, loader);
return lazy(loader);
}
@@ -78,32 +49,31 @@ function lazyView(loader: ViewLoader): LazyExoticComponent<ComponentType> {
* answer for it (see `MainView`).
*/
function lazyPropView<P>(
+ sections: readonly SectionId[],
loader: () => Promise<{ default: ComponentType<P> }>,
): LazyExoticComponent<ComponentType<P>> {
- prefetchQueue.push(loader);
+ sectionPrefetch.register(sections, loader);
return lazy(loader);
}
-// Ordered roughly by how likely a section is to be opened, so the warm-up
-// front-loads what the user reaches for first. Views are named exports, hence
-// the explicit unwrap into the { default } shape React.lazy expects.
+// Views are named exports, hence the explicit React.lazy default unwrap.
// The Settings hub — Profile, {name}.md, Contacts, Socials, API Keys, Local
// models, Wallpaper, Spend and Feedback behind one left-nav dialog. The hub
// statically owns only its shell; every tab stays its own lazy chunk (see
// SettingsHubView), so this one import replaces the eleven per-view imports
// below without merging their chunks back together.
-const SettingsHubDialog = lazyPropView<{ onClose: () => void }>(() =>
+const SettingsHubDialog = lazyPropView<{ onClose: () => void }>(SETTINGS_HUB_IDS, () =>
import("@/views/SettingsHubView").then((m) => ({ default: m.SettingsHubDialog })),
);
// The Agents section is the society (MASTERPLAN §4.1): stage + agents rail +
// model cards. The board it replaced is the society's stage until the island
// lands, loaded by SocietyView itself.
-const SocietyView = lazyView(() =>
+const SocietyView = lazyView(["agents"], () =>
import("@/views/society/SocietyView").then((m) => ({
default: m.SocietyView,
})),
);
-const WikiView = lazyView(() =>
+const WikiView = lazyView(["memory"], () =>
import("@/views/WikiView").then((m) => ({ default: m.WikiView })),
);
type PluginArea = "plugins" | "mcps" | "skills";
@@ -115,31 +85,31 @@ const isSettingsHub = (section: string) =>
// replacing it.
const isOverlaySection = (section: string) => isPluginArea(section) || isSettingsHub(section);
-const PluginsDialog = lazyPropView<{ onClose: () => void; area: PluginArea; onAreaChange: (area: PluginArea) => void }>(() =>
+const PluginsDialog = lazyPropView<{ onClose: () => void; area: PluginArea; onAreaChange: (area: PluginArea) => void }>(["plugins", "mcps", "skills"], () =>
import("@/views/PluginsDialog").then((m) => ({ default: m.PluginsDialog })),
);
// The prop type is named rather than inferred: inferring it from the loader's
// return value is circular (the loader's contextual type is what depends on it),
// and TypeScript resolves that by falling back to `never`.
-const AgenticIdeView = lazyPropView<AgenticIdeViewProps>(() =>
+const AgenticIdeView = lazyPropView<AgenticIdeViewProps>(["agentic-ide", "agentic-ide-classic", "chat-workspace"], () =>
import("@/views/AgenticIdeView").then((m) => ({ default: m.AgenticIdeView })),
);
-const AutomationsView = lazyView(() =>
+const AutomationsView = lazyView(["tasks"], () =>
import("@/views/AutomationsView").then((m) => ({ default: m.AutomationsView })),
);
-const SessionsView = lazyView(() =>
+const SessionsView = lazyView(["sessions"], () =>
import("@/views/SessionsView").then((m) => ({ default: m.SessionsView })),
);
-const ClisHubView = lazyView(() =>
+const ClisHubView = lazyView(["clis", "cli-test-hub"], () =>
import("@/views/ClisHubView").then((m) => ({ default: m.ClisHubView })),
);
-const DocsView = lazyView(() =>
+const DocsView = lazyView(["docs"], () =>
import("@/views/DocsView").then((m) => ({ default: m.DocsView })),
);
-const BoardView = lazyView(() =>
+const BoardView = lazyView(["board"], () =>
import("@/views/BoardView").then((m) => ({ default: m.BoardView })),
);
-const RunInspectorView = lazyView(() =>
+const RunInspectorView = lazyView(["run_inspector"], () =>
import("@/views/RunInspectorView").then((m) => ({
default: m.RunInspectorView,
})),
@@ -148,123 +118,20 @@ const RunInspectorView = lazyView(() =>
// behind the one "{name} Voice" sidebar entry. Only the hub is split out here —
// it statically imports its five tabs, so they travel in its chunk instead of
// being prefetched as separate ones.
-const VoiceHubView = lazyView(() =>
+const VoiceHubView = lazyView(["dictation", "dictionary", "voice-shortcuts", "voice-language", "voice-api-keys"], () =>
import("@/views/VoiceHubView").then((m) => ({ default: m.VoiceHubView })),
);
-const VisualizationView = lazyView(() =>
+const VisualizationView = lazyView(["visualization"], () =>
import("@/views/VisualizationView").then((m) => ({
default: m.VisualizationView,
})),
);
-const MarketplaceView = lazyView(() =>
+const MarketplaceView = lazyView(["marketplace"], () =>
import("@/views/MarketplaceView").then((m) => ({
default: m.MarketplaceView,
})),
);
-type IdleWindow = Window & {
- requestIdleCallback?: (
- cb: () => void,
- opts?: { timeout: number },
- ) => number;
- cancelIdleCallback?: (handle: number) => void;
-};
-
-/**
- * Run `task` when the browser is idle, falling back to a timer.
- *
- * `requestIdleCallback` is absent on older Safari/WebKit, which is exactly the
- * macOS WebView this app also ships in, so the timer fallback is load-bearing
- * rather than cosmetic. The returned function cancels a pending slot.
- */
-function scheduleIdle(task: () => void): () => void {
- const w = window as IdleWindow;
- if (typeof w.requestIdleCallback === "function") {
- // The timeout caps how long a busy main thread may starve the warm-up.
- const handle = w.requestIdleCallback(task, { timeout: 2_000 });
- return () => w.cancelIdleCallback?.(handle);
- }
- const handle = window.setTimeout(task, 300);
- return () => window.clearTimeout(handle);
-}
-
-/**
- * Warm the split view chunks one at a time, each in its own idle slot.
- *
- * Sequential rather than parallel on purpose: firing 20 imports at once would
- * compete with the requests the visible section is making, which is the very
- * stall this is meant to remove. A failed prefetch is ignored — the chunk is
- * simply fetched again on navigation, where Suspense handles it.
- */
-/**
- * How long after mount the Spend warm-up runs. Past the boot burst — this app
- * makes about thirty API calls before it settles — and well inside the time it
- * takes anyone to read the home screen and reach for the sidebar.
- */
-const SPEND_WARM_DELAY_MS = 2_500;
-
-function useIdleViewPrefetch(): void {
- // Optional on purpose: the shell renders without a QueryClient in some
- // tests, and the data warm-up is a bonus, never a requirement.
- const queryClient = useContext(QueryClientContext);
- useEffect(() => {
- let cancelled = false;
- let cancelSlot: (() => void) | null = null;
- let index = 0;
- const queue = [...prefetchQueue];
- if (queryClient) {
- // After the chunks: the Local models overview, when a previous open
- // left a seed — so the section paints with server truth, not just the
- // on-disk snapshot, the moment it is opened.
- queue.push(() => {
- const seed = readLocalModelsSeed();
- return seed
- ? queryClient.prefetchQuery(overviewQueryOptions(seed))
- : Promise.resolve();
- });
- }
-
- const pump = () => {
- if (cancelled || index >= queue.length) return;
- const loader = queue[index++];
- void loader()
- .catch(() => undefined)
- .then(() => {
- if (cancelled) return;
- cancelSlot = scheduleIdle(pump);
- });
- };
-
- cancelSlot = scheduleIdle(pump);
-
- // Spend, on its own clock rather than at the end of that queue.
- //
- // It is the one section whose first read is measured in a second rather
- // than milliseconds — it aggregates every store the app writes plus the
- // coding-CLI transcripts — so it is the one where arriving to a finished
- // page instead of a loading one is the whole difference. Queued behind
- // twenty module imports, each waiting for its own idle slot, it had not
- // run twenty-five seconds into a fresh bundle. A plain timer is late
- // enough to stay out of the boot burst and early enough to beat a click.
- // The section opens on `EMPTY_FILTERS`, so these are the keys it asks for.
- const warmSpend = window.setTimeout(() => {
- if (cancelled || !queryClient) return;
- void queryClient
- .prefetchQuery(costSummaryQueryOptions(EMPTY_FILTERS))
- .catch(() => undefined);
- void queryClient
- .prefetchQuery(costDailyQueryOptions(EMPTY_FILTERS))
- .catch(() => undefined);
- }, SPEND_WARM_DELAY_MS);
-
- return () => {
- cancelled = true;
- cancelSlot?.();
- window.clearTimeout(warmSpend);
- };
- }, [queryClient]);
-}
-
/** Quiet time before a loading section admits it is loading. */
export const LOADING_HINT_MS = 400;
@@ -397,8 +264,6 @@ export function MainView() {
if (!isOverlaySection(active) && backgroundSection !== active) setBackgroundSection(active);
const displayed = isOverlaySection(active) ? backgroundSection : active;
- useIdleViewPrefetch();
-
/*
* While a coding view lives in a detached solo window, THIS (non-solo)
* window must not keep a mounted IDE instance around — not even hidden: the
diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx
index ae33972c8c..eed46894e6 100644
--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx
@@ -13,6 +13,34 @@ import { isSectionId, useEventStore } from "@/store/events";
import { useHomeStore } from "@/store/home";
import { useIdeChatStore } from "@/store/ideChat";
import { useIdeProjectsStore } from "@/store/ideProjects";
+import { sectionPrefetch } from "@/lib/sectionPrefetch";
+import { SECTION_PREFETCH_DELAY_MS } from "@/hooks/useSectionPrefetch";
+
+test.each([SIDEBAR_DEFAULT_WIDTH, SIDEBAR_RAIL_WIDTH])(
+ "sidebar intent warms a destination without navigating (width=%s)",
+ (width) => {
+ vi.useFakeTimers();
+ const warm = vi.spyOn(sectionPrefetch, "prefetch").mockResolvedValue();
+ try {
+ useEventStore.setState({ activeSection: "chats" });
+ renderSidebar(width);
+ expect(warm).not.toHaveBeenCalled();
+ fireEvent.mouseEnter(screen.getByTestId("nav-row-agents"));
+ act(() => { vi.advanceTimersByTime(SECTION_PREFETCH_DELAY_MS); });
+ expect(warm).toHaveBeenCalledExactlyOnceWith("agents");
+ expect(useEventStore.getState().activeSection).toBe("chats");
+ fireEvent.focus(screen.getByTestId("sidebar-profile-toggle"));
+ act(() => { vi.advanceTimersByTime(SECTION_PREFETCH_DELAY_MS); });
+ expect(warm).toHaveBeenLastCalledWith("profile");
+ fireEvent.click(screen.getByTestId("nav-row-agents"));
+ expect(useEventStore.getState().activeSection).toBe("agents");
+ } finally {
+ cleanup();
+ warm.mockRestore();
+ vi.useRealTimers();
+ }
+ },
+);
test("IDE rail keeps workspace options and Jarvis Live reachable", () => {
act(() => {
diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
index 4ea6d87502..e64775f1c6 100644
--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
@@ -17,6 +17,7 @@ import {
type NavItem,
} from "@/components/layout/navGroups";
import { useEventStore } from "@/store/events";
+import { useSectionPrefetch } from "@/hooks/useSectionPrefetch";
import { useVoiceReadiness } from "@/hooks/useVoiceReadiness";
import { useVoiceMode } from "@/hooks/useVoiceMode";
import { useSectionHealth } from "@/hooks/useProviders";
@@ -168,6 +169,8 @@ export function Sidebar({
collapsed = false,
}: SidebarProps = {}) {
const t = useT();
+ const profilePrefetch = useSectionPrefetch("profile");
+ const marketplacePrefetch = useSectionPrefetch("marketplace");
const active = useEventStore((s) => s.activeSection);
const setActive = useEventStore((s) => s.setActiveSection);
const activeIdeWorkspaceId = useIdeProjectsStore((s) => s.activeWorkspaceId);
@@ -549,7 +552,7 @@ export function Sidebar({
needs care, must be visible without opening anything. */}
<div className="shrink-0 border-t border-border p-2">
<div className={cn("flex items-center gap-1", railed && "flex-col")}>
- <button type="button" onClick={() => setActive("profile")} title={t("nav.profile")}
+ <button type="button" {...profilePrefetch} onClick={() => setActive("profile")} title={t("nav.profile")}
data-testid="sidebar-profile-toggle"
className={cn(rowClass, "min-w-0 flex-1", hubActive && "jarvis-nav-active bg-secondary text-foreground")}>
<span className="relative shrink-0">
@@ -560,7 +563,7 @@ export function Sidebar({
</span>
{!railed && <span className="min-w-0 flex-1 truncate text-left">{identity.data?.signed_in ? identity.data.login || t("nav.profile") : t("nav.profile")}</span>}
</button>
- <button type="button" onClick={() => setActive("marketplace")} title={t("nav.marketplace")}
+ <button type="button" {...marketplacePrefetch} onClick={() => setActive("marketplace")} title={t("nav.marketplace")}
aria-label={t("nav.marketplace")} data-testid="nav-row-marketplace"
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<Store aria-hidden className="h-5 w-5" />
@@ -612,6 +615,7 @@ function NavRow({
warnTitle?: string;
onClick: () => void;
}) {
+ const prefetch = useSectionPrefetch(item.id);
const Icon = item.icon;
const hint = alert ? alertTitle : warn ? warnTitle : undefined;
/*
@@ -640,6 +644,7 @@ function NavRow({
<button
type="button"
data-testid={`nav-row-${item.id}`}
+ {...prefetch}
onClick={onClick}
title={compact ? `${label}${hint ? ` — ${hint}` : ""}` : hint}
aria-label={compact ? label : undefined}
diff --git a/jarvis/ui/web/frontend/src/hooks/useSectionPrefetch.test.tsx b/jarvis/ui/web/frontend/src/hooks/useSectionPrefetch.test.tsx
new file mode 100644
index 0000000000..5042dd7cec
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useSectionPrefetch.test.tsx
@@ -0,0 +1,51 @@
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import { sectionPrefetch } from "@/lib/sectionPrefetch";
+import { SECTION_PREFETCH_DELAY_MS, useSectionPrefetch } from "./useSectionPrefetch";
+import type { SectionId } from "@/store/events";
+
+function Link({ section = "agents" }: { section?: SectionId }) {
+ return <button {...useSectionPrefetch(section)}>destination</button>;
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.spyOn(sectionPrefetch, "prefetch").mockResolvedValue();
+});
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+});
+
+test("mounting and a passing pointer do no work", () => {
+ render(<Link />);
+ act(() => { vi.advanceTimersByTime(60_000); });
+ const button = screen.getByRole("button");
+ fireEvent.mouseEnter(button);
+ act(() => { vi.advanceTimersByTime(SECTION_PREFETCH_DELAY_MS - 1); });
+ fireEvent.mouseLeave(button);
+ act(() => { vi.advanceTimersByTime(60_000); });
+ expect(sectionPrefetch.prefetch).not.toHaveBeenCalled();
+});
+
+test.each(["mouseEnter", "focus"] as const)("%s warms only the intended destination", (event) => {
+ render(<Link />);
+ fireEvent[event](screen.getByRole("button"));
+ act(() => { vi.advanceTimersByTime(SECTION_PREFETCH_DELAY_MS); });
+ expect(sectionPrefetch.prefetch).toHaveBeenCalledExactlyOnceWith("agents");
+});
+
+test("blur, a new destination and unmount cancel pending work", () => {
+ const { rerender, unmount } = render(<Link />);
+ fireEvent.focus(screen.getByRole("button"));
+ fireEvent.blur(screen.getByRole("button"));
+ act(() => { vi.advanceTimersByTime(SECTION_PREFETCH_DELAY_MS); });
+ fireEvent.mouseEnter(screen.getByRole("button"));
+ rerender(<Link section="docs" />);
+ act(() => { vi.advanceTimersByTime(SECTION_PREFETCH_DELAY_MS); });
+ fireEvent.focus(screen.getByRole("button"));
+ unmount();
+ act(() => { vi.advanceTimersByTime(SECTION_PREFETCH_DELAY_MS); });
+ expect(sectionPrefetch.prefetch).not.toHaveBeenCalled();
+});
diff --git a/jarvis/ui/web/frontend/src/hooks/useSectionPrefetch.ts b/jarvis/ui/web/frontend/src/hooks/useSectionPrefetch.ts
new file mode 100644
index 0000000000..5b47cce645
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useSectionPrefetch.ts
@@ -0,0 +1,30 @@
+import { useEffect, useRef } from "react";
+import { sectionPrefetch } from "@/lib/sectionPrefetch";
+import type { SectionId } from "@/store/events";
+
+export const SECTION_PREFETCH_DELAY_MS = 150;
+
+/** A brief hover/focus warms one destination; passing over the rail warms none. */
+export function useSectionPrefetch(section: SectionId) {
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const cancel = () => {
+ if (timer.current !== null) clearTimeout(timer.current);
+ timer.current = null;
+ };
+ useEffect(() => cancel, [section]);
+
+ const schedule = () => {
+ cancel();
+ timer.current = setTimeout(() => {
+ timer.current = null;
+ void sectionPrefetch.prefetch(section);
+ }, SECTION_PREFETCH_DELAY_MS);
+ };
+
+ return {
+ onMouseEnter: schedule,
+ onMouseLeave: cancel,
+ onFocus: schedule,
+ onBlur: cancel,
+ };
+}
diff --git a/jarvis/ui/web/frontend/src/lib/sectionPrefetch.test.ts b/jarvis/ui/web/frontend/src/lib/sectionPrefetch.test.ts
new file mode 100644
index 0000000000..5e7a619834
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/sectionPrefetch.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it, vi } from "vitest";
+import { createSectionPrefetcher } from "./sectionPrefetch";
+
+describe("section prefetch", () => {
+ it("does no work at registration and only warms the requested section", async () => {
+ const registry = createSectionPrefetcher();
+ const agents = vi.fn().mockResolvedValue({});
+ const docs = vi.fn().mockResolvedValue({});
+ registry.register(["agents"], agents);
+ registry.register(["docs"], docs);
+ expect(agents).not.toHaveBeenCalled();
+ expect(docs).not.toHaveBeenCalled();
+ await registry.prefetch("agents");
+ await registry.prefetch("chats");
+ expect(agents).toHaveBeenCalledTimes(1);
+ expect(docs).not.toHaveBeenCalled();
+ });
+
+ it("deduplicates in-flight and completed requests across section aliases", async () => {
+ const registry = createSectionPrefetcher();
+ let resolve!: () => void;
+ const loader = vi.fn(() => new Promise<void>((done) => { resolve = done; }));
+ registry.register(["agentic-ide", "agentic-ide-classic"], loader);
+ const first = registry.prefetch("agentic-ide");
+ expect(registry.prefetch("agentic-ide-classic")).toBe(first);
+ await Promise.resolve();
+ resolve();
+ await first;
+ await registry.prefetch("agentic-ide");
+ expect(loader).toHaveBeenCalledTimes(1);
+ });
+
+ it("permits retry after a rejected or synchronously throwing loader", async () => {
+ const registry = createSectionPrefetcher();
+ const loader = vi.fn()
+ .mockRejectedValueOnce(new Error("offline"))
+ .mockImplementationOnce(() => { throw new Error("unavailable"); })
+ .mockResolvedValue({});
+ registry.register(["docs"], loader);
+ await registry.prefetch("docs");
+ await registry.prefetch("docs");
+ await registry.prefetch("docs");
+ await registry.prefetch("docs");
+ expect(loader).toHaveBeenCalledTimes(3);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/sectionPrefetch.ts b/jarvis/ui/web/frontend/src/lib/sectionPrefetch.ts
new file mode 100644
index 0000000000..a1c3c6b351
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/sectionPrefetch.ts
@@ -0,0 +1,33 @@
+import type { SectionId } from "@/store/events";
+
+type Loader = () => Promise<unknown>;
+
+/** Register without executing: unopened windows must not warm every feature. */
+export function createSectionPrefetcher() {
+ const loaders = new Map<SectionId, Loader>();
+ const pending = new Map<Loader, Promise<void>>();
+
+ return {
+ register(sections: readonly SectionId[], loader: Loader) {
+ for (const section of sections) loaders.set(section, loader);
+ },
+ prefetch(section: SectionId): Promise<void> {
+ const loader = loaders.get(section);
+ if (!loader) return Promise.resolve();
+ const existing = pending.get(loader);
+ if (existing) return existing;
+ const request = Promise.resolve().then(loader).then(
+ () => undefined,
+ () => {
+ // Speculation is optional. Navigation retries through React.lazy
+ // and its error boundary; a failed warm-up must not poison it.
+ pending.delete(loader);
+ },
+ );
+ pending.set(loader, request);
+ return request;
+ },
+ };
+}
+
+export const sectionPrefetch = createSectionPrefetcher();