fix(webui): support WSL browser launch and clearer startup output (#6150)
* feat(webui): add local first-run access setup * feat(webui): defer password setup until network access Keep generated local credentials and provide the full browser login link in every launch mode. Require a chosen password when enabling network access, preserve existing authentication, and show pending listener changes until restart. Remove mandatory first-run initialization gates and simplify startup output while retaining gateway warnings and errors. * fix(webui): align access settings with channel contracts * fix(webui): clarify startup guidance and spacing * fix(webui): keep setup guidance readable in narrow terminals * fix(webui): clarify startup and preserve remote password access * fix(webui): move access explanations into settings hints * fix(webui): require strong ASCII passwords and reject malformed auth * fix(webui): simplify access password character rules * test(webui): reflect pending restart after password save * fix(webui): open Windows browser from WSL * fix(webui): clarify public access copy * refactor(webui): focus on WSL launch and startup output * fix(webui): preserve platform browser fallback
This commit is contained in:
1 parent
a27f294f52
commit
41f2eeb7ba
12 files changed
+693
-374
No files matched your search
+58
-139
@@ -8,7 +8,6 @@ from rich.console import Console
|
||||
|
||||
from nanobot.cli import terminal as cli_terminal
|
||||
from nanobot.cli.runtime_config import (
|
||||
_load_runtime_config,
|
||||
_print_config_error,
|
||||
_print_runtime_config_validation_error,
|
||||
_provider_setup_error,
|
||||
@@ -18,22 +17,20 @@ from nanobot.cli.webui_support import (
|
||||
_attach_to_background_gateway,
|
||||
_confirm_webui_action,
|
||||
_ensure_local_webui_channel,
|
||||
_gateway_health_bind_note,
|
||||
_gateway_health_ready,
|
||||
_gateway_health_url,
|
||||
_gateway_instance_command,
|
||||
_host_for_local_browser,
|
||||
_load_webui_setup_config,
|
||||
_open_webui_browser,
|
||||
_prepare_webui_bundle_for_gateway,
|
||||
_print_foreground_port_conflict,
|
||||
_print_webui_manual_access,
|
||||
_print_webui_ready,
|
||||
_resolve_webui_config_path,
|
||||
_start_gateway_log_cursor,
|
||||
_tcp_endpoint_reachable,
|
||||
_wait_for_webui,
|
||||
_warn_webui_bind_scope,
|
||||
_webui_browser_url,
|
||||
_webui_build_mode_for_interactive,
|
||||
_webui_display_url,
|
||||
_webui_endpoint_reachable,
|
||||
)
|
||||
from nanobot.config.paths import get_workspace_path
|
||||
@@ -57,10 +54,6 @@ def _wait_with_existing_foreground_gateway(
|
||||
"""Keep a Vite sidecar alive without taking ownership of an external gateway."""
|
||||
import time
|
||||
|
||||
console.print(
|
||||
"[dim]Vite is attached to the existing foreground gateway. "
|
||||
"Press Ctrl+C to stop Vite; the gateway will keep running.[/dim]"
|
||||
)
|
||||
try:
|
||||
while True:
|
||||
dev_server.ensure_running()
|
||||
@@ -127,8 +120,7 @@ def webui(
|
||||
raise typer.Exit(1)
|
||||
created_config = not config_path.exists()
|
||||
if created_config:
|
||||
console.print(f"[yellow]No config found at {config_path}.[/yellow]")
|
||||
_confirm_webui_action("Create a nanobot config and workspace now?", yes=yes)
|
||||
_confirm_webui_action("Set up nanobot and open WebUI on this device?", yes=yes)
|
||||
|
||||
setup_config = _load_webui_setup_config(config_path)
|
||||
if workspace:
|
||||
@@ -145,18 +137,18 @@ def webui(
|
||||
|
||||
_validate_session_storage(resolved_setup_config, workspace_override=workspace)
|
||||
provider_error = _provider_setup_error(resolved_setup_config)
|
||||
if provider_error:
|
||||
console.print(f"[yellow]Model setup is incomplete: {provider_error}[/yellow]")
|
||||
console.print("Configure a provider and model in WebUI Settings → Models.")
|
||||
|
||||
try:
|
||||
changed_webui = _ensure_local_webui_channel(
|
||||
setup_config,
|
||||
port=port,
|
||||
yes=yes,
|
||||
yes=yes or created_config,
|
||||
)
|
||||
_warn_webui_bind_scope(setup_config)
|
||||
webui_url = _webui_browser_url(setup_config)
|
||||
resolved_webui_config = resolve_config_env_vars(
|
||||
setup_config.model_copy(deep=True), config_path=config_path,
|
||||
)
|
||||
_warn_webui_bind_scope(resolved_webui_config)
|
||||
webui_url = _webui_browser_url(resolved_webui_config)
|
||||
except ValidationError as exc:
|
||||
retry_command = f'nanobot webui --config "{config_path}"'
|
||||
_print_runtime_config_validation_error(
|
||||
@@ -173,35 +165,15 @@ def webui(
|
||||
|
||||
if created_config or provider_error or changed_webui or workspace:
|
||||
save_config(setup_config, config_path)
|
||||
console.print(f"[green]✓[/green] Saved config: {config_path}")
|
||||
|
||||
workspace_path = get_workspace_path(setup_config.workspace_path)
|
||||
workspace_path.mkdir(parents=True, exist_ok=True)
|
||||
sync_workspace_templates(workspace_path)
|
||||
sync_workspace_templates(workspace_path, silent=True)
|
||||
|
||||
runtime_config = _load_runtime_config(str(config_path), workspace)
|
||||
runtime_config = resolved_webui_config
|
||||
effective_gateway_port = gateway_port if gateway_port is not None else runtime_config.gateway.port
|
||||
|
||||
dev_browser_url = webui_dev_browser_url(webui_url) if dev else None
|
||||
console.print()
|
||||
if dev_browser_url:
|
||||
console.print(f"WebUI dev: [cyan]{_webui_display_url(dev_browser_url)}[/cyan]")
|
||||
console.print(f"WebUI gateway: [cyan]{_webui_display_url(webui_url)}[/cyan]")
|
||||
else:
|
||||
console.print(f"WebUI: [cyan]{_webui_display_url(webui_url)}[/cyan]")
|
||||
gateway_health_url = _gateway_health_url(
|
||||
runtime_config.gateway.host,
|
||||
effective_gateway_port,
|
||||
)
|
||||
console.print(
|
||||
f"Gateway health: [cyan]{gateway_health_url}[/cyan]"
|
||||
f"{_gateway_health_bind_note(runtime_config.gateway.host)}"
|
||||
)
|
||||
if no_open:
|
||||
console.print("[dim]Browser opening disabled by --no-open.[/dim]")
|
||||
if not dev:
|
||||
_print_webui_manual_access(runtime_config, config_path, webui_url)
|
||||
|
||||
if not dev:
|
||||
webui_bundle_mode = _webui_build_mode_for_interactive(yes=yes)
|
||||
_prepare_webui_bundle_for_gateway(runtime_config, mode=webui_bundle_mode)
|
||||
@@ -211,92 +183,77 @@ def webui(
|
||||
workspace=workspace,
|
||||
)
|
||||
runtime = GatewayRuntime(paths=instance.paths)
|
||||
log_cursor = _start_gateway_log_cursor(runtime.paths.log_path)
|
||||
start_options = instance.start_options(port=effective_gateway_port)
|
||||
|
||||
def ensure_shared_gateway(*, client_lease: GatewayClientLease) -> None:
|
||||
"""Start or refresh the one managed gateway shared by local clients."""
|
||||
result = client_lease.ensure_on_demand_gateway(start_options)
|
||||
restarted = False
|
||||
restart_attempted = False
|
||||
if not result.ok and result.message == "gateway_already_running" and changed_webui:
|
||||
restart_attempted = True
|
||||
console.print("[yellow]WebUI config changed; restarting the background gateway.[/yellow]")
|
||||
result = runtime.restart(start_options, timeout_s=20)
|
||||
restarted = result.ok
|
||||
if not result.ok and (restart_attempted or result.message != "gateway_already_running"):
|
||||
action = "restarted" if restart_attempted else "started"
|
||||
console.print(f"[yellow]Gateway was not {action}: {result.message}[/yellow]")
|
||||
console.print(f"Logs: {result.status.log_path}")
|
||||
raise typer.Exit(1)
|
||||
if restarted:
|
||||
console.print("[green]Gateway restarted in the background.[/green]")
|
||||
elif result.ok:
|
||||
console.print("[green]Gateway started in the background.[/green]")
|
||||
else:
|
||||
console.print("[yellow]Gateway is already running in the background.[/yellow]")
|
||||
if not _wait_for_webui(webui_url, timeout_s=20):
|
||||
console.print("[red]WebUI did not become ready. Check the gateway logs.[/red]")
|
||||
console.print(f"Logs: {runtime.paths.log_path}", markup=False)
|
||||
raise typer.Exit(1)
|
||||
|
||||
def print_shared_gateway_controls() -> None:
|
||||
console.print(
|
||||
"Manage this instance: "
|
||||
f"[cyan]{_gateway_instance_command('status', config_path=config_path, workspace=workspace)}[/cyan]"
|
||||
)
|
||||
console.print(
|
||||
"View logs: "
|
||||
f"[cyan]{_gateway_instance_command('logs', config_path=config_path, workspace=workspace)}[/cyan]"
|
||||
)
|
||||
console.print("[dim]Closing the browser does not stop channels or automations.[/dim]")
|
||||
console.print(
|
||||
"Stop nanobot: "
|
||||
f"[cyan]{_gateway_instance_command('stop', config_path=config_path, workspace=workspace)}[/cyan]"
|
||||
def announce_ready(url: str, *, managed: bool) -> None:
|
||||
_print_webui_ready(
|
||||
runtime_config, config_path, url, workspace=workspace, dev=dev, managed=managed,
|
||||
provider_error=provider_error,
|
||||
)
|
||||
if not no_open:
|
||||
_open_webui_browser(url, wait=False)
|
||||
|
||||
gateway_ready = _gateway_health_ready(runtime_config.gateway.host, effective_gateway_port)
|
||||
webui_ready = _webui_endpoint_reachable(webui_url)
|
||||
if gateway_ready and webui_ready:
|
||||
lease = GatewayClientLease(runtime, kind="webui")
|
||||
lease.acquire()
|
||||
try:
|
||||
if changed_webui and runtime.status().running:
|
||||
ensure_shared_gateway(client_lease=lease)
|
||||
gateway_ready = _gateway_health_ready(
|
||||
runtime_config.gateway.host,
|
||||
effective_gateway_port,
|
||||
)
|
||||
webui_ready = _webui_endpoint_reachable(webui_url)
|
||||
if not gateway_ready or not webui_ready:
|
||||
console.print("[red]Gateway did not become ready after the config update.[/red]")
|
||||
raise typer.Exit(1)
|
||||
console.print(
|
||||
"[yellow]Gateway is already running; attaching to the existing WebUI.[/yellow]"
|
||||
existing_gateway = gateway_ready and webui_ready
|
||||
if not existing_gateway:
|
||||
gateway_port_taken = gateway_ready or _tcp_endpoint_reachable(
|
||||
_host_for_local_browser(runtime_config.gateway.host),
|
||||
effective_gateway_port,
|
||||
)
|
||||
if gateway_port_taken or webui_ready:
|
||||
_print_foreground_port_conflict(
|
||||
webui_url=webui_url,
|
||||
gateway_host=runtime_config.gateway.host,
|
||||
gateway_port=effective_gateway_port,
|
||||
)
|
||||
if not dev:
|
||||
console.print(
|
||||
"Restart the gateway if you need it to pick up local source changes: "
|
||||
f"[cyan]{_gateway_instance_command('restart', config_path=config_path, workspace=workspace)}[/cyan]"
|
||||
)
|
||||
if not no_open and not _open_webui_browser(webui_url, wait=False):
|
||||
_print_webui_manual_access(runtime_config, config_path, webui_url)
|
||||
if runtime.status().running:
|
||||
_attach_to_background_gateway(runtime)
|
||||
else:
|
||||
console.print(
|
||||
"[yellow]This gateway is controlled by another foreground command. "
|
||||
"Stop it from that terminal.[/yellow]"
|
||||
)
|
||||
return
|
||||
raise typer.Exit(1)
|
||||
|
||||
lease = GatewayClientLease(runtime, kind="webui")
|
||||
lease.acquire()
|
||||
try:
|
||||
if not existing_gateway:
|
||||
console.print("[dim]Starting WebUI…[/dim]")
|
||||
ensure_shared_gateway(client_lease=lease)
|
||||
elif changed_webui and runtime.status().running:
|
||||
ensure_shared_gateway(client_lease=lease)
|
||||
if not (_gateway_health_ready(runtime_config.gateway.host, effective_gateway_port)
|
||||
and _webui_endpoint_reachable(webui_url)):
|
||||
console.print("[red]Gateway did not become ready after the config update.[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
if dev_browser_url:
|
||||
try:
|
||||
assert dev_browser_url is not None
|
||||
with run_webui_dev_server(
|
||||
target_url=webui_dev_proxy_target(webui_url),
|
||||
browser_url=dev_browser_url,
|
||||
output=lambda message: console.print(f"[green]✓[/green] {message}"),
|
||||
output=lambda message: console.print(message, style="dim", markup=False),
|
||||
) as dev_server:
|
||||
if not no_open:
|
||||
_open_webui_browser(dev_browser_url, wait=False)
|
||||
if runtime.status().running:
|
||||
managed = not existing_gateway or runtime.status().running
|
||||
announce_ready(dev_browser_url, managed=managed)
|
||||
if managed:
|
||||
_attach_to_background_gateway(
|
||||
runtime,
|
||||
log_cursor=log_cursor,
|
||||
poll_hook=dev_server.ensure_running,
|
||||
)
|
||||
else:
|
||||
@@ -309,48 +266,10 @@ def webui(
|
||||
console.print(f"[red]Error: {exc}[/red]")
|
||||
raise typer.Exit(1) from exc
|
||||
return
|
||||
finally:
|
||||
lease.release(wait_for_stop=False)
|
||||
|
||||
gateway_port_taken = gateway_ready or _tcp_endpoint_reachable(
|
||||
_host_for_local_browser(runtime_config.gateway.host),
|
||||
effective_gateway_port,
|
||||
)
|
||||
webui_port_taken = webui_ready
|
||||
if gateway_port_taken or webui_port_taken:
|
||||
_print_foreground_port_conflict(
|
||||
webui_url=webui_url,
|
||||
gateway_host=runtime_config.gateway.host,
|
||||
gateway_port=effective_gateway_port,
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
|
||||
lease = GatewayClientLease(runtime, kind="webui")
|
||||
lease.acquire()
|
||||
try:
|
||||
ensure_shared_gateway(client_lease=lease)
|
||||
print_shared_gateway_controls()
|
||||
if dev_browser_url:
|
||||
dev_proxy_target = webui_dev_proxy_target(webui_url)
|
||||
try:
|
||||
with run_webui_dev_server(
|
||||
target_url=dev_proxy_target,
|
||||
browser_url=dev_browser_url,
|
||||
output=lambda message: console.print(f"[green]✓[/green] {message}"),
|
||||
) as dev_server:
|
||||
if not no_open:
|
||||
_open_webui_browser(dev_browser_url)
|
||||
_attach_to_background_gateway(
|
||||
runtime,
|
||||
poll_hook=dev_server.ensure_running,
|
||||
)
|
||||
except WebUIDevError as exc:
|
||||
console.print(f"[red]Error: {exc}[/red]")
|
||||
raise typer.Exit(1) from exc
|
||||
return
|
||||
|
||||
if not no_open and not _open_webui_browser(webui_url):
|
||||
_print_webui_manual_access(runtime_config, config_path, webui_url)
|
||||
_attach_to_background_gateway(runtime)
|
||||
managed = not existing_gateway or runtime.status().running
|
||||
announce_ready(webui_url, managed=managed)
|
||||
if managed:
|
||||
_attach_to_background_gateway(runtime, log_cursor=log_cursor)
|
||||
finally:
|
||||
lease.release(wait_for_stop=False)
|
||||
+145
-108
@@ -1,6 +1,7 @@
|
||||
"""Shared WebUI setup, URL, health, and browser helpers."""
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
@@ -48,11 +49,12 @@ __all__ = [
|
||||
"_open_webui_browser",
|
||||
"_prepare_webui_bundle_for_gateway",
|
||||
"_print_foreground_port_conflict",
|
||||
"_print_webui_manual_access",
|
||||
"_print_webui_foreground_lifecycle",
|
||||
"_print_webui_ready",
|
||||
"_resolve_webui_config_path",
|
||||
"_start_gateway_log_cursor",
|
||||
"_tcp_endpoint_reachable",
|
||||
"_validate_gateway_startup",
|
||||
"_wait_for_webui",
|
||||
"_warn_webui_bind_scope",
|
||||
"_webui_browser_url",
|
||||
"webui_bootstrap_secret",
|
||||
@@ -71,16 +73,68 @@ def _launch_browser(url: str) -> bool:
|
||||
"""Open *url* and request a foreground browser window."""
|
||||
if sys.platform == "darwin":
|
||||
return _launch_macos_browser(url)
|
||||
if sys.platform == "win32":
|
||||
if sys.platform == "win32" or _use_wsl_browser():
|
||||
from nanobot.cli.windows_browser import launch_browser
|
||||
|
||||
return launch_browser(url)
|
||||
return bool(webbrowser.open(url, new=2, autoraise=True))
|
||||
return _launch_unix_browser(url)
|
||||
|
||||
|
||||
def _use_wsl_browser() -> bool:
|
||||
"""Use the Windows desktop in WSL unless the user selected a browser."""
|
||||
return (
|
||||
sys.platform == "linux" and bool(os.environ.get("WSL_DISTRO_NAME"))
|
||||
and not os.environ.get("BROWSER")
|
||||
)
|
||||
|
||||
|
||||
def _launch_unix_browser(url: str) -> bool:
|
||||
"""Launch the selected Unix browser without exposing launcher diagnostics."""
|
||||
try:
|
||||
webbrowser.get()
|
||||
except webbrowser.Error:
|
||||
return False
|
||||
# get() initializes the stdlib's BROWSER-first ordering. Its public API
|
||||
# exposes only the first controller, so read the complete registered order.
|
||||
choices: list[str] = getattr(webbrowser, "_tryorder")
|
||||
for choice in choices:
|
||||
browser = webbrowser.get(choice)
|
||||
if isinstance(browser, webbrowser.GenericBrowser):
|
||||
# gio, xdg-open, and BROWSER command templates inherit this class.
|
||||
# BackgroundBrowser.open only polls once and inherits our stderr.
|
||||
command = [browser.name, *(arg.replace("%s", url) for arg in browser.args)]
|
||||
sys.audit("webbrowser.open", url)
|
||||
if _launch_browser_command(command):
|
||||
return True
|
||||
elif browser.open(url, new=2, autoraise=True):
|
||||
# Native Unix controllers already isolate their subprocess output.
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _launch_browser_command(command: list[str]) -> bool:
|
||||
"""Report an immediate launch failure while allowing a browser to stay open."""
|
||||
import subprocess
|
||||
import threading
|
||||
|
||||
try:
|
||||
process = subprocess.Popen(
|
||||
command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL, close_fds=True, start_new_session=True,
|
||||
)
|
||||
except OSError:
|
||||
return False
|
||||
try:
|
||||
return process.wait(timeout=5) == 0
|
||||
except subprocess.TimeoutExpired:
|
||||
# A direct browser command can stay alive for the whole browsing session.
|
||||
threading.Thread(target=process.wait, daemon=True).start()
|
||||
return True
|
||||
|
||||
|
||||
def _text_only_browser_name() -> str | None:
|
||||
"""Return the configured text browser name when it cannot run the WebUI."""
|
||||
if sys.platform in {"darwin", "win32"}:
|
||||
if sys.platform in {"darwin", "win32"} or _use_wsl_browser():
|
||||
return None
|
||||
|
||||
try:
|
||||
@@ -330,11 +384,7 @@ def _webui_browser_url(config: Config) -> str:
|
||||
|
||||
|
||||
def _webui_display_url(url: str) -> str:
|
||||
marker = "bootstrapSecret="
|
||||
if marker not in url:
|
||||
return url
|
||||
prefix, _ = url.split(marker, 1)
|
||||
return f"{prefix}{marker}<redacted>"
|
||||
return url.split("#", 1)[0].rstrip("/")
|
||||
|
||||
|
||||
def _ensure_local_webui_channel(
|
||||
@@ -356,19 +406,7 @@ def _ensure_local_webui_channel(
|
||||
if not needs_enable and not needs_port and not needs_secret:
|
||||
return False
|
||||
|
||||
target_port = port if port is not None else model.port
|
||||
console.print()
|
||||
console.print("[bold]Local WebUI setup[/bold]")
|
||||
console.print(f" URL: [cyan]http://127.0.0.1:{target_port}[/cyan]")
|
||||
console.print(" Bind: [cyan]127.0.0.1 only[/cyan] (not exposed to your LAN)")
|
||||
if needs_secret:
|
||||
console.print(" WebUI password: will be generated and stored in config")
|
||||
else:
|
||||
console.print(" WebUI password: already stored in config")
|
||||
console.print(
|
||||
" LAN access requires an explicit host change plus a WebUI password in config."
|
||||
)
|
||||
_confirm_webui_action("Enable the WebUI channel?", yes=yes)
|
||||
_confirm_webui_action("Set up WebUI?", yes=yes)
|
||||
|
||||
if not model.enabled:
|
||||
model.enabled = True
|
||||
@@ -403,19 +441,14 @@ def _warn_webui_bind_scope(config: Config) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _wait_for_webui(url: str, *, timeout_s: float = 5.0) -> None:
|
||||
"""Best-effort wait for the WebUI listener before opening a browser."""
|
||||
import time
|
||||
from urllib.parse import urlparse
|
||||
|
||||
parsed = urlparse(url)
|
||||
host = parsed.hostname or "127.0.0.1"
|
||||
port = parsed.port or (443 if parsed.scheme == "https" else 80)
|
||||
def _wait_for_webui(url: str, *, timeout_s: float = 5.0) -> bool:
|
||||
"""Return whether the WebUI listener becomes available within the timeout."""
|
||||
deadline = time.monotonic() + timeout_s
|
||||
while time.monotonic() < deadline:
|
||||
if _tcp_endpoint_reachable(host, port, timeout_s=0.2):
|
||||
return
|
||||
if _webui_endpoint_reachable(url, timeout_s=0.2):
|
||||
return True
|
||||
time.sleep(0.1)
|
||||
return False
|
||||
|
||||
|
||||
def _tcp_endpoint_reachable(host: str, port: int, *, timeout_s: float = 0.25) -> bool:
|
||||
@@ -470,39 +503,25 @@ def _print_foreground_port_conflict(
|
||||
gateway_host: str,
|
||||
gateway_port: int,
|
||||
) -> None:
|
||||
gateway_running = _gateway_health_ready(gateway_host, gateway_port)
|
||||
if gateway_running:
|
||||
console.print(
|
||||
"[yellow]A nanobot gateway is already running for this local instance.[/yellow]"
|
||||
)
|
||||
else:
|
||||
console.print(
|
||||
"[red]Error: nanobot cannot start because one of its local ports "
|
||||
"is already in use.[/red]"
|
||||
)
|
||||
console.print(f" WebUI: [cyan]{_webui_display_url(webui_url)}[/cyan]")
|
||||
console.print("[red]Cannot open this WebUI: the address is already in use.[/red]")
|
||||
console.print()
|
||||
console.print(Text(f"Page: {_webui_display_url(webui_url)}", style="cyan"), soft_wrap=True)
|
||||
console.print(
|
||||
f" Gateway health: "
|
||||
f"[cyan]http://{_host_for_local_browser(gateway_host)}:{gateway_port}/health[/cyan]"
|
||||
Text(f"Service: {_gateway_health_url(gateway_host, gateway_port)}", style="dim"),
|
||||
soft_wrap=True,
|
||||
)
|
||||
console.print()
|
||||
if gateway_running:
|
||||
console.print("Use the existing instance, or stop it first:")
|
||||
else:
|
||||
console.print("If this is an existing nanobot instance, use it or stop it first:")
|
||||
console.print(" [cyan]nanobot gateway status[/cyan]")
|
||||
console.print(" [cyan]nanobot gateway stop[/cyan]")
|
||||
console.print("Stop the existing instance from the terminal where you started it.")
|
||||
console.print(
|
||||
"Or choose different ports with [cyan]--port[/cyan] "
|
||||
"and [cyan]--gateway-port[/cyan]."
|
||||
"To run another instance, choose unused ports with "
|
||||
"[cyan]--port[/cyan] and [cyan]--gateway-port[/cyan]."
|
||||
)
|
||||
|
||||
|
||||
def _open_webui_browser(url: str, *, wait: bool = True) -> bool:
|
||||
"""Open the WebUI in the user's default browser, with a copyable fallback."""
|
||||
"""Request a browser launch; the printed login link remains the fallback."""
|
||||
if wait:
|
||||
_wait_for_webui(url)
|
||||
display_url = _webui_display_url(url)
|
||||
text_browser = _text_only_browser_name()
|
||||
if text_browser:
|
||||
console.print(
|
||||
@@ -512,57 +531,60 @@ def _open_webui_browser(url: str, *, wait: bool = True) -> bool:
|
||||
return False
|
||||
try:
|
||||
if _launch_browser(url):
|
||||
console.print(f"[green]✓[/green] Opened WebUI: [cyan]{display_url}[/cyan]")
|
||||
return True
|
||||
else:
|
||||
console.print("[yellow]Could not open a browser automatically.[/yellow]")
|
||||
except Exception as exc:
|
||||
console.print(f"[yellow]Could not open a browser automatically ({escape(str(exc))}).[/yellow]")
|
||||
except Exception:
|
||||
pass
|
||||
console.print(
|
||||
"[yellow]Could not open a browser automatically. Open the link above.[/yellow]"
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def _print_webui_manual_access(config: Config, config_path: Path, url: str) -> None:
|
||||
"""Print a complete local or SSH-tunnel browser handoff without exposing credentials."""
|
||||
from urllib.parse import urlparse
|
||||
|
||||
browser_url = url.split("/#/", 1)[0]
|
||||
parsed = urlparse(browser_url)
|
||||
port = parsed.port or (443 if parsed.scheme == "https" else 80)
|
||||
tunnel_host = _host_for_local_browser(parsed.hostname or "127.0.0.1")
|
||||
tunnel_url = f"{parsed.scheme}://127.0.0.1:{port}"
|
||||
def _print_webui_ready(
|
||||
config: Config,
|
||||
config_path: Path,
|
||||
url: str,
|
||||
*,
|
||||
workspace: str | None,
|
||||
dev: bool,
|
||||
managed: bool,
|
||||
provider_error: str | None = None,
|
||||
) -> None:
|
||||
"""Show one ready state and a complete browser handoff in the local terminal."""
|
||||
ws_cfg = _webui_config_dict(config)
|
||||
password_key = (
|
||||
"tokenIssueSecret" if str(ws_cfg.get("tokenIssueSecret") or "").strip() else "token"
|
||||
)
|
||||
|
||||
console.print()
|
||||
console.print("[bold]Open the WebUI manually[/bold]")
|
||||
console.print(f" WebUI: [cyan]{browser_url}[/cyan]")
|
||||
console.print(
|
||||
" WebUI password: "
|
||||
f"[cyan]channels.websocket.{password_key}[/cyan] in [cyan]{config_path}[/cyan]"
|
||||
)
|
||||
console.print("[bold green]WebUI ready[/bold green]" + (" [dim](development)[/dim]" if dev else ""))
|
||||
console.print()
|
||||
console.print("If nanobot is running on another machine, create an SSH tunnel from yours:")
|
||||
console.print(
|
||||
f" [cyan]ssh -N -L {port}:{tunnel_host}:{port} <user>@<server>[/cyan]"
|
||||
)
|
||||
console.print("Replace [cyan]<user>[/cyan] and [cyan]<server>[/cyan] and keep the tunnel open.")
|
||||
console.print(f"Then open [cyan]{tunnel_url}[/cyan] on your computer.")
|
||||
|
||||
|
||||
def _print_webui_foreground_lifecycle(*, attached: bool) -> None:
|
||||
"""Explain how the browser and gateway lifecycles differ."""
|
||||
console.print("Open in your browser:")
|
||||
# Terminal wrapping keeps this one copyable line, including in narrow panes.
|
||||
console.print(url, style="cyan", markup=False, highlight=False, soft_wrap=True)
|
||||
if webui_bootstrap_secret(config):
|
||||
console.print("[dim]This link signs you in. Do not share it.[/dim]")
|
||||
console.print(Text(f"Page: {_webui_display_url(url)}", style="dim"), soft_wrap=True)
|
||||
elif ws_cfg.get("trustedProxyAuth"):
|
||||
console.print("Sign in through your configured trusted proxy.")
|
||||
if provider_error:
|
||||
console.print()
|
||||
console.print("[bold]Next step[/bold]")
|
||||
if config.get_provider_name():
|
||||
console.print(Text(f"Model setup is incomplete:\n{provider_error}", style="yellow"))
|
||||
console.print("Choose a provider and model:")
|
||||
console.print("WebUI Settings → Models.", style="bold")
|
||||
console.print()
|
||||
if attached:
|
||||
console.print("[green]WebUI is attached to the shared gateway.[/green]")
|
||||
console.print(Text(f"Config: {config_path}", style="dim"), soft_wrap=True)
|
||||
console.print()
|
||||
log_command = _gateway_instance_command("logs", config_path=config_path, workspace=workspace)
|
||||
console.print(Text(f"Logs: {log_command}", style="dim"), soft_wrap=True)
|
||||
if managed:
|
||||
lifecycle = "Keep this terminal open while using WebUI.\n"
|
||||
lifecycle += "Ctrl+C stops development mode." if dev else "Press Ctrl+C to exit."
|
||||
else:
|
||||
console.print("[green]WebUI is attached to the shared gateway.[/green]")
|
||||
console.print("[dim]Closing the browser does not stop channels or automations.[/dim]")
|
||||
console.print(
|
||||
"[dim]Following live gateway logs. Press Ctrl+C to detach; the gateway stops "
|
||||
"only when the last local client exits.[/dim]"
|
||||
)
|
||||
lifecycle = "WebUI is already running. To stop it, use the terminal where it was started."
|
||||
if dev:
|
||||
lifecycle += "\nCtrl+C stops development mode."
|
||||
console.print()
|
||||
console.print(Text(lifecycle, style="dim"))
|
||||
console.print()
|
||||
|
||||
|
||||
_LOG_ANCHOR_BYTES = 64
|
||||
@@ -634,30 +656,45 @@ def _read_new_gateway_logs(
|
||||
def _attach_to_background_gateway(
|
||||
runtime: "GatewayRuntime",
|
||||
*,
|
||||
log_cursor: _GatewayLogCursor | None = None,
|
||||
poll_hook: Callable[[], None] | None = None,
|
||||
sleep: Callable[[float], None] = time.sleep,
|
||||
) -> None:
|
||||
"""Keep the launcher attached and mirror this gateway's new log output."""
|
||||
"""Keep the launcher attached and surface new gateway warnings and errors."""
|
||||
status = runtime.status()
|
||||
log_path = status.log_path
|
||||
cursor = _start_gateway_log_cursor(log_path)
|
||||
_print_webui_foreground_lifecycle(attached=True)
|
||||
cursor = log_cursor or _start_gateway_log_cursor(log_path)
|
||||
show_detail = False
|
||||
|
||||
def print_logs(*, flush: bool = False) -> None:
|
||||
nonlocal show_detail
|
||||
for line in _read_new_gateway_logs(log_path, cursor, flush=flush):
|
||||
# Full logs remain available through `nanobot gateway logs`.
|
||||
match = re.match(r"^\S+ \| (TRACE|DEBUG|INFO|SUCCESS|WARNING|ERROR|CRITICAL)\s+\|", line)
|
||||
if match:
|
||||
show_detail = match[1] in {"WARNING", "ERROR", "CRITICAL"}
|
||||
elif re.search(r"\b(?:\w*Warning:|WARNING:|ERROR:|CRITICAL:|Traceback \()", line):
|
||||
show_detail = True
|
||||
if not show_detail:
|
||||
continue
|
||||
style = "yellow" if match and match[1] == "WARNING" else None
|
||||
if match and match[1] in {"ERROR", "CRITICAL"}:
|
||||
style = "red"
|
||||
console.print(line, style=style, markup=False, highlight=False)
|
||||
|
||||
try:
|
||||
while status.running:
|
||||
for line in _read_new_gateway_logs(log_path, cursor):
|
||||
console.print(line, markup=False, highlight=False)
|
||||
print_logs()
|
||||
if poll_hook is not None:
|
||||
poll_hook()
|
||||
sleep(0.5)
|
||||
status = runtime.status()
|
||||
except KeyboardInterrupt:
|
||||
for line in _read_new_gateway_logs(log_path, cursor, flush=True):
|
||||
console.print(line, markup=False, highlight=False)
|
||||
console.print("\n[yellow]WebUI launcher detached.[/yellow]")
|
||||
print_logs(flush=True)
|
||||
console.print("\n[dim]WebUI launcher detached.[/dim]")
|
||||
return
|
||||
|
||||
for line in _read_new_gateway_logs(log_path, cursor, flush=True):
|
||||
console.print(line, markup=False, highlight=False)
|
||||
print_logs(flush=True)
|
||||
console.print("[yellow]Gateway stopped.[/yellow]")
|
||||
|
||||
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
"""Windows browser handoff without putting bootstrap URLs in process arguments.
|
||||
"""Windows and WSL browser handoff without credential-bearing process arguments.
|
||||
|
||||
This stdlib-only module also runs in an isolated, short-lived child interpreter.
|
||||
The child owns the redirect file so its lifetime does not depend on the CLI staying
|
||||
open. URLs travel only through an anonymous pipe and the ACL-protected file.
|
||||
open. WSL uses the inbox Windows PowerShell for the same handoff. URLs travel only
|
||||
through an anonymous pipe and a private redirect file.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import ctypes
|
||||
import html
|
||||
import re
|
||||
@@ -48,13 +50,22 @@ def launch_browser(url: str) -> bool:
|
||||
worker: threading.Thread | None = None
|
||||
opened = False
|
||||
try:
|
||||
payload = _url_bytes(url) + b"\n"
|
||||
# -I -S keeps user-site, cwd, PYTHONPATH and .pth startup code out of this
|
||||
# stdlib-only helper. In particular, do not use BROWSER or URL arguments.
|
||||
if sys.platform == "linux":
|
||||
payload = base64.b64encode(_redirect_html(url)) + b"\n"
|
||||
command = [
|
||||
"powershell.exe", "-NoProfile", "-NonInteractive", "-STA", "-EncodedCommand",
|
||||
base64.b64encode(_WSL_OPEN_SCRIPT.encode("utf-16-le")).decode("ascii"),
|
||||
]
|
||||
else:
|
||||
payload = _url_bytes(url) + b"\n"
|
||||
command = [sys.executable, "-I", "-S", str(Path(__file__).resolve()), "--serve"]
|
||||
# -I -S / -NoProfile exclude user startup code. Both helpers receive
|
||||
# credentials only through stdin and outlive the calling CLI.
|
||||
process = subprocess.Popen(
|
||||
[sys.executable, "-I", "-S", str(Path(__file__).resolve()), "--serve"],
|
||||
command,
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
||||
close_fds=True, creationflags=0x08000000, # CREATE_NO_WINDOW
|
||||
close_fds=True, start_new_session=sys.platform != "win32",
|
||||
creationflags=0x08000000 if sys.platform == "win32" else 0, # CREATE_NO_WINDOW
|
||||
)
|
||||
incoming, outgoing = process.stdin, process.stdout
|
||||
if incoming is None or outgoing is None:
|
||||
@@ -123,6 +134,87 @@ def _serve(incoming: BinaryIO, outgoing: BinaryIO, *, lifetime: float = _FILE_LI
|
||||
return 0
|
||||
|
||||
|
||||
# The HTTP association selects the default browser even when an editor owns
|
||||
# .html files. Only the private file path reaches browser arguments, never the URL.
|
||||
_WSL_OPEN_SCRIPT = r'''
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
$path = $null
|
||||
$guard = $null
|
||||
$owned = $false
|
||||
try {
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class NanobotBrowser {
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
public struct ExecuteInfo {
|
||||
public uint cbSize, fMask;
|
||||
public IntPtr hwnd;
|
||||
public string lpVerb, lpFile, lpParameters, lpDirectory;
|
||||
public int nShow;
|
||||
public IntPtr hInstApp, lpIDList;
|
||||
public string lpClass;
|
||||
public IntPtr hkeyClass;
|
||||
public uint dwHotKey;
|
||||
public IntPtr hIcon, hProcess;
|
||||
}
|
||||
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
|
||||
public static extern bool ShellExecuteEx(ref ExecuteInfo info);
|
||||
public static bool Open(string path) {
|
||||
var info = new ExecuteInfo();
|
||||
info.cbSize = (uint)Marshal.SizeOf(info);
|
||||
info.fMask = 0x501;
|
||||
info.lpVerb = "open";
|
||||
info.lpClass = "http";
|
||||
info.lpFile = path;
|
||||
info.nShow = 1;
|
||||
return ShellExecuteEx(ref info);
|
||||
}
|
||||
}
|
||||
'@
|
||||
$content = [Convert]::FromBase64String([Console]::ReadLine())
|
||||
$root = [Environment]::GetFolderPath('LocalApplicationData')
|
||||
$drive = [IO.DriveInfo]::new([IO.Path]::GetPathRoot($root))
|
||||
if ($drive.DriveFormat -notin @('NTFS', 'ReFS')) { exit 1 }
|
||||
$user = [Security.Principal.WindowsIdentity]::GetCurrent().User
|
||||
$security = [Security.AccessControl.FileSecurity]::new()
|
||||
$security.SetOwner($user)
|
||||
$security.SetAccessRuleProtection($true, $false)
|
||||
$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new(
|
||||
$user, [Security.AccessControl.FileSystemRights]::FullControl,
|
||||
[Security.AccessControl.AccessControlType]::Allow))
|
||||
foreach ($old in [IO.Directory]::EnumerateFiles($root, 'NanobotWslBrowser-*.html')) {
|
||||
try {
|
||||
$info = [IO.FileInfo]::new($old)
|
||||
if ($info.Name -notmatch '^NanobotWslBrowser-[0-9a-f]{32}\.html$' -or
|
||||
$info.Attributes -band [IO.FileAttributes]::ReparsePoint -or
|
||||
$info.LastWriteTimeUtc -ge [DateTime]::UtcNow.AddMinutes(-10)) { continue }
|
||||
if ($info.GetAccessControl().GetOwner([Security.Principal.SecurityIdentifier]) -eq $user) {
|
||||
[IO.File]::Delete($old)
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
$path = [IO.Path]::Combine($root, ('NanobotWslBrowser-' + [Guid]::NewGuid().ToString('N') + '.html'))
|
||||
$file = [IO.FileStream]::new($path, [IO.FileMode]::CreateNew,
|
||||
[Security.AccessControl.FileSystemRights]::Write, [IO.FileShare]::None,
|
||||
4096, [IO.FileOptions]::None, $security)
|
||||
$owned = $true
|
||||
try { $file.Write($content, 0, $content.Length) } finally { $file.Dispose() }
|
||||
$guard = [IO.File]::Open($path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read)
|
||||
if (-not [NanobotBrowser]::Open($path)) { exit 1 }
|
||||
[Console]::Write('1')
|
||||
[Console]::Out.Flush()
|
||||
Start-Sleep -Seconds 120
|
||||
} catch {
|
||||
exit 1
|
||||
} finally {
|
||||
if ($guard) { $guard.Dispose() }
|
||||
if ($owned) { try { [IO.File]::Delete($path) } catch {} }
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def _bind(library: Any, name: str, result: Any, *arguments: Any) -> Any:
|
||||
function = getattr(library, name)
|
||||
function.restype = result
|
||||
|
||||
@@ -115,7 +115,7 @@ class GitStore:
|
||||
author=b"nanobot <nanobot@dream>",
|
||||
committer=b"nanobot <nanobot@dream>",
|
||||
)
|
||||
logger.info("Git store initialized at {}", self._workspace)
|
||||
logger.debug("Git store initialized at {}", self._workspace)
|
||||
return True
|
||||
except Exception as exc:
|
||||
raise GitStoreError(f"Git store init failed for {self._workspace}") from exc
|
||||
|
||||
@@ -157,7 +157,7 @@ def start_webui_dev_server(
|
||||
subprocess_run=subprocess_run,
|
||||
output=output,
|
||||
)
|
||||
command = _vite_command(command_runner, vite_cli)
|
||||
command = [*_vite_command(command_runner, vite_cli), "--logLevel", "warn", "--clearScreen", "false"]
|
||||
child_env = dict(environ or os.environ)
|
||||
child_env["NANOBOT_API_URL"] = target_url
|
||||
|
||||
@@ -176,12 +176,6 @@ def start_webui_dev_server(
|
||||
f"WebUI development server exited before it was ready (code {process.returncode})"
|
||||
)
|
||||
if endpoint_reachable(WEBUI_DEV_HOST, WEBUI_DEV_PORT):
|
||||
if output is not None:
|
||||
parsed_url = urlsplit(browser_url)
|
||||
display_url = urlunsplit(
|
||||
(parsed_url.scheme, parsed_url.netloc, parsed_url.path, "", "")
|
||||
)
|
||||
output(f"WebUI dev server: {display_url}")
|
||||
return server
|
||||
sleep(0.1)
|
||||
|
||||
|
||||
Reference in new issue
Block a user