perf(webui): batch startup recovery and authenticate before React (#6708)
This commit is contained in:
1 parent
9652302324
commit
273582916b
26 files changed
+537
-330
No files matched your search
@@ -152,17 +152,13 @@ class SubagentSessions:
|
||||
|
||||
async def interrupt_pending(self) -> None:
|
||||
"""Seal abandoned work after the gateway acquires execution ownership."""
|
||||
for row in self.sessions.list_sessions():
|
||||
key = row["key"]
|
||||
payload = self.sessions.read_session_metadata(key)
|
||||
metadata = (payload or {}).get("metadata", {})
|
||||
if metadata.get(SESSION_TYPE_KEY) != SUBAGENT.name:
|
||||
continue
|
||||
for key, metadata in await self.sessions.state.typed_session_headers(SUBAGENT.name):
|
||||
task_id = key.removeprefix("subagent:")
|
||||
owner = metadata.get(PARENT_SESSION_KEY)
|
||||
if not isinstance(owner, str):
|
||||
if key != self.key(task_id) or not isinstance(owner, str):
|
||||
continue
|
||||
try:
|
||||
status = self.status(key.removeprefix("subagent:"), owner)
|
||||
status = self._status_from_metadata(task_id, owner, metadata)
|
||||
if status is None or status.state not in _ACTIVE_STATES:
|
||||
continue
|
||||
status.state = status.phase = "interrupted"
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
"""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"
|
||||
)
|
||||
@@ -2,7 +2,6 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import errno
|
||||
import ipaddress
|
||||
import json
|
||||
import socket
|
||||
import ssl
|
||||
@@ -11,11 +10,9 @@ from collections.abc import Sequence
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Self, TypeGuard, cast
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
from typing import Any, TypeGuard, cast
|
||||
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
|
||||
@@ -26,7 +23,8 @@ 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.config_base import Base
|
||||
from nanobot.channels.websocket.config import TrustedProxyAuthConfig as TrustedProxyAuthConfig
|
||||
from nanobot.channels.websocket.config import WebSocketConfig as WebSocketConfig
|
||||
from nanobot.runtime_admission import RuntimeMaintenanceError
|
||||
from nanobot.webui.gateway_services import GatewayServices
|
||||
from nanobot.webui.http_utils import (
|
||||
@@ -85,194 +83,6 @@ _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:
|
||||
|
||||
@@ -35,7 +35,6 @@ 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
|
||||
@@ -352,7 +351,6 @@ 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,
|
||||
|
||||
@@ -48,7 +48,7 @@ def create_gateway_app(
|
||||
console: Console,
|
||||
log_handler_id: int,
|
||||
load_runtime_config: RuntimeConfigLoader,
|
||||
run_gateway: GatewayRunner,
|
||||
run_gateway: GatewayRunner | None = None,
|
||||
validate_startup_config: GatewayConfigValidator | None = None,
|
||||
runtime_factory: GatewayRuntimeFactory | None = None,
|
||||
service_factory: GatewayServiceFactory | None = None,
|
||||
@@ -234,8 +234,15 @@ 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:
|
||||
run_gateway(
|
||||
runner(
|
||||
cfg,
|
||||
port=port,
|
||||
verbose=verbose,
|
||||
|
||||
@@ -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.runtime import WebSocketConfig
|
||||
from nanobot.channels.websocket.config 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.runtime import WebSocketConfig
|
||||
from nanobot.channels.websocket.config import WebSocketConfig
|
||||
|
||||
current: Any = getattr(config.channels, "websocket", None) or {}
|
||||
return bool(WebSocketConfig.model_validate(current).enabled)
|
||||
|
||||
@@ -135,6 +135,23 @@ class HistoryReader:
|
||||
(self.key, ordinal),
|
||||
)]
|
||||
|
||||
def open_tail_sequences(self) -> dict[str, int]:
|
||||
"""Last sequence for each identity in an unclosed tail, in first-appearance order."""
|
||||
ordinal = self.turn_count - 1
|
||||
last = self._db.execute(
|
||||
"""SELECT kind FROM history_entries WHERE session_key=? AND turn_ordinal=?
|
||||
ORDER BY position DESC LIMIT 1""", (self.key, ordinal),
|
||||
).fetchone()
|
||||
if last is None or last[0] == HistoryKind.COMPLETION:
|
||||
# Do not append over a terminal transcript_incomplete marker.
|
||||
return {}
|
||||
return {turn_id: sequence for turn_id, sequence in self._db.execute(
|
||||
"""SELECT json_extract(record, '$.turn_id') AS turn_id,
|
||||
max(coalesce(json_extract(record, '$.sequence'), 0))
|
||||
FROM history_entries WHERE session_key=? AND turn_ordinal=?
|
||||
GROUP BY turn_id ORDER BY min(position)""", (self.key, ordinal),
|
||||
) if turn_id}
|
||||
|
||||
def read_entry_page(
|
||||
self, ordinal: int, *, start: int, end: int, reverse: bool,
|
||||
max_records: int, max_bytes: int, allow_oversized: bool = False,
|
||||
|
||||
@@ -514,6 +514,45 @@ class SqliteSessionStore:
|
||||
return {"key": key, "created_at": row[0], "updated_at": row[1],
|
||||
"metadata": self._metadata(db, key, row[2])}
|
||||
|
||||
def recovery_candidates(self, key_prefix: str) -> list[tuple[str, bool]]:
|
||||
"""Return (key, unfinished display tail) in the same order as list_sessions.
|
||||
|
||||
The turn and entry primary keys locate the last ordinal and its last
|
||||
decisive fact. Fork/telemetry facts do not settle activity. As in the
|
||||
transcript reader, an incomplete marker *anywhere in that ordinal*
|
||||
takes precedence, including on imported records. The append cursor's
|
||||
`completed` flag alone cannot answer either question.
|
||||
"""
|
||||
with self.transaction(write=False) as db:
|
||||
rows = db.execute("""
|
||||
WITH scan AS (
|
||||
SELECT s.key, s.updated_at, s.rowid AS tie,
|
||||
json_type(s.metadata, '$.pending_user_turn')='true'
|
||||
OR (json_extract(s.metadata, '$.webui_recovery.status')
|
||||
IN ('resuming', 'awaiting_user', 'failed')
|
||||
AND json_type(s.metadata, '$.webui_recovery.recovery_id')='text')
|
||||
OR EXISTS (SELECT 1 FROM checkpoints WHERE session_key=s.key)
|
||||
OR EXISTS (SELECT 1 FROM pending_inputs WHERE session_key=s.key
|
||||
AND kind='pending_user_followups') AS journaled,
|
||||
(SELECT CASE WHEN
|
||||
(SELECT e.kind NOT IN ('input', 'answer', 'completion')
|
||||
FROM history_entries e WHERE e.session_key=t.session_key
|
||||
AND e.turn_ordinal=t.ordinal
|
||||
AND e.kind NOT IN ('fork_boundary', 'compaction', 'model_request')
|
||||
ORDER BY e.position DESC LIMIT 1)
|
||||
THEN 1 ELSE EXISTS (
|
||||
SELECT 1 FROM history_entries e WHERE e.session_key=t.session_key
|
||||
AND e.turn_ordinal=t.ordinal
|
||||
AND json_type(e.record, '$.content.transcript_incomplete')='true'
|
||||
) END
|
||||
FROM history_turns t WHERE t.session_key=s.key
|
||||
ORDER BY t.ordinal DESC LIMIT 1) AS unfinished
|
||||
FROM sessions s WHERE s.key GLOB ?
|
||||
)
|
||||
SELECT key, unfinished FROM scan WHERE journaled OR unfinished ORDER BY updated_at DESC, tie
|
||||
""", (f"{key_prefix}*",))
|
||||
return [(key, bool(unfinished)) for key, unfinished in rows]
|
||||
|
||||
def read_history_header(self, key: str) -> SessionHistoryPayload | None:
|
||||
"""Read search identity and metadata without runtime checkpoints or inputs."""
|
||||
with self.transaction(write=False) as db:
|
||||
@@ -756,6 +795,14 @@ class SqliteSessionStore:
|
||||
(parent_key,),
|
||||
)]
|
||||
|
||||
def typed_session_headers(self, session_type: str) -> list[tuple[str, dict[str, Any]]]:
|
||||
"""Read just this owner's metadata, without rehydrating messages, checkpoints or inputs."""
|
||||
with self.transaction(write=False) as db:
|
||||
return [(key, _object(metadata)) for key, metadata in db.execute(
|
||||
f"""SELECT key, metadata FROM sessions WHERE json_extract(metadata, '$.{SESSION_TYPE_KEY}')=?
|
||||
ORDER BY updated_at DESC, rowid""", (session_type,),
|
||||
)]
|
||||
|
||||
def list_child_session_metadata(self, parent_key: str) -> list[SessionMetadataPayload]:
|
||||
"""Read child headers from one snapshot, excluding checkpoints and pending inputs."""
|
||||
with self.transaction(write=False) as db:
|
||||
|
||||
@@ -872,6 +872,19 @@ class SessionState:
|
||||
None, lambda: self._store.set_archived_keys(values), operation_name="set_archived_keys",
|
||||
)
|
||||
|
||||
async def typed_session_headers(self, session_type: str) -> list[tuple[str, dict[str, Any]]]:
|
||||
return await self._execute(
|
||||
None, lambda: self._store.typed_session_headers(session_type),
|
||||
operation_name="typed_session_headers", write=False,
|
||||
)
|
||||
|
||||
async def recovery_candidates(self, key_prefix: str) -> list[tuple[str, bool]]:
|
||||
"""Take one ordered read snapshot before startup admits new work."""
|
||||
return await self._execute(
|
||||
None, lambda: self._store.recovery_candidates(key_prefix),
|
||||
operation_name="recovery_candidates", write=False,
|
||||
)
|
||||
|
||||
async def list_sessions(self) -> list[dict[str, Any]]:
|
||||
return await self._execute(
|
||||
None,
|
||||
|
||||
+12
-43
@@ -21,7 +21,6 @@ from nanobot.session.display_history import HistoryFact, HistoryKind, HistoryRea
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
from nanobot.session.recovery import (
|
||||
KNOWN_CHECKPOINT_PHASES,
|
||||
PENDING_FOLLOWUPS_KEY,
|
||||
PENDING_USER_TURN_KEY,
|
||||
RECOVERY_INBOUND_METADATA_KEY,
|
||||
RECOVERY_METADATA_KEY,
|
||||
@@ -38,7 +37,11 @@ from nanobot.session.recovery import (
|
||||
runtime_checkpoint_is_well_formed,
|
||||
)
|
||||
from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY
|
||||
from nanobot.webui.session_identity import webui_chat_id, webui_session_key
|
||||
from nanobot.webui.session_identity import (
|
||||
WEBUI_SESSION_STORAGE_PREFIX,
|
||||
webui_chat_id,
|
||||
webui_session_key,
|
||||
)
|
||||
|
||||
|
||||
class RecoveryActionError(ValueError):
|
||||
@@ -85,20 +88,15 @@ class RecoveryCoordinator:
|
||||
from nanobot.webui.history import initialize_history
|
||||
|
||||
await initialize_history(self.sessions)
|
||||
for item in await self.sessions.state.list_sessions():
|
||||
key = item["key"]
|
||||
for key, unfinished in await self.sessions.state.recovery_candidates(WEBUI_SESSION_STORAGE_PREFIX):
|
||||
chat_id = webui_chat_id(key)
|
||||
if chat_id is None:
|
||||
continue
|
||||
metadata_payload = await self.sessions.state.read_metadata(key)
|
||||
raw_metadata = metadata_payload.get("metadata") if metadata_payload else None
|
||||
metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}
|
||||
unfinished = await self._has_unfinished_webui_transcript(key)
|
||||
if not self._needs_recovery(metadata) and not unfinished:
|
||||
session = await self.sessions.state.read(key)
|
||||
if session is None:
|
||||
continue
|
||||
session = await self.sessions.state.get(key)
|
||||
try:
|
||||
await self._recover_session(session, chat_id)
|
||||
await self._recover_session(session, chat_id, unfinished=unfinished)
|
||||
await self._close_interrupted_turns(session)
|
||||
await self._requeue_pending_followups(session)
|
||||
except Exception:
|
||||
@@ -115,18 +113,6 @@ class RecoveryCoordinator:
|
||||
await self.sessions.state.restore_interruption(session)
|
||||
await self._publish(chat_id, failed)
|
||||
|
||||
@staticmethod
|
||||
def _needs_recovery(metadata: Mapping[str, Any]) -> bool:
|
||||
if metadata.get(PENDING_USER_TURN_KEY) is True:
|
||||
return True
|
||||
if isinstance(metadata.get(RUNTIME_CHECKPOINT_KEY), dict):
|
||||
return True
|
||||
followups = metadata.get(PENDING_FOLLOWUPS_KEY)
|
||||
if isinstance(followups, list) and len(cast(list[object], followups)) > 0:
|
||||
return True
|
||||
state = recovery_state_from_metadata(metadata)
|
||||
return bool(state and state["status"] in {"resuming", "awaiting_user", "failed"})
|
||||
|
||||
async def admit(self, message: InboundMessage) -> bool:
|
||||
"""Reject stale queued recoveries and let new user input supersede them."""
|
||||
recovery_id = message.metadata.get(RECOVERY_INBOUND_METADATA_KEY)
|
||||
@@ -254,7 +240,7 @@ class RecoveryCoordinator:
|
||||
await self._queue_continuation(session, chat_id, next_state)
|
||||
return next_state
|
||||
|
||||
async def _recover_session(self, session: Session, chat_id: str) -> None:
|
||||
async def _recover_session(self, session: Session, chat_id: str, *, unfinished: bool) -> None:
|
||||
checkpoint_value = cast(object, session.metadata.get(RUNTIME_CHECKPOINT_KEY))
|
||||
checkpoint = (
|
||||
cast(dict[str, Any], checkpoint_value)
|
||||
@@ -284,7 +270,7 @@ class RecoveryCoordinator:
|
||||
)
|
||||
await self.sessions.state.restore_interruption(session)
|
||||
await self._publish(chat_id, next_state)
|
||||
elif await self._has_unfinished_webui_transcript(session.key):
|
||||
elif unfinished:
|
||||
# A normal last-client shutdown can materialize the checkpoint
|
||||
# before the process exits. In that path there is no pending
|
||||
# marker left to classify, but the append-only transcript still
|
||||
@@ -431,20 +417,10 @@ class RecoveryCoordinator:
|
||||
queued_turns = {message.metadata.get(WEBUI_TURN_METADATA_KEY) for message in pending_followups(session)}
|
||||
|
||||
def completions(history: HistoryReader) -> list[HistoryFact]:
|
||||
if not history.turn_count:
|
||||
return []
|
||||
tail = history.read_entries(history.turn_count - 1)
|
||||
if not tail or tail[-1][1].kind is HistoryKind.COMPLETION:
|
||||
# In particular, don't bypass a transcript_incomplete marker.
|
||||
return []
|
||||
sequences: dict[str, int] = {}
|
||||
for _, fact in tail:
|
||||
if fact.turn_id and fact.turn_id not in queued_turns:
|
||||
sequences[fact.turn_id] = max(sequences.get(fact.turn_id, 0), fact.sequence or 0)
|
||||
return [HistoryFact(
|
||||
HistoryKind.COMPLETION, {"outcome": "interrupted"}, turn_id=turn_id,
|
||||
phase="complete", sequence=sequence + 1, created_at_ms=int(datetime.now().timestamp() * 1000),
|
||||
) for turn_id, sequence in sequences.items()]
|
||||
) for turn_id, sequence in history.open_tail_sequences().items() if turn_id not in queued_turns]
|
||||
|
||||
facts = await self.sessions.state.project_history(session.key, completions)
|
||||
if facts:
|
||||
@@ -517,13 +493,6 @@ class RecoveryCoordinator:
|
||||
session.updated_at = datetime.now()
|
||||
return state
|
||||
|
||||
async def _has_unfinished_webui_transcript(self, session_key: str) -> bool:
|
||||
from nanobot.webui.transcript import has_unfinished_transcript_tail
|
||||
|
||||
return await self.sessions.state.project_history(
|
||||
session_key, lambda history: has_unfinished_transcript_tail(session_key, history=history),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _has_saved_continuation_context(session: Session) -> bool:
|
||||
"""Whether an interrupted turn left model-visible context to continue from."""
|
||||
|
||||
@@ -144,6 +144,7 @@ class _EmptyGatewaySessionManager:
|
||||
def state(self):
|
||||
return SimpleNamespace(
|
||||
list_sessions=AsyncMock(return_value=[]),
|
||||
recovery_candidates=AsyncMock(return_value=[]),
|
||||
migrate_history=AsyncMock(),
|
||||
record_delivery=AsyncMock(),
|
||||
aclose=AsyncMock(),
|
||||
@@ -3642,8 +3643,10 @@ 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:
|
||||
cli_commands._run_gateway(
|
||||
_run_gateway(
|
||||
config,
|
||||
health_server_enabled=False,
|
||||
unconfigured_provider_error=setup_error,
|
||||
|
||||
@@ -101,10 +101,7 @@ async def test_stale_incomplete_transcript_waits_for_confirmation(tmp_path: Path
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_materialized_interruption_can_continue_from_saved_context(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
async def test_materialized_interruption_can_continue_from_saved_context(tmp_path: Path) -> None:
|
||||
sessions = SessionManager(tmp_path)
|
||||
session = sessions.get_or_create("websocket:chat")
|
||||
session.messages.extend(
|
||||
@@ -115,10 +112,12 @@ async def test_materialized_interruption_can_continue_from_saved_context(
|
||||
]
|
||||
)
|
||||
_persist(sessions, session)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.transcript.has_unfinished_transcript_tail",
|
||||
lambda _key, **_kwargs: True,
|
||||
)
|
||||
# A model request after a saved tool result is not a terminal reply. On
|
||||
# restart the last decisive display fact is still the earlier tool activity.
|
||||
sessions.append_history(session.key, [
|
||||
HistoryFact(HistoryKind.TOOL_ACTIVITY, {"text": "search"}, turn_id="work", sequence=3),
|
||||
HistoryFact(HistoryKind.MODEL_REQUEST, {"request_id": "next"}, turn_id="work", sequence=4),
|
||||
])
|
||||
|
||||
coordinator, bus, restarted = _coordinator(tmp_path)
|
||||
await coordinator.scan()
|
||||
@@ -127,6 +126,8 @@ async def test_materialized_interruption_can_continue_from_saved_context(
|
||||
assert state["status"] == "awaiting_user"
|
||||
assert state["reason"] == "interrupted_with_saved_context"
|
||||
assert "can_continue" not in state
|
||||
last = await restarted.state.project_history(session.key, lambda history: history.all_facts()[-1])
|
||||
assert (last.kind, last.turn_id, last.sequence) == (HistoryKind.COMPLETION, "work", 5)
|
||||
event = bus.outbound.get_nowait().event
|
||||
assert isinstance(event, RecoveryStateEvent)
|
||||
assert event.can_continue is None
|
||||
@@ -141,9 +142,16 @@ async def test_materialized_interruption_can_continue_from_saved_context(
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("tail", [
|
||||
'{"event":"message","chat_id":"unfinished","kind":"progress","text":"Working"}\n',
|
||||
# The legacy importer retains incomplete markers on nonterminal facts too.
|
||||
'{"event":"stream_end","chat_id":"unfinished","text":"partial","transcript_incomplete":true}\n'
|
||||
'{"event":"turn_end","chat_id":"unfinished"}\n',
|
||||
], ids=["open-activity", "earlier-incomplete-marker"])
|
||||
async def test_transcript_only_interruption_is_discovered_without_materializing_completed_history(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
tail: str,
|
||||
) -> None:
|
||||
webui_dir = tmp_path / "webui"
|
||||
webui_dir.mkdir()
|
||||
@@ -151,8 +159,7 @@ async def test_transcript_only_interruption_is_discovered_without_materializing_
|
||||
unfinished_key = "websocket:unfinished"
|
||||
completed_key = "websocket:completed"
|
||||
(webui_dir / f"{SessionManager.safe_key(unfinished_key)}.jsonl").write_text(
|
||||
'{"event":"user","chat_id":"unfinished","text":"keep going"}\n'
|
||||
'{"event":"message","chat_id":"unfinished","kind":"progress","text":"Working"}\n',
|
||||
'{"event":"user","chat_id":"unfinished","text":"keep going"}\n' + tail,
|
||||
encoding="utf-8",
|
||||
)
|
||||
(webui_dir / f"{SessionManager.safe_key(completed_key)}.jsonl").write_text(
|
||||
@@ -197,27 +204,40 @@ async def test_scan_loads_only_sessions_that_need_webui_recovery(
|
||||
if key == "discord:pending":
|
||||
session.metadata[PENDING_USER_TURN_KEY] = True
|
||||
_persist(sessions, session)
|
||||
sessions.append_history("websocket:idle", [
|
||||
HistoryFact(HistoryKind.FILE_ACTIVITY, {"edits": [{"diff": "-old\n+new\n" * 4096}]}, turn_id="settled"),
|
||||
HistoryFact(HistoryKind.ANSWER, turn_id="settled"), HistoryFact(HistoryKind.FORK_BOUNDARY),
|
||||
])
|
||||
pending = sessions.get_or_create("websocket:pending")
|
||||
pending.metadata[PENDING_USER_TURN_KEY] = True
|
||||
_persist(sessions, pending)
|
||||
# Identical timestamps from an import must retain list_sessions' order,
|
||||
# even when the two candidates are found via different kinds of evidence.
|
||||
active = Session(key="websocket:activity", updated_at=pending.updated_at)
|
||||
sessions.save(active)
|
||||
sessions.append_history(active.key, [HistoryFact(HistoryKind.REASONING)])
|
||||
|
||||
coordinator, _, restarted = _coordinator(tmp_path)
|
||||
loaded: list[str] = []
|
||||
get_or_create = restarted.state.get
|
||||
read = restarted.state.read
|
||||
|
||||
async def tracked_get_or_create(key: str) -> Session:
|
||||
async def tracked_read(key: str) -> Session | None:
|
||||
loaded.append(key)
|
||||
return await get_or_create(key)
|
||||
return await read(key)
|
||||
|
||||
monkeypatch.setattr(restarted.state, "get", tracked_get_or_create)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.transcript.has_unfinished_transcript_tail",
|
||||
lambda _key, **_kwargs: False,
|
||||
)
|
||||
decode = HistoryFact.decode
|
||||
|
||||
def decode_fact(record: str) -> HistoryFact:
|
||||
fact = decode(record)
|
||||
assert fact.turn_id != "settled", "startup must not materialize settled transcript bodies"
|
||||
return fact
|
||||
|
||||
monkeypatch.setattr(restarted.state, "read", tracked_read)
|
||||
monkeypatch.setattr(HistoryFact, "decode", staticmethod(decode_fact))
|
||||
|
||||
await coordinator.scan()
|
||||
|
||||
assert loaded == ["websocket:pending"]
|
||||
assert loaded == [pending.key, active.key]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -622,11 +642,13 @@ async def test_empty_final_response_is_not_reported_as_restored(tmp_path: Path)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_final_answer_is_restored_without_model_call(tmp_path: Path) -> None:
|
||||
@pytest.mark.parametrize("pending", [True, False])
|
||||
async def test_final_answer_is_restored_without_model_call(tmp_path: Path, pending: bool) -> None:
|
||||
sessions = SessionManager(tmp_path)
|
||||
session = sessions.get_or_create("websocket:chat")
|
||||
session.messages.append({"role": "user", "content": "answer"})
|
||||
session.metadata[PENDING_USER_TURN_KEY] = True
|
||||
if pending:
|
||||
session.metadata[PENDING_USER_TURN_KEY] = True
|
||||
session.metadata[RUNTIME_CHECKPOINT_KEY] = {
|
||||
"phase": "final_response",
|
||||
"assistant_message": {"role": "assistant", "content": "already finished"},
|
||||
@@ -895,11 +917,11 @@ async def test_scan_failure_is_visible_instead_of_aborting_other_sessions(
|
||||
recover_session = RecoveryCoordinator._recover_session
|
||||
attempted = []
|
||||
|
||||
async def fail_first(self, session: Session, chat_id: str) -> None:
|
||||
async def fail_first(self, session: Session, chat_id: str, *, unfinished: bool) -> None:
|
||||
attempted.append((session.key, chat_id))
|
||||
if len(attempted) == 1:
|
||||
raise RuntimeError("boom")
|
||||
await recover_session(self, session, chat_id)
|
||||
await recover_session(self, session, chat_id, unfinished=unfinished)
|
||||
|
||||
monkeypatch.setattr(RecoveryCoordinator, "_recover_session", fail_first)
|
||||
try:
|
||||
|
||||
+18
-22
@@ -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";
|
||||
@@ -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,
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
@@ -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
@@ -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";
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user