Skip to content

πŸ™Œ OpenHands: AI-Driven Development

perf(frontend): shrink eager dev/prod graph with lazy boundaries (Tier 1) (#238)

Robert Brennan65e5a3792b44
diff --git a/AGENTS.md b/AGENTS.md
index 7533d9e7c8..7de09980a8 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -115,6 +115,12 @@
- `scripts/ingress.mjs` is a standalone HTTP reverse proxy that can be used independently to route traffic to multiple backends based on URL path prefix.
- `scripts/dev-safe.mjs` (now `npm run dev:minimal`) runs just agent-server + Vite without automation.
- Vite dev mode can black-screen on first load with `504 Outdated Optimize Dep` if core client-entry deps are not prebundled; keep `react`, `react/jsx-runtime`, `react-dom/client`, and `react-router/dom` in `optimizeDeps.include`.
+- Bundle/dev-graph hygiene (Tier 1 cleanup landed):
+ - `src/i18n/translation.json` (~1 MB) is imported only by `src/i18n/resources.ts`, which `src/i18n/index.ts` re-exports as `translationResources` for the `@openhands/agent-canvas/i18n` subpath. The re-export is a `export … from` plus `/* @__PURE__ */` annotation, so rollup drops the JSON from the app build (the prod `custom-toast-handlers` chunk went from ~909 KB to ~74 KB). Do not move the JSON import back into `src/i18n/index.ts` β€” that immediately re-bundles all translations into every chunk that imports `i18n`.
+ - The environment-switch overlay is split: lightweight store/triggers live in `components/features/backends/environment-switch-store.ts`; the React component lives in `environment-switch-overlay.tsx` (re-exports the store API for back-compat). Eagerly-mounted callers (e.g. `backend-selector.tsx`) MUST import trigger helpers from the store, not the overlay file. The overlay is `React.lazy`'d from `routes/root-layout.tsx`.
+ - Other always-conditional UI is `React.lazy`'d to keep the root layout's eager graph small: `AnalyticsConsentFormModal`, `AlertBanner` (root-layout), `SettingsModal` (sidebar), `AgentServerConnectionForm` (root.tsx). Tests that assert on these mounted nodes need `await screen.findByTestId(...)` instead of `getByTestId(...)`.
+ - The terminal tab (`components/features/terminal/terminal.tsx`) is `React.lazy`'d in `conversation-tab-content.tsx` alongside the other tabs, so xterm + addon-fit + xterm.css don't enter the conversation route's eager graph.
+ - Avoid importing app code through `#/components/conversation-events/chat` or its `event-message-components/index.ts` barrel β€” they exist for `lib/index.ts` (npm subpath) consumers only. Internal callers use deep paths (`./messages`, `./event-message-components/<name>`, `./event-content-helpers/should-render-event`) so Vite dev doesn't fan out the barrel.
- Vercel deployment note: React Router builds for this repo must keep `build/client` intact on actual Vercel builds and include `presets: [vercelPreset()]` from `@vercel/react-router/vite`; flattening `build/client` during a Vercel build produces deployments with empty outputs (`routes: null`, no static files) and a production 404.
- The repo should include a root `LICENSE` file to satisfy the incubator-program requirements.
@@ -162,6 +168,12 @@
- `npm run build` remains the standalone app build (`react-router build`), while `npm run build:lib` runs `vite build` in library mode plus `tsc -p tsconfig.lib.json` to emit `.d.ts` files into `dist/`.
- The library build relies on `vite.config.ts` with `BUILD_LIB=true`, preserved modules in `dist/`, and package `exports` entries that map root/subpaths to `dist/**/*.js` plus matching declaration files.
- Declaration emit needs `src/library-env.d.ts` and the narrowed `tsconfig.lib.json`; broad `src/**/*.tsx` declaration builds pulled in route-only files and missed `?react`/window globals.
+- Bundle/dev-graph hygiene (Tier 1 cleanup landed):
+ - `src/i18n/translation.json` (~1 MB) is imported only by `src/i18n/resources.ts`, which `src/i18n/index.ts` re-exports as `translationResources` for the `@openhands/agent-canvas/i18n` subpath. The re-export is a `export … from` plus `/* @__PURE__ */` annotation, so rollup drops the JSON from the app build (prod `custom-toast-handlers` chunk: 909 KB -> 74 KB; `conversation` chunk: 728 KB -> 392 KB). Do not move the JSON import back into `src/i18n/index.ts` β€” that immediately re-bundles all translations into every chunk that imports `i18n`.
+ - The environment-switch overlay is split: lightweight store/triggers live in `components/features/backends/environment-switch-store.ts`; the React component lives in `environment-switch-overlay.tsx` (re-exports the store API for back-compat). Eagerly-mounted callers (e.g. `backend-selector.tsx`) MUST import trigger helpers from the store, not the overlay file. The overlay is `React.lazy`'d from `routes/root-layout.tsx`.
+ - Other always-conditional UI is `React.lazy`'d to keep the root layout's eager graph small: `AnalyticsConsentFormModal`, `AlertBanner` (root-layout), `SettingsModal` (sidebar), and the unreachable-backend modal path in `root.tsx` (`ManageBackendsModal`). Tests that assert on these mounted nodes may need `await screen.findByTestId(...)` / `waitFor(...)` instead of synchronous `getByTestId(...)`.
+ - The terminal tab (`components/features/terminal/terminal.tsx`) is `React.lazy`'d in `conversation-tab-content.tsx` alongside the other tabs, so xterm + addon-fit + xterm.css don't enter the conversation route's eager graph (they ship as a separate `terminal-*.js` chunk now).
+ - Avoid importing app code through `#/components/conversation-events/chat` or its `event-message-components/index.ts` barrel β€” they exist for `lib/index.ts` (npm subpath) consumers only. Internal callers use deep paths (`./messages`, `./event-message-components/<name>`, `./event-content-helpers/should-render-event`) so Vite dev doesn't fan out the barrel.
- Backend dropdown connectivity indicator: `useBackendsHealth` (`src/hooks/query/use-backends-health.ts`) polls each registered backend every 10s. Local agent-server backends are probed via `ServerClient.getServerInfo()` (`/server_info`); cloud SaaS backends are probed via `getCurrentCloudApiKey()` (`/api/keys/current` through the bundled `/api/cloud-proxy`). Verdicts are surfaced as a colored dot rendered through `DropdownOption.prefix` (added to `src/ui/dropdown/types.ts`); the trigger reads its prefix from the live `options` array (not downshift's frozen `selectedItem`) so the indicator updates without remounting. The same dot is also rendered in each row of `ManageBackendsModal`. Tests live in `__tests__/hooks/query/use-backends-health.test.tsx`, the `connection indicator` block of `__tests__/components/backends/backend-selector.test.tsx`, and `__tests__/components/backends/manage-backends-modal.test.tsx`.
diff --git a/__tests__/root.test.tsx b/__tests__/root.test.tsx
index c8beb8c419..5b7b276062 100644
--- a/__tests__/root.test.tsx
+++ b/__tests__/root.test.tsx
@@ -121,9 +121,9 @@ describe("App root agent-server availability guard", () => {
// modal additionally probes /server_info per registered backend
// for its status dot + version label, so the request count is
// bounded but greater than the single config probe.
- expect(
- screen.getByTestId("manage-backends-modal"),
- ).toBeInTheDocument();
+ await waitFor(() => {
+ expect(screen.getByTestId("manage-backends-modal")).toBeInTheDocument();
+ });
expect(serverInfoRequests).toBeGreaterThanOrEqual(1);
expect(screen.queryByTestId("app-outlet")).not.toBeInTheDocument();
});
diff --git a/__tests__/routes/root-layout.test.tsx b/__tests__/routes/root-layout.test.tsx
index 49b9c178a1..74aeda0099 100644
--- a/__tests__/routes/root-layout.test.tsx
+++ b/__tests__/routes/root-layout.test.tsx
@@ -111,7 +111,7 @@ describe("root layout", () => {
expect(screen.getByTestId("loading-spinner")).toBeInTheDocument();
});
- it("renders the OSS layout and analytics modal when consent is missing", () => {
+ it("renders the OSS layout and analytics modal when consent is missing", async () => {
useSettingsMock.mockReturnValue({
data: {
language: "en",
@@ -127,7 +127,11 @@ describe("root layout", () => {
expect(screen.getByTestId("sidebar")).toBeInTheDocument();
expect(screen.getByTestId("outlet-content")).toBeInTheDocument();
- expect(screen.getByTestId("analytics-consent-modal")).toBeInTheDocument();
+ // The consent modal is loaded via React.lazy() to keep it out of the root
+ // layout's eager graph, so it resolves on the next microtask.
+ expect(
+ await screen.findByTestId("analytics-consent-modal"),
+ ).toBeInTheDocument();
expect(migrateUserConsentMock).toHaveBeenCalled();
});
diff --git a/src/components/conversation-events/chat/event-message.tsx b/src/components/conversation-events/chat/event-message.tsx
index 791ea0730e..e695dd0152 100644
--- a/src/components/conversation-events/chat/event-message.tsx
+++ b/src/components/conversation-events/chat/event-message.tsx
@@ -23,14 +23,12 @@ import { useAgentState } from "#/hooks/use-agent-state";
import { AgentState } from "#/types/agent-state";
import { ChatMessage } from "../../features/chat/chat-message";
import { PlanPreview } from "../../features/chat/plan-preview";
-import {
- ErrorEventMessage,
- UserAssistantEventMessage,
- FinishEventMessage,
- GenericEventMessageWrapper,
- ThoughtEventMessage,
- HookExecutionEventMessage,
-} from "./event-message-components";
+import { ErrorEventMessage } from "./event-message-components/error-event-message";
+import { UserAssistantEventMessage } from "./event-message-components/user-assistant-event-message";
+import { FinishEventMessage } from "./event-message-components/finish-event-message";
+import { GenericEventMessageWrapper } from "./event-message-components/generic-event-message-wrapper";
+import { ThoughtEventMessage } from "./event-message-components/thought-event-message";
+import { HookExecutionEventMessage } from "./event-message-components/hook-execution-event-message";
import { createSkillReadyEvent } from "./event-content-helpers/create-skill-ready-event";
import { shouldShowPlanPreview } from "./hooks/use-plan-preview-events";
diff --git a/src/components/conversation-events/chat/messages.tsx b/src/components/conversation-events/chat/messages.tsx
index c4ef5871dc..b2a78697b8 100644
--- a/src/components/conversation-events/chat/messages.tsx
+++ b/src/components/conversation-events/chat/messages.tsx
@@ -5,7 +5,8 @@ import { ChatMessage } from "../../features/chat/chat-message";
import { useOptimisticUserMessageStore } from "#/stores/optimistic-user-message-store";
import { usePlanPreviewEvents } from "./hooks/use-plan-preview-events";
import { groupEvents } from "./group-events";
-import { EventGroup, ThoughtEventMessage } from "./event-message-components";
+import { EventGroup } from "./event-message-components/event-group";
+import { ThoughtEventMessage } from "./event-message-components/thought-event-message";
// TODO: Implement microagent functionality for V1 when APIs support V1 event IDs
// import { AgentState } from "#/types/agent-state";
// import MemoryIcon from "#/icons/memory_icon.svg?react";
diff --git a/src/components/features/backends/backend-selector.tsx b/src/components/features/backends/backend-selector.tsx
index c258c1e416..40da854773 100644
--- a/src/components/features/backends/backend-selector.tsx
+++ b/src/components/features/backends/backend-selector.tsx
@@ -15,11 +15,15 @@ import {
import { useSwitchCloudOrganization } from "#/hooks/mutation/use-switch-cloud-organization";
import { I18nKey } from "#/i18n/declaration";
import type { Backend } from "#/api/backend-registry/types";
+// Import the trigger helpers from the lightweight store, not the overlay
+// component, so the eagerly-mounted sidebar/backend-selector graph does not
+// pull in the overlay's render code (the overlay is lazy-loaded from
+// `routes/root-layout.tsx`).
import {
dismissEnvironmentSwitch,
ENVIRONMENT_SWITCH_SETACTIVE_DELAY_MS,
triggerEnvironmentSwitch,
-} from "#/components/features/backends/environment-switch-overlay";
+} from "#/components/features/backends/environment-switch-store";
import { displayErrorToast } from "#/utils/custom-toast-handlers";
import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";
import { AddBackendModal } from "./add-backend-modal";
diff --git a/src/components/features/backends/environment-switch-overlay.tsx b/src/components/features/backends/environment-switch-overlay.tsx
index 53604190fc..9635b0df7e 100644
--- a/src/components/features/backends/environment-switch-overlay.tsx
+++ b/src/components/features/backends/environment-switch-overlay.tsx
@@ -2,75 +2,21 @@ import React from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { I18nKey } from "#/i18n/declaration";
+import {
+ getEnvironmentSwitchSnapshot,
+ subscribeEnvironmentSwitch,
+} from "./environment-switch-store";
-export const ENVIRONMENT_SWITCH_DURATION_MS = 980;
-export const ENVIRONMENT_SWITCH_SETACTIVE_DELAY_MS = 400;
-
-// Module-level store. The overlay state must survive the unmount of the
-// component that triggers a switch β€” the user-context menu remounts
-// (`menuResetCount` key flip in user-actions.tsx) the moment the dropdown's
-// portaled option list is clicked, because that click registers as outside
-// the menu's `useClickOutsideElement` ref. If state lived inside
-// BackendSelector, the trigger would fire and immediately get torn down
-// before React paints the overlay.
-interface EnvironmentSwitchSnapshot {
- visible: boolean;
- target: string;
-}
-
-let snapshot: EnvironmentSwitchSnapshot = { visible: false, target: "" };
-const listeners = new Set<() => void>();
-let hideTimeoutId: ReturnType<typeof setTimeout> | null = null;
-
-function setSnapshot(next: EnvironmentSwitchSnapshot) {
- snapshot = next;
- if (typeof document !== "undefined") {
- if (next.visible) {
- document.body.setAttribute("data-environment-switching", "true");
- } else {
- document.body.removeAttribute("data-environment-switching");
- }
- }
- listeners.forEach((listener) => listener());
-}
-
-export function triggerEnvironmentSwitch(target: string) {
- setSnapshot({ visible: true, target });
- if (hideTimeoutId) clearTimeout(hideTimeoutId);
- hideTimeoutId = setTimeout(() => {
- setSnapshot({ visible: false, target: "" });
- hideTimeoutId = null;
- }, ENVIRONMENT_SWITCH_DURATION_MS);
-}
-
-export function dismissEnvironmentSwitch() {
- if (hideTimeoutId) {
- clearTimeout(hideTimeoutId);
- hideTimeoutId = null;
- }
- setSnapshot({ visible: false, target: "" });
-}
-
-function subscribe(listener: () => void) {
- listeners.add(listener);
- return () => {
- listeners.delete(listener);
- };
-}
-
-function getSnapshot() {
- return snapshot;
-}
-
-/** Test-only: clear the pending hide timer and reset the snapshot. */
-// eslint-disable-next-line @typescript-eslint/naming-convention
-export function __resetEnvironmentSwitchOverlayForTests() {
- if (hideTimeoutId) {
- clearTimeout(hideTimeoutId);
- hideTimeoutId = null;
- }
- setSnapshot({ visible: false, target: "" });
-}
+// Re-export the store API so existing call sites and tests that import from
+// this module keep working unchanged.
+export {
+ ENVIRONMENT_SWITCH_DURATION_MS,
+ ENVIRONMENT_SWITCH_SETACTIVE_DELAY_MS,
+ triggerEnvironmentSwitch,
+ dismissEnvironmentSwitch,
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ __resetEnvironmentSwitchOverlayForTests,
+} from "./environment-switch-store";
function EnvironmentSwitchIcon({ className }: { className?: string }) {
return (
@@ -197,9 +143,9 @@ function EnvironmentSwitchIcon({ className }: { className?: string }) {
export function EnvironmentSwitchOverlay() {
const { t } = useTranslation("openhands");
const { visible, target } = React.useSyncExternalStore(
- subscribe,
- getSnapshot,
- getSnapshot,
+ subscribeEnvironmentSwitch,
+ getEnvironmentSwitchSnapshot,
+ getEnvironmentSwitchSnapshot,
);
if (!visible || typeof document === "undefined") return null;
@@ -222,3 +168,6 @@ export function EnvironmentSwitchOverlay() {
document.body,
);
}
+
+// React.lazy() expects a default export.
+export default EnvironmentSwitchOverlay;
diff --git a/src/components/features/backends/environment-switch-store.ts b/src/components/features/backends/environment-switch-store.ts
new file mode 100644
index 0000000000..13fe259239
--- /dev/null
+++ b/src/components/features/backends/environment-switch-store.ts
@@ -0,0 +1,78 @@
+// Module-level store for the environment-switch overlay.
+//
+// This file is intentionally separate from `environment-switch-overlay.tsx`
+// (which contains the React component and an inline SVG icon) so that the
+// always-mounted sidebar can import `triggerEnvironmentSwitch` /
+// `dismissEnvironmentSwitch` without dragging the overlay's render code
+// into the eager graph. The overlay component is loaded lazily from
+// `routes/root-layout.tsx`.
+//
+// The overlay state must survive the unmount of the component that triggers a
+// switch β€” the user-context menu remounts (`menuResetCount` key flip in
+// user-actions.tsx) the moment the dropdown's portaled option list is
+// clicked, because that click registers as outside the menu's
+// `useClickOutsideElement` ref. If state lived inside BackendSelector, the
+// trigger would fire and immediately get torn down before React paints the
+// overlay.
+
+export const ENVIRONMENT_SWITCH_DURATION_MS = 980;
+export const ENVIRONMENT_SWITCH_SETACTIVE_DELAY_MS = 400;
+
+export interface EnvironmentSwitchSnapshot {
+ visible: boolean;
+ target: string;
+}
+
+let snapshot: EnvironmentSwitchSnapshot = { visible: false, target: "" };
+const listeners = new Set<() => void>();
+let hideTimeoutId: ReturnType<typeof setTimeout> | null = null;
+
+function setSnapshot(next: EnvironmentSwitchSnapshot) {
+ snapshot = next;
+ if (typeof document !== "undefined") {
+ if (next.visible) {
+ document.body.setAttribute("data-environment-switching", "true");
+ } else {
+ document.body.removeAttribute("data-environment-switching");
+ }
+ }
+ listeners.forEach((listener) => listener());
+}
+
+export function triggerEnvironmentSwitch(target: string) {
+ setSnapshot({ visible: true, target });
+ if (hideTimeoutId) clearTimeout(hideTimeoutId);
+ hideTimeoutId = setTimeout(() => {
+ setSnapshot({ visible: false, target: "" });
+ hideTimeoutId = null;
+ }, ENVIRONMENT_SWITCH_DURATION_MS);
+}
+
+export function dismissEnvironmentSwitch() {
+ if (hideTimeoutId) {
+ clearTimeout(hideTimeoutId);
+ hideTimeoutId = null;
+ }
+ setSnapshot({ visible: false, target: "" });
+}
+
+export function subscribeEnvironmentSwitch(listener: () => void) {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+export function getEnvironmentSwitchSnapshot() {
+ return snapshot;
+}
+
+/** Test-only: clear the pending hide timer and reset the snapshot. */
+// eslint-disable-next-line @typescript-eslint/naming-convention
+export function __resetEnvironmentSwitchOverlayForTests() {
+ if (hideTimeoutId) {
+ clearTimeout(hideTimeoutId);
+ hideTimeoutId = null;
+ }
+ setSnapshot({ visible: false, target: "" });
+}
diff --git a/src/components/features/chat/chat-interface.tsx b/src/components/features/chat/chat-interface.tsx
index 2f70c161d8..a059d78a71 100644
--- a/src/components/features/chat/chat-interface.tsx
+++ b/src/components/features/chat/chat-interface.tsx
@@ -23,7 +23,7 @@ import { displayErrorToast } from "#/utils/custom-toast-handlers";
import { useErrorMessageStore } from "#/stores/error-message-store";
import { useOptimisticUserMessageStore } from "#/stores/optimistic-user-message-store";
import { ErrorMessageBanner } from "./error-message-banner";
-import { Messages } from "#/components/conversation-events/chat";
+import { Messages } from "#/components/conversation-events/chat/messages";
import { useUnifiedUploadFiles } from "#/hooks/mutation/use-unified-upload-files";
import { validateFiles } from "#/utils/file-validation";
import { useConversationStore } from "#/stores/conversation-store";
diff --git a/src/components/features/conversation/conversation-tabs/conversation-tab-content/conversation-tab-content.tsx b/src/components/features/conversation/conversation-tabs/conversation-tab-content/conversation-tab-content.tsx
index f86492ef95..dad2dce2d5 100644
--- a/src/components/features/conversation/conversation-tabs/conversation-tab-content/conversation-tab-content.tsx
+++ b/src/components/features/conversation/conversation-tabs/conversation-tab-content/conversation-tab-content.tsx
@@ -6,17 +6,19 @@ import { TabWrapper } from "./tab-wrapper";
import { TabContainer } from "./tab-container";
import { TabContentArea } from "./tab-content-area";
import { ConversationTabTitle } from "../conversation-tab-title";
-import Terminal from "#/components/features/terminal/terminal";
import { useConversationStore } from "#/stores/conversation-store";
import { useConversationId } from "#/hooks/use-conversation-id";
-// Lazy load all tab components
+// Lazy load all tab components, including the terminal β€” xterm + addon-fit +
+// xterm.css are large enough that we don't want them in the conversation
+// route's eager graph just because the terminal tab might be selected later.
const EditorTab = lazy(() => import("#/routes/changes-tab"));
const BrowserTab = lazy(() => import("#/routes/browser-tab"));
const ServedTab = lazy(() => import("#/routes/served-tab"));
const VSCodeTab = lazy(() => import("#/routes/vscode-tab"));
const PlannerTab = lazy(() => import("#/routes/planner-tab"));
const TaskListTab = lazy(() => import("#/routes/task-list-tab"));
+const Terminal = lazy(() => import("#/components/features/terminal/terminal"));
const TAB_CONFIG = {
tasklist: {
diff --git a/src/components/features/sidebar/sidebar.tsx b/src/components/features/sidebar/sidebar.tsx
index 0e70810937..bc52ce5352 100644
--- a/src/components/features/sidebar/sidebar.tsx
+++ b/src/components/features/sidebar/sidebar.tsx
@@ -2,7 +2,6 @@ import React from "react";
import { useTranslation } from "react-i18next";
import { OpenHandsLogoButton } from "#/components/shared/buttons/openhands-logo-button";
import { SidebarNavLink } from "./sidebar-nav-link";
-import { SettingsModal } from "#/components/shared/modals/settings/settings-modal";
import { getErrorStatus, useSettings } from "#/hooks/query/use-settings";
import { useConfig } from "#/hooks/query/use-config";
import { displayErrorToast } from "#/utils/custom-toast-handlers";
@@ -14,6 +13,14 @@ import { BackendSelector } from "#/components/features/backends/backend-selector
import { OSS_NAV_ITEMS } from "#/constants/settings-nav";
import { SidebarConversationList } from "./sidebar-conversation-list";
+// The LLM settings modal is only mounted when the settings query 404s and
+// LLM settings aren't hidden β€” keep it out of the sidebar's eager graph.
+const SettingsModal = React.lazy(() =>
+ import("#/components/shared/modals/settings/settings-modal").then((m) => ({
+ default: m.SettingsModal,
+ })),
+);
+
const SETTINGS_NAV_ICON_BY_PATH = new Map(
OSS_NAV_ITEMS.map((item) => [item.to, item.icon] as const),
);
@@ -205,10 +212,12 @@ export function Sidebar() {
</aside>
{settingsModalIsOpen && (
- <SettingsModal
- settings={settings}
- onClose={() => setSettingsModalIsOpen(false)}
- />
+ <React.Suspense fallback={null}>
+ <SettingsModal
+ settings={settings}
+ onClose={() => setSettingsModalIsOpen(false)}
+ />
+ </React.Suspense>
)}
</>
);
diff --git a/src/hooks/use-filtered-events.ts b/src/hooks/use-filtered-events.ts
index 53349c97f5..3d4de33d13 100644
--- a/src/hooks/use-filtered-events.ts
+++ b/src/hooks/use-filtered-events.ts
@@ -3,7 +3,7 @@ import { useEventStore } from "#/stores/use-event-store";
import {
shouldRenderEvent as shouldRenderAgentServerEvent,
hasUserEvent as hasAgentServerUserEvent,
-} from "#/components/conversation-events/chat";
+} from "#/components/conversation-events/chat/event-content-helpers/should-render-event";
import {
isSystemPromptEvent,
isConversationStateUpdateEvent,
diff --git a/src/i18n/index.ts b/src/i18n/index.ts
index 822fd8ac9e..6e201530f6 100644
--- a/src/i18n/index.ts
+++ b/src/i18n/index.ts
@@ -2,7 +2,12 @@ import { createInstance, type i18n as I18nInstance } from "i18next";
import Backend from "i18next-http-backend";
import LanguageDetector from "i18next-browser-languagedetector";
import { initReactI18next } from "react-i18next";
-import translationDefinitions from "./translation.json";
+
+// Re-export so library consumers (`@openhands/agent-canvas/i18n`) keep working
+// without pulling the 1 MB `translation.json` into the app build. Rollup drops
+// this re-export when the consumer does not reference `translationResources`,
+// which is the case for the app entry that uses i18next-http-backend.
+export { translationResources, type TranslationResources } from "./resources";
export const OPENHANDS_I18N_NAMESPACE = "openhands";
@@ -24,35 +29,6 @@ export const AvailableLanguages = [
{ label: "Π£ΠΊΡ€Π°Ρ—Π½ΡΡŒΠΊΠ°", value: "uk" },
] as const;
-type TranslationDefinitionMap = Record<string, Partial<Record<string, string>>>;
-export type TranslationResources = Record<string, Record<string, string>>;
-
-const buildTranslationResources = (
- definitions: TranslationDefinitionMap,
-): TranslationResources => {
- const resources: TranslationResources = {};
-
- Object.entries(definitions).forEach(([key, translations]) => {
- Object.entries(translations).forEach(([language, value]) => {
- if (typeof value !== "string") {
- return;
- }
-
- if (!resources[language]) {
- resources[language] = {};
- }
-
- resources[language][key] = value;
- });
- });
-
- return resources;
-};
-
-export const translationResources = buildTranslationResources(
- translationDefinitions as TranslationDefinitionMap,
-);
-
const initializationPromises = new WeakMap<I18nInstance, Promise<unknown>>();
const initializeI18n = (instance: I18nInstance) => {
diff --git a/src/i18n/resources.ts b/src/i18n/resources.ts
new file mode 100644
index 0000000000..1fe222fa83
--- /dev/null
+++ b/src/i18n/resources.ts
@@ -0,0 +1,45 @@
+// Translation resources for downstream library consumers.
+//
+// This module is intentionally separate from `src/i18n/index.ts` so that the
+// 1 MB `translation.json` does not enter the app's eager dev/prod graph. The
+// app initialises i18next with `i18next-http-backend`, which fetches
+// `/locales/<lng>/openhands.json` at runtime; it never needs the embedded
+// resources object.
+//
+// Library consumers (`@openhands/agent-canvas/i18n`) can still import
+// `translationResources` from `src/i18n/index.ts`, which re-exports from here.
+// The re-export is `export … from`, which rollup is able to drop when the
+// app build does not reference `translationResources`.
+import translationDefinitions from "./translation.json";
+
+type TranslationDefinitionMap = Record<string, Partial<Record<string, string>>>;
+export type TranslationResources = Record<string, Record<string, string>>;
+
+const buildTranslationResources = (
+ definitions: TranslationDefinitionMap,
+): TranslationResources => {
+ const resources: TranslationResources = {};
+
+ Object.entries(definitions).forEach(([key, translations]) => {
+ Object.entries(translations).forEach(([language, value]) => {
+ if (typeof value !== "string") {
+ return;
+ }
+
+ if (!resources[language]) {
+ resources[language] = {};
+ }
+
+ resources[language][key] = value;
+ });
+ });
+
+ return resources;
+};
+
+// `/* @__PURE__ */` lets rollup drop both this call *and* the
+// `./translation.json` import when no consumer references
+// `translationResources` β€” i.e. the standard app build path.
+export const translationResources = /* @__PURE__ */ buildTranslationResources(
+ translationDefinitions as TranslationDefinitionMap,
+);
diff --git a/src/root.tsx b/src/root.tsx
index 4274b01adb..a860b6e7d8 100644
--- a/src/root.tsx
+++ b/src/root.tsx
@@ -11,12 +11,19 @@ import "./index.css";
import React from "react";
import { Toaster } from "react-hot-toast";
import { isAgentServerUnavailableError } from "#/api/agent-server-compatibility";
-import { ManageBackendsModal } from "#/components/features/backends/manage-backends-modal";
import { TelemetryConsentBanner } from "#/components/features/analytics/telemetry-consent-banner";
import { LoadingSpinner } from "#/components/shared/loading-spinner";
import { useConfig } from "#/hooks/query/use-config";
import { AgentServerUIRoot } from "#/components/providers";
+// Only rendered when the active backend is unreachable; keep the modal out of
+// the default root graph.
+const ManageBackendsModal = React.lazy(() =>
+ import("#/components/features/backends/manage-backends-modal").then((m) => ({
+ default: m.ManageBackendsModal,
+ })),
+);
+
export function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
@@ -54,18 +61,11 @@ function AgentServerBootstrapLoading() {
/**
* When the active backend is unreachable, the rest of the app cannot
- * render (most queries chain off of `/server_info`). Instead of the
- * old full-screen onboarding error, drop a minimal placeholder behind
- * the Manage Backends modal so the user can edit, add, or pick another
- * backend right away. Closing the modal just reopens it β€” the only way
- * out is a successful reconnection (the modal triggers a refetch via
- * its health probe and the user can reload).
+ * render (most queries chain off of `/server_info`). Drop a minimal
+ * placeholder behind the Manage Backends modal so the user can edit,
+ * add, or pick another backend right away.
*/
function MissingAgentServerScreen() {
- // Provide a no-op `onClose` so the user can't dismiss the modal into
- // a broken empty state. Editing/adding a backend reseeds the registry
- // and the next config refetch (via React Query's natural retry on
- // mount or a manual reload) recovers the app.
const noop = React.useCallback(() => {}, []);
return (
@@ -73,7 +73,9 @@ function MissingAgentServerScreen() {
data-testid="agent-server-onboarding-screen"
className="min-h-screen bg-base"
>
- <ManageBackendsModal onClose={noop} />
+ <React.Suspense fallback={null}>
+ <ManageBackendsModal onClose={noop} />
+ </React.Suspense>
</main>
);
}
diff --git a/src/routes/root-layout.tsx b/src/routes/root-layout.tsx
index 50fd2f2e41..5bf57a7a68 100644
--- a/src/routes/root-layout.tsx
+++ b/src/routes/root-layout.tsx
@@ -10,17 +10,31 @@ import { I18nKey } from "#/i18n/declaration";
import i18n from "#/i18n";
import { useConfig } from "#/hooks/query/use-config";
import { Sidebar } from "#/components/features/sidebar/sidebar";
-import { EnvironmentSwitchOverlay } from "#/components/features/backends/environment-switch-overlay";
-import { AnalyticsConsentFormModal } from "#/components/features/analytics/analytics-consent-form-modal";
import { useSettings } from "#/hooks/query/use-settings";
import { useMigrateUserConsent } from "#/hooks/use-migrate-user-consent";
import { useSyncPostHogConsent } from "#/hooks/use-sync-posthog-consent";
-import { AlertBanner } from "#/components/features/alerts/alert-banner";
import { cn } from "#/utils/utils";
import { LoadingSpinner } from "#/components/shared/loading-spinner";
import { useAppTitle } from "#/hooks/use-app-title";
import { ReactRouterNavigationProvider } from "./react-router-navigation-provider";
+// Lazy-load components that are only rendered conditionally β€” keeps them out
+// of the root layout's eager dev/prod graph (and out of every page's first
+// paint) until the relevant condition triggers.
+const EnvironmentSwitchOverlay = React.lazy(
+ () => import("#/components/features/backends/environment-switch-overlay"),
+);
+const AnalyticsConsentFormModal = React.lazy(() =>
+ import("#/components/features/analytics/analytics-consent-form-modal").then(
+ (m) => ({ default: m.AnalyticsConsentFormModal }),
+ ),
+);
+const AlertBanner = React.lazy(() =>
+ import("#/components/features/alerts/alert-banner").then((m) => ({
+ default: m.AlertBanner,
+ })),
+);
+
export function ErrorBoundary() {
const error = useRouteError();
const { t } = useTranslation("openhands");
@@ -116,12 +130,14 @@ export default function MainApp() {
(config.data.faulty_models &&
config.data.faulty_models.length > 0) ||
config.data.error_message) && (
- <AlertBanner
- maintenanceStartTime={config.data.maintenance_start_time}
- faultyModels={config.data.faulty_models}
- errorMessage={config.data.error_message}
- updatedAt={config.data.updated_at}
- />
+ <React.Suspense fallback={null}>
+ <AlertBanner
+ maintenanceStartTime={config.data.maintenance_start_time}
+ faultyModels={config.data.faulty_models}
+ errorMessage={config.data.error_message}
+ updatedAt={config.data.updated_at}
+ />
+ </React.Suspense>
)}
<div
id="root-outlet"
@@ -132,14 +148,18 @@ export default function MainApp() {
</div>
{consentFormIsOpen && (
- <AnalyticsConsentFormModal
- onClose={() => {
- setConsentFormIsOpen(false);
- }}
- />
+ <React.Suspense fallback={null}>
+ <AnalyticsConsentFormModal
+ onClose={() => {
+ setConsentFormIsOpen(false);
+ }}
+ />
+ </React.Suspense>
)}
</div>
- <EnvironmentSwitchOverlay />
+ <React.Suspense fallback={null}>
+ <EnvironmentSwitchOverlay />
+ </React.Suspense>
</ReactRouterNavigationProvider>
);
}
diff --git a/src/routes/shared-conversation.tsx b/src/routes/shared-conversation.tsx
index adc30fd682..d6023b9f9d 100644
--- a/src/routes/shared-conversation.tsx
+++ b/src/routes/shared-conversation.tsx
@@ -4,7 +4,7 @@ import { useTranslation } from "react-i18next";
import { I18nKey } from "#/i18n/declaration";
import { useSharedConversation } from "#/hooks/query/use-shared-conversation";
import { useSharedConversationEvents } from "#/hooks/query/use-shared-conversation-events";
-import { Messages } from "#/components/conversation-events/chat";
+import { Messages } from "#/components/conversation-events/chat/messages";
import { shouldRenderEvent } from "#/components/conversation-events/chat/event-content-helpers/should-render-event";
import { LoadingSpinner } from "#/components/shared/loading-spinner";
import { handleEventForUI } from "#/utils/handle-event-for-ui";