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): code-split section views out of the startup bundle

Ruben Lütke56e717b58fee
diff --git a/.github/workflows/frontend.yml b/.github/workflows/frontend.yml
index 05466b4302..0da8796cb6 100644
--- a/.github/workflows/frontend.yml
+++ b/.github/workflows/frontend.yml
@@ -45,3 +45,12 @@ jobs:
- name: Build and verify production assets
run: npm run build
+
+ # The entry chunk is parsed and executed before the UI paints a single
+ # pixel, so its size IS startup latency. Guarding it here is the frontend
+ # twin of the Python boot budget in .githooks/pre-push: both block the
+ # same regression class, where a statically imported view or library
+ # quietly adds seconds to every launch.
+ - name: Check startup bundle budget
+ working-directory: ${{ github.workspace }}
+ run: python3 scripts/ci/check_frontend_bundle_budget.py
diff --git a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
index 0c0b0490d2..c097cc13a7 100644
--- a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
@@ -1,26 +1,190 @@
+import {
+ lazy,
+ Suspense,
+ useEffect,
+ type ComponentType,
+ type LazyExoticComponent,
+} from "react";
import { useEventStore } from "@/store/events";
import { ViewErrorBoundary } from "@/components/ViewErrorBoundary";
-import { BoardView } from "@/views/BoardView";
+// The default section is the one view that must be on screen the moment React
+// mounts, so it stays statically linked into the entry chunk. Every other view
+// is code-split below.
import { ChatsView } from "@/views/ChatsView";
-import { JarvisAgentsView } from "@/views/JarvisAgentsView";
-import { ExtensionsView } from "@/views/ExtensionsView";
-import { DocsView } from "@/views/DocsView";
-import { TasksView } from "@/views/TasksView";
-import { ProfileView } from "@/views/ProfileView";
-import { WikiView } from "@/views/WikiView";
-import { ApiKeysView } from "@/views/ApiKeysView";
-import { SettingsView } from "@/views/SettingsView";
-import { ClisHubView } from "@/views/ClisHubView";
-import { OutputsView } from "@/views/OutputsView";
-import { RunInspectorView } from "@/views/RunInspectorView";
-import { SessionsView } from "@/views/SessionsView";
-import { SocialsView } from "@/views/socials/SocialsView";
-import { ContactsView } from "@/views/contacts/ContactsView";
-import { FeedbackView } from "@/views/feedback/FeedbackView";
-import { AgentInstructionsView } from "@/views/AgentInstructionsView";
-import { TelephonySetupView } from "@/views/TelephonyView";
-import { DictionaryView } from "@/views/DictionaryView";
-import { AgenticIdeView } from "@/views/AgenticIdeView";
+
+/**
+ * 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.
+ */
+type ViewModule = { default: ComponentType };
+type ViewLoader = () => Promise<ViewModule>;
+
+/** Loaders for every split view, in the order the idle prefetch warms them. */
+const prefetchQueue: ViewLoader[] = [];
+
+function lazyView(loader: ViewLoader): LazyExoticComponent<ComponentType> {
+ prefetchQueue.push(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.
+const SettingsView = lazyView(() =>
+ import("@/views/SettingsView").then((m) => ({ default: m.SettingsView })),
+);
+const JarvisAgentsView = lazyView(() =>
+ import("@/views/JarvisAgentsView").then((m) => ({
+ default: m.JarvisAgentsView,
+ })),
+);
+const WikiView = lazyView(() =>
+ import("@/views/WikiView").then((m) => ({ default: m.WikiView })),
+);
+const ApiKeysView = lazyView(() =>
+ import("@/views/ApiKeysView").then((m) => ({ default: m.ApiKeysView })),
+);
+const ExtensionsView = lazyView(() =>
+ import("@/views/ExtensionsView").then((m) => ({ default: m.ExtensionsView })),
+);
+const AgenticIdeView = lazyView(() =>
+ import("@/views/AgenticIdeView").then((m) => ({ default: m.AgenticIdeView })),
+);
+const TasksView = lazyView(() =>
+ import("@/views/TasksView").then((m) => ({ default: m.TasksView })),
+);
+const SessionsView = lazyView(() =>
+ import("@/views/SessionsView").then((m) => ({ default: m.SessionsView })),
+);
+const OutputsView = lazyView(() =>
+ import("@/views/OutputsView").then((m) => ({ default: m.OutputsView })),
+);
+const ClisHubView = lazyView(() =>
+ import("@/views/ClisHubView").then((m) => ({ default: m.ClisHubView })),
+);
+const ProfileView = lazyView(() =>
+ import("@/views/ProfileView").then((m) => ({ default: m.ProfileView })),
+);
+const DocsView = lazyView(() =>
+ import("@/views/DocsView").then((m) => ({ default: m.DocsView })),
+);
+const BoardView = lazyView(() =>
+ import("@/views/BoardView").then((m) => ({ default: m.BoardView })),
+);
+const RunInspectorView = lazyView(() =>
+ import("@/views/RunInspectorView").then((m) => ({
+ default: m.RunInspectorView,
+ })),
+);
+const DictionaryView = lazyView(() =>
+ import("@/views/DictionaryView").then((m) => ({ default: m.DictionaryView })),
+);
+const AgentInstructionsView = lazyView(() =>
+ import("@/views/AgentInstructionsView").then((m) => ({
+ default: m.AgentInstructionsView,
+ })),
+);
+const SocialsView = lazyView(() =>
+ import("@/views/socials/SocialsView").then((m) => ({
+ default: m.SocialsView,
+ })),
+);
+const ContactsView = lazyView(() =>
+ import("@/views/contacts/ContactsView").then((m) => ({
+ default: m.ContactsView,
+ })),
+);
+const FeedbackView = lazyView(() =>
+ import("@/views/feedback/FeedbackView").then((m) => ({
+ default: m.FeedbackView,
+ })),
+);
+const TelephonySetupView = lazyView(() =>
+ import("@/views/TelephonyView").then((m) => ({
+ default: m.TelephonySetupView,
+ })),
+);
+
+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.
+ */
+function useIdleViewPrefetch(): void {
+ useEffect(() => {
+ let cancelled = false;
+ let cancelSlot: (() => void) | null = null;
+ let index = 0;
+
+ const pump = () => {
+ if (cancelled || index >= prefetchQueue.length) return;
+ const loader = prefetchQueue[index++];
+ void loader()
+ .catch(() => undefined)
+ .then(() => {
+ if (cancelled) return;
+ cancelSlot = scheduleIdle(pump);
+ });
+ };
+
+ cancelSlot = scheduleIdle(pump);
+ return () => {
+ cancelled = true;
+ cancelSlot?.();
+ };
+ }, []);
+}
+
+/**
+ * Placeholder shown while a section chunk is in flight.
+ *
+ * Deliberately empty: the idle prefetch means this is almost never seen, and a
+ * spinner that appears for 30 ms reads as a flicker — worse than nothing. It
+ * only holds the layout so the surrounding chrome does not jump. Being
+ * text-free, it also needs no translation.
+ */
+function ViewLoadingFallback() {
+ return <div className="h-full w-full" aria-busy="true" />;
+}
/**
* Main area to the right of the sidebar. All views are switched the classic
@@ -32,13 +196,19 @@ export function MainView() {
const active = useEventStore((s) => s.activeSection);
const setActive = useEventStore((s) => s.setActiveSection);
+ useIdleViewPrefetch();
+
return (
<ViewErrorBoundary
viewName={active}
resetKey={active}
onRecover={() => setActive("chats")}
>
- <SwitchOnActiveSection active={active} />
+ {/* Keyed on the active section so switching away from a still-loading
+ view cannot leave the previous section's fallback on screen. */}
+ <Suspense key={active} fallback={<ViewLoadingFallback />}>
+ <SwitchOnActiveSection active={active} />
+ </Suspense>
</ViewErrorBoundary>
);
}
diff --git a/scripts/ci/check_frontend_bundle_budget.py b/scripts/ci/check_frontend_bundle_budget.py
new file mode 100644
index 0000000000..83ece6ab20
--- /dev/null
+++ b/scripts/ci/check_frontend_bundle_budget.py
@@ -0,0 +1,118 @@
+#!/usr/bin/env python
+"""Frontend startup-bundle budget guard — fail when the entry chunk gets fat again.
+
+Why this exists (2026-07-26): ``MainView.tsx`` imported all 21 section views
+statically, so EVERY section — plus the terminal emulator and the charting
+library almost nobody opens on start — was linked into the single entry chunk.
+It reached 2.83 MB, and a WebView must download, parse and execute all of it
+before React paints its first pixel. The boot splash in ``index.html`` only
+hid the wait; it did not shorten it.
+
+This is the frontend twin of ``check_boot_budget.py``: that one guards the
+Python startup path, this one guards the bytes the UI must chew through before
+it is interactive. Both exist because the regression class is identical — a
+feature "only adds a bit" until the app takes seconds to become usable.
+
+What it measures: the size of the ES module entry chunk that ``dist/index.html``
+actually references (never a guessed filename — ``dist/`` accumulates stale
+hashed chunks from earlier builds), plus the stylesheet it loads. Lazy chunks
+are deliberately NOT counted: they are the fix, and they load off the critical
+path.
+
+Budget: ``JARVIS_BUNDLE_BUDGET_ENTRY_KB`` (default 1200). The measured entry
+after the code-splitting fix is ~700 KB, so the budget leaves generous headroom
+for normal feature work while still blocking a relapse toward 2.8 MB.
+
+Exit codes: 0 = within budget, 1 = budget exceeded, 78 = skipped (no build
+present) so callers can treat "could not measure" as neutral rather than red.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+DIST = REPO_ROOT / "jarvis" / "ui" / "web" / "dist"
+INDEX_HTML = DIST / "index.html"
+
+SKIP_EXIT = 78 # "could not measure" — neutral, not a failure
+
+DEFAULT_ENTRY_BUDGET_KB = 1200.0
+
+# The entry is the module script Vite injects; the stylesheet rides the same
+# critical path. Both are matched off index.html so a stale sibling chunk in
+# dist/ can never be mistaken for the live entry.
+_ENTRY_RE = re.compile(
+ r"""<script[^>]*\btype=["']module["'][^>]*\bsrc=["']([^"']+)["']""",
+ re.IGNORECASE,
+)
+_CSS_RE = re.compile(
+ r"""<link[^>]*\brel=["']stylesheet["'][^>]*\bhref=["']([^"']+)["']""",
+ re.IGNORECASE,
+)
+
+
+def _resolve(asset_href: str) -> Path:
+ """Map an index.html href ("/assets/index-abc.js") onto its file in dist/."""
+ return DIST / asset_href.lstrip("/")
+
+
+def _kb(path: Path) -> float:
+ return path.stat().st_size / 1024.0
+
+
+def main() -> int:
+ if not INDEX_HTML.is_file():
+ print(f"SKIP: no frontend build at {INDEX_HTML} (run `npm run build`)")
+ return SKIP_EXIT
+
+ html = INDEX_HTML.read_text(encoding="utf-8", errors="replace")
+
+ entry_match = _ENTRY_RE.search(html)
+ if entry_match is None:
+ print("SKIP: index.html references no module entry script — unknown build layout")
+ return SKIP_EXIT
+
+ entry = _resolve(entry_match.group(1))
+ if not entry.is_file():
+ print(f"SKIP: entry chunk {entry.name} referenced but missing from dist/")
+ return SKIP_EXIT
+
+ try:
+ budget_kb = float(
+ os.environ.get("JARVIS_BUNDLE_BUDGET_ENTRY_KB", DEFAULT_ENTRY_BUDGET_KB)
+ )
+ except ValueError:
+ budget_kb = DEFAULT_ENTRY_BUDGET_KB
+
+ entry_kb = _kb(entry)
+
+ css_match = _CSS_RE.search(html)
+ css_kb = 0.0
+ if css_match is not None:
+ css = _resolve(css_match.group(1))
+ if css.is_file():
+ css_kb = _kb(css)
+
+ print(f"entry chunk : {entry.name} {entry_kb:8.1f} KB (budget {budget_kb:.0f} KB)")
+ if css_kb:
+ print(f"stylesheet : {css_kb:8.1f} KB (not budgeted, reported for context)")
+
+ if entry_kb > budget_kb:
+ print(
+ f"\nFAIL: the startup bundle is {entry_kb - budget_kb:.1f} KB over budget.\n"
+ "Every byte here is parsed before the UI paints. The usual cause is a\n"
+ "view or heavy library imported STATICALLY where it should be lazy:\n"
+ "check src/components/layout/MainView.tsx and any new top-level import."
+ )
+ return 1
+
+ print("\nOK: startup bundle within budget.")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())