Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

perf(desktop): load less at launch, panels when they open (#4173)

Milind Sonif6d98f62740d
diff --git a/scripts/bench-desktop.ts b/scripts/bench-desktop.ts
index d9a7c59762..90aacc2d14 100644
--- a/scripts/bench-desktop.ts
+++ b/scripts/bench-desktop.ts
@@ -1,7 +1,7 @@
#!/usr/bin/env -S node --experimental-strip-types
// The desktop app's performance baseline, on isolated fixtures only: a temporary HOME and data folder per server, the
// fake engine, and a headless Chrome with its own profile. Prints one JSON object, so a change can show before/after.
-// node --experimental-strip-types scripts/bench-desktop.ts [--only bundle,server,start,idle,stream,big,routines]
+// node --experimental-strip-types scripts/bench-desktop.ts [--only bundle,server,start,screens,idle,stream,big,routines]
// [--chrome PATH] [--idle-seconds 30] [--bots 150] [--threads 300] [--messages 2000] [--advanced] [--out FILE] [--keep]
// [--screenshots DIR]
// bundle: the production build's first-load JavaScript and which libraries it pulls in eagerly.
@@ -15,7 +15,7 @@
// thread switch and read-marker writes, and a streamed reply there.
// routines: routines.json with a full run history: its route, and the bytes one run rewrites.
import { execFileSync, spawn, type ChildProcess } from "node:child_process";
-import { copyFileSync, existsSync, mkdirSync, mkdtempSync, openSync, closeSync, readFileSync, statSync, writeFileSync, createReadStream } from "node:fs";
+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, openSync, closeSync, readdirSync, readFileSync, statSync, writeFileSync, createReadStream } from "node:fs";
import { createServer, request as httpRequest, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { cpus, tmpdir, totalmem } from "node:os";
@@ -31,7 +31,7 @@ import { removeTempDir, waitForExit } from "../server/testing/cleanup.ts";
import { freePortBlock } from "../server/testing/ports.ts";
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
-const PHASES = ["bundle", "server", "start", "idle", "stream", "big", "routines"] as const;
+const PHASES = ["bundle", "server", "start", "screens", "idle", "stream", "big", "routines"] as const;
const { values } = parseArgs({
options: {
only: { type: "string" },
@@ -272,17 +272,26 @@ async function buildUi(outDir: string, profiling: boolean) {
const initial = new Set<string>();
const visit = (name: string) => { if (initial.has(name)) return; initial.add(name); for (const next of byName.get(name)?.imports ?? []) visit(next); };
visit(entry.fileName);
+ // main.tsx starts the App chunk's fetch at once, so an app launch loads it too; only /pair and /home stop at the entry.
+ const entryOnly = [...initial].map((name) => byName.get(name)!);
+ const appChunk = chunks.find((chunk) => Object.keys(chunk.modules).some((id) => id.endsWith("/src/App.tsx")));
+ if (appChunk) visit(appChunk.fileName);
const initialChunks = [...initial].map((name) => byName.get(name)!);
const sum = (list: ChunkInfo[], key: "bytes" | "gzip") => list.reduce((total, chunk) => total + chunk[key], 0);
const cssBytes = (names: string[]) => names.reduce((total, name) => total + (assets.find((asset) => asset.fileName === name)?.bytes ?? 0), 0);
const initialCss = [...new Set(initialChunks.flatMap((chunk) => chunk.css))];
const packages = new Map<string, number>();
+ const ownModules = new Map<string, number>();
const heavy: Record<string, { eagerKb: number; lazyKb: number }> = Object.fromEntries(Object.keys(HEAVY).map((name) => [name, { eagerKb: 0, lazyKb: 0 }]));
let initialModules = 0;
for (const chunk of chunks) {
const eager = initial.has(chunk.fileName);
for (const [id, length] of Object.entries(chunk.modules)) {
- if (eager) { initialModules += 1; packages.set(packageOf(id), (packages.get(packageOf(id)) ?? 0) + length); }
+ if (eager) {
+ initialModules += 1;
+ packages.set(packageOf(id), (packages.get(packageOf(id)) ?? 0) + length);
+ if (id.includes("/src/") && !id.includes("/node_modules/")) ownModules.set(id.slice(id.lastIndexOf("/src/") + 1), length);
+ }
for (const [name, pattern] of Object.entries(HEAVY)) if (pattern.test(id)) heavy[name]![eager ? "eagerKb" : "lazyKb"] += length / 1024;
}
}
@@ -296,7 +305,9 @@ async function buildUi(outDir: string, profiling: boolean) {
chunks: initialChunks.map((chunk) => ({ file: chunk.fileName, kb: kb(chunk.bytes), gzipKb: kb(chunk.gzip) })),
jsKb: kb(sum(initialChunks, "bytes")), jsGzipKb: kb(sum(initialChunks, "gzip")), cssKb: kb(cssBytes(initialCss)), modules: initialModules,
topPackagesKb: Object.fromEntries([...packages].sort((a, b) => b[1] - a[1]).slice(0, 25).map(([name, length]) => [name, kb(length)])),
+ topOwnModulesKb: Object.fromEntries([...ownModules].sort((a, b) => b[1] - a[1]).slice(0, 40).map(([name, length]) => [name, kb(length)])),
},
+ signInPage: { jsKb: kb(sum(entryOnly, "bytes")), jsGzipKb: kb(sum(entryOnly, "gzip")) },
heavyLibraries: heavy,
largestLazyChunks: chunks.filter((chunk) => !initial.has(chunk.fileName)).sort((a, b) => b.bytes - a.bytes).slice(0, 10)
.map((chunk) => ({ file: chunk.fileName, kb: kb(chunk.bytes), top: [...new Set(Object.keys(chunk.modules).map(packageOf))].slice(0, 4) })),
@@ -490,7 +501,7 @@ async function main() {
try { commit = execFileSync("git", ["rev-parse", "--short", "HEAD"], { cwd: ROOT, encoding: "utf8" }).trim(); } catch { /* not a checkout */ }
const chromePath = values.chrome ?? installedChrome() ?? "";
result.meta = { commit, date: new Date().toISOString(), node: process.version, platform: `${process.platform}-${process.arch}`, cpu: cpus()[0]?.model, cores: cpus().length, memoryGb: round(totalmem() / 2 ** 30), chrome: chromePath, mode: values.advanced ? "advanced" : "simple", idleSeconds: IDLE_MS / 1000 };
- const needsUi = ["start", "idle", "stream", "big"].some((phase) => only.has(phase));
+ const needsUi = ["start", "screens", "idle", "stream", "big"].some((phase) => only.has(phase));
const dist = join(work, "dist");
const profileDist = join(work, "dist-profile");
if (only.has("bundle") || needsUi) {
@@ -565,8 +576,8 @@ async function main() {
cleanups.push(() => chrome!.close());
}
- if (chrome && (only.has("start") || only.has("idle") || only.has("stream"))) {
- log("small workspace: start, idle, stream");
+ if (chrome && (only.has("start") || only.has("screens") || only.has("idle") || only.has("stream"))) {
+ log("small workspace: start, screens, idle, stream");
const fixture = await startFixture({ staticDir: dist, fake: STREAM_ENV });
const botId = await newBot(fixture, "Pepper");
const page = await chrome.newPage({ storage: STORAGE });
@@ -577,6 +588,38 @@ async function main() {
} else {
await pageLoad(page, fixture.url);
}
+ if (only.has("screens")) {
+ // A person's first open of a screen: its chunks fetched, compiled and evaluated (0 when something loaded them already).
+ const conditions: Record<string, { cpu?: number; latencyMs?: number }> = { asIs: {}, cpu4x: { cpu: 4 }, remote100ms: { latencyMs: 100 } };
+ const assets = readdirSync(join(dist, "assets"));
+ const firstOpen: Record<string, Record<string, number>> = {};
+ for (const [condition, { cpu, latencyMs }] of Object.entries(conditions)) {
+ firstOpen[condition] = {};
+ for (const name of ["SettingsModal", "PluginsPanel", "ComputerPanel", "BotSettingsDialog", "TriggersPage", "TeamMapPage"]) {
+ const file = assets.find((asset) => asset.startsWith(`${name}-`) && asset.endsWith(".js"));
+ if (!file) continue;
+ const open = await chrome.newPage({ storage: STORAGE });
+ await pageLoad(open, fixture.url);
+ await sleep(2_500);
+ if (cpu) await open.send("Emulation.setCPUThrottlingRate", { rate: cpu });
+ if (latencyMs) {
+ await open.send("Network.enable", {});
+ await open.send("Network.setCacheDisabled", { cacheDisabled: true });
+ await open.send("Network.emulateNetworkConditions", { offline: false, latency: latencyMs, downloadThroughput: 1_250_000, uploadThroughput: 625_000 });
+ }
+ firstOpen[condition]![name] = Math.round(await open.evaluate<number>(`(async () => { const at = performance.now(); await import("/assets/${file}"); return performance.now() - at; })()`));
+ await open.close();
+ }
+ }
+ const pair = await chrome.newPage({ storage: STORAGE });
+ await pair.send("Page.navigate", { url: `${fixture.url}/pair` });
+ await sleep(2_000);
+ const signIn = await pair.evaluate<Record<string, unknown>>(`(() => ({
+ scriptKb: Math.round(performance.getEntriesByType("resource").filter((e) => /\\.js$/.test(e.name)).reduce((t, e) => t + (e.decodedBodySize || 0), 0) / 1024),
+ drew: document.getElementById("root").childElementCount > 0, inputs: document.querySelectorAll("input").length }))()`);
+ await pair.close();
+ result.screens = { firstOpenMs: firstOpen, signInPage: signIn };
+ }
if (only.has("idle")) {
const rail = await chrome.newPage({ storage: STORAGE, railBridge: true }, 72, 900);
await rail.send("Page.navigate", { url: `${fixture.url}/rail` });
diff --git a/scripts/testing/control-omb-ui.e2e.test.ts b/scripts/testing/control-omb-ui.e2e.test.ts
index aa54a76db5..d397a513ae 100644
--- a/scripts/testing/control-omb-ui.e2e.test.ts
+++ b/scripts/testing/control-omb-ui.e2e.test.ts
@@ -7,7 +7,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
-import { afterAll, describe, expect, it } from "vitest";
+import { afterAll, describe, expect, it, vi } from "vitest";
import { resolveAgentBrowserBinary } from "../../server/browser-engine.ts";
import { removeTempDir, waitForExit } from "../../server/testing/cleanup.ts";
@@ -387,7 +387,12 @@ describe("control-omb ui drives the real renderer", () => {
await ui("click", info.ui, "--name", "More");
await ui("click", info.ui, "--name", "Inspector");
- const inspected = await ui("snapshot", info.ui);
+ // A local page fetches a screen when it opens, so the panel arrives just after the click.
+ const inspected = await vi.waitFor(async () => {
+ const snapshot = await ui("snapshot", info.ui);
+ expect(snapshot.snapshot).toContain('complementary "Inspector"');
+ return snapshot;
+ }, { timeout: 5_000, interval: 100 });
const runLog = (inspected.snapshot as string).slice((inspected.snapshot as string).indexOf('complementary "Inspector"'));
expect(runLog).toContain('tab "Run Log" [selected');
expect(runLog).toContain("pnpm control:omb doctor");
diff --git a/src/App.tsx b/src/App.tsx
index 3b50f638c2..8d2027286b 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -16,10 +16,10 @@ import { Sidebar } from "@/components/Sidebar";
import { ChatView } from "@/components/ChatView";
import { GroupView } from "@/components/GroupView";
import { SIDEBAR_AND_PANEL_FIT, SIDEBAR_INLINE, TWO_SIDE_PANELS_FIT, useMediaQuery } from "@/lib/use-media-query";
-import { PluginsPanel, preloadConnectedApps } from "@/components/PluginsPanel";
+import { preloadConnectedApps } from "@/lib/connected-apps";
import {
- ActivityPanel, BotSettingsDialog, ComputerPanel, FilesView, InspectorPanel, KeyboardShortcutsModal, LocalVmWorkspace,
- preloadScreens, RemoteAgentSettingsPanel, RemoteDesktopPanel, RoomPanel, SettingsModal, TeamMapPage, TriggersPage,
+ ActivityPanel, BotSettingsDialog, CloudAddDialog, ComputerPanel, FilesView, InspectorPanel, KeyboardShortcutsModal, LocalVmWorkspace,
+ PluginsPanel, preloadScreens, RemoteAgentSettingsPanel, RemoteDesktopPanel, RoomPanel, SettingsModal, TeamMapPage, TriggersPage,
} from "@/components/lazy-screens";
import { useAdvancedMode } from "@/lib/interface-mode";
import { useRoomPanelShown } from "@/lib/room-panel";
@@ -36,7 +36,6 @@ import { useTeamChats } from "@/state/team-chats";
import { needsYouVersion, useTeamPeopleLoader } from "@/state/team-people";
import { inboxVersion, useInboxLoader, useInboxPanel } from "@/state/inbox";
import { InboxPanel } from "@/components/inbox/InboxPanel";
-import { CloudAddDialog } from "@/components/CloudAddDialog";
import { PlacesRail } from "@/components/PlacesRail";
import { CloudHowTo } from "@/components/CloudHowTo";
import { DesktopCapabilitiesProvider, useCaptionChrome, useDesktopCapabilities, WindowDragStrip, windowFramed } from "@/components/DesktopCapabilities";
@@ -132,6 +131,9 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
const [drawerOpen, setDrawerOpen] = useState(false);
usePageLanguage(effectiveLanguage(useLanguageChoice(), state.config?.language));
const [paletteOpen, setPaletteOpen] = useState(false);
+ // Stays mounted once opened: a Cloud bought in it can arrive after the sheet is closed.
+ const cloudAddOpened = useRef(false);
+ cloudAddOpened.current ||= Boolean(state.cloudAdd);
const [localVmWorkspaceBotId, setLocalVmWorkspaceBotId] = useState<string | null>(null);
const menuButtonRef = useRef<HTMLButtonElement>(null);
const previousViewRef = useRef(state.activeView);
@@ -416,7 +418,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
</div>
</div>
{state.appSettingsOpen && <SettingsModal />}
- <CloudAddDialog />
+ {cloudAddOpened.current && <CloudAddDialog />}
<CloudHowTo />
<CloudSetup viewer={viewer} welcomeShown={welcomeOnScreen} />
<WelcomeKeeper viewer={viewer} />
diff --git a/src/components/PhoneSetupFlow.tsx b/src/components/PhoneSetupFlow.tsx
index 7e8c0cc5f8..f5397ad534 100644
--- a/src/components/PhoneSetupFlow.tsx
+++ b/src/components/PhoneSetupFlow.tsx
@@ -1,3 +1,4 @@
+import { companionBridge } from "@/lib/companion-bridge";
import {
useCallback,
useEffect,
@@ -125,9 +126,7 @@ interface PhonePairingRequest {
generation: number;
}
-export const companionBridge = (): CompanionBridge | null =>
- // SAFETY: the preload owns this narrow bridge; browser builds are guarded by the optional lookup.
- (globalThis as { ogb?: { companion?: CompanionBridge } }).ogb?.companion ?? null;
+export { companionBridge };
export const companionAccountBridge = (): AccountBridge | null =>
// SAFETY: Electron exposes only these account operations and never sends credentials to the renderer.
diff --git a/src/components/PluginsPanel.tsx b/src/components/PluginsPanel.tsx
index 94826e0f20..9b83a8dd80 100644
--- a/src/components/PluginsPanel.tsx
+++ b/src/components/PluginsPanel.tsx
@@ -5,7 +5,8 @@ import { cn } from "@/lib/cn";
import { glassPopupFrameStyle } from "@/lib/glass-popup";
import { t } from "@/lib/i18n";
import type { LocaleKey } from "@/locales";
-import { readCachedInventory, writeCachedInventory } from "@/lib/connected-apps-cache";
+import { readCachedInventory } from "@/lib/connected-apps-cache";
+import { connectorStatusMemory, preloadConnectedApps, rememberConnectorStatus } from "@/lib/connected-apps";
import { reserveConnectionPage, reusableConnectionUrl, type PendingAuthorization } from "@/lib/connector-oauth";
import { mcpSignInLink } from "@/lib/mcp-sign-in";
import { pollConnector } from "@/lib/connector-poll";
@@ -35,55 +36,11 @@ import { X_CARD_SEARCH, XCard } from "./XCard";
import { mergeCompleteConnectorStatus, mergeCurrentConnectorStatus, onlyLatestConnectorResponses } from "@/lib/connector-status-merge";
import { openBotSettings } from "./bot-panel/panel-link";
import { openKeySettings } from "./keys/key-focus";
-import { lacksAdminScope, unlessRefused } from "@/lib/admin-scope";
+import { lacksAdminScope } from "@/lib/admin-scope";
import { ServiceIcon, type ToolkitCard } from "./ServiceIcon"; import { AppsSection } from "./AppsSection";
export { ServiceIcon, type ToolkitCard } from "./ServiceIcon";
-let cachedConnectorStatus: Record<string, ConnectorStatus> | null = null;
-let cachedConnectorStatusAt = 0;
-let cachedConnectorStatusAuthoritative = true;
-let connectorStatusRequest: Promise<ConnectorInventory> | null = null;
-const CONNECTOR_STATUS_CACHE_MS = 30_000;
-
-export interface ConnectorInventory {
- services: Record<string, ConnectorStatus>;
- /** false when the server could not read the credential store: nothing may be cleared on the strength of it. */
- authoritative: boolean;
- /** This session may not see the connected apps: its role, not the credential store. */
- refused?: true;
-}
-
-const REFUSED_INVENTORY: ConnectorInventory = { services: {}, authoritative: true, refused: true };
-
-export function preloadConnectedApps(force = false, background = false): Promise<ConnectorInventory> { // background: src/state/api.ts
- if (!force && cachedConnectorStatus !== null && Date.now() - cachedConnectorStatusAt < CONNECTOR_STATUS_CACHE_MS) {
- return Promise.resolve({
- services: cachedConnectorStatus,
- authoritative: cachedConnectorStatusAuthoritative,
- });
- }
- if (connectorStatusRequest) return connectorStatusRequest;
- type ConnectedAnswer = { services?: Record<string, ConnectorStatus>; credentialStore?: string; inventoryComplete?: boolean };
- connectorStatusRequest = unlessRefused<ConnectedAnswer | null>("/api/connectors/connected", () => api("/api/connectors/connected", background ? { background: true } : undefined), null)
- .then((response): ConnectorInventory => {
- if (!response) return REFUSED_INVENTORY;
- const services: Record<string, ConnectorStatus> = response.services ?? {};
- if (response.credentialStore === "unavailable" || response.inventoryComplete === false) {
- cachedConnectorStatusAuthoritative = false;
- return { services: readCachedInventory()?.services ?? services, authoritative: false };
- }
- cachedConnectorStatus = services;
- cachedConnectorStatusAt = Date.now();
- cachedConnectorStatusAuthoritative = true;
- writeCachedInventory(services, Date.now());
- return { services, authoritative: true };
- })
- .catch(() => ({ services: readCachedInventory()?.services ?? {}, authoritative: false }))
- .finally(() => {
- connectorStatusRequest = null;
- });
- return connectorStatusRequest;
-}
+export { preloadConnectedApps, type ConnectorInventory } from "@/lib/connected-apps";
export function disconnectAccountConfirmation(
service: string,
@@ -167,10 +124,10 @@ export function PluginsPanel() {
const [mode, setMode] = useState<"managed" | "self-hosted" | "unavailable">("unavailable");
const [setup, setSetup] = useState<ConnectorSetup | undefined>(undefined);
const [status, setStatus] = useState<Record<string, ConnectorStatus>>(
- () => cachedConnectorStatus ?? readCachedInventory()?.services ?? {},
+ () => connectorStatusMemory()?.services ?? readCachedInventory()?.services ?? {},
);
const [stale, setStale] = useState(
- cachedConnectorStatus !== null && !cachedConnectorStatusAuthoritative,
+ connectorStatusMemory()?.authoritative === false,
);
const [pendingUrls, setPendingUrls] = useState<Record<string, PendingAuthorization>>({});
const [aliasSlug, setAliasSlug] = useState<string | null>(null);
@@ -178,7 +135,7 @@ export function PluginsPanel() {
const [busySlug, setBusySlug] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState(false);
const [inventoryPhase, setInventoryPhase] = useState<ConnectorInventoryPhase>(
- cachedConnectorStatus === null ? "loading" : "ready",
+ connectorStatusMemory() === null ? "loading" : "ready",
);
const [error, setError] = useState<string | { key: LocaleKey } | null>(null);
const [search, setSearch] = useState("");
@@ -253,7 +210,7 @@ export function PluginsPanel() {
}, []);
const loadConnectionInventory = useCallback((force = false) => {
- const hadCachedInventory = cachedConnectorStatus !== null;
+ const hadCachedInventory = connectorStatusMemory() !== null;
if (!hadCachedInventory) setInventoryPhase("loading");
setError(null);
return refreshConnectedStatus(force)
@@ -277,9 +234,7 @@ export function PluginsPanel() {
useEffect(() => {
if (inventoryPhase !== "ready") return;
- cachedConnectorStatus = status;
- cachedConnectorStatusAt = Date.now();
- cachedConnectorStatusAuthoritative = !stale;
+ rememberConnectorStatus(status, !stale);
}, [inventoryPhase, stale, status]);
useEffect(() => {
diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx
index 57b2a6337b..4e412e1fb3 100644
--- a/src/components/Sidebar.tsx
+++ b/src/components/Sidebar.tsx
@@ -27,10 +27,9 @@ import { LocalComputerAutoWarning } from "./LocalComputerAutoWarning";
import { nextRename } from "@/lib/rename";
import { useDesktopCapabilities, windowFramed } from "./DesktopCapabilities";
import { MIN_QUERY, SearchResults } from "./SearchResults";
-import { TeamLibraryPanel } from "./TeamLibraryPanel";
+import { ShareTeamDialog, TeamLibraryPanel } from "./lazy-screens";
import { SidebarNewChatPanel } from "./SidebarNewChatPanel";
import { openCommandPalette } from "./CommandPalette";
-import { ShareTeamDialog } from "./ShareTeamDialog";
import { TeamSettingsDialog } from "./TeamSettingsDialog";
import { TeamDialog } from "./TeamDialog";
import { RenameTitle } from "./RenameTitle";
diff --git a/src/components/SidebarConnectApps.dom.test.ts b/src/components/SidebarConnectApps.dom.test.ts
index dcad327ea9..e8083e447a 100644
--- a/src/components/SidebarConnectApps.dom.test.ts
+++ b/src/components/SidebarConnectApps.dom.test.ts
@@ -8,7 +8,7 @@ import { initialState } from "@/state/store";
const inventory = vi.hoisted(() => ({ services: {} as Record<string, { connected: boolean }> }));
vi.mock("@/state/store", async (original) => ({ ...await original<typeof import("@/state/store")>(), useStore: () => ({ state: initialState, dispatch: vi.fn() }) }));
-vi.mock("./PluginsPanel", () => ({ preloadConnectedApps: async () => ({ services: inventory.services, authoritative: true }) }));
+vi.mock("@/lib/connected-apps", () => ({ preloadConnectedApps: async () => ({ services: inventory.services, authoritative: true }) }));
vi.mock("./bot-settings/useBotApps", () => ({ loadAppCards: async () => new Map([["github", { slug: "github", label: "GitHub", logo: null, domain: "github.com" }]]) }));
import { SidebarConnectApps } from "./SidebarConnectApps";
diff --git a/src/components/SidebarConnectApps.tsx b/src/components/SidebarConnectApps.tsx
index fb67c130e3..05403c44eb 100644
--- a/src/components/SidebarConnectApps.tsx
+++ b/src/components/SidebarConnectApps.tsx
@@ -6,7 +6,8 @@ import { t } from "@/lib/i18n";
import { useStore } from "@/state/store";
import { loadAppCards } from "./bot-settings/useBotApps";
-import { preloadConnectedApps, type ToolkitCard } from "./PluginsPanel";
+import { preloadConnectedApps } from "@/lib/connected-apps";
+import type { ToolkitCard } from "./ServiceIcon";
import { ELEVATED_CONTROL, ELEVATED_HOVER } from "./elevated";
import { SIMPLE_TOP_BUTTON } from "./SidebarSimpleTop";
diff --git a/src/components/SidebarPhoneButton.tsx b/src/components/SidebarPhoneButton.tsx
index feff640cb4..4699c12777 100644
--- a/src/components/SidebarPhoneButton.tsx
+++ b/src/components/SidebarPhoneButton.tsx
@@ -5,7 +5,8 @@ import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
import { phonePairingSettingsAction } from "@/lib/phone-pairing";
import type { SidebarDensity } from "@/lib/sidebar-preferences";
-import { companionBridge, type CompanionState } from "./PhoneSetupFlow";
+import { companionBridge } from "@/lib/companion-bridge";
+import type { CompanionState } from "./PhoneSetupFlow";
export const SIDEBAR_PHONE_RECENT_MS = 2 * 60_000;
const SIDEBAR_PHONE_POLL_MS = 15_000;
diff --git a/src/components/SidebarProfileMenu.tsx b/src/components/SidebarProfileMenu.tsx
index 1081ad8c34..d6abe6b558 100644
--- a/src/components/SidebarProfileMenu.tsx
+++ b/src/components/SidebarProfileMenu.tsx
@@ -27,7 +27,7 @@ import { AccountMoveStatus, useAccountMove, type AccountMoveKind } from "./Accou
import { InitialsAvatar } from "./Avatar";
import { DiscordIcon } from "./DiscordIcon";
import { AboutDialog } from "./AboutDialog";
-import { PhoneAppDialog } from "./PhoneAppDialog";
+import { PhoneAppDialog } from "./lazy-screens";
import { CloudTile } from "./cloud-buy/parts";
import { usageBridge } from "./CloudUsageMeter";
import { useCloudPlanSnapshot } from "./CloudTrialNotice";
@@ -692,15 +692,15 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = fa
)}
/>
<AboutDialog open={aboutOpen} onClose={() => setAboutOpen(false)} />
- <PhoneAppDialog
- open={phoneAppOpen}
+ {phoneAppOpen && <PhoneAppDialog
+ open
onClose={() => setPhoneAppOpen(false)}
connect={destinations.map((destination) => ({
key: destination.id,
subtitle: destination.team ? t("sidebar.menu.connectPhone.team", { team: destination.team }) : t(destination.subtitleKey),
onSelect: () => connectTo(destination),
}))}
- />
+ />}
</>
);
}
diff --git a/src/components/SimpleHelperIntro.tsx b/src/components/SimpleHelperIntro.tsx
index 34ce8da6a6..d8b180375b 100644
--- a/src/components/SimpleHelperIntro.tsx
+++ b/src/components/SimpleHelperIntro.tsx
@@ -14,7 +14,7 @@ import { loadAppCards } from "./bot-settings/useBotApps";
import { engineReady } from "./EngineLibrary";
import { IntroChips } from "./HelperSetup";
import { usePrefersReducedMotion } from "./mascot-clock";
-import { preloadConnectedApps } from "./PluginsPanel";
+import { preloadConnectedApps } from "@/lib/connected-apps";
/** How long after the part before each part arrives, when a first run has just landed here: the three lines, the typing
* row, the follow-up and its chips. With no AI there is no typing row, and the follow-up comes `noAi` after the last line. */
diff --git a/src/components/bot-panel/pages.tsx b/src/components/bot-panel/pages.tsx
index 1a6ddbfaba..fb3775d7ea 100644
--- a/src/components/bot-panel/pages.tsx
+++ b/src/components/bot-panel/pages.tsx
@@ -10,7 +10,7 @@ import type { Routine } from "@/lib/routines";
import { shortPath } from "@/lib/short-path";
import { useStore, type Bot } from "@/state/store";
import { useDesktopCapabilities } from "../DesktopCapabilities";
-import { ServiceIcon } from "../PluginsPanel";
+import { ServiceIcon } from "../ServiceIcon";
import { RoutineEditor } from "../RoutinesPage";
import { useWorkingFolder } from "../bot-settings/AccessSection";
import { useBotEditor } from "../bot-settings/BotEditorContext";
diff --git a/src/components/bot-settings/useBotApps.ts b/src/components/bot-settings/useBotApps.ts
index 8b6d611b7e..a943ea80b9 100644
--- a/src/components/bot-settings/useBotApps.ts
+++ b/src/components/bot-settings/useBotApps.ts
@@ -6,7 +6,8 @@ import { highLevelConnected, preloadHighLevelStatus } from "@/lib/highlevel-stat
import { t } from "@/lib/i18n";
import { api, type Bot } from "@/state/store";
import type { ConnectorScope } from "../../../shared/connector-scopes";
-import { preloadConnectedApps, type ConnectorInventory, type ToolkitCard } from "../PluginsPanel";
+import { preloadConnectedApps, type ConnectorInventory } from "@/lib/connected-apps";
+import type { ToolkitCard } from "../ServiceIcon";
export interface BotApp {
slug: string;
diff --git a/src/components/cloud-welcome/CloudWelcome.test.ts b/src/components/cloud-welcome/CloudWelcome.test.ts
index f62be7a2d9..416509b033 100644
--- a/src/components/cloud-welcome/CloudWelcome.test.ts
+++ b/src/components/cloud-welcome/CloudWelcome.test.ts
@@ -163,7 +163,7 @@ describe("CloudWelcome", () => {
render();
await vi.waitFor(() => expect(button("Choose a team")).toBeDefined());
click("Choose a team");
- expect(host.querySelector("[data-team-library]")).not.toBeNull();
+ await vi.waitFor(() => expect(host.querySelector("[data-team-library]")).not.toBeNull());
flushSync(() => fixture.imported!());
expect(hintsPut().at(-1)).toEqual([SHOWN, welcomeStepHint("bring")]);
expect(host.querySelector('[data-welcome-step="engine"]')).not.toBeNull();
diff --git a/src/components/cloud-welcome/WelcomeBring.tsx b/src/components/cloud-welcome/WelcomeBring.tsx
index 3bfd9127e2..91ddb91fd7 100644
--- a/src/components/cloud-welcome/WelcomeBring.tsx
+++ b/src/components/cloud-welcome/WelcomeBring.tsx
@@ -1,6 +1,6 @@
import { useRef, useState, type Ref } from "react";
import { Check, Laptop, Loader2, Sparkles, Users } from "lucide-react";
-import { TeamLibraryPanel } from "@/components/TeamLibraryPanel";
+import { TeamLibraryPanel } from "@/components/lazy-screens";
import { cn } from "@/lib/cn";
import { listOf } from "@/lib/cloud-send";
import { t } from "@/lib/i18n";
diff --git a/src/components/lazy-screens.test.ts b/src/components/lazy-screens.test.ts
index 18dbd2d0e9..ae6843bc40 100644
--- a/src/components/lazy-screens.test.ts
+++ b/src/components/lazy-screens.test.ts
@@ -152,33 +152,58 @@ describe("lazyScreen", () => {
});
describe("preloadScreens", () => {
- it("fetches every deferred screen once the launch is idle, and can be cancelled", () => {
- let idle: (() => void) | undefined;
+ it("a page on this machine fetches nothing ahead: each screen loads when it opens", () => {
+ vi.useFakeTimers();
+ const preloads = stubPreloads();
+ expect(preloads.length).toBe(19);
+ for (const host of ["127.0.0.1", "localhost", "[::1]"]) preloadScreens(host);
+ vi.runAllTimers();
+ for (const preload of preloads) expect(preload).not.toHaveBeenCalled();
+ });
+
+ it("a Cloud page fetches the screens after launch, one per idle moment, and can be cancelled", async () => {
+ vi.useFakeTimers();
+ const idle: Array<() => void> = [];
const cancel = vi.fn();
vi.stubGlobal("requestIdleCallback", (run: () => void, options: { timeout: number }) => {
expect(options.timeout).toBeGreaterThan(0);
- idle = run;
- return 7;
+ idle.push(run);
+ return idle.length;
});
vi.stubGlobal("cancelIdleCallback", cancel);
const preloads = stubPreloads();
- expect(preloads.length).toBe(14);
- const stop = preloadScreens();
- for (const preload of preloads) expect(preload).not.toHaveBeenCalled();
- idle!();
- for (const preload of preloads) expect(preload).toHaveBeenCalledTimes(1);
+ const called = () => preloads.filter((preload) => preload.mock.calls.length > 0).length;
+ const stop = preloadScreens("cloud.example");
+ vi.advanceTimersByTime(4_999);
+ expect(idle.length, "nothing during launch").toBe(0);
+ vi.advanceTimersByTime(1);
+ expect(idle.length).toBe(1);
+ expect(called()).toBe(0);
+ idle.shift()!();
+ expect(called(), "one at a time").toBe(1);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(idle.length, "the next waits for the last to arrive").toBe(1);
+ idle.shift()!();
+ expect(called()).toBe(2);
+ await vi.advanceTimersByTimeAsync(0);
stop();
- expect(cancel).toHaveBeenCalledWith(7);
+ expect(cancel).toHaveBeenCalledTimes(1);
+ while (idle.length) idle.shift()!();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(idle.length, "nothing after cancel").toBe(0);
});
- it("falls back to a timer where requestIdleCallback is missing", () => {
+ it("reaches every screen on a Cloud page, by timer where requestIdleCallback is missing", async () => {
vi.useFakeTimers();
vi.stubGlobal("requestIdleCallback", undefined);
const preloads = stubPreloads();
- preloadScreens();
+ preloadScreens("cloud.example");
for (const preload of preloads) expect(preload).not.toHaveBeenCalled();
- vi.runAllTimers();
- for (const preload of preloads) expect(preload).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(60_000);
+ const rarelyOpened = [screens.CloudAddDialog, screens.PhoneAppDialog, screens.ShareTeamDialog, screens.TeamLibraryPanel];
+ const stubbed = Object.values(screens).filter((value): value is ReturnType<typeof lazyScreen> => typeof value === "function" && "preload" in value);
+ for (const screen of stubbed) expect(screen.preload).toHaveBeenCalledTimes(rarelyOpened.includes(screen as never) ? 0 : 1);
+ expect(preloads.length).toBe(stubbed.length);
});
it("a window opened onto Settings fetches Settings at once, not when idle", async () => {
@@ -212,10 +237,11 @@ describe("launch bundle", () => {
}
return null;
};
- const staticImports = /(?:^|\n)\s*(?:import|export)\s+(?!type\s)(?:[^"'`;]*?\sfrom\s+)?["']([^"']+)["']/g;
- const launchModules = (entry = "main.tsx") => {
+ const staticImports = /(?:^|[\n;])\s*(?:import|export)\s+(?!type\s)(?:[^"'`;]*?\sfrom\s+)?["']([^"']+)["']/g;
+ // The app's launch is main.tsx and App.tsx, whose fetch main.tsx starts at once on every path but /pair and /home.
+ const launchModules = (...entries: string[]) => {
const seen = new Set<string>();
- const queue = [join(srcRoot, entry)];
+ const queue = (entries.length ? entries : ["main.tsx", "App.tsx"]).map((entry) => join(srcRoot, entry));
while (queue.length) {
const file = queue.pop()!;
if (seen.has(file)) continue;
@@ -235,11 +261,19 @@ describe("launch bundle", () => {
expect(reached.has("App.tsx")).toBe(true);
expect(reached.has("components/Sidebar.tsx")).toBe(true);
const deferred = [
- "ActivityPanel", "BotSettingsDialog", "ComputerPanel", "InspectorPanel", "KeyboardShortcutsModal",
- "LocalVmWorkspace", "NewBotDialog", "RemoteAgentSettingsPanel", "remote-desktop-panel", "RoutineCalendarPage",
- "RoutinesPage", "SettingsModal", "TeamMapPage", "TriggersPage", "WebhookTrigger", "room-panel/RoomPanel",
+ "ActivityPanel", "BotSettingsDialog", "CloudAddDialog", "ComputerPanel", "InspectorPanel", "KeyboardShortcutsModal",
+ "LocalVmWorkspace", "NewBotDialog", "PhoneAppDialog", "PhoneSetupFlow", "PluginsPanel", "RemoteAgentSettingsPanel", "remote-desktop-panel", "RoutineCalendarPage",
+ "RoutinesPage", "SettingsModal", "ShareTeamDialog", "TeamLibraryPanel", "TeamMapPage", "TriggersPage", "WebhookTrigger", "room-panel/RoomPanel",
].map((name) => `components/${name}.tsx`);
expect(deferred.filter((file) => reached.has(file))).toEqual([]);
+ expect(reached.has("lib/team-import.ts"), "the team library brings the YAML parser in").toBe(false);
+ });
+
+ it("the sign-in and home pages leave the app out", () => {
+ const page = launchModules("main.tsx");
+ expect(page.has("pair/PairPage.tsx")).toBe(true);
+ expect(page.has("components/HomeScreen.tsx")).toBe(true);
+ expect(["App.tsx", "state/store.tsx", "components/Sidebar.tsx", "components/ChatView.tsx"].filter((file) => page.has(file))).toEqual([]);
});
it("carries English and no other language: the one a person chose loads before the first render", () => {
diff --git a/src/components/lazy-screens.tsx b/src/components/lazy-screens.tsx
index 732f5d1bc2..6360e9696c 100644
--- a/src/components/lazy-screens.tsx
+++ b/src/components/lazy-screens.tsx
@@ -73,6 +73,7 @@ export const InspectorPanel = lazyScreen("InspectorPanel", async () => (await im
export const KeyboardShortcutsModal = lazyScreen("KeyboardShortcutsModal", async () => (await import("./KeyboardShortcutsModal")).KeyboardShortcutsModal);
export const LocalVmWorkspace = lazyScreen("LocalVmWorkspace", async () => (await import("./LocalVmWorkspace")).LocalVmWorkspace);
export const NewBotDialog = lazyScreen("NewBotDialog", async () => (await import("./NewBotDialog")).NewBotDialog);
+export const PluginsPanel = lazyScreen("PluginsPanel", async () => (await import("./PluginsPanel")).PluginsPanel);
export const RemoteAgentSettingsPanel = lazyScreen("RemoteAgentSettingsPanel", async () => (await import("./RemoteAgentSettingsPanel")).RemoteAgentSettingsPanel);
export const RoomPanel = lazyScreen("RoomPanel", async () => (await import("./room-panel/RoomPanel")).RoomPanel);
export const RemoteDesktopPanel = lazyScreen("RemoteDesktopPanel", async () => (await import("./remote-desktop-panel")).RemoteDesktopPanel);
@@ -80,24 +81,55 @@ export const TriggersPage = lazyScreen("TriggersPage", async () => (await import
export const SettingsModal = lazyScreen("SettingsModal", async () => (await import("./SettingsModal")).SettingsModal);
export const TeamMapPage = lazyScreen("TeamMapPage", async () => (await import("./TeamMapPage")).TeamMapPage);
+// Rarely opened, so never fetched ahead. The team library is what brings the YAML parser in.
+export const CloudAddDialog = lazyScreen("CloudAddDialog", async () => (await import("./CloudAddDialog")).CloudAddDialog);
+export const PhoneAppDialog = lazyScreen("PhoneAppDialog", async () => (await import("./PhoneAppDialog")).PhoneAppDialog);
+export const ShareTeamDialog = lazyScreen("ShareTeamDialog", async () => (await import("./ShareTeamDialog")).ShareTeamDialog);
+export const TeamLibraryPanel = lazyScreen("TeamLibraryPanel", async () => (await import("./TeamLibraryPanel")).TeamLibraryPanel);
+
+// Most opened first: a Cloud page fetches these in this order.
const SCREENS = [
- ActivityPanel, BotSettingsDialog, ComputerPanel, FilesView, InspectorPanel, KeyboardShortcutsModal, LocalVmWorkspace, NewBotDialog,
- RemoteAgentSettingsPanel, RemoteDesktopPanel, RoomPanel, SettingsModal, TeamMapPage, TriggersPage,
+ SettingsModal, BotSettingsDialog, PluginsPanel, ComputerPanel, TriggersPage, ActivityPanel, FilesView, InspectorPanel, KeyboardShortcutsModal,
+ LocalVmWorkspace, NewBotDialog, RemoteAgentSettingsPanel, RemoteDesktopPanel, RoomPanel, TeamMapPage,
];
if (typeof location !== "undefined" && new URLSearchParams(location.search).has("desktop-settings")) {
void SettingsModal.preload().catch(() => {});
}
-export function preloadScreens(): () => void {
- const run = () => {
- for (const screen of SCREENS) void screen.preload().catch(() => {});
+const LOCAL_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]"]);
+const REMOTE_PRELOAD_AFTER_MS = 5_000;
+
+// On this machine a first open costs 8-28 ms, and fetching every screen during launch held the first paint back by a
+// quarter, so a local page fetches each when it opens. Over a network a first open takes up to a second, so a Cloud page
+// still fetches them, once launch is over and one per idle moment.
+export function preloadScreens(hostname = location.hostname): () => void {
+ if (LOCAL_HOSTS.has(hostname)) return () => {};
+ let stopped = false;
+ let cancelWait = () => {};
+ const whenIdle = (run: () => void) => {
+ if (typeof requestIdleCallback === "function") {
+ const handle = requestIdleCallback(run, { timeout: 2_000 });
+ cancelWait = () => cancelIdleCallback(handle);
+ } else {
+ // Safari has no requestIdleCallback.
+ const timer = setTimeout(run, 1_000);
+ cancelWait = () => clearTimeout(timer);
+ }
+ };
+ const fetchFrom = (index: number) => {
+ const screen = SCREENS[index];
+ if (!screen) return;
+ whenIdle(() => {
+ void screen.preload().catch(() => {}).then(() => {
+ if (!stopped) fetchFrom(index + 1);
+ });
+ });
+ };
+ const start = setTimeout(() => fetchFrom(0), REMOTE_PRELOAD_AFTER_MS);
+ cancelWait = () => clearTimeout(start);
+ return () => {
+ stopped = true;
+ cancelWait();
};
- if (typeof requestIdleCallback === "function") {
- const handle = requestIdleCallback(run, { timeout: 2_000 });
- return () => cancelIdleCallback(handle);
- }
- // Safari has no requestIdleCallback.
- const timer = setTimeout(run, 1_000);
- return () => clearTimeout(timer);
}
diff --git a/src/components/usage/TraceIcon.tsx b/src/components/usage/TraceIcon.tsx
index 3ee716756f..b3ced6c556 100644
--- a/src/components/usage/TraceIcon.tsx
+++ b/src/components/usage/TraceIcon.tsx
@@ -8,7 +8,7 @@ import type { Bot } from "@/state/store";
import type { TraceToolIcon } from "../../../shared/usage-trace";
import { BotAvatar } from "../Avatar";
import { loadAppCards } from "../bot-settings/useBotApps";
-import { ServiceIcon, type ToolkitCard } from "../PluginsPanel";
+import { ServiceIcon, type ToolkitCard } from "../ServiceIcon";
const ICONS: Record<Exclude<TraceToolIcon, "app">, LucideIcon> = {
search: Search, web: Globe, browser: Globe, computer: Monitor, phone: Smartphone, files: FileText, terminal: SquareTerminal,
diff --git a/src/hooks/use-usage-snapshot.test.ts b/src/hooks/use-usage-snapshot.test.ts
index c6a60666e9..c855bd9dfc 100644
--- a/src/hooks/use-usage-snapshot.test.ts
+++ b/src/hooks/use-usage-snapshot.test.ts
@@ -10,7 +10,7 @@ import type { AppState, ConfigStatus, InstanceInfo } from "@/state/store";
const fixture = vi.hoisted(() => ({ owner: true as boolean | null, track: vi.fn(), api: vi.fn(), connectedApps: vi.fn() }));
vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => fixture.owner }));
vi.mock("@/lib/analytics", () => ({ track: fixture.track, analyticsEnabled: () => true }));
-vi.mock("@/components/PluginsPanel", () => ({ preloadConnectedApps: fixture.connectedApps }));
+vi.mock("@/lib/connected-apps", () => ({ preloadConnectedApps: fixture.connectedApps }));
vi.mock("@/state/store", async (original) => ({ ...await original<typeof import("@/state/store")>(), api: fixture.api }));
const LATE_EVENING = Date.parse("2026-10-15T22:30:00.000Z");
diff --git a/src/hooks/use-usage-snapshot.ts b/src/hooks/use-usage-snapshot.ts
index 1791f8840b..aa70ca518a 100644
--- a/src/hooks/use-usage-snapshot.ts
+++ b/src/hooks/use-usage-snapshot.ts
@@ -1,5 +1,5 @@
import { useEffect, useRef } from "react";
-import { preloadConnectedApps } from "@/components/PluginsPanel";
+import { preloadConnectedApps } from "@/lib/connected-apps";
import { localDesktopPage } from "@/components/onboarding/WelcomeGate";
import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
import { sendDailySnapshot, SNAPSHOT_CHECK_MS, snapshotReady, type UsageSources } from "@/lib/usage-snapshot";
diff --git a/src/lib/companion-bridge.ts b/src/lib/companion-bridge.ts
new file mode 100644
index 0000000000..d17d4d16ce
--- /dev/null
+++ b/src/lib/companion-bridge.ts
@@ -0,0 +1,6 @@
+import type { CompanionBridge } from "@/components/PhoneSetupFlow";
+
+// Its own module so the sidebar's phone button can read the phone's state without loading the setup flow and its QR code.
+export const companionBridge = (): CompanionBridge | null =>
+ // SAFETY: the preload owns this narrow bridge; browser builds are guarded by the optional lookup.
+ (globalThis as { ogb?: { companion?: CompanionBridge } }).ogb?.companion ?? null;
diff --git a/src/lib/connected-apps.ts b/src/lib/connected-apps.ts
new file mode 100644
index 0000000000..6ad94fe159
--- /dev/null
+++ b/src/lib/connected-apps.ts
@@ -0,0 +1,65 @@
+import { api } from "@/state/store";
+import { unlessRefused } from "@/lib/admin-scope";
+import { readCachedInventory, writeCachedInventory } from "@/lib/connected-apps-cache";
+import type { ConnectorStatus } from "@/lib/connector-status";
+
+// The connected-apps inventory and its 30 s memory cache. Its own module so the sidebar, the usage meter and a bot's apps
+// can ask for it without loading the Apps panel.
+
+let cachedConnectorStatus: Record<string, ConnectorStatus> | null = null;
+let cachedConnectorStatusAt = 0;
+let cachedConnectorStatusAuthoritative = true;
+let connectorStatusRequest: Promise<ConnectorInventory> | null = null;
+const CONNECTOR_STATUS_CACHE_MS = 30_000;
+
+export interface ConnectorInventory {
+ services: Record<string, ConnectorStatus>;
+ /** false when the server could not read the credential store: nothing may be cleared on the strength of it. */
+ authoritative: boolean;
+ /** This session may not see the connected apps: its role, not the credential store. */
+ refused?: true;
+}
+
+const REFUSED_INVENTORY: ConnectorInventory = { services: {}, authoritative: true, refused: true };
+
+export function preloadConnectedApps(force = false, background = false): Promise<ConnectorInventory> { // background: src/state/api.ts
+ if (!force && cachedConnectorStatus !== null && Date.now() - cachedConnectorStatusAt < CONNECTOR_STATUS_CACHE_MS) {
+ return Promise.resolve({
+ services: cachedConnectorStatus,
+ authoritative: cachedConnectorStatusAuthoritative,
+ });
+ }
+ if (connectorStatusRequest) return connectorStatusRequest;
+ type ConnectedAnswer = { services?: Record<string, ConnectorStatus>; credentialStore?: string; inventoryComplete?: boolean };
+ connectorStatusRequest = unlessRefused<ConnectedAnswer | null>("/api/connectors/connected", () => api("/api/connectors/connected", background ? { background: true } : undefined), null)
+ .then((response): ConnectorInventory => {
+ if (!response) return REFUSED_INVENTORY;
+ const services: Record<string, ConnectorStatus> = response.services ?? {};
+ if (response.credentialStore === "unavailable" || response.inventoryComplete === false) {
+ cachedConnectorStatusAuthoritative = false;
+ return { services: readCachedInventory()?.services ?? services, authoritative: false };
+ }
+ cachedConnectorStatus = services;
+ cachedConnectorStatusAt = Date.now();
+ cachedConnectorStatusAuthoritative = true;
+ writeCachedInventory(services, Date.now());
+ return { services, authoritative: true };
+ })
+ .catch(() => ({ services: readCachedInventory()?.services ?? {}, authoritative: false }))
+ .finally(() => {
+ connectorStatusRequest = null;
+ });
+ return connectorStatusRequest;
+}
+
+/** What the Apps panel starts from: the last answer this page holds, if any. */
+export function connectorStatusMemory(): { services: Record<string, ConnectorStatus>; authoritative: boolean } | null {
+ return cachedConnectorStatus === null ? null : { services: cachedConnectorStatus, authoritative: cachedConnectorStatusAuthoritative };
+}
+
+/** The Apps panel's own reads land here, so the next preload within 30 s reuses them. */
+export function rememberConnectorStatus(services: Record<string, ConnectorStatus>, authoritative: boolean): void {
+ cachedConnectorStatus = services;
+ cachedConnectorStatusAt = Date.now();
+ cachedConnectorStatusAuthoritative = authoritative;
+}
diff --git a/src/main.tsx b/src/main.tsx
index 61a7ebd3ba..578acbac1c 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -1,6 +1,5 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
-import App from "./App";
import {
BROWSER_SIGN_IN_FAILED, previewBrowserSignIn, readSessionState, SERVICE_TRUST_REASON, takeBrowserSignInFromLocation, takePairingCodeFromLocation, takeInvitedEmailFromLocation,
} from "./lib/session";
@@ -23,6 +22,12 @@ applySkinChoice(readSkinChoice());
applyFont(readFont());
applyChatWidth(readChatWidth());
+// The app is its own chunk, so these pages don't parse it. Everywhere else its fetch starts now, alongside the session
+// read, instead of after it. A failed fetch renders as a throw, so PageBoundary offers a reload.
+const PAGES_WITHOUT_THE_APP = new Set(["/home", "/pair", "/desktop-viewer"]);
+const loadApp = () => import("./App").catch((error: unknown) => ({ default: (): never => { throw error; } }));
+const appPage = PAGES_WITHOUT_THE_APP.has(location.pathname) ? null : loadApp();
+
async function chooseRoot(): Promise<React.ReactNode> {
const home = window.ogb?.home;
if (location.pathname === "/home" && home) return <HomeScreen bridge={home} manage={window.ogb?.cloudPlan?.manage} />;
@@ -45,6 +50,7 @@ async function chooseRoot(): Promise<React.ReactNode> {
const { DesktopViewer } = await import("./components/DesktopViewer");
return <DesktopViewer />;
}
+ const { default: App } = await (appPage ?? loadApp());
return <App />;
}