diff --git a/docs/cli-reference.md b/docs/cli-reference.md index f600807e9..5c3d2aac0 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -33,6 +33,27 @@ python -m nanobot --version `python -m nanobot ...` is useful when the package is installed but the `nanobot` script is not on `PATH`. +### Coexisting with Nanobot Desktop + +The Python package and Nanobot Desktop keep separate runtimes, configuration, +workspaces, and state. When a running Desktop release publishes its private +terminal-access descriptor, an interactive bare `nanobot` or `nanobot webui` +asks which installation to use for that invocation. With no running Desktop +target, the command reports the current Python executable and continues normally. + +Choosing Desktop for `nanobot webui` opens its already-running browser workbench +and exits; closing the browser never stops the Desktop gateway. The current +Desktop discovery protocol does not yet advertise attach-only terminal chat, so +choosing Desktop for bare `nanobot` fails explicitly without starting, restarting, +or replacing a backend. Use explicit `nanobot agent` for the Python terminal UI +until the Desktop TUI attachment protocol is available. + +Any explicit subcommand or option—including `nanobot agent`, +`nanobot webui --no-open`, config/workspace selectors, help, version, completion, +and gateway lifecycle commands—keeps its existing Python meaning and never opens +the Desktop picker. Target choices are not remembered, and Desktop settings are +not copied into the Python installation. + ## Common Patterns Most day-to-day commands use the default config and workspace. Advanced or multi-instance runs usually pass both paths explicitly: diff --git a/nanobot/cli/desktop_target.py b/nanobot/cli/desktop_target.py new file mode 100644 index 000000000..9a46b5332 --- /dev/null +++ b/nanobot/cli/desktop_target.py @@ -0,0 +1,560 @@ +"""Discover and attach to an already-running Nanobot Desktop instance.""" + +from __future__ import annotations + +import ctypes +import json +import os +import socket +import stat +import struct +import sys +import time +import uuid +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Literal, cast +from urllib.parse import urlsplit + +_DESCRIPTOR_NAME = "instance-v1.json" +_MAX_MESSAGE_BYTES = 8192 +_PROTOCOL_TIMEOUT_S = 6.0 +_SCHEMA_VERSION = 1 + + +class DesktopTargetError(RuntimeError): + """Raised when a discovered Desktop target cannot be used safely.""" + + +@dataclass(frozen=True) +class DesktopReply: + """Validated reply from the Desktop rendezvous protocol.""" + + state: str + capabilities: frozenset[str] + webui_url: str | None = None + + +@dataclass(frozen=True) +class DesktopTarget: + """Authenticated-on-use handle for one advertised Desktop instance.""" + + instance_id: str + transport: Literal["unix", "namedPipe"] + address: str + + def request(self, operation: Literal["status", "webui"]) -> DesktopReply: + """Perform one bounded, side-effect-free Desktop rendezvous request.""" + payload = json.dumps( + { + "schemaVersion": _SCHEMA_VERSION, + "instanceId": self.instance_id, + "operation": operation, + }, + separators=(",", ":"), + ).encode("utf-8") + b"\n" + try: + if self.transport == "unix": + raw = _unix_exchange(self.address, payload) + else: + raw = _named_pipe_exchange(self.address, payload) + return _parse_reply(raw, expected_instance_id=self.instance_id) + except DesktopTargetError: + raise + except Exception as exc: + raise DesktopTargetError("Desktop connection unavailable") from exc + + +def discover_desktop_target() -> DesktopTarget | None: + """Return the current user's advertised Desktop target, if one exists.""" + directory = _desktop_terminal_directory() + if directory is None: + return None + descriptor = directory / _DESCRIPTOR_NAME + try: + descriptor.lstat() + except FileNotFoundError: + return None + except OSError as exc: + raise DesktopTargetError("Desktop discovery is unavailable") from exc + + raw = _read_private_descriptor(directory, descriptor) + return _parse_descriptor(raw, directory=directory) + + +def dispatch_bare_desktop_target(args: list[str]) -> int | None: + """Handle Desktop selection for a bare interactive command. + + ``None`` means the caller should continue through the current Python + environment. An integer means the invocation was handled here and should + exit with that status. + """ + if args not in ([], ["webui"]) or not _interactive_shell(): + return None + + try: + target = discover_desktop_target() + except DesktopTargetError: + _print_desktop_error( + "Nanobot Desktop discovery could not be authenticated. Restart Desktop, " + "or run `nanobot agent` to use this Python environment explicitly." + ) + return 3 + + if target is None: + _print_python_target() + return None + + try: + status = target.request("status") + except DesktopTargetError: + _print_desktop_error( + "Nanobot Desktop was discovered but did not accept an authenticated " + "connection. Restart Desktop, or run `nanobot agent` to use this Python " + "environment explicitly." + ) + return 3 + + if _choose_target(status) == "python": + _print_python_target() + return None + + # Revalidate after selection. A status probe is never treated as authority + # to reuse stale bootstrap data or silently choose another backend. + if not args: + try: + current = target.request("status") + except DesktopTargetError: + _print_desktop_error("Nanobot Desktop disconnected after it was selected.") + return 3 + if current.state != "ready": + _print_desktop_error(f"Nanobot Desktop is not ready ({current.state}).") + return 3 + _print_desktop_error( + "This Desktop version does not yet provide attach-only terminal chat. " + "Run `nanobot agent` to use this Python environment." + ) + return 4 + + try: + reply = target.request("webui") + url = _desktop_webui_url(reply) + from nanobot.cli.webui_support import _launch_browser + + opened = _launch_browser(url) + except DesktopTargetError: + _print_desktop_error("Nanobot Desktop disconnected or returned an incompatible WebUI.") + return 3 + if not opened: + _print_desktop_error("The default browser could not open Nanobot Desktop.") + return 3 + print("Connected to Nanobot Desktop. Closing the browser leaves Desktop running.") + return 0 + + +def _interactive_shell() -> bool: + try: + return sys.stdin.isatty() and sys.stdout.isatty() + except Exception: + return False + + +def _python_target_label() -> str: + return str(Path(sys.executable).resolve(strict=False)) + + +def _print_python_target() -> None: + print(f"Using current Python environment: {_python_target_label()}") + + +def _print_desktop_error(message: str) -> None: + print(f"{message} No backend was started.", file=sys.stderr) + + +def _choose_target(status: DesktopReply) -> Literal["desktop", "python"]: + detail = "" if status.state == "ready" else f" ({status.state})" + print("Nanobot Desktop is running. Choose a target for this invocation:") + print(f" 1. Nanobot Desktop{detail}") + print(f" 2. Current Python environment ({_python_target_label()})") + while True: + try: + answer = input("Target [1/2]: ").strip().lower() + except (EOFError, KeyboardInterrupt) as exc: + print(file=sys.stderr) + raise SystemExit(130) from exc + if answer in {"1", "desktop", "d"}: + return "desktop" + if answer in {"2", "python", "p"}: + return "python" + print("Enter 1 for Desktop or 2 for the current Python environment.") + + +def _desktop_terminal_directory() -> Path | None: + if sys.platform == "darwin": + root = os.environ.get("NANOBOT_DESKTOP_ROOT", "").strip() + base = Path(root).expanduser() if root else Path.home() / "Library/Application Support/Nanobot" + return base / "terminal" + if sys.platform == "win32": + override = os.environ.get("NANOBOT_DESKTOP_DATA_DIR", "").strip() + local_app_data = override or os.environ.get("LOCALAPPDATA", "").strip() + if not local_app_data: + return None + base = Path(os.path.expandvars(local_app_data)).expanduser() + if not override: + base /= "Nanobot" + return base / "terminal" + return None + + +def _read_private_descriptor(directory: Path, descriptor: Path) -> bytes: + if os.name == "nt": + _validate_windows_path(directory, directory=True) + _validate_windows_path(descriptor, directory=False) + try: + with descriptor.open("rb") as handle: + raw = handle.read(_MAX_MESSAGE_BYTES + 1) + except OSError as exc: + raise DesktopTargetError("Desktop descriptor could not be read") from exc + else: + directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0) + file_flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0) + try: + directory_fd = os.open(directory, directory_flags) + except OSError as exc: + raise DesktopTargetError("Desktop terminal directory is not private") from exc + try: + _validate_posix_stat(os.fstat(directory_fd), directory=True) + descriptor_fd = os.open(_DESCRIPTOR_NAME, file_flags, dir_fd=directory_fd) + try: + _validate_posix_stat(os.fstat(descriptor_fd), directory=False) + raw = os.read(descriptor_fd, _MAX_MESSAGE_BYTES + 1) + finally: + os.close(descriptor_fd) + except OSError as exc: + raise DesktopTargetError("Desktop descriptor could not be read safely") from exc + finally: + os.close(directory_fd) + if len(raw) > _MAX_MESSAGE_BYTES: + raise DesktopTargetError("Desktop descriptor is too large") + return raw + + +def _validate_posix_stat(value: os.stat_result, *, directory: bool) -> None: + expected_type = stat.S_ISDIR if directory else stat.S_ISREG + if ( + not expected_type(value.st_mode) + or value.st_uid != os.geteuid() + or stat.S_IMODE(value.st_mode) & 0o077 + ): + raise DesktopTargetError("Desktop discovery is not private to the current user") + + +def _validate_windows_path(path: Path, *, directory: bool) -> None: + try: + value = path.lstat() + except OSError as exc: + raise DesktopTargetError("Desktop discovery path is unavailable") from exc + expected_type = stat.S_ISDIR if directory else stat.S_ISREG + attributes = int(getattr(value, "st_file_attributes", 0)) + reparse = int(getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)) + if not expected_type(value.st_mode) or attributes & reparse: + raise DesktopTargetError("Desktop discovery path is not a private regular path") + + +def _parse_descriptor(raw: bytes, *, directory: Path) -> DesktopTarget: + try: + value: object = json.loads(raw.decode("utf-8")) + except (UnicodeError, json.JSONDecodeError) as exc: + raise DesktopTargetError("Desktop descriptor is invalid") from exc + if not isinstance(value, dict): + raise DesktopTargetError("Desktop descriptor is invalid") + fields = cast(dict[str, object], value) + schema_version = fields.get("schemaVersion") + instance_id = fields.get("instanceId") + transport = fields.get("transport") + address = fields.get("address") + if ( + type(schema_version) is not int + or schema_version != _SCHEMA_VERSION + or not isinstance(instance_id, str) + or not isinstance(transport, str) + or not isinstance(address, str) + ): + raise DesktopTargetError("Unsupported Desktop descriptor") + try: + uuid.UUID(instance_id) + except ValueError as exc: + raise DesktopTargetError("Desktop instance identity is invalid") from exc + + if sys.platform == "darwin": + expected = str(directory / "connect-v1.sock") + if transport != "unix" or address != expected: + raise DesktopTargetError("Unsupported Desktop transport") + selected_transport: Literal["unix", "namedPipe"] = "unix" + elif sys.platform == "win32": + expected = f"nanobot-desktop-v1-{instance_id}" + if transport != "namedPipe" or address != expected: + raise DesktopTargetError("Unsupported Desktop transport") + selected_transport = "namedPipe" + else: + raise DesktopTargetError("Nanobot Desktop is not supported on this platform") + return DesktopTarget(instance_id, selected_transport, address) + + +def _parse_reply(raw: bytes, *, expected_instance_id: str) -> DesktopReply: + if len(raw) > _MAX_MESSAGE_BYTES: + raise DesktopTargetError("Desktop reply is too large") + try: + value: object = json.loads(raw.decode("utf-8")) + except (UnicodeError, json.JSONDecodeError) as exc: + raise DesktopTargetError("Desktop reply is invalid") from exc + if not isinstance(value, dict): + raise DesktopTargetError("Desktop reply is invalid") + fields = cast(dict[str, object], value) + schema_version = fields.get("schemaVersion") + instance_id = fields.get("instanceId") + state_value = fields.get("state") + raw_capabilities = fields.get("capabilities") + webui_url = fields.get("webuiUrl") + if ( + type(schema_version) is not int + or schema_version != _SCHEMA_VERSION + or instance_id != expected_instance_id + or not isinstance(state_value, str) + or state_value not in {"ready", "busy", "unavailable"} + or not isinstance(raw_capabilities, list) + or webui_url is not None + and not isinstance(webui_url, str) + ): + raise DesktopTargetError("Desktop reply is incompatible") + capability_values = cast(list[object], raw_capabilities) + if any(not isinstance(item, str) for item in capability_values): + raise DesktopTargetError("Desktop reply is incompatible") + capabilities = frozenset(cast(list[str], capability_values)) + return DesktopReply(state=state_value, capabilities=capabilities, webui_url=webui_url) + + +def _desktop_webui_url(reply: DesktopReply) -> str: + if reply.state != "ready": + raise DesktopTargetError(f"Desktop is not ready ({reply.state})") + if "webui" not in reply.capabilities or not reply.webui_url: + raise DesktopTargetError("Desktop does not advertise WebUI attachment") + if reply.webui_url != reply.webui_url.strip() or any( + ord(character) < 0x20 or ord(character) == 0x7F for character in reply.webui_url + ): + raise DesktopTargetError("Desktop returned an invalid WebUI URL") + parsed = urlsplit(reply.webui_url) + if ( + parsed.scheme != "http" + or parsed.hostname not in {"127.0.0.1", "localhost", "::1"} + or parsed.username is not None + or parsed.password is not None + ): + raise DesktopTargetError("Desktop returned a non-loopback WebUI URL") + return reply.webui_url + + +def _unix_exchange(address: str, payload: bytes) -> bytes: + try: + value = os.lstat(address) + except OSError as exc: + raise DesktopTargetError("Desktop socket is unavailable") from exc + if ( + not stat.S_ISSOCK(value.st_mode) + or value.st_uid != os.geteuid() + or stat.S_IMODE(value.st_mode) & 0o077 + ): + raise DesktopTargetError("Desktop socket is not private to the current user") + + client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + client.settimeout(_PROTOCOL_TIMEOUT_S) + try: + client.connect(address) + if not _peer_is_current_user(client): + raise DesktopTargetError("Desktop socket peer identity did not match") + client.sendall(payload) + return _read_socket_line(client) + finally: + client.close() + + +def _peer_is_current_user(client: socket.socket) -> bool: + if sys.platform == "darwin": + uid = ctypes.c_uint() + gid = ctypes.c_uint() + library = ctypes.CDLL(None, use_errno=True) + getpeereid = library.getpeereid + getpeereid.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint)] + getpeereid.restype = ctypes.c_int + return getpeereid(client.fileno(), ctypes.byref(uid), ctypes.byref(gid)) == 0 and uid.value == os.geteuid() + peer_credential = getattr(socket, "SO_PEERCRED", None) + if peer_credential is None: + return False + raw = client.getsockopt(socket.SOL_SOCKET, peer_credential, struct.calcsize("3i")) + _pid, uid, _gid = struct.unpack("3i", raw) + return uid == os.geteuid() + + +def _read_socket_line(client: socket.socket) -> bytes: + data = bytearray() + deadline = time.monotonic() + _PROTOCOL_TIMEOUT_S + while len(data) <= _MAX_MESSAGE_BYTES: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise DesktopTargetError("Desktop response timed out") + client.settimeout(remaining) + chunk = client.recv(min(1024, _MAX_MESSAGE_BYTES + 1 - len(data))) + if not chunk: + break + newline = chunk.find(b"\n") + if newline >= 0: + data.extend(chunk[:newline]) + return bytes(data) + data.extend(chunk) + raise DesktopTargetError("Desktop disconnected or returned an oversized reply") + + +def _named_pipe_exchange(address: str, payload: bytes) -> bytes: + if sys.platform != "win32": + raise DesktopTargetError("Desktop named pipes are available only on Windows") + return _windows_pipe_request(address, payload) + + +def _windows_pipe_request(address: str, payload: bytes) -> bytes: + """Exchange one line over a bounded overlapped Windows named pipe.""" + from ctypes import wintypes + + loader = getattr(ctypes, "WinDLL", None) + if loader is None: # pragma: no cover - defensive for non-Windows runtimes + raise DesktopTargetError("Windows named pipe support is unavailable") + kernel32: Any = loader("kernel32", use_last_error=True) + + class Overlapped(ctypes.Structure): + _fields_ = [ + ("Internal", ctypes.c_size_t), + ("InternalHigh", ctypes.c_size_t), + ("Offset", wintypes.DWORD), + ("OffsetHigh", wintypes.DWORD), + ("hEvent", wintypes.HANDLE), + ] + + kernel32.WaitNamedPipeW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD] + kernel32.WaitNamedPipeW.restype = wintypes.BOOL + kernel32.CreateFileW.argtypes = [ + wintypes.LPCWSTR, + wintypes.DWORD, + wintypes.DWORD, + wintypes.LPVOID, + wintypes.DWORD, + wintypes.DWORD, + wintypes.HANDLE, + ] + kernel32.CreateFileW.restype = wintypes.HANDLE + kernel32.CreateEventW.argtypes = [ + wintypes.LPVOID, + wintypes.BOOL, + wintypes.BOOL, + wintypes.LPCWSTR, + ] + kernel32.CreateEventW.restype = wintypes.HANDLE + io_arguments = [ + wintypes.HANDLE, + wintypes.LPVOID, + wintypes.DWORD, + ctypes.POINTER(wintypes.DWORD), + ctypes.POINTER(Overlapped), + ] + kernel32.WriteFile.argtypes = io_arguments + kernel32.WriteFile.restype = wintypes.BOOL + kernel32.ReadFile.argtypes = io_arguments + kernel32.ReadFile.restype = wintypes.BOOL + kernel32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD] + kernel32.WaitForSingleObject.restype = wintypes.DWORD + kernel32.GetOverlappedResult.argtypes = [ + wintypes.HANDLE, + ctypes.POINTER(Overlapped), + ctypes.POINTER(wintypes.DWORD), + wintypes.BOOL, + ] + kernel32.GetOverlappedResult.restype = wintypes.BOOL + kernel32.CancelIoEx.argtypes = [wintypes.HANDLE, ctypes.POINTER(Overlapped)] + kernel32.CancelIoEx.restype = wintypes.BOOL + kernel32.CloseHandle.argtypes = [wintypes.HANDLE] + kernel32.CloseHandle.restype = wintypes.BOOL + + generic_read = 0x80000000 + generic_write = 0x40000000 + open_existing = 3 + file_flag_overlapped = 0x40000000 + error_io_pending = 997 + wait_object_0 = 0 + invalid_handle = ctypes.c_void_p(-1).value + pipe_name = rf"\\.\pipe\{address}" + deadline = time.monotonic() + _PROTOCOL_TIMEOUT_S + + remaining_ms = max(1, int((deadline - time.monotonic()) * 1000)) + if not kernel32.WaitNamedPipeW(pipe_name, remaining_ms): + raise DesktopTargetError("Desktop named pipe is unavailable") + handle = kernel32.CreateFileW( + pipe_name, + generic_read | generic_write, + 0, + None, + open_existing, + file_flag_overlapped, + None, + ) + if handle == invalid_handle: + raise DesktopTargetError("Desktop named pipe could not be opened") + + def transfer(function: Any, buffer: Any, size: int) -> int: + event = kernel32.CreateEventW(None, True, False, None) + if not event: + raise DesktopTargetError("Desktop named pipe event could not be created") + try: + overlapped = Overlapped() + overlapped.hEvent = event + transferred = wintypes.DWORD() + complete = function( + handle, + buffer, + size, + ctypes.byref(transferred), + ctypes.byref(overlapped), + ) + if not complete and ctypes.get_last_error() != error_io_pending: + raise DesktopTargetError("Desktop named pipe I/O failed") + if not complete: + wait_ms = max(1, int((deadline - time.monotonic()) * 1000)) + if kernel32.WaitForSingleObject(event, wait_ms) != wait_object_0: + kernel32.CancelIoEx(handle, ctypes.byref(overlapped)) + raise DesktopTargetError("Desktop named pipe response timed out") + if not kernel32.GetOverlappedResult( + handle, ctypes.byref(overlapped), ctypes.byref(transferred), False + ): + raise DesktopTargetError("Desktop named pipe I/O failed") + return int(transferred.value) + finally: + kernel32.CloseHandle(event) + + try: + outgoing = ctypes.create_string_buffer(payload) + if transfer(kernel32.WriteFile, outgoing, len(payload)) != len(payload): + raise DesktopTargetError("Desktop named pipe write was incomplete") + data = bytearray() + while len(data) <= _MAX_MESSAGE_BYTES: + incoming = ctypes.create_string_buffer( + min(1024, _MAX_MESSAGE_BYTES + 1 - len(data)) + ) + count = transfer(kernel32.ReadFile, incoming, len(incoming)) + if count <= 0: + break + chunk = incoming.raw[:count] + newline = chunk.find(b"\n") + if newline >= 0: + data.extend(chunk[:newline]) + return bytes(data) + data.extend(chunk) + finally: + kernel32.CloseHandle(handle) + raise DesktopTargetError("Desktop disconnected or returned an oversized reply") diff --git a/nanobot/cli/entry.py b/nanobot/cli/entry.py index 65ae4d28e..6adfc2443 100644 --- a/nanobot/cli/entry.py +++ b/nanobot/cli/entry.py @@ -79,6 +79,14 @@ def main() -> None: dispatch_args = ["agent", *agent_args] if agent_args is not None else raw_args set_cli_process_identity(dispatch_args) _configure_windows_console() + if not shell_completion: + from nanobot.cli.desktop_target import dispatch_bare_desktop_target + + desktop_exit = dispatch_bare_desktop_target(raw_args) + if desktop_exit is not None: + if desktop_exit: + raise SystemExit(desktop_exit) + return root_agent_alias = agent_args is not None and raw_args[:1] != ["agent"] if agent_args is not None and ( root_agent_alias or _native_tui_candidate(dispatch_args) diff --git a/tests/cli/test_desktop_target.py b/tests/cli/test_desktop_target.py new file mode 100644 index 000000000..69cf07040 --- /dev/null +++ b/tests/cli/test_desktop_target.py @@ -0,0 +1,275 @@ +import json +import os +import socket +import tempfile +import threading +from pathlib import Path + +import pytest + +from nanobot.cli import desktop_target +from nanobot.cli.desktop_target import ( + DesktopReply, + DesktopTarget, + DesktopTargetError, + _desktop_webui_url, + _parse_descriptor, + _parse_reply, + discover_desktop_target, + dispatch_bare_desktop_target, +) + + +def _write_descriptor(directory: Path, *, instance_id: str, transport: str, address: str) -> None: + directory.mkdir(mode=0o700) + descriptor = directory / "instance-v1.json" + descriptor.write_text( + json.dumps( + { + "schemaVersion": 1, + "instanceId": instance_id, + "transport": transport, + "address": address, + } + ), + encoding="utf-8", + ) + descriptor.chmod(0o600) + + +def test_macos_discovery_uses_private_versioned_descriptor(monkeypatch, tmp_path: Path) -> None: + instance_id = "0b47107a-cd31-4711-b1ca-3b53dcedf90a" + terminal = tmp_path / "terminal" + address = str(terminal / "connect-v1.sock") + _write_descriptor( + terminal, + instance_id=instance_id, + transport="unix", + address=address, + ) + monkeypatch.setattr(desktop_target.sys, "platform", "darwin") + monkeypatch.setenv("NANOBOT_DESKTOP_ROOT", str(tmp_path)) + + assert discover_desktop_target() == DesktopTarget(instance_id, "unix", address) + + +def test_discovery_rejects_non_private_directory(monkeypatch, tmp_path: Path) -> None: + instance_id = "0b47107a-cd31-4711-b1ca-3b53dcedf90a" + terminal = tmp_path / "terminal" + _write_descriptor( + terminal, + instance_id=instance_id, + transport="unix", + address=str(terminal / "connect-v1.sock"), + ) + terminal.chmod(0o755) + monkeypatch.setattr(desktop_target.sys, "platform", "darwin") + monkeypatch.setenv("NANOBOT_DESKTOP_ROOT", str(tmp_path)) + + with pytest.raises(DesktopTargetError, match="private"): + discover_desktop_target() + + +def test_descriptor_transport_is_bound_to_platform(monkeypatch, tmp_path: Path) -> None: + instance_id = "0b47107a-cd31-4711-b1ca-3b53dcedf90a" + raw = json.dumps( + { + "schemaVersion": 1, + "instanceId": instance_id, + "transport": "namedPipe", + "address": f"nanobot-desktop-v1-{instance_id}", + } + ).encode() + monkeypatch.setattr(desktop_target.sys, "platform", "win32") + + assert _parse_descriptor(raw, directory=tmp_path) == DesktopTarget( + instance_id, + "namedPipe", + f"nanobot-desktop-v1-{instance_id}", + ) + + +@pytest.mark.skipif(os.name == "nt", reason="Unix-domain socket protocol") +def test_unix_request_revalidates_instance_identity() -> None: + instance_id = "0b47107a-cd31-4711-b1ca-3b53dcedf90a" + with tempfile.TemporaryDirectory(prefix="nb-desktop-", dir="/tmp") as temporary: + address = Path(temporary) / "connect-v1.sock" + server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + server.bind(str(address)) + address.chmod(0o600) + server.listen(1) + received: list[dict[str, object]] = [] + + def serve() -> None: + client, _ = server.accept() + with client: + request = client.makefile("rb").readline() + received.append(json.loads(request)) + client.sendall( + json.dumps( + { + "schemaVersion": 1, + "instanceId": instance_id, + "state": "ready", + "capabilities": ["webui"], + } + ).encode() + + b"\n" + ) + + thread = threading.Thread(target=serve) + thread.start() + try: + reply = DesktopTarget(instance_id, "unix", str(address)).request("status") + finally: + thread.join(timeout=2) + server.close() + + assert reply == DesktopReply("ready", frozenset({"webui"})) + assert received == [ + { + "schemaVersion": 1, + "instanceId": instance_id, + "operation": "status", + } + ] + + +def test_webui_url_requires_ready_capability_and_loopback() -> None: + assert ( + _desktop_webui_url( + DesktopReply( + "ready", + frozenset({"webui"}), + "http://127.0.0.1:8765/#/?bootstrapSecret=private", + ) + ) + == "http://127.0.0.1:8765/#/?bootstrapSecret=private" + ) + with pytest.raises(DesktopTargetError, match="non-loopback"): + _desktop_webui_url( + DesktopReply("ready", frozenset({"webui"}), "https://example.com/") + ) + + +def test_reply_must_match_selected_instance() -> None: + raw = json.dumps( + { + "schemaVersion": 1, + "instanceId": "7ebaf7ba-194e-4df5-a9a0-b9a760086a89", + "state": "ready", + "capabilities": ["webui"], + } + ).encode() + + with pytest.raises(DesktopTargetError, match="incompatible"): + _parse_reply( + raw, + expected_instance_id="0b47107a-cd31-4711-b1ca-3b53dcedf90a", + ) + + +def test_non_bare_or_noninteractive_invocations_do_not_discover(monkeypatch) -> None: + monkeypatch.setattr( + desktop_target, + "discover_desktop_target", + lambda: pytest.fail("explicit invocation must not discover Desktop"), + ) + monkeypatch.setattr(desktop_target, "_interactive_shell", lambda: True) + + assert dispatch_bare_desktop_target(["webui", "--no-open"]) is None + assert dispatch_bare_desktop_target(["agent"]) is None + + monkeypatch.setattr(desktop_target, "_interactive_shell", lambda: False) + assert dispatch_bare_desktop_target([]) is None + assert dispatch_bare_desktop_target(["webui"]) is None + + +def test_absent_desktop_selects_current_python(monkeypatch, capsys) -> None: + monkeypatch.setattr(desktop_target, "_interactive_shell", lambda: True) + monkeypatch.setattr(desktop_target, "discover_desktop_target", lambda: None) + + assert dispatch_bare_desktop_target([]) is None + assert "Using current Python environment:" in capsys.readouterr().out + + +def test_python_choice_does_not_request_desktop_operation(monkeypatch, capsys) -> None: + calls: list[str] = [] + + class Target: + def request(self, operation: str) -> DesktopReply: + calls.append(operation) + return DesktopReply("ready", frozenset({"webui"})) + + monkeypatch.setattr(desktop_target, "_interactive_shell", lambda: True) + monkeypatch.setattr(desktop_target, "discover_desktop_target", Target) + monkeypatch.setattr(desktop_target, "_choose_target", lambda _status: "python") + + assert dispatch_bare_desktop_target(["webui"]) is None + assert calls == ["status"] + assert "Using current Python environment:" in capsys.readouterr().out + + +def test_desktop_webui_selection_revalidates_and_opens_browser(monkeypatch, capsys) -> None: + calls: list[str] = [] + browser_urls: list[str] = [] + url = "http://localhost:8765/#/?bootstrapSecret=private" + + class Target: + def request(self, operation: str) -> DesktopReply: + calls.append(operation) + return 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 _status: "desktop") + monkeypatch.setattr( + "nanobot.cli.webui_support._launch_browser", + lambda value: browser_urls.append(value) or True, + ) + + assert dispatch_bare_desktop_target(["webui"]) == 0 + assert calls == ["status", "webui"] + assert browser_urls == [url] + output = capsys.readouterr().out + assert "Closing the browser leaves Desktop running" in output + assert "bootstrapSecret" not in output + + +def test_desktop_tui_selection_fails_without_fallback(monkeypatch, capsys) -> None: + calls: list[str] = [] + + class Target: + def request(self, operation: str) -> DesktopReply: + calls.append(operation) + return DesktopReply("ready", frozenset({"webui"})) + + monkeypatch.setattr(desktop_target, "_interactive_shell", lambda: True) + monkeypatch.setattr(desktop_target, "discover_desktop_target", Target) + monkeypatch.setattr(desktop_target, "_choose_target", lambda _status: "desktop") + + assert dispatch_bare_desktop_target([]) == 4 + assert calls == ["status", "status"] + error = capsys.readouterr().err + assert "does not yet provide attach-only terminal chat" in error + assert "No backend was started" in error + + +def test_disconnect_after_desktop_selection_never_falls_back(monkeypatch, capsys) -> None: + calls = 0 + + class Target: + def request(self, _operation: str) -> DesktopReply: + nonlocal calls + calls += 1 + if calls == 1: + return DesktopReply("ready", frozenset({"webui"})) + raise DesktopTargetError("disconnected") + + monkeypatch.setattr(desktop_target, "_interactive_shell", lambda: True) + monkeypatch.setattr(desktop_target, "discover_desktop_target", Target) + monkeypatch.setattr(desktop_target, "_choose_target", lambda _status: "desktop") + + assert dispatch_bare_desktop_target(["webui"]) == 3 + assert calls == 2 + assert "No backend was started" in capsys.readouterr().err diff --git a/tests/cli/test_entry.py b/tests/cli/test_entry.py index bee8a9ce2..861ade34e 100644 --- a/tests/cli/test_entry.py +++ b/tests/cli/test_entry.py @@ -3,6 +3,8 @@ import subprocess import sys from pathlib import Path +import pytest + from nanobot.cli import entry from nanobot.cli.entry import _agent_invocation_args, _native_tui_candidate @@ -82,6 +84,22 @@ def test_root_alias_dispatches_the_shared_agent_command(monkeypatch) -> None: } +def test_desktop_handled_bare_invocation_does_not_start_python(monkeypatch) -> None: + from nanobot.cli import desktop_target + + monkeypatch.setattr(entry.sys, "argv", ["nanobot", "webui"]) + monkeypatch.setattr(entry, "set_cli_process_identity", lambda _args: None) + monkeypatch.setattr(entry, "_configure_windows_console", lambda: None) + monkeypatch.setattr(desktop_target, "dispatch_bare_desktop_target", lambda _args: 0) + monkeypatch.setattr( + entry, + "_run_agent", + lambda *_args, **_kwargs: pytest.fail("Python agent must not start"), + ) + + entry.main() + + def test_native_agent_invocations_use_the_lightweight_entrypoint() -> None: assert _native_tui_candidate(["agent"]) assert _native_tui_candidate(["agent", "--session", "websocket:chat"])