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(cli): keep macOS bootstrap URLs out of argv [skip ci]
Xubin Ren29bf9f9ca71f
diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex 9c4e7fe03..104cf2b51 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -51,6 +51,9 @@ or replacing a backend. Use explicit `nanobot agent` for the Python terminal UIuntil the Desktop TUI attachment protocol is available.After Desktop is selected, a disconnect or incompatible reply ends that invocationwith an error; it never silently switches to Python or launches a replacement.+On macOS, browser URLs are delivered through native Launch Services rather than+command-line arguments. A failed native handoff does not fall back to `open` or+a `BROWSER` command, keeping bootstrap credentials out of launcher arguments.Any explicit subcommand or option—including `nanobot agent`,`nanobot webui --no-open`, config/workspace selectors, help, version, completion,diff --git a/nanobot/cli/webui_support.py b/nanobot/cli/webui_support.pyindex 4e737e016..2f658db0e 100644--- a/nanobot/cli/webui_support.py+++ b/nanobot/cli/webui_support.py@@ -1,7 +1,6 @@"""Shared WebUI setup, URL, health, and browser helpers."""import os-import subprocessimport sysimport timeimport webbrowser@@ -67,17 +66,43 @@ console = Console()def _launch_browser(url: str) -> bool:"""Open *url* and request a foreground browser window."""if sys.platform == "darwin":- result = subprocess.run(- ["open", url],- stdin=subprocess.DEVNULL,- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- check=False,- )- return result.returncode == 0+ return _launch_macos_browser(url)return bool(webbrowser.open(url, new=2, autoraise=True))+def _launch_macos_browser(url: str) -> bool:+ """Deliver URLs through Launch Services, never a credential-bearing argv."""+ import ctypes++ try:+ foundation = ctypes.CDLL(+ "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"+ )+ services = ctypes.CDLL("/System/Library/Frameworks/CoreServices.framework/CoreServices")+ foundation.CFURLCreateWithBytes.argtypes = [+ ctypes.c_void_p, ctypes.c_char_p, ctypes.c_long, ctypes.c_uint32, ctypes.c_void_p,+ ]+ foundation.CFURLCreateWithBytes.restype = ctypes.c_void_p+ foundation.CFRelease.argtypes = [ctypes.c_void_p]+ foundation.CFRelease.restype = None+ services.LSOpenCFURLRef.argtypes = [ctypes.c_void_p, ctypes.c_void_p]+ services.LSOpenCFURLRef.restype = ctypes.c_int32+ encoded = url.encode("utf-8")+ url_ref = foundation.CFURLCreateWithBytes(None, encoded, len(encoded), 0x08000100, None)+ if not url_ref:+ return False+ try:+ # HTTP URLs reach the preferred browser in a GURL Apple event, not+ # through `open <url>` or a BROWSER command's process arguments.+ return services.LSOpenCFURLRef(url_ref, None) == 0+ finally:+ foundation.CFRelease(url_ref)+ except (OSError, AttributeError, UnicodeError):+ # Callers may display exception text. Keep URLs out of error output and+ # never retry with a subprocess/controller that can expose credentials.+ return False++def _confirm_webui_action(message: str, *, yes: bool) -> None:"""Confirm a WebUI first-run mutation or fail clearly in non-interactive shells."""if yes:diff --git a/tests/cli/test_browser_launch.py b/tests/cli/test_browser_launch.pynew file mode 100644index 000000000..37bd2dacb--- /dev/null+++ b/tests/cli/test_browser_launch.py@@ -0,0 +1,107 @@+"""Credential-bearing browser URLs must not enter a macOS command line."""++import ctypes+import subprocess+from unittest.mock import MagicMock++import pytest++from nanobot.cli import desktop_target, webui_support+++def macos_url_services(monkeypatch):+ foundation = MagicMock()+ services = MagicMock()+ foundation.CFURLCreateWithBytes.return_value = 123+ services.LSOpenCFURLRef.return_value = 0++ def load(path):+ if path == "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation":+ return foundation+ assert path == "/System/Library/Frameworks/CoreServices.framework/CoreServices"+ return services++ monkeypatch.setattr(ctypes, "CDLL", load)+ monkeypatch.setattr(webui_support.sys, "platform", "darwin")+ monkeypatch.setenv("BROWSER", "unsafe-browser %s")+ monkeypatch.setattr(+ subprocess, "run", lambda *_a, **_kw: pytest.fail("URL reached subprocess")+ )+ monkeypatch.setattr(+ subprocess, "Popen", lambda *_a, **_kw: pytest.fail("URL reached process argv")+ )+ monkeypatch.setattr(+ webui_support.webbrowser, "open", lambda *_a, **_kw: pytest.fail("unsafe browser fallback")+ )+ return foundation, services++[email protected]("url", [+ "http://127.0.0.1:8765/",+ "http://127.0.0.1:8765/#/?bootstrapSecret=synthetic-only",+ "http://localhost:5173/#/?bootstrapSecret=quote%22%27%24%28%29%26",+ "http://[::1]:8765/#/中文?bootstrapSecret=synthetic-only",+])+def test_macos_uses_os_url_events_without_process_arguments(macos_url_services, capsys, url):+ foundation, services = macos_url_services+ assert webui_support._launch_browser(url) is True+ encoded = url.encode("utf-8")+ foundation.CFURLCreateWithBytes.assert_called_once_with(+ None, encoded, len(encoded), 0x08000100, None+ )+ services.LSOpenCFURLRef.assert_called_once_with(123, None)+ foundation.CFRelease.assert_called_once_with(123)+ assert capsys.readouterr() == ("", "")++[email protected]("failure", ["load", "symbol", "create", "open", "exception", "encoding"])+def test_macos_browser_failures_never_fall_back_or_log_url(+ macos_url_services, monkeypatch, capsys, failure,+):+ foundation, services = macos_url_services+ url = "http://localhost/#/?bootstrapSecret=synthetic-only"+ if failure in {"load", "symbol"}:+ error_type = OSError if failure == "load" else AttributeError+ monkeypatch.setattr(ctypes, "CDLL", MagicMock(side_effect=error_type(url)))+ elif failure == "create":+ foundation.CFURLCreateWithBytes.return_value = None+ elif failure == "open":+ services.LSOpenCFURLRef.return_value = -50+ elif failure == "exception":+ services.LSOpenCFURLRef.side_effect = OSError(url)+ else:+ url += "\ud800"+ assert webui_support._launch_browser(url) is False+ assert capsys.readouterr() == ("", "")+ if failure in {"open", "exception"}:+ foundation.CFRelease.assert_called_once_with(123)+ else:+ foundation.CFRelease.assert_not_called()++[email protected]("launch_status, exit_code", [(0, 0), (-50, 3)])+def test_desktop_handoff_uses_the_protected_shared_launcher(+ macos_url_services, monkeypatch, capsys, launch_status, exit_code,+):+ foundation, services = macos_url_services+ services.LSOpenCFURLRef.return_value = launch_status+ url = "http://localhost:8765/#/?bootstrapSecret=synthetic-only"+ calls = []++ class Target:+ def request(self, operation):+ calls.append(operation)+ return desktop_target.DesktopReply(+ "ready", frozenset({"webui"}), url if operation == "webui" else None,+ )++ monkeypatch.setattr(desktop_target, "_interactive_shell", lambda: True)+ monkeypatch.setattr(desktop_target, "discover_desktop_target", Target)+ monkeypatch.setattr(desktop_target, "_choose_target", lambda _: "desktop")+ assert desktop_target.dispatch_bare_desktop_target(["webui"]) == exit_code+ assert calls == ["status", "webui"]+ assert foundation.CFURLCreateWithBytes.call_args.args[1] == url.encode()+ output = capsys.readouterr()+ assert "synthetic-only" not in output.out + output.err+ assert "Using current Python" not in output.outdiff --git a/tests/cli/test_commands.py b/tests/cli/test_commands.pyindex cc5fd38bc..023628c89 100644--- a/tests/cli/test_commands.py+++ b/tests/cli/test_commands.py@@ -2564,17 +2564,17 @@ def test_open_webui_browser_reports_launch_failure(monkeypatch, capsys) -> None:)-def test_launch_browser_uses_macos_foreground_opener(monkeypatch) -> None:- seen: list[list[str]] = []+def test_launch_browser_uses_macos_url_services(monkeypatch) -> None:+ seen: list[str] = []monkeypatch.setattr(cli_webui_support.sys, "platform", "darwin")monkeypatch.setattr(- cli_webui_support.subprocess,- "run",- lambda command, **_kwargs: seen.append(command) or SimpleNamespace(returncode=0),+ cli_webui_support,+ "_launch_macos_browser",+ lambda url: seen.append(url) or True,)assert cli_webui_support._launch_browser("http://127.0.0.1:8765/") is True- assert seen == [["open", "http://127.0.0.1:8765/"]]+ assert seen == ["http://127.0.0.1:8765/"]def test_launch_browser_uses_default_browser_off_macos(monkeypatch) -> None: