feat: launch first-time setup in webui (#5078)

This commit is contained in:
chengyongru
2026-07-24 21:16:43 +08:00
committed by GitHub
parent e260d9b31c
commit 6e0eb46705
5 changed files with 195 additions and 26 deletions
+11 -8
View File
@@ -17,12 +17,12 @@ Use the launcher:
nanobot webui
```
`nanobot webui` creates the config/workspace when needed, checks provider setup,
offers Quick Start when the model provider is not ready, enables the local
`nanobot webui` creates the config/workspace when needed, enables the local
WebSocket channel after confirmation, generates a WebUI bootstrap secret when
one is missing, starts the gateway, and opens the browser. The first-run path
binds the WebUI to `127.0.0.1` by default, so it is not available from other
devices on your LAN.
one is missing, starts the gateway, and opens the browser. With a fresh config,
it can open before a model is configured so you can finish setup in **Settings
→ Models**. The first-run path binds the WebUI to `127.0.0.1` by default, so
it is not available from other devices on your LAN.
Run it in the background when you do not want to keep a terminal open:
@@ -30,6 +30,9 @@ Run it in the background when you do not want to keep a terminal open:
nanobot webui --background
```
Complete first-time model setup in a foreground `nanobot webui` session before using
`--background`.
Manage the background gateway with `nanobot gateway status`, `nanobot gateway
logs`, `nanobot gateway restart`, and `nanobot gateway stop`.
@@ -55,10 +58,10 @@ gateway health endpoint, `18790` by default, is not the browser UI.
## First 10 Minutes
Use the WebUI as the primary setup surface after Quick Start:
Use the WebUI as the primary setup surface:
1. Send `Hello!` in a new topic to prove the selected model works.
2. Open **Settings → Models** and confirm the active model preset.
1. Open **Settings → Models** and configure a provider, credential, and active model preset.
2. Send `Hello!` in a new topic to prove the selected model works.
3. Start a separate topic before project work, then choose the intended workspace and access mode.
4. Add only one capability next: a chat channel in **Settings → Channels**, a web/voice/image provider in **Settings**, or an App/MCP integration in **Apps**.
5. Restart when the WebUI shows a restart requirement, then test that capability with the smallest possible request.
+44 -12
View File
@@ -920,11 +920,10 @@ def _load_webui_setup_config(config_path: Path) -> Config:
def _provider_setup_error(config: Config) -> str | None:
"""Return the provider setup error, or None when the current model can start."""
from nanobot.config.loader import resolve_config_env_vars
from nanobot.providers.factory import build_provider_snapshot
try:
build_provider_snapshot(resolve_config_env_vars(config.model_copy(deep=True)))
build_provider_snapshot(config)
except ValueError as exc:
return str(exc)
return None
@@ -1427,7 +1426,7 @@ def webui(
),
) -> None:
"""Prepare the local WebUI, start the gateway, and open the browser workbench."""
from nanobot.config.loader import save_config
from nanobot.config.loader import resolve_config_env_vars, save_config
from nanobot.gateway import GatewayRuntime, GatewayRuntimePaths, GatewayStartOptions
_ensure_interactive_tty_mode()
@@ -1441,8 +1440,24 @@ def webui(
if workspace:
setup_config.agents.defaults.workspace = workspace
provider_error = _provider_setup_error(setup_config)
if provider_error:
try:
resolved_setup_config = resolve_config_env_vars(setup_config.model_copy(deep=True))
except ValueError as exc:
console.print(f"[red]Error: {exc}[/red]")
raise typer.Exit(1) from exc
provider_error = _provider_setup_error(resolved_setup_config)
settings_setup_error = provider_error if provider_error and created_config else None
if settings_setup_error:
console.print(f"[yellow]Model setup is incomplete: {provider_error}[/yellow]")
console.print("Configure a provider and model in WebUI Settings → Models.")
if background:
console.print(
"[red]First-time WebUI setup must run in the foreground. "
"Run `nanobot webui` without --background.[/red]"
)
raise typer.Exit(1)
elif provider_error:
console.print(f"[dim]Provider check: {provider_error}[/dim]")
setup_config = _run_quick_start_for_webui(setup_config, yes=yes)
if workspace:
@@ -1585,6 +1600,7 @@ def webui(
port=effective_gateway_port,
open_browser_url=None if no_open else webui_url,
webui_bundle_mode=webui_bundle_mode,
unconfigured_provider_error=settings_setup_error,
)
@@ -1603,6 +1619,7 @@ def _run_gateway(
webui_runtime_surface: str = "browser",
webui_runtime_capabilities: dict[str, Any] | None = None,
health_server_enabled: bool = True,
unconfigured_provider_error: str | None = None,
) -> None:
"""Shared gateway runtime; ``open_browser_url`` opens a tab once channels are up."""
from nanobot.agent.model_presets import load_model_preset_catalog
@@ -1616,7 +1633,11 @@ def _run_gateway(
from nanobot.cron.service import CronJobSkippedError, CronService
from nanobot.cron.session_turns import is_bound_cron_job
from nanobot.cron.types import CronJob
from nanobot.providers.factory import build_provider_snapshot, load_provider_snapshot
from nanobot.providers.factory import (
build_provider_snapshot,
build_unconfigured_provider_snapshot,
load_provider_snapshot,
)
from nanobot.providers.fallback_provider import FallbackProvider
from nanobot.providers.image_generation import image_gen_provider_configs
from nanobot.session.manager import SessionManager
@@ -1664,13 +1685,24 @@ def _run_gateway(
return snapshot
def _load_gateway_provider_snapshot(*args: Any, **kwargs: Any):
return _observe_fallback_models(load_provider_snapshot(*args, **kwargs))
try:
return _observe_fallback_models(load_provider_snapshot(*args, **kwargs))
except ValueError as exc:
if unconfigured_provider_error is None:
raise
return build_unconfigured_provider_snapshot(config, str(exc))
try:
provider_snapshot = _observe_fallback_models(build_provider_snapshot(config))
except ValueError as exc:
console.print(f"[red]Error: {exc}[/red]")
raise typer.Exit(1) from exc
if unconfigured_provider_error is not None:
provider_snapshot = build_unconfigured_provider_snapshot(
config,
unconfigured_provider_error,
)
else:
try:
provider_snapshot = _observe_fallback_models(build_provider_snapshot(config))
except ValueError as exc:
console.print(f"[red]Error: {exc}[/red]")
raise typer.Exit(1) from exc
session_manager = SessionManager(config.workspace_path)
# Self-heal the gateway state file with the current PID after any restart.
+16
View File
@@ -212,6 +212,22 @@ def make_provider(
return provider
def build_unconfigured_provider_snapshot(config: Config, setup_error: str) -> ProviderSnapshot:
"""Build a non-networking runtime so the WebUI can collect first-time setup."""
from nanobot.providers.unconfigured_provider import UnconfiguredProvider
preset = config.resolve_preset()
provider = UnconfiguredProvider(preset.model)
provider.generation = preset.to_generation_settings()
return ProviderSnapshot(
provider=provider,
model=preset.model,
context_window_tokens=preset.context_window_tokens,
signature=("unconfigured", setup_error, preset.model),
generation=provider.generation,
)
def provider_signature(
config: Config,
*,
@@ -0,0 +1,36 @@
"""Provider used while the local WebUI is waiting for first-time setup."""
from __future__ import annotations
from nanobot.providers.base import LLMProvider, LLMResponse
class UnconfiguredProvider(LLMProvider):
"""Keep the gateway available for settings before a model is configured."""
def __init__(self, default_model: str) -> None:
super().__init__()
self._default_model = default_model
async def chat(
self,
messages: list[dict],
tools: list[dict] | None = None,
model: str | None = None,
max_tokens: int = 4096,
temperature: float = 0.7,
reasoning_effort: str | None = None,
tool_choice: str | dict | None = None,
) -> LLMResponse:
return LLMResponse(
content=(
"Nanobot needs a model before it can chat. Open Settings → Models "
"to configure a provider and model, then send your message again."
),
finish_reason="error",
error_kind="configuration",
error_should_retry=False,
)
def get_default_model(self) -> str:
return self._default_model
+88 -6
View File
@@ -25,6 +25,7 @@ from nanobot.cron.webui_metadata import cron_proactive_delivery_metadata
from nanobot.providers.factory import ProviderSnapshot, make_provider, provider_signature
from nanobot.providers.openai_codex_provider import _strip_model_prefix
from nanobot.providers.registry import find_by_name
from nanobot.providers.unconfigured_provider import UnconfiguredProvider
from nanobot.session.webui_turns import WebuiTurnRoutePolicy
from nanobot.webui.metadata import (
WEBUI_MESSAGE_SOURCE_METADATA_KEY,
@@ -2023,6 +2024,7 @@ def test_webui_yes_creates_config_and_enables_local_websocket(
"port": 18888,
"open_browser_url": None,
"webui_bundle_mode": "auto",
"unconfigured_provider_error": None,
}
compact_output = re.sub(r"\s+", " ", _strip_ansi(result.stdout))
assert "bootstrap secret was generated" in compact_output
@@ -2032,19 +2034,92 @@ def test_webui_yes_creates_config_and_enables_local_websocket(
assert "Press Ctrl+C here to stop nanobot" in compact_output
def test_webui_yes_refuses_missing_provider_setup(monkeypatch, tmp_path: Path) -> None:
def test_webui_yes_starts_first_run_without_provider_setup(monkeypatch, tmp_path: Path) -> None:
config_file = tmp_path / "config.json"
seen: dict[str, object] = {}
def _missing_provider(_config: Config, **_kwargs) -> ProviderSnapshot:
raise ValueError("No API key configured for provider 'custom'.")
monkeypatch.setattr(
"nanobot.cli.commands._provider_setup_error",
lambda _config: "No API key configured for provider 'custom'.",
)
_patch_gateway_ports_free(monkeypatch)
monkeypatch.setattr("nanobot.cli.commands.sync_workspace_templates", lambda _path: None)
monkeypatch.setattr(
"nanobot.cli.commands._run_gateway",
lambda config, **kwargs: seen.update(config=config, **kwargs),
)
monkeypatch.setattr("nanobot.providers.factory.build_provider_snapshot", _missing_provider)
result = runner.invoke(app, ["webui", "--config", str(config_file), "--yes", "--no-open"])
assert result.exit_code == 0
assert config_file.exists()
assert seen["unconfigured_provider_error"] == "No API key configured for provider 'custom'."
assert "Configure a provider and model in WebUI Settings → Models." in result.stdout
def test_webui_missing_runtime_env_fails_before_starting_gateway(
monkeypatch,
tmp_path: Path,
) -> None:
config_file = tmp_path / "config.json"
missing_env = "NANOBOT_TEST_MISSING_WEBUI_SECRET"
monkeypatch.delenv(missing_env, raising=False)
config_file.write_text(
json.dumps({
"agents": {
"defaults": {
"provider": "ollama",
"model": "ollama/qwen3",
}
},
"channels": {
"websocket": {
"enabled": True,
"host": "0.0.0.0",
"tokenIssueSecret": f"${{{missing_env}}}",
}
},
}),
encoding="utf-8",
)
monkeypatch.setattr(
"nanobot.cli.commands._run_gateway",
lambda *_args, **_kwargs: pytest.fail("gateway must not start with unresolved config"),
)
result = runner.invoke(app, ["webui", "--config", str(config_file), "--yes", "--no-open"])
assert result.exit_code == 1
assert missing_env in result.stdout
assert f"${{{missing_env}}}" in config_file.read_text(encoding="utf-8")
def test_webui_yes_still_refuses_invalid_custom_model_setup(
monkeypatch,
tmp_path: Path,
) -> None:
config_file = tmp_path / "config.json"
config_file.write_text(
json.dumps({
"agents": {
"defaults": {
"provider": "custom",
"model": "custom/test-model",
}
},
"providers": {
"custom": {
"displayName": "Custom",
}
},
}),
encoding="utf-8",
)
result = runner.invoke(app, ["webui", "--config", str(config_file), "--yes"])
assert result.exit_code == 1
assert "provider/model setup is incomplete" in result.stdout
assert not config_file.exists()
def test_webui_background_starts_runtime_and_opens_browser(monkeypatch, tmp_path: Path) -> None:
@@ -2775,9 +2850,11 @@ def test_gateway_bound_cron_runs_as_session_turn(
assert msg.metadata["thread_id"] == "om_root123"
@pytest.mark.parametrize("setup_error", [None, "No API key configured"])
def test_gateway_local_trigger_queue_submits_agent_turns(
monkeypatch,
tmp_path: Path,
setup_error: str | None,
) -> None:
config = Config()
config.agents.defaults.workspace = str(tmp_path / "config-workspace")
@@ -2885,11 +2962,16 @@ def test_gateway_local_trigger_queue_submits_agent_turns(
_fake_run_local_trigger_queue,
)
cli_commands._run_gateway(config, health_server_enabled=False)
cli_commands._run_gateway(
config,
health_server_enabled=False,
unconfigured_provider_error=setup_error,
)
agent = seen["agent"]
agent_kwargs = seen["agent_from_config_kwargs"]
kwargs = seen["local_trigger_queue_kwargs"]
assert isinstance(agent_kwargs["provider"], UnconfiguredProvider) is bool(setup_error)
assert "local_trigger_store" in agent_kwargs
assert kwargs["store"] is agent_kwargs["local_trigger_store"]
assert "bus" not in kwargs