fix(webui): restore startup flow while keeping recovery batching (#6712)

* fix(webui): restore startup flow while keeping recovery batching

Keep the two restart recovery scans from #6708. Withdraw the browser preload and launcher changes until they can be measured independently against the Windows first-send regression.

* fix(webui): skip graph layout measurement in reduced motion

A zero-duration shared layout still measured the panel while the 500-node graph was mounting. Disable the shared-layout link in reduced motion and start the browser budget after the initial graph paints. Keep the existing 150ms limit and all 500 node checks.
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-18 23:40:49 +08:00
1 parent cab49a1c66
commit 995f9e36c1
21 files changed
+260 -400

No files matched your search

-199
View File
@@ -1,199 +0,0 @@
"""WebSocket configuration shared by the launcher and the gateway listener."""
from __future__ import annotations
import ipaddress
from pathlib import Path
from typing import Self
from urllib.parse import urlsplit, urlunsplit
from pydantic import Field, PrivateAttr, field_validator, model_validator
from nanobot.config_base import Base
from nanobot.webui.http_utils import normalize_config_path as _normalize_config_path
_ROUTING_ASSERTION_HEADERS = frozenset(
{
"host",
"forwarded",
"x-forwarded-for",
"x-forwarded-host",
"x-forwarded-proto",
"x-real-ip",
"cf-connecting-ip",
}
)
def _is_routing_assertion_header(value: str) -> bool:
normalized = value.casefold()
return normalized in _ROUTING_ASSERTION_HEADERS or normalized.startswith("x-forwarded-")
class TrustedProxyAuthConfig(Base):
"""Authentication assertions accepted from explicitly trusted proxy peers."""
trusted_peer_cidrs: list[str] = Field(min_length=1)
assertion_header: str = Field(min_length=1)
_trusted_peer_networks: tuple[ipaddress.IPv4Network | ipaddress.IPv6Network, ...] = PrivateAttr(
default=()
)
@field_validator("trusted_peer_cidrs")
@classmethod
def validate_trusted_peer_cidrs(cls, values: list[str]) -> list[str]:
normalized: list[str] = []
for value in values:
value = value.strip()
try:
network = ipaddress.ip_network(value, strict=False)
except ValueError as exc:
raise ValueError(f"invalid trusted proxy CIDR: {value!r}") from exc
if network.prefixlen == 0:
raise ValueError("universal trusted proxy CIDRs are not allowed")
if isinstance(network, ipaddress.IPv6Network):
mapped_start = ipaddress.IPv6Address("::ffff:0:0")
mapped_end = ipaddress.IPv6Address("::ffff:ffff:ffff")
if mapped_start in network and mapped_end in network:
raise ValueError("trusted proxy CIDRs must not cover all IPv4-mapped addresses")
normalized.append(network.with_prefixlen)
return normalized
@field_validator("assertion_header")
@classmethod
def validate_assertion_header(cls, value: str) -> str:
value = value.strip()
if not value or any(char.isspace() or ord(char) < 0x21 for char in value):
raise ValueError("assertion_header must be a valid HTTP header name")
if _is_routing_assertion_header(value):
raise ValueError(
"assertion_header must identify a proxy-generated authentication assertion, "
"not a routing or client metadata header"
)
return value
@model_validator(mode="after")
def compile_trusted_peer_networks(self) -> Self:
self._trusted_peer_networks = tuple(
ipaddress.ip_network(value, strict=False) for value in self.trusted_peer_cidrs
)
return self
class WebSocketConfig(Base):
"""WebSocket server channel configuration.
Clients connect with URLs like ``ws://{host}:{port}{path}?client_id=...&token=...``.
- ``client_id``: Used for ``allow_from`` authorization; if omitted, a value is generated and logged.
- ``token``: If non-empty, the ``token`` query param may match this static secret; short-lived tokens
from ``token_issue_path`` are also accepted.
- ``token_issue_path``: If non-empty, **GET** (HTTP/1.1) to this path returns JSON
``{"token": "...", "expires_in": <seconds>}``; use ``?token=...`` when opening the WebSocket.
Must differ from ``path`` (the WS upgrade path). If the client runs in the **same process** as
nanobot and shares the asyncio loop, use a thread or async HTTP client for GET—do not call
blocking ``urllib`` or synchronous ``httpx`` from inside a coroutine.
- ``token_issue_secret``: If non-empty, token requests must send ``Authorization: Bearer <secret>`` or
``X-Nanobot-Auth: <secret>``.
- ``public_ws_url``: Optional public WebSocket endpoint returned by WebUI bootstrap instead of
deriving one from proxy request headers. Its path must match ``path``.
- ``websocket_requires_token``: If True, the handshake must include a valid token (static or issued and not expired).
- Each connection has its own session: a unique ``chat_id`` maps to the agent session internally.
- ``media`` field in outbound messages contains local filesystem paths; remote clients need a
shared filesystem or an HTTP file server to access these files.
"""
enabled: bool = True
host: str = "127.0.0.1"
port: int = 8765
unix_socket_path: str = ""
path: str = "/"
public_ws_url: str = ""
token: str = ""
token_issue_path: str = ""
token_issue_secret: str = ""
trusted_proxy_auth: TrustedProxyAuthConfig | None = None
token_ttl_s: int = Field(default=300, ge=30, le=86_400)
websocket_requires_token: bool = True
allow_from: list[str] = Field(default_factory=lambda: ["*"])
streaming: bool = True
# Keep the existing configurable guard (also used for non-attachment
# frames and older clients). HTTP attachments are outside this limit.
max_message_bytes: int = Field(default=37_748_736, ge=1024, le=41_943_040)
ping_interval_s: float = Field(default=20.0, ge=5.0, le=300.0)
ping_timeout_s: float = Field(default=20.0, ge=5.0, le=300.0)
ssl_certfile: str = ""
ssl_keyfile: str = ""
@field_validator("unix_socket_path")
@classmethod
def unix_socket_path_format(cls, value: str) -> str:
value = value.strip()
if not value:
return ""
if "\x00" in value:
raise ValueError("unix_socket_path must not contain NUL bytes")
path = Path(value).expanduser()
if not path.is_absolute():
raise ValueError("unix_socket_path must be an absolute path")
return str(path)
@field_validator("path")
@classmethod
def path_must_start_with_slash(cls, value: str) -> str:
if not value.startswith("/"):
raise ValueError('path must start with "/"')
return _normalize_config_path(value)
@field_validator("token_issue_path")
@classmethod
def token_issue_path_format(cls, value: str) -> str:
value = value.strip()
if not value:
return ""
if not value.startswith("/"):
raise ValueError('token_issue_path must start with "/"')
return _normalize_config_path(value)
@field_validator("public_ws_url")
@classmethod
def public_ws_url_format(cls, value: str) -> str:
value = value.strip()
if not value:
return ""
parsed = urlsplit(value)
if (
parsed.scheme not in {"ws", "wss"}
or not parsed.netloc
or parsed.username is not None
or parsed.password is not None
or parsed.query
or parsed.fragment
):
raise ValueError("public_ws_url must be an absolute ws:// or wss:// URL without credentials")
return urlunsplit(
(parsed.scheme, parsed.netloc, _normalize_config_path(parsed.path or "/"), "", "")
)
@model_validator(mode="after")
def public_ws_url_matches_path(self) -> Self:
if self.public_ws_url and urlsplit(self.public_ws_url).path != _normalize_config_path(self.path):
raise ValueError("public_ws_url path must match path")
return self
@model_validator(mode="after")
def token_issue_path_differs_from_ws_path(self) -> Self:
if not self.token_issue_path:
return self
if _normalize_config_path(self.token_issue_path) == _normalize_config_path(self.path):
raise ValueError("token_issue_path must differ from path (the WebSocket upgrade path)")
return self
@model_validator(mode="after")
def wildcard_host_requires_auth(self) -> Self:
if self.host not in ("0.0.0.0", "::"):
return self
if self.token.strip() or self.token_issue_secret.strip() or self.trusted_proxy_auth is not None:
return self
raise ValueError(
"host is 0.0.0.0 (all interfaces) but neither token, token_issue_secret, "
"nor trusted_proxy_auth is set — set one to prevent unauthenticated access"
)
+193 -3
View File
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import errno
import ipaddress
import json
import socket
import ssl
@@ -10,9 +11,11 @@ from collections.abc import Sequence
from contextlib import suppress
from dataclasses import dataclass
from pathlib import Path
from typing import Any, TypeGuard, cast
from typing import Any, Self, TypeGuard, cast
from urllib.parse import urlsplit, urlunsplit
from weakref import WeakSet
from pydantic import Field, PrivateAttr, field_validator, model_validator
from websockets.asyncio.server import Server, ServerConnection, serve, unix_serve
from websockets.exceptions import ConnectionClosed
from websockets.http11 import Request as WsRequest
@@ -23,8 +26,7 @@ from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.channels.websocket.binary_http import BinaryHTTPBridge
from nanobot.channels.websocket.config import TrustedProxyAuthConfig as TrustedProxyAuthConfig
from nanobot.channels.websocket.config import WebSocketConfig as WebSocketConfig
from nanobot.config_base import Base
from nanobot.runtime_admission import RuntimeMaintenanceError
from nanobot.webui.gateway_services import GatewayServices
from nanobot.webui.http_utils import (
@@ -83,6 +85,194 @@ _RECOVERABLE_LISTENER_WINERRORS = {
}
_ROUTING_ASSERTION_HEADERS = frozenset(
{
"host",
"forwarded",
"x-forwarded-for",
"x-forwarded-host",
"x-forwarded-proto",
"x-real-ip",
"cf-connecting-ip",
}
)
def _is_routing_assertion_header(value: str) -> bool:
normalized = value.casefold()
return normalized in _ROUTING_ASSERTION_HEADERS or normalized.startswith("x-forwarded-")
class TrustedProxyAuthConfig(Base):
"""Authentication assertions accepted from explicitly trusted proxy peers."""
trusted_peer_cidrs: list[str] = Field(min_length=1)
assertion_header: str = Field(min_length=1)
_trusted_peer_networks: tuple[ipaddress.IPv4Network | ipaddress.IPv6Network, ...] = PrivateAttr(
default=()
)
@field_validator("trusted_peer_cidrs")
@classmethod
def validate_trusted_peer_cidrs(cls, values: list[str]) -> list[str]:
normalized: list[str] = []
for value in values:
value = value.strip()
try:
network = ipaddress.ip_network(value, strict=False)
except ValueError as exc:
raise ValueError(f"invalid trusted proxy CIDR: {value!r}") from exc
if network.prefixlen == 0:
raise ValueError("universal trusted proxy CIDRs are not allowed")
if isinstance(network, ipaddress.IPv6Network):
mapped_start = ipaddress.IPv6Address("::ffff:0:0")
mapped_end = ipaddress.IPv6Address("::ffff:ffff:ffff")
if mapped_start in network and mapped_end in network:
raise ValueError("trusted proxy CIDRs must not cover all IPv4-mapped addresses")
normalized.append(network.with_prefixlen)
return normalized
@field_validator("assertion_header")
@classmethod
def validate_assertion_header(cls, value: str) -> str:
value = value.strip()
if not value or any(char.isspace() or ord(char) < 0x21 for char in value):
raise ValueError("assertion_header must be a valid HTTP header name")
if _is_routing_assertion_header(value):
raise ValueError(
"assertion_header must identify a proxy-generated authentication assertion, "
"not a routing or client metadata header"
)
return value
@model_validator(mode="after")
def compile_trusted_peer_networks(self) -> Self:
self._trusted_peer_networks = tuple(
ipaddress.ip_network(value, strict=False) for value in self.trusted_peer_cidrs
)
return self
class WebSocketConfig(Base):
"""WebSocket server channel configuration.
Clients connect with URLs like ``ws://{host}:{port}{path}?client_id=...&token=...``.
- ``client_id``: Used for ``allow_from`` authorization; if omitted, a value is generated and logged.
- ``token``: If non-empty, the ``token`` query param may match this static secret; short-lived tokens
from ``token_issue_path`` are also accepted.
- ``token_issue_path``: If non-empty, **GET** (HTTP/1.1) to this path returns JSON
``{"token": "...", "expires_in": <seconds>}``; use ``?token=...`` when opening the WebSocket.
Must differ from ``path`` (the WS upgrade path). If the client runs in the **same process** as
nanobot and shares the asyncio loop, use a thread or async HTTP client for GET—do not call
blocking ``urllib`` or synchronous ``httpx`` from inside a coroutine.
- ``token_issue_secret``: If non-empty, token requests must send ``Authorization: Bearer <secret>`` or
``X-Nanobot-Auth: <secret>``.
- ``public_ws_url``: Optional public WebSocket endpoint returned by WebUI bootstrap instead of
deriving one from proxy request headers. Its path must match ``path``.
- ``websocket_requires_token``: If True, the handshake must include a valid token (static or issued and not expired).
- Each connection has its own session: a unique ``chat_id`` maps to the agent session internally.
- ``media`` field in outbound messages contains local filesystem paths; remote clients need a
shared filesystem or an HTTP file server to access these files.
"""
enabled: bool = True
host: str = "127.0.0.1"
port: int = 8765
unix_socket_path: str = ""
path: str = "/"
public_ws_url: str = ""
token: str = ""
token_issue_path: str = ""
token_issue_secret: str = ""
trusted_proxy_auth: TrustedProxyAuthConfig | None = None
token_ttl_s: int = Field(default=300, ge=30, le=86_400)
websocket_requires_token: bool = True
allow_from: list[str] = Field(default_factory=lambda: ["*"])
streaming: bool = True
# Keep the existing configurable guard (also used for non-attachment
# frames and older clients). HTTP attachments are outside this limit.
max_message_bytes: int = Field(default=37_748_736, ge=1024, le=41_943_040)
ping_interval_s: float = Field(default=20.0, ge=5.0, le=300.0)
ping_timeout_s: float = Field(default=20.0, ge=5.0, le=300.0)
ssl_certfile: str = ""
ssl_keyfile: str = ""
@field_validator("unix_socket_path")
@classmethod
def unix_socket_path_format(cls, value: str) -> str:
value = value.strip()
if not value:
return ""
if "\x00" in value:
raise ValueError("unix_socket_path must not contain NUL bytes")
path = Path(value).expanduser()
if not path.is_absolute():
raise ValueError("unix_socket_path must be an absolute path")
return str(path)
@field_validator("path")
@classmethod
def path_must_start_with_slash(cls, value: str) -> str:
if not value.startswith("/"):
raise ValueError('path must start with "/"')
return _normalize_config_path(value)
@field_validator("token_issue_path")
@classmethod
def token_issue_path_format(cls, value: str) -> str:
value = value.strip()
if not value:
return ""
if not value.startswith("/"):
raise ValueError('token_issue_path must start with "/"')
return _normalize_config_path(value)
@field_validator("public_ws_url")
@classmethod
def public_ws_url_format(cls, value: str) -> str:
value = value.strip()
if not value:
return ""
parsed = urlsplit(value)
if (
parsed.scheme not in {"ws", "wss"}
or not parsed.netloc
or parsed.username is not None
or parsed.password is not None
or parsed.query
or parsed.fragment
):
raise ValueError("public_ws_url must be an absolute ws:// or wss:// URL without credentials")
return urlunsplit(
(parsed.scheme, parsed.netloc, _normalize_config_path(parsed.path or "/"), "", "")
)
@model_validator(mode="after")
def public_ws_url_matches_path(self) -> Self:
if self.public_ws_url and urlsplit(self.public_ws_url).path != _normalize_config_path(self.path):
raise ValueError("public_ws_url path must match path")
return self
@model_validator(mode="after")
def token_issue_path_differs_from_ws_path(self) -> Self:
if not self.token_issue_path:
return self
if _normalize_config_path(self.token_issue_path) == _normalize_config_path(self.path):
raise ValueError("token_issue_path must differ from path (the WebSocket upgrade path)")
return self
@model_validator(mode="after")
def wildcard_host_requires_auth(self) -> Self:
if self.host not in ("0.0.0.0", "::"):
return self
if self.token.strip() or self.token_issue_secret.strip() or self.trusted_proxy_auth is not None:
return self
raise ValueError(
"host is 0.0.0.0 (all interfaces) but neither token, token_issue_secret, "
"nor trusted_proxy_auth is set — set one to prevent unauthenticated access"
)
def _parse_inbound_payload(raw: str) -> str | None:
text = raw.strip()
if not text:
+2
View File
@@ -35,6 +35,7 @@ from nanobot import optional_features as feature_support # noqa: E402
from nanobot.cli import terminal as cli_terminal # noqa: E402
from nanobot.cli.agent import agent # noqa: E402
from nanobot.cli.gateway import create_gateway_app # noqa: E402
from nanobot.cli.gateway_runtime import _run_gateway # noqa: E402
from nanobot.cli.log_control import _set_nanobot_logs # noqa: E402
from nanobot.cli.process_identity import set_cli_process_identity # noqa: E402
from nanobot.cli.provider import provider_app # noqa: E402
@@ -351,6 +352,7 @@ app.add_typer(
console=console,
log_handler_id=_log_handler_id,
load_runtime_config=_load_runtime_config,
run_gateway=_run_gateway,
validate_startup_config=_validate_gateway_startup,
prepare_webui_bundle=lambda config, mode: _prepare_webui_bundle_for_gateway(
config,
+2 -9
View File
@@ -48,7 +48,7 @@ def create_gateway_app(
console: Console,
log_handler_id: int,
load_runtime_config: RuntimeConfigLoader,
run_gateway: GatewayRunner | None = None,
run_gateway: GatewayRunner,
validate_startup_config: GatewayConfigValidator | None = None,
runtime_factory: GatewayRuntimeFactory | None = None,
service_factory: GatewayServiceFactory | None = None,
@@ -234,15 +234,8 @@ def create_gateway_app(
unconfigured_provider_error = None
if validate_startup_config is not None:
unconfigured_provider_error = validate_startup_config(cfg)
# The WebUI launcher starts a separate gateway process. Load the agent runtime
# only in the process that actually serves requests, not when registering CLI commands.
runner = run_gateway
if runner is None:
from nanobot.cli.gateway_runtime import _run_gateway
runner = _run_gateway
try:
runner(
run_gateway(
cfg,
port=port,
verbose=verbose,
+2 -2
View File
@@ -230,7 +230,7 @@ def _load_webui_setup_config(config_path: Path) -> Config:
def _webui_config_dict(config: Config) -> dict[str, Any]:
from nanobot.channels.websocket.config import WebSocketConfig
from nanobot.channels.websocket.runtime import WebSocketConfig
current: Any = getattr(config.channels, "websocket", None) or {}
model = WebSocketConfig.model_validate(current)
@@ -238,7 +238,7 @@ def _webui_config_dict(config: Config) -> dict[str, Any]:
def _webui_channel_enabled(config: Config) -> bool:
from nanobot.channels.websocket.config import WebSocketConfig
from nanobot.channels.websocket.runtime import WebSocketConfig
current: Any = getattr(config.channels, "websocket", None) or {}
return bool(WebSocketConfig.model_validate(current).enabled)
+1 -3
View File
@@ -3643,10 +3643,8 @@ def test_gateway_local_trigger_queue_submits_agent_turns(
_fake_run_local_trigger_queue,
)
from nanobot.cli.gateway_runtime import _run_gateway
with pytest.raises(typer.Exit) as exc_info:
_run_gateway(
cli_commands._run_gateway(
config,
health_server_enabled=False,
unconfigured_provider_error=setup_error,
+2 -1
View File
@@ -174,7 +174,8 @@ test("500 reduced-motion nodes settle over multiple frames and are all painted",
}).observe({ entryTypes: ["longtask"] });
});
await page.goto("/browser/context-graph.html");
await expect(page.getByRole("button", { name: "a.md", exact: true })).toBeAttached();
// Start timing the update after the initial two-node graph has painted.
await expect.poll(() => page.evaluate(() => window.graphDrawTrace.arcs)).toBe(2);
await page.evaluate(() => { window.graphDrawTrace = { arcs: 0, frames: 0, maxTask: 0, start: performance.now() }; });
await page.getByRole("button", { name: "Load 500 nodes" }).click();
await expect(page.getByRole("button", { name: /^file-\d+\.md$/ })).toHaveCount(500);
+22 -18
View File
@@ -66,10 +66,12 @@ 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";
@@ -359,6 +361,10 @@ 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(
@@ -610,24 +616,24 @@ function resolveRuntimeSurface(
return surface ? toRuntimeSurface(surface) : fallback;
}
export default function App({ takeInitialBootstrap }: {
takeInitialBootstrap?: () => BootstrapRequest | undefined;
}) {
export default function App() {
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, tokenExpiresAt } = await requestBootstrap(bootstrapSecretRef.current);
const boot = await fetchBootstrap("", 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 {
@@ -652,14 +658,14 @@ export default function App({ takeInitialBootstrap }: {
[],
);
const connectBootstrap = useCallback(
(request: BootstrapRequest, onAuthRejected?: () => void) => {
const bootstrapWithSecret = useCallback(
(secret: string, onAuthRejected?: () => void) => {
let cancelled = false;
if (readShellRoute().view === "chat") void loadThreadShell().catch(() => {});
(async () => {
if (!onAuthRejected) setState({ status: "loading" });
try {
const { boot, secret, tokenExpiresAt } = await request;
const boot = await fetchBootstrap("", secret);
if (cancelled) return;
if (secret) saveSecret(secret);
const url = deriveWsUrl(boot.ws_path, boot.token, boot.ws_url);
@@ -685,7 +691,9 @@ export default function App({ takeInitialBootstrap }: {
status: "ready",
client,
token: boot.api_token ?? "",
tokenExpiresAt,
tokenExpiresAt: boot.expires_in
? bootstrapTokenExpiresAt(boot.expires_in)
: null,
modelName: boot.model_name ?? null,
ingressLimits: boot.limits ?? null,
runtimeSurface,
@@ -705,8 +713,6 @@ export default function App({ takeInitialBootstrap }: {
message: e instanceof Error ? e.message : String(e),
});
}
} finally {
if (initialRequest.current === request) initialRequest.current = undefined;
}
})();
return () => {
@@ -735,16 +741,15 @@ export default function App({ takeInitialBootstrap }: {
}, [refreshReadyClient, state]);
useEffect(() => {
// Direct App mounts have no document entry. Effect replays share the same pending attempt.
initialRequest.current ??= takeInitialBootstrap?.() ?? requestBootstrap();
return connectBootstrap(initialRequest.current);
}, [connectBootstrap, takeInitialBootstrap]);
const saved = consumeUrlBootstrapSecret() || loadSavedSecret();
return bootstrapWithSecret(saved);
}, [bootstrapWithSecret]);
if (state.status === "loading") {
return <StartupShell />;
}
if (state.status === "auth") {
return <AuthForm onSecret={(secret, rejected) => connectBootstrap(requestBootstrap(secret), rejected)} />;
return <AuthForm onSecret={bootstrapWithSecret} />;
}
if (state.status === "error") {
return (
@@ -770,7 +775,6 @@ export default function App({ takeInitialBootstrap }: {
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 type { channelUiPresentation } from "@/channel-plugins/registry";
import { channelUiPresentation } from "@/channel-plugins/registry";
import { Button } from "@/components/ui/button";
import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface";
import { useLogoFallback } from "@/hooks/useLogoFallback";
@@ -37,7 +37,6 @@ 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);
@@ -87,7 +86,7 @@ export function PairingCodePopup({
)}
>
<div className="flex items-start gap-3">
<PairingChannelBadge presentation={presentation} />
<PairingChannelBadge channel={displayRequest.channel} />
<div className="min-w-0 flex-1">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
@@ -139,7 +138,7 @@ export function PairingCodePopup({
{matchedRequest && busyCode === matchedRequest.code
? t("app.pairing.matched", {
defaultValue: "Matched {{channel}}. Connecting...",
channel: presentation.label,
channel: channelLabel(matchedRequest.channel),
})
: deliveryBlocked ? null : t("app.pairing.expiresInline", {
defaultValue: "Code expires {{expires}}.",
@@ -186,7 +185,8 @@ export function PairingCodePopup({
);
}
function PairingChannelBadge({ presentation }: { presentation: ReturnType<typeof usePairingChannelPresentation> }) {
function PairingChannelBadge({ channel }: { channel: string }) {
const presentation = pairingChannelPresentation(channel);
const initials = presentation.initials;
const color = presentation.color;
const brandLogoUrl = presentation.logoUrl;
@@ -321,20 +321,13 @@ function pairingChannelKey(channel: string): string {
return raw.split(/[.:]/)[0] ?? raw;
}
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));
function channelLabel(channel: string): string {
return pairingChannelPresentation(channel).label;
}
function pairingChannelPresentation(channel: string) {
const key = pairingChannelKey(channel);
const plugin = channelUiPresentation(key);
return {
label: plugin?.displayName ?? channel,
initials: plugin?.initials ?? channel.slice(0, 2).toUpperCase(),
@@ -1,7 +1,5 @@
import { lazy, Suspense, useCallback, useEffect, useId, useRef, useState } from "react";
import { LayoutGroup, useReducedMotion } from "motion/react";
import { div as MotionDiv } from "motion/react-m";
import { DeferredMotion } from "@/components/ui/deferred-motion";
import { LayoutGroup, motion, useReducedMotion } from "motion/react";
import { useTranslation } from "react-i18next";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { cn } from "@/lib/utils";
@@ -28,8 +26,9 @@ export function ContextInspector({ context, rounds, snapshots, onOpenFile, sideb
snapshots: readonly ContextSnapshot[]; onOpenFile?: (path: string) => void; sidebar?: boolean; expandable?: boolean; onClose?: () => void;
}) {
const { t, i18n } = useTranslation();
const layoutId = useId();
const panelId = useId();
const reducedMotion = useReducedMotion();
const layoutId = reducedMotion ? undefined : panelId;
const [expanded, setExpanded] = useState(false);
const [replay, setReplay] = useState<{ frames: readonly ContextSnapshot[]; index: number; startedAt: number; interval: number } | null>(null);
const [readyGraph, setReadyGraph] = useState<ContextGraph | null>(null);
@@ -63,7 +62,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) => <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")}>
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")}>
<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>
@@ -97,8 +96,8 @@ export function ContextInspector({ context, rounds, snapshots, onOpenFile, sideb
setReplay({ frames: [...snapshots], index: 0, startedAt: performance.now(), interval: 1000 / stepsPerSecond });
}} />
</div>
</MotionDiv>;
return <DeferredMotion><LayoutGroup>
</motion.div>;
return <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">
@@ -106,5 +105,5 @@ export function ContextInspector({ context, rounds, snapshots, onOpenFile, sideb
{content(true)}
</DialogContent>
</Dialog>
</LayoutGroup></DeferredMotion>;
</LayoutGroup>;
}
@@ -1,6 +1,5 @@
import { useLayoutEffect, useRef, useState, type ReactElement } from "react";
import { div as MotionDiv } from "motion/react-m";
import { DeferredMotion } from "@/components/ui/deferred-motion";
import { motion } from "motion/react";
import { useMediaQuery } from "@/hooks/useMediaQuery";
@@ -30,7 +29,6 @@ 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
@@ -38,7 +36,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 ? <DeferredMotion><MotionDiv
{canRoll ? <motion.div
key={frame.key}
initial={outgoing ? { y: "100%" } : false}
animate={{ y: 0 }}
@@ -48,8 +46,8 @@ export function LatestActivityWheel({ row, visible }: { row: ReactElement; visib
}}
>
{outgoing ? <div className={`absolute inset-x-0 bottom-full ${rowClass}`}>{outgoing}</div> : null}
{current}
</MotionDiv></DeferredMotion> : current}
<div className={rowClass}>{row}</div>
</motion.div> : <div className={rowClass}>{row}</div>}
</div>
);
}
@@ -1,8 +0,0 @@
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>;
}
@@ -1 +0,0 @@
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", "thread/ContextInspector", "ui/deferred-motion"], Preview: UsagePreview,
{ title: "previews.usage.title", files: ["thread/ComposerUsagePopover"], 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,7 +75,6 @@ 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
@@ -1,22 +0,0 @@
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;
};
}
+7 -11
View File
@@ -1,5 +1,8 @@
import ReactDOM from "react-dom/client";
import App from "./App";
import "./globals.css";
import { preloadInitialBootstrap } from "./lib/initial-bootstrap";
import { initializeI18n } from "./i18n";
import { initializePairReturn } from "./lib/remote-pair-return";
// `crypto.randomUUID` is only defined in secure contexts (HTTPS or localhost).
@@ -25,14 +28,6 @@ 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) => {
@@ -43,8 +38,9 @@ async function renderWebui(container: HTMLElement) {
link.rel = "stylesheet";
if (link.sheet) ready();
}));
const [{ mountWebui }] = await Promise.all([app, localeReady, ...styles]);
mountWebui(container, takeInitialBootstrap);
await Promise.all([initializeI18n(), ...styles]);
/* StrictMode disabled: dev double-invokes state updaters; delta accumulation must stay pure — see useNanobotStream. */
ReactDOM.createRoot(container).render(<App />);
}
void renderWebui(root);
-8
View File
@@ -1,8 +0,0 @@
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} />);
}
@@ -1,55 +0,0 @@
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();
}
});
+1 -3
View File
@@ -101,9 +101,7 @@ 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");
});
it("does not make the document's dynamic-import helper pull in React DOM", () => {
expect(webuiManualChunk("\0vite/preload-helper.js")).toBe("preload-helper");
expect(webuiManualChunk("\0vite/preload-helper.js")).toBe("react-vendor");
});
it("keeps markdown-only hast utilities in the markdown chunk", () => {
+4 -22
View File
@@ -47,27 +47,11 @@ function guardWebuiEntryChunk(): Plugin {
apply: "build",
generateBundle(_options, bundle) {
for (const output of Object.values(bundle)) {
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 (output.type !== "chunk" || !output.isEntry) continue;
const unexpected = entryLazyFeatureImports(output.imports);
if (unexpected.length > 0) {
throw new Error(
`${output.fileName} statically imports deferred WebUI features: ${unexpected.join(", ")}`,
`WebUI entry chunk statically imports lazy features: ${unexpected.join(", ")}`,
);
}
}
@@ -113,14 +97,12 @@ 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";
}