perf(webui): batch startup recovery and authenticate before React (#6708)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-18 22:47:44 +08:00
1 parent 9652302324
commit 273582916b
26 files changed
+537 -330

No files matched your search

+18 -22
View File
@@ -66,12 +66,10 @@ import { cn } from "@/lib/utils";
import {
BootstrapAuthRequiredError,
clearSavedSecret,
consumeUrlBootstrapSecret,
deriveWsUrl,
fetchBootstrap,
loadSavedSecret,
saveSecret,
} from "@/lib/bootstrap";
import { requestBootstrap, type BootstrapRequest } from "@/lib/initial-bootstrap";
import { displayTitle, sortSessions } from "@/lib/chat-groups";
import { deriveTitle } from "@/lib/format";
import { NanobotClient } from "@/lib/nanobot-client";
@@ -361,10 +359,6 @@ function writeShellRoute(route: ShellRoute, replace = false): void {
}
}
function bootstrapTokenExpiresAt(expiresInSeconds: number): number {
return Date.now() + Math.max(0, expiresInSeconds) * 1000;
}
function tokenRefreshDelayMs(expiresAt: number): number {
const remaining = Math.max(0, expiresAt - Date.now());
const margin = Math.min(
@@ -616,24 +610,24 @@ function resolveRuntimeSurface(
return surface ? toRuntimeSurface(surface) : fallback;
}
export default function App() {
export default function App({ takeInitialBootstrap }: {
takeInitialBootstrap?: () => BootstrapRequest | undefined;
}) {
useAppViewport();
useBrowserNotificationLifecycle();
useReadingTypography();
const { t } = useTranslation();
const [state, setState] = useState<BootState>({ status: "loading" });
const bootstrapSecretRef = useRef("");
const initialRequest = useRef<BootstrapRequest>();
const refreshReadyClient = useCallback(
async (client: NanobotClient, fallbackSurface: RuntimeSurface, signal?: AbortSignal) => {
const boot = await fetchBootstrap("", bootstrapSecretRef.current);
const { boot, tokenExpiresAt } = await requestBootstrap(bootstrapSecretRef.current);
signal?.throwIfAborted();
const url = deriveWsUrl(boot.ws_path, boot.token, boot.ws_url);
const runtimeSurface = resolveRuntimeSurface(boot.runtime_surface, fallbackSurface);
const runtimeHost = createRuntimeHost(runtimeSurface, boot.runtime_capabilities);
const tokenExpiresAt = boot.expires_in
? bootstrapTokenExpiresAt(boot.expires_in)
: null;
if (runtimeHost.socketFactory) {
client.updateUrl(url, runtimeHost.socketFactory);
} else {
@@ -658,14 +652,14 @@ export default function App() {
[],
);
const bootstrapWithSecret = useCallback(
(secret: string, onAuthRejected?: () => void) => {
const connectBootstrap = useCallback(
(request: BootstrapRequest, onAuthRejected?: () => void) => {
let cancelled = false;
if (readShellRoute().view === "chat") void loadThreadShell().catch(() => {});
(async () => {
if (!onAuthRejected) setState({ status: "loading" });
try {
const boot = await fetchBootstrap("", secret);
const { boot, secret, tokenExpiresAt } = await request;
if (cancelled) return;
if (secret) saveSecret(secret);
const url = deriveWsUrl(boot.ws_path, boot.token, boot.ws_url);
@@ -691,9 +685,7 @@ export default function App() {
status: "ready",
client,
token: boot.api_token ?? "",
tokenExpiresAt: boot.expires_in
? bootstrapTokenExpiresAt(boot.expires_in)
: null,
tokenExpiresAt,
modelName: boot.model_name ?? null,
ingressLimits: boot.limits ?? null,
runtimeSurface,
@@ -713,6 +705,8 @@ export default function App() {
message: e instanceof Error ? e.message : String(e),
});
}
} finally {
if (initialRequest.current === request) initialRequest.current = undefined;
}
})();
return () => {
@@ -741,15 +735,16 @@ export default function App() {
}, [refreshReadyClient, state]);
useEffect(() => {
const saved = consumeUrlBootstrapSecret() || loadSavedSecret();
return bootstrapWithSecret(saved);
}, [bootstrapWithSecret]);
// Direct App mounts have no document entry. Effect replays share the same pending attempt.
initialRequest.current ??= takeInitialBootstrap?.() ?? requestBootstrap();
return connectBootstrap(initialRequest.current);
}, [connectBootstrap, takeInitialBootstrap]);
if (state.status === "loading") {
return <StartupShell />;
}
if (state.status === "auth") {
return <AuthForm onSecret={bootstrapWithSecret} />;
return <AuthForm onSecret={(secret, rejected) => connectBootstrap(requestBootstrap(secret), rejected)} />;
}
if (state.status === "error") {
return (
@@ -775,6 +770,7 @@ export default function App() {
if (state.status === "ready") {
state.client.close();
}
bootstrapSecretRef.current = "";
clearSavedSecret();
clearReloadCache();
clearStoredComposerDrafts();
@@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef, useState } from "react";
import { ShieldCheck, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { channelUiPresentation } from "@/channel-plugins/registry";
import type { channelUiPresentation } from "@/channel-plugins/registry";
import { Button } from "@/components/ui/button";
import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface";
import { useLogoFallback } from "@/hooks/useLogoFallback";
@@ -37,6 +37,7 @@ export function PairingCodePopup({
!request.delivery_status || request.delivery_status === "sent"
)) ?? requests[0] ?? null;
const displayRequest = matchedRequest ?? firstRequest;
const presentation = usePairingChannelPresentation(displayRequest?.channel ?? "");
const deliveryBlocked = displayRequest?.delivery_status === "failed"
|| displayRequest?.delivery_status === "sending";
const expires = formatPairingExpiry(displayRequest?.expires_in_seconds);
@@ -86,7 +87,7 @@ export function PairingCodePopup({
)}
>
<div className="flex items-start gap-3">
<PairingChannelBadge channel={displayRequest.channel} />
<PairingChannelBadge presentation={presentation} />
<div className="min-w-0 flex-1">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
@@ -138,7 +139,7 @@ export function PairingCodePopup({
{matchedRequest && busyCode === matchedRequest.code
? t("app.pairing.matched", {
defaultValue: "Matched {{channel}}. Connecting...",
channel: channelLabel(matchedRequest.channel),
channel: presentation.label,
})
: deliveryBlocked ? null : t("app.pairing.expiresInline", {
defaultValue: "Code expires {{expires}}.",
@@ -185,8 +186,7 @@ export function PairingCodePopup({
);
}
function PairingChannelBadge({ channel }: { channel: string }) {
const presentation = pairingChannelPresentation(channel);
function PairingChannelBadge({ presentation }: { presentation: ReturnType<typeof usePairingChannelPresentation> }) {
const initials = presentation.initials;
const color = presentation.color;
const brandLogoUrl = presentation.logoUrl;
@@ -321,13 +321,20 @@ function pairingChannelKey(channel: string): string {
return raw.split(/[.:]/)[0] ?? raw;
}
function channelLabel(channel: string): string {
return pairingChannelPresentation(channel).label;
}
function pairingChannelPresentation(channel: string) {
const key = pairingChannelKey(channel);
const plugin = channelUiPresentation(key);
function usePairingChannelPresentation(channel: string) {
const [lookup, setLookup] = useState<typeof channelUiPresentation>();
const needed = !!channel;
useEffect(() => {
// The registry also imports channel setup UIs. A real pairing request can
// already accept input with the text badge while its branding loads.
if (!needed || lookup) return;
let active = true;
void import("@/channel-plugins/registry").then(({ channelUiPresentation }) => {
if (active) setLookup(() => channelUiPresentation);
}).catch(() => {});
return () => { active = false; };
}, [needed, lookup]);
const plugin = lookup?.(pairingChannelKey(channel));
return {
label: plugin?.displayName ?? channel,
initials: plugin?.initials ?? channel.slice(0, 2).toUpperCase(),
@@ -1,5 +1,7 @@
import { lazy, Suspense, useCallback, useEffect, useId, useRef, useState } from "react";
import { LayoutGroup, motion, useReducedMotion } from "motion/react";
import { LayoutGroup, useReducedMotion } from "motion/react";
import { div as MotionDiv } from "motion/react-m";
import { DeferredMotion } from "@/components/ui/deferred-motion";
import { useTranslation } from "react-i18next";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { cn } from "@/lib/utils";
@@ -61,7 +63,7 @@ export function ContextInspector({ context, rounds, snapshots, onOpenFile, sideb
const openFileCallback = useRef(onOpenFile);
openFileCallback.current = onOpenFile;
const openFile = useCallback((path: string) => { setExpanded(false); openFileCallback.current?.(path); }, []);
const content = (large: boolean) => <motion.div layoutId={layoutId} transition={{ duration: reducedMotion ? 0 : 0.25, ease: [0.2, 0, 0, 1] }} className={cn("flex flex-col gap-3", sidebar && !large && "h-full min-h-0")}>
const content = (large: boolean) => <MotionDiv layoutId={layoutId} transition={{ duration: reducedMotion ? 0 : 0.25, ease: [0.2, 0, 0, 1] }} className={cn("flex flex-col gap-3", sidebar && !large && "h-full min-h-0")}>
<Suspense fallback={<div aria-busy="true" className={cn(surface, "min-h-[300px]", sidebar && !large && "min-h-0 flex-1")} />}>
<ContextGraphScene graph={snapshot?.graph ?? EMPTY_GRAPH} epoch={epoch} onReady={setReadyGraph} expanded={large} sidebar={sidebar && !large} onExpand={expandable ? toggleExpanded : undefined} onClose={large ? undefined : onClose} onOpenFile={onOpenFile ? openFile : undefined} />
</Suspense>
@@ -95,8 +97,8 @@ export function ContextInspector({ context, rounds, snapshots, onOpenFile, sideb
setReplay({ frames: [...snapshots], index: 0, startedAt: performance.now(), interval: 1000 / stepsPerSecond });
}} />
</div>
</motion.div>;
return <LayoutGroup>
</MotionDiv>;
return <DeferredMotion><LayoutGroup>
{!expanded && content(false)}
<Dialog open={expanded} onOpenChange={setExpanded}>
<DialogContent showCloseButton={false} aria-describedby={undefined} overlayClassName="context-expanded-overlay bg-background/30 backdrop-blur-md" className="w-[min(1440px,calc(100vw-2rem))] max-w-none border-0 bg-transparent p-0 shadow-none !animate-none">
@@ -104,5 +106,5 @@ export function ContextInspector({ context, rounds, snapshots, onOpenFile, sideb
{content(true)}
</DialogContent>
</Dialog>
</LayoutGroup>;
</LayoutGroup></DeferredMotion>;
}
@@ -1,5 +1,6 @@
import { useLayoutEffect, useRef, useState, type ReactElement } from "react";
import { motion } from "motion/react";
import { div as MotionDiv } from "motion/react-m";
import { DeferredMotion } from "@/components/ui/deferred-motion";
import { useMediaQuery } from "@/hooks/useMediaQuery";
@@ -29,6 +30,7 @@ export function LatestActivityWheel({ row, visible }: { row: ReactElement; visib
}, [canRoll, row]);
const outgoing = canRoll && frame.key === row.key ? frame.previous : undefined;
const current = <div className={rowClass}>{row}</div>;
return (
<div
aria-hidden
@@ -36,7 +38,7 @@ export function LatestActivityWheel({ row, visible }: { row: ReactElement; visib
data-testid="latest-activity-wheel"
className="relative h-6 min-w-0 overflow-hidden pe-1 max-sm:ms-6 sm:flex-1 [mask-image:linear-gradient(transparent,black_10%,black_90%,transparent)] [&_[data-activity-marker]]:self-center [&_[data-activity-marker]]:items-center [&_[data-activity-marker]]:pt-0"
>
{canRoll ? <motion.div
{canRoll ? <DeferredMotion><MotionDiv
key={frame.key}
initial={outgoing ? { y: "100%" } : false}
animate={{ y: 0 }}
@@ -46,8 +48,8 @@ export function LatestActivityWheel({ row, visible }: { row: ReactElement; visib
}}
>
{outgoing ? <div className={`absolute inset-x-0 bottom-full ${rowClass}`}>{outgoing}</div> : null}
<div className={rowClass}>{row}</div>
</motion.div> : <div className={rowClass}>{row}</div>}
{current}
</MotionDiv></DeferredMotion> : current}
</div>
);
}
@@ -0,0 +1,8 @@
import type { ReactNode } from "react";
import { LazyMotion } from "motion/react";
// Render the real elements immediately; load the animation/layout engine only on these surfaces.
const loadFeatures = () => import("./motion-features").then((module) => module.default);
export function DeferredMotion({ children }: { children: ReactNode }) {
return <LazyMotion features={loadFeatures}>{children}</LazyMotion>;
}
@@ -0,0 +1 @@
export { domMax as default } from "motion/react";
+1 -1
View File
@@ -366,7 +366,7 @@ export const conversationExamples: ComponentExample[] = [
{ title: "previews.modelPreset.title", files: ["thread/ModelPresetBadge"], Preview: ModelPresetPreview,
description: "previews.modelPreset.description", options: "previews.modelPreset.options",
code: '<ModelPresetBadge label={preset} modelPreset={preset} modelPresets={presets} onPresetChange={setPreset} isHero={false} />' },
{ title: "previews.usage.title", files: ["thread/ComposerUsagePopover"], Preview: UsagePreview,
{ title: "previews.usage.title", files: ["thread/ComposerUsagePopover", "thread/ContextInspector", "ui/deferred-motion"], Preview: UsagePreview,
description: "previews.usage.description", options: "previews.usage.options",
code: '<ComposerUsagePopover context={{ contextTokens: 18500, contextWindowTokens: 200000 }} rounds={rounds} showLabel />' },
{ title: "previews.workspace.title", files: ["thread/WorkspaceControls"], Preview: WorkspacePreview,
+1
View File
@@ -75,6 +75,7 @@ export async function fetchBootstrap(
const res = await fetchWithTimeout(`${baseUrl}/webui/bootstrap`, {
method: "GET",
credentials: "same-origin",
cache: "no-store",
headers,
}, timeoutMs);
if (!res.ok) {
+22
View File
@@ -0,0 +1,22 @@
import { consumeUrlBootstrapSecret, fetchBootstrap, loadSavedSecret } from "./bootstrap";
export async function requestBootstrap(secret = consumeUrlBootstrapSecret() || loadSavedSecret()) {
const boot = await fetchBootstrap("", secret);
// The document can receive the token well before React mounts. Do not extend its TTL.
const tokenExpiresAt = boot.expires_in ? Date.now() + Math.max(0, boot.expires_in) * 1000 : null;
return { boot, secret, tokenExpiresAt };
}
export type BootstrapRequest = ReturnType<typeof requestBootstrap>;
/** Hand this document's request to its App, not to a global or persistent cache. */
export function preloadInitialBootstrap() {
let pending: BootstrapRequest | undefined = requestBootstrap();
// A fast 401 (or timeout) may arrive before the UI imports. App handles the original rejection.
void pending.catch(() => {});
return () => {
const request = pending;
pending = undefined;
return request;
};
}
+11 -7
View File
@@ -1,8 +1,5 @@
import ReactDOM from "react-dom/client";
import App from "./App";
import "./globals.css";
import { initializeI18n } from "./i18n";
import { preloadInitialBootstrap } from "./lib/initial-bootstrap";
import { initializePairReturn } from "./lib/remote-pair-return";
// `crypto.randomUUID` is only defined in secure contexts (HTTPS or localhost).
@@ -28,6 +25,14 @@ initializePairReturn();
window.addEventListener("hashchange", initializePairReturn);
async function renderWebui(container: HTMLElement) {
const takeInitialBootstrap = preloadInitialBootstrap();
const localeReady = import("./i18n").then(({ initializeI18n }) => initializeI18n());
const app = import("./mount");
// The HTML skeleton already resolved the initial route (including restart links).
// Warm only code: neither chat nor a socket mounts until App accepts the bootstrap.
if (container.querySelector('[data-startup-surface="chat"]')) {
void import("./components/thread/ThreadShell").catch(() => {});
}
// The critical skeleton paints immediately; React must wait for the full stylesheet.
const styles = [...document.querySelectorAll<HTMLLinkElement>("link[data-app-stylesheet]")]
.map((link) => new Promise<void>((resolve, reject) => {
@@ -38,9 +43,8 @@ async function renderWebui(container: HTMLElement) {
link.rel = "stylesheet";
if (link.sheet) ready();
}));
await Promise.all([initializeI18n(), ...styles]);
/* StrictMode disabled: dev double-invokes state updaters; delta accumulation must stay pure — see useNanobotStream. */
ReactDOM.createRoot(container).render(<App />);
const [{ mountWebui }] = await Promise.all([app, localeReady, ...styles]);
mountWebui(container, takeInitialBootstrap);
}
void renderWebui(root);
+8
View File
@@ -0,0 +1,8 @@
import ReactDOM from "react-dom/client";
import App from "./App";
import type { preloadInitialBootstrap } from "./lib/initial-bootstrap";
export function mountWebui(container: HTMLElement, takeInitialBootstrap: ReturnType<typeof preloadInitialBootstrap>) {
/* StrictMode disabled: dev double-invokes state updaters; delta accumulation must stay pure — see useNanobotStream. */
ReactDOM.createRoot(container).render(<App takeInitialBootstrap={takeInitialBootstrap} />);
}
@@ -0,0 +1,55 @@
import { act, screen } from "@testing-library/react";
import ReactDOM from "react-dom/client";
import { expect, it, vi } from "vitest";
const events = vi.hoisted(() => [] as string[]);
vi.mock("@/mount", async (original) => {
events.push("mount module");
return original<typeof import("@/mount")>();
});
vi.mock("@/components/thread/ThreadShell", () => {
events.push("thread module");
return { ThreadShell: () => null };
});
it("starts the fragment-authenticated request and chat import before mount, then consumes even a fast 401 once", async () => {
const root = document.createElement("div");
root.id = "root";
root.innerHTML = '<main data-startup-surface="chat" aria-busy="true"></main>';
document.body.append(root);
const css = document.createElement("link");
css.dataset.appStylesheet = "";
document.head.append(css);
window.history.replaceState(null, "", "/#/?bootstrapSecret=from-fragment&keep=1");
const createRoot = vi.spyOn(ReactDOM, "createRoot");
const request = vi.fn(async () => {
events.push("bootstrap");
return new Response(null, { status: 401 });
});
vi.stubGlobal("fetch", request);
try {
await import("@/main");
await vi.dynamicImportSettled();
expect(events[0]).toBe("bootstrap");
expect(events).toContain("thread module");
expect(events).toContain("mount module");
expect(request).toHaveBeenCalledWith("/webui/bootstrap", expect.objectContaining({
credentials: "same-origin", cache: "no-store", headers: { "X-Nanobot-Auth": "from-fragment" },
}));
expect(window.location.hash).toBe("#/?keep=1");
expect(createRoot).not.toHaveBeenCalled();
expect(root.querySelector("input, textarea")).toBeNull();
await act(async () => { css.dispatchEvent(new Event("load")); });
expect(await screen.findByLabelText("WebUI password")).toBeVisible();
expect(request).toHaveBeenCalledTimes(1);
expect(localStorage.getItem("nanobot-webui.bootstrap-secret")).toBeNull();
} finally {
await act(async () => { createRoot.mock.results[0]?.value?.unmount(); });
vi.restoreAllMocks();
vi.unstubAllGlobals();
window.history.replaceState(null, "", "/");
css.remove();
root.remove();
}
});
+3 -1
View File
@@ -101,7 +101,9 @@ describe("webuiManualChunk", () => {
expect(webuiManualChunk("/repo/node_modules/react-dom/client.js")).toBe("react-vendor");
expect(webuiManualChunk("/repo/node_modules/scheduler/index.js")).toBe("react-vendor");
expect(webuiManualChunk("/repo/node_modules/clsx/dist/clsx.mjs")).toBe("react-vendor");
expect(webuiManualChunk("\0vite/preload-helper.js")).toBe("react-vendor");
});
it("does not make the document's dynamic-import helper pull in React DOM", () => {
expect(webuiManualChunk("\0vite/preload-helper.js")).toBe("preload-helper");
});
it("keeps markdown-only hast utilities in the markdown chunk", () => {
+22 -4
View File
@@ -47,11 +47,27 @@ function guardWebuiEntryChunk(): Plugin {
apply: "build",
generateBundle(_options, bundle) {
for (const output of Object.values(bundle)) {
if (output.type !== "chunk" || !output.isEntry) continue;
const unexpected = entryLazyFeatureImports(output.imports);
if (output.type !== "chunk") continue;
// The external document entry starts the app and chat imports concurrently.
// Protect their real static closures too, not just the tiny dispatcher.
const isApp = output.facadeModuleId?.endsWith("/src/mount.tsx");
const isChat = output.facadeModuleId?.endsWith("/components/thread/ThreadShell.tsx");
if (!output.isEntry && !isApp && !isChat) continue;
const imports = new Set<string>();
const visit = (name: string) => {
if (imports.has(name)) return;
imports.add(name);
const dependency = bundle[name];
if (dependency?.type === "chunk") dependency.imports.forEach(visit);
};
output.imports.forEach(visit);
const unexpected = entryLazyFeatureImports([...imports]);
if (output.isEntry && output.facadeModuleId?.endsWith("/index.html")) {
unexpected.push(...[...imports].filter((name) => path.basename(name).startsWith("react-vendor-")));
}
if (unexpected.length > 0) {
throw new Error(
`WebUI entry chunk statically imports lazy features: ${unexpected.join(", ")}`,
`${output.fileName} statically imports deferred WebUI features: ${unexpected.join(", ")}`,
);
}
}
@@ -97,12 +113,14 @@ export function webuiManualChunk(id: string): string | undefined {
|| (id.includes("node_modules/micromark-extension-math/") && id.endsWith("/html.js"))) {
return "markdown-math";
}
// The document entry uses dynamic imports before mounting. Keep their tiny helper
// independent: putting it in react-vendor makes the bootstrap wait for React DOM.
if (id.includes("vite/preload-helper")) return "preload-helper";
if (
id.includes("node_modules/react/")
|| id.includes("node_modules/react-dom/")
|| id.includes("node_modules/scheduler/")
|| id.includes("node_modules/clsx/")
|| id.includes("vite/preload-helper")
) {
return "react-vendor";
}