Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(webui): support WSL browser launch and clearer startup output (#6150)
chengyongru41f2eeb7bad6
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex b06ee5783..6b600a5d3 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -273,6 +273,8 @@ Open:http://127.0.0.1:8765```+For first access, copy the complete login link printed by `nanobot webui`, including the fragment after `#`. In WSL, open that link in your Windows browser if automatic opening fails. The plain page address does not sign in a new browser.+If accessing from another device, bind the WebSocket channel to `0.0.0.0` and set `token` or `tokenIssueSecret`. The WebSocket channel refuses public binds without a token or token issue secret.| Symptom | Check |diff --git a/docs/webui.md b/docs/webui.mdindex 59f1381cd..acef24fa4 100644--- a/docs/webui.md+++ b/docs/webui.md@@ -16,7 +16,7 @@ Use the launcher:nanobot webui```-`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 or joins the same on-demand gateway used by the native TUI, 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. While the launcher remains attached, it mirrors new log output from that exact gateway instance in the terminal without replaying older logs.+`nanobot webui` asks for one confirmation on a new installation, creates the config/workspace, enables the local WebSocket channel, and generates a WebUI bootstrap secret when one is missing. It starts or joins the same on-demand gateway used by the native TUI 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. The startup summary groups the login link, model setup guidance, config, and exit controls with blank lines. While attached, the launcher displays new gateway warnings and errors; use the printed logs command for full output.After model setup, explicitly promote the shared gateway when you do not want to keep a client open:@@ -28,6 +28,12 @@ nanobot gateway --backgroundEach foreground WebUI or TUI launcher releases only its own client. The last interactive launcher stops an on-demand gateway. `nanobot gateway --background` makes the gateway persistent; manage it with `nanobot gateway status`, `nanobot gateway logs`, `nanobot gateway restart`, and `nanobot gateway stop`.+The browser signs in automatically using the generated credential in the launch URL. The terminal also prints the complete login link: if automatic opening fails, copy that link into your browser, including the fragment after `#`. In WSL, the launcher opens your Windows default browser through Windows PowerShell; an explicit `BROWSER` setting takes precedence. If Windows integration is unavailable, open the printed link in your Windows browser. The plain page address does not sign in a new browser. Treat the login link as a credential and do not share it.++`nanobot webui --no-open` prints the same login link without opening a browser. Development mode uses the Vite address, normally `http://127.0.0.1:5173`, with the same gateway authentication.++If no provider is configured, follow the **Next step** prompt to open **Settings → Models**. Errors for a configured provider appear with that prompt.+Manual config still works. Same-machine localhost WebUI access can run without a browser password. Set `tokenIssueSecret` when you intentionally expose the WebUI beyond localhost or want a browser password:```jsondiff --git a/nanobot/cli/webui.py b/nanobot/cli/webui.pyindex 7af12bb2c..64bd9d93c 100644--- a/nanobot/cli/webui.py+++ b/nanobot/cli/webui.py@@ -8,7 +8,6 @@ from rich.console import Consolefrom nanobot.cli import terminal as cli_terminalfrom 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,+ )+ resolved_webui_config = resolve_config_env_vars(+ setup_config.model_copy(deep=True), config_path=config_path,)- _warn_webui_bind_scope(setup_config)- webui_url = _webui_browser_url(setup_config)+ _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_configeffective_gateway_port = gateway_port if gateway_port is not None else runtime_config.gateway.portdev_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 = Falserestart_attempted = Falseif not result.ok and result.message == "gateway_already_running" and changed_webui:restart_attempted = Trueconsole.print("[yellow]WebUI config changed; restarting the background gateway.[/yellow]")result = runtime.restart(start_options, timeout_s=20)- restarted = result.okif 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 Nonewith 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 excreturn- 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)diff --git a/nanobot/cli/webui_support.py b/nanobot/cli/webui_support.pyindex ce0e3e11b..88e80b77c 100644--- a/nanobot/cli/webui_support.py+++ b/nanobot/cli/webui_support.py@@ -1,6 +1,7 @@"""Shared WebUI setup, URL, health, and browser helpers."""import os+import reimport shutilimport sysimport 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_browserreturn 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 Truedef _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 Nonetry:@@ -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_swhile time.monotonic() < deadline:- if _tcp_endpoint_reachable(host, port, timeout_s=0.2):- return+ if _webui_endpoint_reachable(url, timeout_s=0.2):+ return Truetime.sleep(0.1)+ return Falsedef _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 Falsetry: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]")diff --git a/nanobot/cli/windows_browser.py b/nanobot/cli/windows_browser.pyindex c6170b7e6..61c417436 100644--- a/nanobot/cli/windows_browser.py+++ b/nanobot/cli/windows_browser.py@@ -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 base64import ctypesimport htmlimport re@@ -48,13 +50,22 @@ def launch_browser(url: str) -> bool:worker: threading.Thread | None = Noneopened = Falsetry:- 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.stdoutif incoming is None or outgoing is None:@@ -123,6 +134,87 @@ def _serve(incoming: BinaryIO, outgoing: BinaryIO, *, lifetime: float = _FILE_LIreturn 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 = resultdiff --git a/nanobot/utils/gitstore.py b/nanobot/utils/gitstore.pyindex b6a7109a2..b1ff13850 100644--- a/nanobot/utils/gitstore.py+++ b/nanobot/utils/gitstore.py@@ -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 Trueexcept Exception as exc:raise GitStoreError(f"Git store init failed for {self._workspace}") from excdiff --git a/nanobot/webui/dev.py b/nanobot/webui/dev.pyindex 1baf40e92..d4d312541 100644--- a/nanobot/webui/dev.py+++ b/nanobot/webui/dev.py@@ -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 serversleep(0.1)diff --git a/tests/cli/test_commands.py b/tests/cli/test_commands.pyindex 258567fc7..d8edba004 100644--- a/tests/cli/test_commands.py+++ b/tests/cli/test_commands.py@@ -8,7 +8,7 @@ from contextlib import contextmanager, suppressfrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock, patch-from urllib.parse import parse_qs, urlparse+from urllib.parse import urlparseimport pytestfrom typer.testing import CliRunner@@ -229,7 +229,7 @@ def test_webui_restores_tty_before_loading_config(monkeypatch, tmp_path: Path) -lambda path: calls.append("config") or original_resolve(path),)_patch_webui_provider_ready(monkeypatch)- monkeypatch.setattr(cli_webui, "sync_workspace_templates", lambda _path: None)+ monkeypatch.setattr(cli_webui, "sync_workspace_templates", lambda _path, **_kwargs: None)monkeypatch.setattr(cli_webui, "_gateway_health_ready", lambda *_args, **_kwargs: False)monkeypatch.setattr(cli_webui, "_webui_endpoint_reachable", lambda *_args, **_kwargs: False)monkeypatch.setattr(cli_webui, "_tcp_endpoint_reachable", lambda *_args, **_kwargs: False)@@ -2025,6 +2025,7 @@ def _patch_webui_managed_gateway("nanobot.cli.webui._attach_to_background_gateway",lambda runtime, **_kwargs: captured.__setitem__("attached_runtime", runtime),)+ monkeypatch.setattr("nanobot.cli.webui._wait_for_webui", lambda *_args, **_kwargs: True)return captured@@ -2054,7 +2055,7 @@ def _patch_cli_command_runtime()monkeypatch.setattr("nanobot.cli.webui.sync_workspace_templates",- sync_templates or (lambda _path: None),+ lambda path, **_kwargs: sync_templates(path) if sync_templates else None,)monkeypatch.setattr("nanobot.cli.gateway_runtime.sync_workspace_templates",@@ -2176,18 +2177,21 @@ def test_heartbeat_empty_response_is_not_evaluated(assert response is None-def test_webui_yes_creates_config_and_enables_local_websocket([email protected]("yes", [True, False])+def test_webui_creates_config_and_enables_local_websocket_with_one_confirmation(monkeypatch,tmp_path: Path,+ yes: bool,) -> None:config_file = tmp_path / "instance" / "config.json"workspace = tmp_path / "workspace"seen: dict[str, object] = {}_patch_webui_provider_ready(monkeypatch)_patch_gateway_ports_free(monkeypatch)+ monkeypatch.setattr(cli_webui_support, "_cli_can_prompt", lambda: True)monkeypatch.setattr("nanobot.cli.webui.sync_workspace_templates",- lambda path: seen.__setitem__("templates", path),+ lambda path, **kwargs: seen.update(templates=path, templates_options=kwargs),)_patch_webui_managed_gateway(monkeypatch, seen)@@ -2204,31 +2208,34 @@ def test_webui_yes_creates_config_and_enables_local_websocket("8899","--gateway-port","18888",- "--yes",+ *(["--yes"] if yes else []),"--no-open",],+ input="y\n" if not yes else None,)assert result.exit_code == 0, result.output- assert result.stdout.count("Using config:") == 1+ assert result.stdout.count("[Y/n]") == (0 if yes else 1)+ assert result.stdout.count("Config:") == 1data = json.loads(config_file.read_text(encoding="utf-8"))websocket = data["channels"]["websocket"]assert websocket["enabled"] is Trueassert websocket["host"] == "127.0.0.1"assert websocket["port"] == 8899assert websocket["websocketRequiresToken"] is True- assert isinstance(websocket["tokenIssueSecret"], str)assert len(websocket["tokenIssueSecret"]) >= 32assert data["agents"]["defaults"]["workspace"] == str(workspace)assert seen["templates"] == workspace+ assert seen["templates_options"] == {"silent": True}options = seen["start_options"]assert options.port == 18888assert options.config_path == str(config_file.resolve(strict=False))assert options.workspace == str(workspace.resolve(strict=False))compact_output = re.sub(r"\s+", " ", _strip_ansi(result.stdout))- assert "Open the WebUI manually" in compact_output- assert "channels.websocket.tokenIssueSecret" in compact_output- assert "ssh -N -L 8899:127.0.0.1:8899 <user>@<server>" in compact_output+ assert "WebUI ready" in compact_output+ assert f"http://127.0.0.1:8899/#/?bootstrapSecret={websocket['tokenIssueSecret']}" in result.stdout.splitlines()+ assert "Open in your browser:" in compact_output+ assert "Ctrl+C" in compact_outputassert seen["lease_release_wait_for_stop"] is Falseassert "stop_timeout" not in seen@@ -2253,8 +2260,26 @@ def test_webui_announces_existing_config_once(monkeypatch, tmp_path: Path, expliresult = runner.invoke(app, args)assert result.exit_code == 0, result.output- assert result.stdout.count("Using config:") == 1- assert f"Using config: {config_file}" in _without_rendered_line_breaks(result.stdout)+ assert result.stdout.count("Config:") == 1+ assert f"Config: {config_file}" in result.stdout+++def test_webui_not_ready_does_not_print_a_login_link(monkeypatch, tmp_path: Path) -> None:+ config_file = tmp_path / "config.json"+ config_file.write_text(json.dumps({+ "agents": {"defaults": {"workspace": str(tmp_path / "workspace")}},+ }), encoding="utf-8")+ _patch_webui_provider_ready(monkeypatch)+ _patch_gateway_ports_free(monkeypatch)+ _patch_webui_managed_gateway(monkeypatch)+ monkeypatch.setattr("nanobot.cli.webui._wait_for_webui", lambda *_args, **_kwargs: False)++ result = runner.invoke(app, ["webui", "--config", str(config_file), "--yes", "--no-open"])++ assert result.exit_code == 1+ assert "WebUI did not become ready" in result.stdout+ assert "Logs:" in result.stdout+ assert "bootstrapSecret=" not in result.stdoutdef test_webui_background_points_to_the_single_persistent_gateway_command(@@ -2289,7 +2314,7 @@ def test_webui_dev_starts_vite_sidecar_and_gateway(monkeypatch, tmp_path: Path)seen: dict[str, object] = {}_patch_webui_provider_ready(monkeypatch)_patch_gateway_ports_free(monkeypatch)- monkeypatch.setattr("nanobot.cli.webui.sync_workspace_templates", lambda _path: None)+ monkeypatch.setattr("nanobot.cli.webui.sync_workspace_templates", lambda _path, **_kwargs: None)@contextmanagerdef fake_dev_server(**kwargs):@@ -2321,7 +2346,7 @@ def test_webui_dev_starts_vite_sidecar_and_gateway(monkeypatch, tmp_path: Path))monkeypatch.setattr("nanobot.cli.webui._open_webui_browser",- lambda url: seen.__setitem__("opened_url", url),+ lambda url, **_kwargs: seen.__setitem__("opened_url", url),)result = runner.invoke(@@ -2345,17 +2370,18 @@ def test_webui_dev_starts_vite_sidecar_and_gateway(monkeypatch, tmp_path: Path)assert dev_kwargs["target_url"] == "http://127.0.0.1:8899"browser_url = dev_kwargs["browser_url"]assert isinstance(browser_url, str)- assert browser_url.startswith("http://127.0.0.1:5173/#/?bootstrapSecret=")+ saved = json.loads(config_file.read_text(encoding="utf-8"))+ secret = saved["channels"]["websocket"]["tokenIssueSecret"]+ assert browser_url == f"http://127.0.0.1:5173/#/?bootstrapSecret={secret}"assert seen["start_options"].port == 18888assert seen["attached_while_dev_running"] is True- assert seen["attach_kwargs"] == {"poll_hook": seen["dev_server"].ensure_running}+ assert seen["attach_kwargs"]["poll_hook"] == seen["dev_server"].ensure_runningassert seen["opened_url"] == browser_urlassert seen["dev_running"] is Falseassert seen["dev_running_at_release"] is Falseassert seen["lease_release_wait_for_stop"] is False- assert "WebUI dev: http://127.0.0.1:5173/#/?bootstrapSecret=<redacted>" in re.sub(- r"\s+", " ", _strip_ansi(result.stdout)- )+ assert "WebUI ready (development)" in result.stdout+ assert browser_url in result.stdout.splitlines()def test_webui_dev_waits_for_external_gateway_via_health_endpoint(monkeypatch) -> None:@@ -2449,16 +2475,8 @@ def test_webui_resumes_first_run_without_provider_setup(config_file = tmp_path / "config.json"seen: dict[str, object] = {}- monkeypatch.setattr(- "nanobot.cli.webui_support._provider_setup_error",- lambda _config: "No API key configured for provider 'custom'.",- )- monkeypatch.setattr(- "nanobot.cli.webui._provider_setup_error",- lambda _config: "No API key configured for provider 'custom'.",- )_patch_gateway_ports_free(monkeypatch)- monkeypatch.setattr("nanobot.cli.webui.sync_workspace_templates", lambda _path: None)+ monkeypatch.setattr("nanobot.cli.webui.sync_workspace_templates", lambda _path, **_kwargs: None)_patch_webui_managed_gateway(monkeypatch, seen)args = ["webui", "--config", str(config_file), "--workspace", str(tmp_path / "workspace")]@@ -2467,7 +2485,10 @@ def test_webui_resumes_first_run_without_provider_setup(assert result.exit_code == 0assert config_file.exists()assert seen["start_options"].config_path == str(config_file.resolve(strict=False))- assert "Configure a provider and model in WebUI Settings → Models." in result.stdout+ assert "Choose a provider and model:\nWebUI Settings → Models." in result.stdout+ assert "anthropic" not in result.stdout.lower()+ assert "Model setup is incomplete" not in result.stdout+ assert result.stdout.index("WebUI ready") < result.stdout.index("Next step")saved_config = json.loads(config_file.read_text(encoding="utf-8"))seen.clear()@@ -2475,7 +2496,9 @@ def test_webui_resumes_first_run_without_provider_setup(assert resumed.exit_code == 0, resumed.stdoutassert seen["start_options"].config_path == str(config_file.resolve(strict=False))- assert "Configure a provider and model in WebUI Settings → Models." in resumed.stdout+ assert "Choose a provider and model:\nWebUI Settings → Models." in resumed.stdout+ assert "anthropic" not in resumed.stdout.lower()+ assert "Model setup is incomplete" not in resumed.stdoutassert "Quick Start" not in resumed.stdoutassert json.loads(config_file.read_text(encoding="utf-8")) == saved_configassert saved_config["channels"]["websocket"]["host"] == "127.0.0.1"@@ -2555,7 +2578,7 @@ def test_webui_yes_opens_settings_for_incomplete_custom_model_setup(assert saved["providers"]["custom"]["displayName"] == "Custom"-def test_open_webui_browser_redacts_bootstrap_secret(monkeypatch, capsys) -> None:+def test_open_webui_browser_does_not_claim_the_browser_loaded(monkeypatch, capsys) -> None:opened: list[str] = []url = "http://127.0.0.1:8765/#/?bootstrapSecret=super-secret"monkeypatch.setattr(cli_webui_support, "_text_only_browser_name", lambda: None)@@ -2569,8 +2592,7 @@ def test_open_webui_browser_redacts_bootstrap_secret(monkeypatch, capsys) -> Nonassert opened == [url]output = _strip_ansi(capsys.readouterr().out)- assert "bootstrapSecret=<redacted>" in output- assert "super-secret" not in output+ assert output == ""def test_open_webui_browser_reports_launch_failure(monkeypatch, capsys) -> None:@@ -2607,6 +2629,7 @@ def test_open_webui_browser_rejects_text_only_browser(monkeypatch, capsys) -> Nodef test_text_only_browser_name_detects_links(monkeypatch) -> None:monkeypatch.setattr(cli_webui_support.sys, "platform", "linux")+ monkeypatch.delenv("WSL_DISTRO_NAME", raising=False)monkeypatch.setattr(cli_webui_support.webbrowser,"get",@@ -2616,39 +2639,6 @@ def test_text_only_browser_name_detects_links(monkeypatch) -> None:assert cli_webui_support._text_only_browser_name() == "links"- ("host", "tunnel_host"),- [- ("127.0.0.1", "127.0.0.1"),- ("0.0.0.0", "127.0.0.1"),- ("::1", "[::1]"),- ("::", "[::1]"),- ("192.0.2.10", "192.0.2.10"),- ],-)-def test_print_webui_manual_access_includes_password_source_and_ssh_tunnel(- capsys, host: str, tunnel_host: str,-) -> None:- config = Config(channels={"websocket": {- "host": host, "port": 8899, "tokenIssueSecret": "do-not-print",- }})- config_path = Path("/srv/nanobot/config.json")-- cli_webui_support._print_webui_manual_access(- config,- config_path,- cli_webui_support._webui_browser_url(config),- )-- output = re.sub(r"\s+", " ", _strip_ansi(capsys.readouterr().out))- assert f"WebUI: http://{tunnel_host}:8899" in output- assert "channels.websocket.tokenIssueSecret" in output- assert str(config_path) in output- assert f"ssh -N -L 8899:{tunnel_host}:8899 <user>@<server>" in output- assert "Then open http://127.0.0.1:8899 on your computer." in output- assert "do-not-print" not in output--def test_launch_browser_uses_macos_url_services(monkeypatch) -> None:seen: list[str] = []monkeypatch.setattr(cli_webui_support.sys, "platform", "darwin")@@ -2662,17 +2652,18 @@ def test_launch_browser_uses_macos_url_services(monkeypatch) -> None:assert seen == ["http://127.0.0.1:8765/"]-def test_launch_browser_uses_default_browser_off_macos(monkeypatch) -> None:- opened: list[tuple[str, int, bool]] = []+def test_launch_browser_uses_unix_launcher_on_linux(monkeypatch) -> None:+ opened: list[str] = []monkeypatch.setattr(cli_webui_support.sys, "platform", "linux")+ monkeypatch.delenv("WSL_DISTRO_NAME", raising=False)monkeypatch.setattr(- cli_webui_support.webbrowser,- "open",- lambda url, *, new, autoraise: opened.append((url, new, autoraise)) or True,+ cli_webui_support,+ "_launch_unix_browser",+ lambda url: opened.append(url) or True,)assert cli_webui_support._launch_browser("http://127.0.0.1:8765/") is True- assert opened == [("http://127.0.0.1:8765/", 2, True)]+ assert opened == ["http://127.0.0.1:8765/"]def test_webui_foreground_attaches_to_existing_managed_gateway(monkeypatch, tmp_path: Path) -> None:@@ -2681,7 +2672,8 @@ def test_webui_foreground_attaches_to_existing_managed_gateway(monkeypatch, tmp_seen: dict[str, object] = {}_record_gateway_lease_release(monkeypatch, seen)_patch_webui_provider_ready(monkeypatch)- monkeypatch.setattr("nanobot.cli.webui.sync_workspace_templates", lambda _path: None)+ monkeypatch.setattr("nanobot.cli.webui.sync_workspace_templates", lambda _path, **_kwargs: None)+ monkeypatch.setattr("nanobot.cli.webui._wait_for_webui", lambda *_args, **_kwargs: True)monkeypatch.setattr("nanobot.cli.webui._gateway_health_ready", lambda *_args, **_kwargs: True)monkeypatch.setattr("nanobot.cli.webui_support._gateway_health_ready",@@ -2700,15 +2692,9 @@ def test_webui_foreground_attaches_to_existing_managed_gateway(monkeypatch, tmp_def __init__(self, **kwargs) -> None:seen["runtime_kwargs"] = kwargsself.paths = kwargs["paths"]- self.status_calls = 0def status(self):- self.status_calls += 1- # The command checks during config refresh and once more before- # delegating to the attach helper.- # If that helper is not patched as intended, make its polling loop- # terminate instead of hanging the Windows test worker forever.- return SimpleNamespace(running=self.status_calls <= 2)+ return SimpleNamespace(running=True)def start_background(self, options):return SimpleNamespace(@@ -2731,20 +2717,19 @@ def test_webui_foreground_attaches_to_existing_managed_gateway(monkeypatch, tmp_monkeypatch.setattr("nanobot.gateway.GatewayRuntime", _FakeRuntime)monkeypatch.setattr("nanobot.cli.webui._attach_to_background_gateway",- lambda runtime: seen.__setitem__("attached_runtime", runtime),+ lambda runtime, **_kwargs: seen.__setitem__("attached_runtime", runtime),)result = runner.invoke(app, ["webui", "--config", str(config_file), "--yes"])assert result.exit_code == 0- assert "Gateway is already running; attaching to the existing WebUI" in result.stdout+ assert "WebUI ready" in result.stdoutassert isinstance(seen["attached_runtime"], _FakeRuntime)opened_url = seen["opened_url"]assert isinstance(opened_url, str)parsed = urlparse(opened_url)assert f"{parsed.scheme}://{parsed.netloc}" == "http://127.0.0.1:8765"- fragment = parsed.fragment.removeprefix("/?")- assert parse_qs(fragment).get("bootstrapSecret")+ assert parsed.fragment.startswith("/?bootstrapSecret=")assert seen["open_kwargs"] == {"wait": False}assert seen["lease_release_wait_for_stop"] is False@@ -2771,14 +2756,15 @@ def test_attach_to_background_gateway_detaches_on_ctrl_c(capsys, tmp_path: Path)assert stopped is Falseoutput = capsys.readouterr().outrendered = " ".join(output.split())- assert "Closing the browser does not stop channels or automations" in rendered- assert "gateway stops only when the last local client exits" in renderedassert "WebUI launcher detached" in rendered-def test_attach_to_background_gateway_follows_only_new_logs(capsys, tmp_path: Path) -> None:+def test_attach_to_background_gateway_surfaces_new_warnings_and_errors(capsys, tmp_path: Path) -> None:log_path = tmp_path / "gateway.log"log_path.write_text("historical log\n", encoding="utf-8")+ cursor = cli_webui_support._start_gateway_log_cursor(log_path)+ with log_path.open("a", encoding="utf-8") as handle:+ handle.write("2026-10-11T02:03:00.000+0800 | WARNING | - | - | startup warning\n")polls = 0class _FakeRuntime:@@ -2789,18 +2775,26 @@ def test_attach_to_background_gateway_follows_only_new_logs(capsys, tmp_path: Panonlocal pollsif polls == 0:with log_path.open("a", encoding="utf-8") as handle:- handle.write("[websocket] live log\n")+ handle.write("2026-10-11T02:04:00.000+0800 | INFO | - | - | idle poll\n")+ handle.write("2026-10-11T02:04:00.000+0800 | WARNING | - | - | connection lost\n")+ handle.write("2026-10-11T02:04:00.000+0800 | ERROR | - | - | request failed\n")+ handle.write("Traceback: diagnostic detail\n")polls += 1returnraise KeyboardInterruptcli_webui_support._attach_to_background_gateway(_FakeRuntime(),+ log_cursor=cursor,sleep=_append_then_interrupt,)output = capsys.readouterr().out- assert "[websocket] live log" in output+ assert "startup warning" in output+ assert "connection lost" in output+ assert "request failed" in output+ assert "Traceback: diagnostic detail" in output+ assert "idle poll" not in outputassert "historical log" not in output@@ -2869,20 +2863,41 @@ def test_attach_to_background_gateway_checks_owned_sidecar(tmp_path: Path) -> No)[email protected]("dev", [False, True])[email protected]("no_open", [False, True])def test_webui_foreground_does_not_claim_unmanaged_gateway(- monkeypatch, tmp_path: Path, mock_webui_bundle: MagicMock,+ monkeypatch, tmp_path: Path, mock_webui_bundle: MagicMock, dev: bool, no_open: bool,) -> None:config_file = tmp_path / "config.json"config_file.write_text("{}")_patch_webui_provider_ready(monkeypatch)- monkeypatch.setattr("nanobot.cli.webui.sync_workspace_templates", lambda _path: None)+ monkeypatch.setattr("nanobot.cli.webui.sync_workspace_templates", lambda _path, **_kwargs: None)monkeypatch.setattr("nanobot.cli.webui._gateway_health_ready", lambda *_args: True)monkeypatch.setattr("nanobot.cli.webui._webui_endpoint_reachable", lambda *_args: True)- monkeypatch.setattr("nanobot.cli.webui._open_webui_browser", lambda *_args, **_kwargs: None)+ opened: list[str] = []+ monkeypatch.setattr(+ "nanobot.cli.webui._open_webui_browser",+ lambda url, **_kwargs: opened.append(url),+ )monkeypatch.setattr("nanobot.cli.webui._attach_to_background_gateway",lambda _runtime: pytest.fail("unmanaged gateway must not be attached"),)+ seen: dict[str, object] = {}+ _record_gateway_lease_release(monkeypatch, seen)+ dev_server = MagicMock()++ @contextmanager+ def fake_dev_server(**_kwargs):+ seen["dev_running"] = True+ try:+ yield dev_server+ finally:+ seen["dev_running"] = False++ wait_for_gateway = MagicMock()+ monkeypatch.setattr(cli_webui, "run_webui_dev_server", fake_dev_server)+ monkeypatch.setattr(cli_webui, "_wait_with_existing_foreground_gateway", wait_for_gateway)class _FakeRuntime:def __init__(self, **kwargs) -> None:@@ -2893,19 +2908,30 @@ def test_webui_foreground_does_not_claim_unmanaged_gateway(monkeypatch.setattr("nanobot.gateway.GatewayRuntime", _FakeRuntime)- result = runner.invoke(app, ["webui", "--config", str(config_file), "--yes"])+ result = runner.invoke(app, [+ "webui", "--config", str(config_file), "--yes",+ *(["--dev"] if dev else []), *(["--no-open"] if no_open else []),+ ])- assert result.exit_code == 0- assert "controlled by another foreground command" in result.stdout- mock_webui_bundle.assert_called_once()- assert mock_webui_bundle.call_args.kwargs == {"mode": "auto"}+ assert result.exit_code == 0, result.output+ assert "WebUI is already running" in result.stdout+ assert len(opened) == (0 if no_open else 1)+ assert seen["lease_release_wait_for_stop"] is False+ if dev:+ wait_for_gateway.assert_called_once_with("127.0.0.1", 18790, dev_server)+ assert seen["dev_running_at_release"] is False+ mock_webui_bundle.assert_not_called()+ else:+ wait_for_gateway.assert_not_called()+ mock_webui_bundle.assert_called_once()+ assert mock_webui_bundle.call_args.kwargs == {"mode": "auto"}def test_webui_foreground_refuses_occupied_webui_port(monkeypatch, tmp_path: Path) -> None:config_file = tmp_path / "config.json"config_file.write_text("{}")_patch_webui_provider_ready(monkeypatch)- monkeypatch.setattr("nanobot.cli.webui.sync_workspace_templates", lambda _path: None)+ monkeypatch.setattr("nanobot.cli.webui.sync_workspace_templates", lambda _path, **_kwargs: None)monkeypatch.setattr("nanobot.cli.webui._gateway_health_ready", lambda *_args, **_kwargs: False)monkeypatch.setattr("nanobot.cli.webui_support._gateway_health_ready",@@ -2916,7 +2942,7 @@ def test_webui_foreground_refuses_occupied_webui_port(monkeypatch, tmp_path: Patresult = runner.invoke(app, ["webui", "--config", str(config_file), "--yes"])assert result.exit_code == 1- assert "nanobot cannot start because one of its local ports is already in use" in result.stdout+ assert "address is already in use" in result.stdoutassert "--port" in result.stdoutassert "--gateway-port" in result.stdout@@ -2931,7 +2957,7 @@ def test_webui_foreground_reports_an_existing_gateway_without_leaking_secret(encoding="utf-8",)_patch_webui_provider_ready(monkeypatch)- monkeypatch.setattr("nanobot.cli.webui.sync_workspace_templates", lambda _path: None)+ monkeypatch.setattr("nanobot.cli.webui.sync_workspace_templates", lambda _path, **_kwargs: None)monkeypatch.setattr("nanobot.cli.webui._gateway_health_ready", lambda *_args, **_kwargs: True)monkeypatch.setattr("nanobot.cli.webui_support._gateway_health_ready",@@ -2942,8 +2968,9 @@ def test_webui_foreground_reports_an_existing_gateway_without_leaking_secret(result = runner.invoke(app, ["webui", "--config", str(config_file), "--yes"])assert result.exit_code == 1- assert "gateway is already running for this local instance" in result.stdout- assert "bootstrapSecret=<redacted>" in result.stdout+ assert "address is already in use" in result.stdout+ assert "http://127.0.0.1:8765" in result.stdout+ assert "bootstrapSecret=" not in result.stdoutassert "do-not-leak" not in result.stdoutdiff --git a/tests/cli/test_webui_support.py b/tests/cli/test_webui_support.pyindex 93577d518..01836cd98 100644--- a/tests/cli/test_webui_support.py+++ b/tests/cli/test_webui_support.py@@ -1,11 +1,147 @@+import os+import shlex+import sys+import webbrowser+from io import StringIO+from pathlib import Pathfrom types import SimpleNamespace+from urllib.parse import quoteimport pytest+from rich.console import Console+from nanobot.cli import webui_supportfrom nanobot.cli.webui_support import _prepare_webui_bundle_for_gatewayfrom nanobot.config.schema import Config[email protected]("width", [32, 100])+def test_webui_ready_keeps_the_complete_login_url_copyable(monkeypatch, width: int) -> None:+ output = StringIO()+ monkeypatch.setattr(webui_support, "console", Console(file=output, width=width))+ password = "local/中文+#?" * 5+ config = Config(channels={"websocket": {"tokenIssueSecret": password}})+ url = webui_support._webui_browser_url(config)+ config_path = Path("/srv/nanobot/config.json")++ webui_support._print_webui_ready(+ config, config_path, url, workspace=None, dev=False, managed=True,+ )++ lines = output.getvalue().splitlines()+ assert f"http://127.0.0.1:8765/#/?bootstrapSecret={quote(password, safe='')}" in lines+ assert "Page: http://127.0.0.1:8765" in lines+ assert lines.index(url) < lines.index("Page: http://127.0.0.1:8765")+ assert lines[lines.index(url) - 1] == "Open in your browser:"+ assert output.getvalue().count("bootstrapSecret=") == 1+ assert "Open in your browser:" in output.getvalue()+ assert f"Config: {config_path}" in lines+ log_command = next(line.removeprefix("Logs: ") for line in lines if line.startswith("Logs: "))+ assert shlex.split(log_command) == ["nanobot", "gateway", "logs", "--config", str(config_path)]+++def test_unix_browser_reports_delayed_launcher_failure_without_raw_output(monkeypatch, tmp_path, capfd) -> None:+ launcher = tmp_path / "failing_browser.py"+ launcher.write_text(+ "import sys, time\n"+ "time.sleep(0.1)\n"+ "print('launcher stdout: ' + sys.argv[-1])\n"+ "print('gio: ' + sys.argv[-1] + ': Operation not supported', file=sys.stderr)\n"+ "sys.exit(1)\n",+ encoding="utf-8",+ )+ browser = webbrowser.BackgroundBrowser([sys.executable, str(launcher), "%s"])+ monkeypatch.setattr(webui_support.sys, "platform", "linux")+ monkeypatch.delenv("WSL_DISTRO_NAME", raising=False)+ monkeypatch.delenv("BROWSER", raising=False)+ monkeypatch.setattr(webbrowser, "_tryorder", ["nanobot-test-browser"])+ monkeypatch.setattr(webui_support.webbrowser, "get", lambda _choice=None: browser)++ assert not webui_support._open_webui_browser(+ "http://127.0.0.1:8765/#/?bootstrapSecret=private-test-credential", wait=False,+ )++ captured = capfd.readouterr()+ assert "Could not open a browser automatically." in captured.out+ assert "Open the link above." in " ".join(captured.out.split())+ assert "private-test-credential" not in captured.out + captured.err+ assert "Operation not supported" not in captured.out + captured.err+ assert "launcher stdout" not in captured.out + captured.err+++def test_unix_browser_preserves_custom_commands_and_candidate_order(monkeypatch, tmp_path) -> None:+ launcher = tmp_path / "custom browser.py"+ result = tmp_path / "received.txt"+ launcher.write_text(+ "import pathlib, sys\n"+ "pathlib.Path(sys.argv[1]).write_text(sys.argv[2], encoding='utf-8')\n",+ encoding="utf-8",+ )+ command = shlex.join([sys.executable, str(launcher), str(result), "%s"])+ monkeypatch.setenv("WSL_DISTRO_NAME", "Ubuntu")+ monkeypatch.setenv("BROWSER", f"unavailable-nanobot-test-browser{os.pathsep}{command}")+ monkeypatch.setenv("DISPLAY", "")+ monkeypatch.setenv("WAYLAND_DISPLAY", "")+ monkeypatch.setattr(webbrowser, "_tryorder", None)+ monkeypatch.setattr(webbrowser, "_browsers", {})+ monkeypatch.setattr(webui_support.sys, "platform", "linux")+ url = "http://127.0.0.1:8765/#/?bootstrapSecret=custom%20password"++ assert webui_support._launch_browser(url)+ assert result.read_text(encoding="utf-8") == url++[email protected]("failure", ["missing", "exits"])+def test_unix_browser_falls_back_to_platform_browser(monkeypatch, tmp_path, capfd, failure) -> None:+ launcher = tmp_path / "browser.py"+ received = tmp_path / "received.txt"+ launcher.write_text(+ "import pathlib, sys\n"+ "if sys.argv[1] == 'fail':\n"+ " print(sys.argv[-1], file=sys.stderr)\n"+ " sys.exit(1)\n"+ "pathlib.Path(sys.argv[1]).write_text(sys.argv[2], encoding='utf-8')\n",+ encoding="utf-8",+ )+ selected = (+ "unavailable-nanobot-test-browser" if failure == "missing"+ else shlex.join([sys.executable, str(launcher), "fail", "%s"])+ )+ fallback = webbrowser.BackgroundBrowser([sys.executable, str(launcher), str(received), "%s"])+ register_standard = webbrowser.register_standard_browsers++ def register_browsers():+ register_standard()+ webbrowser.register("nanobot-test-platform-browser", None, fallback)++ monkeypatch.setenv("BROWSER", selected)+ monkeypatch.setenv("WSL_DISTRO_NAME", "Ubuntu")+ monkeypatch.setenv("DISPLAY", "")+ monkeypatch.setenv("WAYLAND_DISPLAY", "")+ monkeypatch.setenv("TERM", "")+ monkeypatch.setattr(webbrowser, "_tryorder", None)+ monkeypatch.setattr(webbrowser, "_browsers", {})+ monkeypatch.setattr(webbrowser, "register_standard_browsers", register_browsers)+ monkeypatch.setattr(webui_support.sys, "platform", "linux")+ url = "http://127.0.0.1:8765/#/?bootstrapSecret=private-test-credential"++ assert webui_support._launch_browser(url)+ assert received.read_text(encoding="utf-8") == url+ captured = capfd.readouterr()+ assert "private-test-credential" not in captured.out + captured.err+++def test_unix_browser_keeps_native_controller_new_tab_behavior(monkeypatch) -> None:+ opened = []+ controller = SimpleNamespace(open=lambda url, **options: opened.append((url, options)) or True)+ monkeypatch.delenv("BROWSER", raising=False)+ monkeypatch.setattr(webbrowser, "_tryorder", ["nanobot-test-browser"])+ monkeypatch.setattr(webui_support.webbrowser, "get", lambda _choice=None: controller)++ assert webui_support._launch_unix_browser("http://127.0.0.1:8765/")+ assert opened == [("http://127.0.0.1:8765/", {"new": 2, "autoraise": True})]++@pytest.mark.parametrize("mode",[diff --git a/tests/cli/test_windows_browser.py b/tests/cli/test_windows_browser.pyindex 21f540395..ed1b98a6b 100644--- a/tests/cli/test_windows_browser.py+++ b/tests/cli/test_windows_browser.py@@ -1,5 +1,6 @@"""Windows redirect, secret transport and cleanup regressions."""+import base64import ctypesimport ioimport os@@ -28,13 +29,13 @@ class RecordingInput(io.BytesIO):@pytest.fixture-def launcher(monkeypatch):+def launcher(monkeypatch, request):process = SimpleNamespace(stdin=RecordingInput(), stdout=io.BytesIO(b"1"), kill=MagicMock(), wait=MagicMock(),)spawn = MagicMock(return_value=process)monkeypatch.setattr(subprocess, "Popen", spawn)- monkeypatch.setattr(browser.sys, "platform", "win32")+ monkeypatch.setattr(browser.sys, "platform", getattr(request, "param", "win32"))monkeypatch.setenv("BROWSER", "unsafe-browser %s")monkeypatch.setattr(webui_support.webbrowser, "open", lambda *_a, **_kw: pytest.fail("raw URL fallback"),@@ -65,6 +66,7 @@ def test_windows_uses_pipe_not_argv_or_browser_override(launcher, capsys, url):assert capsys.readouterr() == ("", "")[email protected]("launcher", ["win32", "linux"], indirect=True)@pytest.mark.parametrize("url", ["javascript:alert(1)", "file:///tmp/secret", "http:///", "http://[invalid/","http://localhost/\nsecret", "http://localhost/\rsecret", "http://localhost/\x00",@@ -78,6 +80,7 @@ def test_invalid_input_does_not_spawn_a_helper(launcher, url, capsys):assert capsys.readouterr() == ("", "")[email protected]("launcher", ["win32", "linux"], indirect=True)@pytest.mark.parametrize("failure", ["spawn", "eof", "bad_ack", "pipe"])def test_launcher_failure_never_logs_url_or_retries(launcher, failure, capsys):process, spawn = launcher@@ -95,6 +98,7 @@ def test_launcher_failure_never_logs_url_or_retries(launcher, failure, capsys):assert capsys.readouterr() == ("", "")[email protected]("launcher", ["win32", "linux"], indirect=True)def test_startup_timeout_kills_helper_and_drains_pipe_reader(launcher, monkeypatch):process, _ = launcherexited = threading.Event()@@ -481,9 +485,53 @@ def test_native_private_file_permissions_sharing_and_cleanup(tmp_path, monkeypatassert not path.exists()-def test_linux_browser_behavior_is_unchanged(monkeypatch):+def test_linux_uses_the_unix_browser_launcher(monkeypatch):monkeypatch.setattr(browser.sys, "platform", "linux")+ monkeypatch.delenv("WSL_DISTRO_NAME", raising=False)opened = MagicMock(return_value=True)- monkeypatch.setattr(webui_support.webbrowser, "open", opened)+ monkeypatch.setattr(webui_support, "_launch_unix_browser", opened)assert webui_support._launch_browser("http://localhost/")- opened.assert_called_once_with("http://localhost/", new=2, autoraise=True)+ opened.assert_called_once_with("http://localhost/")++[email protected]("launcher", ["linux"], indirect=True)[email protected]("url", [+ "http://localhost:8765/#/?bootstrapSecret=synthetic-only",+ 'http://localhost:5173/#/?bootstrapSecret="/><script>$(test)&中文</script>',+])+def test_wsl_default_browser_uses_private_pipe_and_skips_linux_browser(launcher, monkeypatch, url):+ process, spawn = launcher+ monkeypatch.setenv("WSL_DISTRO_NAME", "Ubuntu")+ monkeypatch.delenv("BROWSER", raising=False)+ monkeypatch.setattr(+ webui_support.webbrowser, "get", lambda: pytest.fail("Linux browser selected in WSL"),+ )++ assert webui_support._open_webui_browser(url, wait=False)++ args, options = spawn.call_args+ assert args[0][0] == "powershell.exe"+ assert "-NoProfile" in args[0] and "-NonInteractive" in args[0]+ assert base64.b64decode(args[0][-1]).decode("utf-16-le") == browser._WSL_OPEN_SCRIPT+ assert base64.b64decode(process.stdin.payload) == browser._redirect_html(url)+ assert url not in repr(spawn.call_args)+ assert options["start_new_session"] is True+ assert options["stderr"] == subprocess.DEVNULL+ process.kill.assert_not_called()+++def test_wsl_without_windows_integration_keeps_the_manual_login_fallback(monkeypatch, capsys):+ monkeypatch.setattr(browser.sys, "platform", "linux")+ monkeypatch.setenv("WSL_DISTRO_NAME", "Ubuntu")+ monkeypatch.delenv("BROWSER", raising=False)+ monkeypatch.setattr(subprocess, "Popen", MagicMock(side_effect=FileNotFoundError))+ monkeypatch.setattr(+ webui_support, "_launch_unix_browser", lambda _: pytest.fail("unsafe raw URL fallback"),+ )++ assert not webui_support._open_webui_browser(+ "http://localhost/#/?bootstrapSecret=synthetic-only", wait=False,+ )+ output = capsys.readouterr()+ assert "Open the link above." in " ".join(output.out.split())+ assert "synthetic-only" not in output.out + output.errdiff --git a/tests/cli/test_wsl_browser.py b/tests/cli/test_wsl_browser.pynew file mode 100644index 000000000..49e8ae363--- /dev/null+++ b/tests/cli/test_wsl_browser.py@@ -0,0 +1,59 @@+"""Exercise the Windows file boundary used by the WSL browser handoff."""++import base64+import os+import shutil+import subprocess++import pytest++from nanobot.cli.windows_browser import _WSL_OPEN_SCRIPT, _redirect_html+++ not shutil.which("powershell.exe") or not (os.name == "nt" or os.environ.get("WSL_DISTRO_NAME")),+ reason="Requires Windows PowerShell, natively or through WSL",+)[email protected]("opens", [True, False])+def test_windows_handoff_file_is_private_readable_and_removed(opens):+ # Keep the native filesystem and helper lifecycle; replace only desktop+ # activation so this regression never opens a user's browser during pytest.+ script = _WSL_OPEN_SCRIPT.replace(+ "return ShellExecuteEx(ref info);", f"return {str(opens).lower()};",+ ).replace("Start-Sleep -Seconds 120", "Start-Sleep -Milliseconds 30")+ check = r'''+ $acl = $guard.GetAccessControl()+ $rules = $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])+ if (-not $acl.AreAccessRulesProtected -or $rules.Count -ne 1 -or+ $acl.GetOwner([Security.Principal.SecurityIdentifier]) -ne $user -or+ $rules[0].IdentityReference -ne $user -or $rules[0].IsInherited -or+ $rules[0].AccessControlType -ne [Security.AccessControl.AccessControlType]::Allow) {+ throw 'Private ACL missing'+ }+ $reader = [IO.File]::OpenRead($path)+ try { if ($reader.Length -ne $content.Length) { throw 'Incomplete redirect' } }+ finally { $reader.Dispose() }+ $blocked = $false+ try { [IO.File]::Delete($path) } catch [IO.IOException] { $blocked = $true }+ if (-not $blocked) { throw 'Active redirect was not protected from deletion' }+ $blocked = $false+ try { [IO.File]::OpenWrite($path).Dispose() } catch [IO.IOException] { $blocked = $true }+ if (-not $blocked) { throw 'Active redirect was writable' }+ [Console]::Write('private;')+'''+ script = script.replace(" if (-not [NanobotBrowser]::Open($path))", check + " if (-not [NanobotBrowser]::Open($path))")+ script = script.replace(+ " if ($owned) { try { [IO.File]::Delete($path) } catch {} }",+ " if ($owned) { [IO.File]::Delete($path) }\n"+ " [Console]::Write('removed=' + (-not [IO.File]::Exists($path)))",+ )+ content = _redirect_html('http://localhost/#/?bootstrapSecret="/><script>$(test)&中文</script>')++ result = subprocess.run(+ ["powershell.exe", "-NoProfile", "-NonInteractive", "-STA", "-EncodedCommand",+ base64.b64encode(script.encode("utf-16-le")).decode("ascii")],+ input=base64.b64encode(content) + b"\n", capture_output=True, timeout=15,+ )++ assert result.returncode == (0 if opens else 1), result.stderr+ assert result.stdout == b"private;" + (b"1" if opens else b"") + b"removed=True"diff --git a/tests/webui/test_dev.py b/tests/webui/test_dev.pyindex dd522c654..f06a097f0 100644--- a/tests/webui/test_dev.py+++ b/tests/webui/test_dev.py@@ -93,14 +93,13 @@ def test_start_webui_dev_server_uses_vite_directly_and_sets_proxy_target(assert server.process is processcommand, kwargs = popen_calls[0]- assert command == ["node", str(vite_cli)]+ assert command == ["node", str(vite_cli), "--logLevel", "warn", "--clearScreen", "false"]assert kwargs["cwd"] == sourceassert kwargs["env"] == {"EXISTING": "value","NANOBOT_API_URL": "http://127.0.0.1:8899",}- assert output == ["WebUI dev server: http://127.0.0.1:5173/"]- assert "secret" not in output[0]+ assert output == []def test_dev_server_installs_locked_dependencies_when_vite_is_missing(tmp_path: Path) -> None: