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
+130
-103
@@ -8,7 +8,7 @@ from contextlib import contextmanager, suppress
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import pytest
|
||||
from 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(
|
||||
@pytest.mark.parametrize("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:") == 1
|
||||
data = json.loads(config_file.read_text(encoding="utf-8"))
|
||||
websocket = data["channels"]["websocket"]
|
||||
assert websocket["enabled"] is True
|
||||
assert websocket["host"] == "127.0.0.1"
|
||||
assert websocket["port"] == 8899
|
||||
assert websocket["websocketRequiresToken"] is True
|
||||
assert isinstance(websocket["tokenIssueSecret"], str)
|
||||
assert len(websocket["tokenIssueSecret"]) >= 32
|
||||
assert data["agents"]["defaults"]["workspace"] == str(workspace)
|
||||
assert seen["templates"] == workspace
|
||||
assert seen["templates_options"] == {"silent": True}
|
||||
options = seen["start_options"]
|
||||
assert options.port == 18888
|
||||
assert 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_output
|
||||
assert seen["lease_release_wait_for_stop"] is False
|
||||
assert "stop_timeout" not in seen
|
||||
|
||||
@@ -2253,8 +2260,26 @@ def test_webui_announces_existing_config_once(monkeypatch, tmp_path: Path, expli
|
||||
result = 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.stdout
|
||||
|
||||
|
||||
def 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)
|
||||
|
||||
@contextmanager
|
||||
def 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 == 18888
|
||||
assert 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_running
|
||||
assert seen["opened_url"] == browser_url
|
||||
assert seen["dev_running"] is False
|
||||
assert seen["dev_running_at_release"] is False
|
||||
assert 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 == 0
|
||||
assert 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.stdout
|
||||
assert 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.stdout
|
||||
assert "Quick Start" not in resumed.stdout
|
||||
assert json.loads(config_file.read_text(encoding="utf-8")) == saved_config
|
||||
assert 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) -> Non
|
||||
|
||||
assert 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) -> No
|
||||
|
||||
def 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"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("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"] = kwargs
|
||||
self.paths = kwargs["paths"]
|
||||
self.status_calls = 0
|
||||
|
||||
def 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.stdout
|
||||
assert 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 False
|
||||
output = capsys.readouterr().out
|
||||
rendered = " ".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 rendered
|
||||
assert "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 = 0
|
||||
|
||||
class _FakeRuntime:
|
||||
@@ -2789,18 +2775,26 @@ def test_attach_to_background_gateway_follows_only_new_logs(capsys, tmp_path: Pa
|
||||
nonlocal polls
|
||||
if 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 += 1
|
||||
return
|
||||
raise KeyboardInterrupt
|
||||
|
||||
cli_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 output
|
||||
assert "historical log" not in output
|
||||
|
||||
|
||||
@@ -2869,20 +2863,41 @@ def test_attach_to_background_gateway_checks_owned_sidecar(tmp_path: Path) -> No
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dev", [False, True])
|
||||
@pytest.mark.parametrize("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: Pat
|
||||
result = 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.stdout
|
||||
assert "--port" in result.stdout
|
||||
assert "--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.stdout
|
||||
assert "do-not-leak" not in result.stdout
|
||||
|
||||
|
||||
|
||||
@@ -1,11 +1,147 @@
|
||||
import os
|
||||
import shlex
|
||||
import sys
|
||||
import webbrowser
|
||||
from io import StringIO
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from urllib.parse import quote
|
||||
|
||||
import pytest
|
||||
from rich.console import Console
|
||||
|
||||
from nanobot.cli import webui_support
|
||||
from nanobot.cli.webui_support import _prepare_webui_bundle_for_gateway
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
|
||||
@pytest.mark.parametrize("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
|
||||
|
||||
|
||||
@pytest.mark.parametrize("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",
|
||||
[
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Windows redirect, secret transport and cleanup regressions."""
|
||||
|
||||
import base64
|
||||
import ctypes
|
||||
import io
|
||||
import 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() == ("", "")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("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() == ("", "")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("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() == ("", "")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("launcher", ["win32", "linux"], indirect=True)
|
||||
def test_startup_timeout_kills_helper_and_drains_pipe_reader(launcher, monkeypatch):
|
||||
process, _ = launcher
|
||||
exited = threading.Event()
|
||||
@@ -481,9 +485,53 @@ def test_native_private_file_permissions_sharing_and_cleanup(tmp_path, monkeypat
|
||||
assert 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/")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("launcher", ["linux"], indirect=True)
|
||||
@pytest.mark.parametrize("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.err
|
||||
@@ -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
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
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",
|
||||
)
|
||||
@pytest.mark.parametrize("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"
|
||||
Reference in new issue
Block a user