diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 201fac4b2..c537a0774 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -44,11 +44,11 @@ reports the current Python executable and continues normally. A virtual environment's executable is shown without resolving it to its base interpreter. Choosing Desktop for `nanobot webui` opens its already-running browser workbench -and exits; closing the browser never stops the Desktop gateway. The current -Python client and Desktop discovery protocol do not yet support 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. +and exits; closing the browser never stops the Desktop gateway. Choosing Desktop +for bare `nanobot` opens the terminal UI against that same running backend when +the Desktop host, gateway and terminal client support terminal protocol 1. Older +versions fail explicitly with update guidance. Use explicit `nanobot agent` for +the original Python terminal UI. After Desktop is selected, a disconnect or incompatible reply ends that invocation with an error; it never silently switches to Python or launches a replacement. On macOS, browser URLs are delivered through native Launch Services rather than @@ -77,6 +77,21 @@ and gateway lifecycle commands—keeps its existing Python meaning and never ope the Desktop picker. Target choices are not remembered, and Desktop settings are not copied into the Python installation. +Desktop terminal credentials are short-lived WebSocket/API tokens obtained through +the authenticated current-user rendezvous. The TUI receives them through a bounded +anonymous pipe, not command arguments, environment variables or temporary files. +Its environment contains only a trusted resolver command and public instance IDs. +The resolver verifies the selected Desktop and gateway again for every credential +refresh. The gateway identity is also checked before any WebSocket mutation. This +mode does not acquire a gateway lifecycle lease: client exit leaves Desktop running, +and disconnect never automatically reconnects or replays an uncertain task. + +Desktop-only distributions use the narrow `nanobot-desktop-tui` entrypoint inside +their existing private runtime; it is not a replacement for the full Python CLI. +They must ship this engine entrypoint and a matching terminal client together. +The client cache can be kept inside Desktop's data root without reading or writing +the separate Python installation's config. No additional system Python is needed. + ## 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/channels/websocket/runtime.py b/nanobot/channels/websocket/runtime.py index d84b7e9e3..b5f1670ca 100644 --- a/nanobot/channels/websocket/runtime.py +++ b/nanobot/channels/websocket/runtime.py @@ -809,6 +809,9 @@ class WebSocketChannel(BaseChannel): "event": "ready", "chat_id": default_chat_id, "client_id": client_id, + **({"terminal": { + "protocolVersion": 1, "gatewayId": self.gateway.tokens.instance_id, + }} if _query_first(query, "terminal_protocol") == "1" else {}), }, ensure_ascii=False, ) diff --git a/nanobot/cli/desktop_target.py b/nanobot/cli/desktop_target.py index 1b44c9bd9..9e352f676 100644 --- a/nanobot/cli/desktop_target.py +++ b/nanobot/cli/desktop_target.py @@ -34,6 +34,7 @@ class DesktopReply: state: str capabilities: frozenset[str] webui_url: str | None = None + tui: dict[str, object] | None = None @dataclass(frozen=True) @@ -44,7 +45,7 @@ class DesktopTarget: transport: Literal["unix", "namedPipe"] address: str - def request(self, operation: Literal["status", "webui"]) -> DesktopReply: + def request(self, operation: Literal["status", "webui", "tui"]) -> DesktopReply: """Perform one bounded, side-effect-free Desktop rendezvous request.""" payload = json.dumps( { @@ -120,9 +121,6 @@ def dispatch_bare_desktop_target(args: list[str]) -> int | None: _print_python_target() return None - if not args: - print("Desktop terminal chat attachment is not supported by this Python client yet.") - if _choose_target(status) == "python": _print_python_target() return None @@ -130,19 +128,13 @@ def dispatch_bare_desktop_target(args: list[str]) -> int | 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: + from nanobot.cli.desktop_tui import launch_desktop_tui + try: - current = target.request("status") + return launch_desktop_tui(target) except DesktopTargetError: - _print_desktop_error("Nanobot Desktop disconnected after it was selected.") + _print_desktop_error("Desktop terminal attachment is unavailable or incompatible. Update Desktop and nanobot, then try again.") return 3 - if current.state != "ready": - _print_desktop_error(f"Nanobot Desktop is not ready ({current.state}).") - return 3 - _print_desktop_error( - "This Python client does not yet provide attach-only terminal chat. " - "Run `nanobot agent` to use this Python environment." - ) - return 4 try: reply = target.request("webui") @@ -348,7 +340,13 @@ def _parse_reply(raw: bytes, *, expected_instance_id: str) -> DesktopReply: 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) + tui = fields.get("tui") + if tui is not None and not isinstance(tui, dict): + raise DesktopTargetError("Desktop terminal connection is incompatible") + return DesktopReply( + state=state_value, capabilities=capabilities, webui_url=webui_url, + tui=cast(dict[str, object] | None, tui), + ) def _desktop_webui_url(reply: DesktopReply) -> str: diff --git a/nanobot/cli/desktop_tui.py b/nanobot/cli/desktop_tui.py new file mode 100644 index 000000000..2a85e4e7b --- /dev/null +++ b/nanobot/cli/desktop_tui.py @@ -0,0 +1,187 @@ +"""Strict Desktop client entrypoint and pipe-only, current-user credential resolver. + +Unlike the normal TUI launcher, this module never loads a Config or acquires a +gateway lease. The resolver is also executable with ``python -I -S ``. +""" + +from __future__ import annotations + +import json +import os +import socket +import stat +import subprocess +import sys +import uuid +from pathlib import Path +from typing import cast +from urllib.parse import urlsplit + +if __name__ == "__main__": + # Only the package beside this trusted script, not cwd/user-site/PYTHONPATH. + sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +from nanobot.cli.desktop_target import ( + DesktopTarget, + DesktopTargetError, + discover_desktop_target, +) + +PROTOCOL_VERSION = 1 +_MAX_BYTES = 8192 + + +def _connection(target: DesktopTarget, gateway_id: str | None = None) -> dict[str, object]: + reply = target.request("tui") + value = reply.tui + if reply.state != "ready" or "tui" not in reply.capabilities or value is None: + raise DesktopTargetError("Desktop does not support terminal attachment") + identity = value.get("gatewayId") + if type(value.get("protocolVersion")) is not int or value["protocolVersion"] != 1: + raise DesktopTargetError("Unsupported terminal protocol") + if not isinstance(identity, str) or (gateway_id is not None and identity != gateway_id): + raise DesktopTargetError("Desktop gateway identity changed") + try: + uuid.UUID(identity) + except ValueError as exc: + raise DesktopTargetError("Invalid gateway identity") from exc + api = _endpoint(value.get("apiUrl"), websocket=False) + ws = _endpoint(value.get("wsUrl"), websocket=True) + if (api.hostname, api.port or 80) != (ws.hostname, ws.port or 80) or api.path not in {"", "/"}: + raise DesktopTargetError("Terminal endpoints must share the same loopback listener") + for key in ("wsToken", "apiToken"): + token = value.get(key) + if not isinstance(token, str) or not 1 <= len(token) <= 2048 or any( + ord(char) < 33 or ord(char) > 126 for char in token + ): + raise DesktopTargetError("Invalid terminal credentials") + # Do not forward unknown fields or untrusted executable/config paths. + return {key: value[key] for key in ( + "protocolVersion", "gatewayId", "apiUrl", "wsUrl", "wsToken", "apiToken", + )} + + +def _endpoint(value: object, *, websocket: bool): + if not isinstance(value, str) or "\\" in value or any( + ord(char) < 33 or ord(char) == 127 for char in value + ): + raise DesktopTargetError("Invalid terminal endpoint") + try: + parsed = urlsplit(value) + port = parsed.port + except ValueError as exc: + raise DesktopTargetError("Invalid terminal endpoint") from exc + if ( + parsed.scheme != ("ws" if websocket else "http") + or parsed.hostname not in {"127.0.0.1", "::1"} + or port == 0 + or parsed.username is not None or parsed.password is not None + or parsed.query or parsed.fragment + ): + raise DesktopTargetError("Terminal endpoint is not a literal loopback address") + return parsed + + +def resolve_request(raw: bytes) -> dict[str, object]: + """Re-discover the selected Desktop; never substitute a newly started instance.""" + if len(raw) > _MAX_BYTES: + raise DesktopTargetError("Invalid resolver request") + value: object = json.loads(raw) + if not isinstance(value, dict): + raise DesktopTargetError("Invalid resolver request") + fields = cast(dict[str, object], value) + identity, gateway_id = fields.get("instanceId"), fields.get("gatewayId") + if not isinstance(identity, str) or not isinstance(gateway_id, str): + raise DesktopTargetError("Invalid resolver identity") + target = discover_desktop_target() + if target is None or target.instance_id != identity: + raise DesktopTargetError("Selected Desktop disconnected") + return _connection(target, gateway_id) + + +def launch_desktop_tui(target: DesktopTarget) -> int: + from nanobot.cli.tui_launcher import TuiUnavailableError, resolve_tui_command + + process: subprocess.Popen[bytes] | None = None + try: + current = _connection(target) + # Resolve/install only the matching terminal client, never a backend. + cache = os.environ.get("NANOBOT_DESKTOP_CLIENT_CACHE") + if cache is not None and not Path(cache).is_absolute(): + raise DesktopTargetError("Desktop client cache must be absolute") + command = resolve_tui_command(data_dir=Path(cache)) if cache else resolve_tui_command() + probe = subprocess.run( + [*command, "--desktop-protocol"], capture_output=True, timeout=15, check=False, + ) + if probe.returncode != 0 or probe.stdout.strip() != b"1": + raise DesktopTargetError("The terminal client does not support Desktop attachment") + env = {key: value for key, value in os.environ.items() if not key.startswith("NANOBOT_TUI_")} + env["NANOBOT_TUI_DESKTOP_RESOLVER"] = json.dumps([ + sys.executable, "-I", "-S", str(Path(__file__).resolve()), "--resolve", + ]) + env["NANOBOT_TUI_DESKTOP_TARGET"] = json.dumps({ + "instanceId": target.instance_id, "gatewayId": current["gatewayId"], + }) + process = subprocess.Popen(command, env=env) + code = process.wait() + return 0 if code == 90 else code + except (OSError, ValueError, subprocess.SubprocessError, TuiUnavailableError) as exc: + raise DesktopTargetError("Desktop terminal attachment failed") from exc + finally: + if process is not None and process.poll() is None: + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + + +def main() -> None: + args = sys.argv[1:] + if args == ["--resolve"]: + try: + # Secret output is permitted only through a pipe captured by our TUI. + if not _anonymous_output(sys.stdout.fileno()): + raise DesktopTargetError("Resolver requires a pipe") + raw = sys.stdin.buffer.readline(_MAX_BYTES + 1) + if not raw.endswith(b"\n"): + raise DesktopTargetError("Incomplete resolver request") + payload = json.dumps(resolve_request(raw), separators=(",", ":")).encode() + if len(payload) > _MAX_BYTES: + raise DesktopTargetError("Resolver response is too large") + sys.stdout.buffer.write(payload + b"\n") + return + except Exception: + raise SystemExit(3) from None # Never print credential-bearing exceptions. + if args == ["--protocol"]: + print(PROTOCOL_VERSION) + return + if args or os.environ.get("_NANOBOT_COMPLETE") or not sys.stdin.isatty() or not sys.stdout.isatty(): + raise SystemExit(2) + try: + target = discover_desktop_target() + if target is None: + raise DesktopTargetError("Desktop is absent") + expected = os.environ.get("NANOBOT_DESKTOP_EXPECTED_INSTANCE") + if expected is not None and target.instance_id != expected: + raise DesktopTargetError("Selected Desktop changed") + raise SystemExit(launch_desktop_tui(target)) + except DesktopTargetError: + print("Desktop terminal connection unavailable. Start or update Desktop; no backend was started.", file=sys.stderr) + raise SystemExit(3) from None + + +def _anonymous_output(fd: int) -> bool: + """Bun uses an unnamed Unix socket pair for its captured subprocess stdout.""" + mode = os.fstat(fd).st_mode + if stat.S_ISFIFO(mode): + return True + if os.name == "posix" and stat.S_ISSOCK(mode): + with socket.fromfd(fd, socket.AF_UNIX, socket.SOCK_STREAM) as stream: + return stream.getsockname() == "" and stream.getpeername() == "" + return False + + +if __name__ == "__main__": + main() diff --git a/nanobot/cli/tui_launcher.py b/nanobot/cli/tui_launcher.py index b0ddfb487..e12f83655 100644 --- a/nanobot/cli/tui_launcher.py +++ b/nanobot/cli/tui_launcher.py @@ -86,7 +86,7 @@ def launch_tui( """Run the native TUI against the shared local gateway.""" chat_id = _initial_tui_chat_id(session_id) tui_workspace = _initial_tui_workspace(workspace_override) - command = _resolve_tui_command() + command = resolve_tui_command() base_url, bootstrap_secret = _tui_gateway_connection(config) gateway: _GatewayHandle | None = None process: subprocess.Popen[Any] | None = None @@ -94,6 +94,8 @@ def launch_tui( env = os.environ.copy() env.pop("NANOBOT_TUI_WS_URL", None) env.pop("NANOBOT_TUI_API_TOKEN", None) + env.pop("NANOBOT_TUI_DESKTOP_RESOLVER", None) + env.pop("NANOBOT_TUI_DESKTOP_TARGET", None) env.update( { "NANOBOT_TUI_BOOTSTRAP_URL": f"{base_url}/webui/bootstrap", @@ -160,7 +162,7 @@ def launch_tui( lease.release(wait_for_stop=False) -def _resolve_tui_command() -> list[str]: +def resolve_tui_command(*, data_dir: Path | None = None) -> list[str]: override = os.environ.get("NANOBOT_TUI_BIN", "").strip() if override: executable = Path(override).expanduser().resolve(strict=False) @@ -191,13 +193,13 @@ def _resolve_tui_command() -> list[str]: "this source checkout requires Bun to run its matching TUI; " "install Bun, then run `nanobot agent` again" ) - return _resolve_source_tui_command(source_dir, bun) + return _resolve_source_tui_command(source_dir, bun, data_dir=data_dir) packaged = Path(__file__).resolve().parents[1] / "tui" / "bin" / asset if packaged.is_file(): return [str(packaged)] - downloaded = _download_release_tui(asset) + downloaded = _download_release_tui(asset, data_dir=data_dir) if downloaded is not None: return [str(downloaded)] @@ -222,7 +224,9 @@ def _tui_source_dir(project_root: Path) -> Path | None: return None -def _resolve_source_tui_command(source_dir: Path, bun: str) -> list[str]: +def _resolve_source_tui_command( + source_dir: Path, bun: str, *, data_dir: Path | None = None, +) -> list[str]: dependency = source_dir / "node_modules" / "@opentui" / "core" try: install = subprocess.run( @@ -241,12 +245,12 @@ def _resolve_source_tui_command(source_dir: Path, bun: str) -> list[str]: executable = named_executable( bun, name="nanobot-tui", - directory=get_data_dir() / "run" / "executables", + directory=(data_dir if data_dir is not None else get_data_dir()) / "run" / "executables", ) return [executable, str(source_dir / "src" / "index.ts")] -def _download_release_tui(asset: str) -> Path | None: +def _download_release_tui(asset: str, *, data_dir: Path | None = None) -> Path | None: """Install the complete, version-matched TUI release bundle.""" if os.environ.get("NANOBOT_TUI_NO_DOWNLOAD") == "1": return None @@ -254,7 +258,7 @@ def _download_release_tui(asset: str) -> Path | None: if not version or version.endswith((".dev0", "+dev")): return None - target_dir = get_data_dir() / "bin" / "tui" / version + target_dir = (data_dir if data_dir is not None else get_data_dir()) / "bin" / "tui" / version cached = _cached_release_tui(target_dir, asset) if cached is not None: return cached diff --git a/nanobot/webui/gateway_endpoint.py b/nanobot/webui/gateway_endpoint.py index 016e6c0f7..83217b2f6 100644 --- a/nanobot/webui/gateway_endpoint.py +++ b/nanobot/webui/gateway_endpoint.py @@ -60,6 +60,12 @@ class WebUIGatewayEndpoint: got, query = parse_request_path(request.path) expected_ws = normalize_config_path(self._config.path) if got == expected_ws and is_websocket_upgrade(request): + terminal_version = query_first(query, "terminal_protocol") + if terminal_version is not None and ( + terminal_version != "1" + or query_first(query, "terminal_instance") != self._tokens.instance_id + ): + return connection.respond(409, "Terminal instance or protocol changed") client_id = query_first(query, "client_id") or "" if len(client_id) > 128: client_id = client_id[:128] diff --git a/nanobot/webui/gateway_tokens.py b/nanobot/webui/gateway_tokens.py index 22fe46cc7..9e9948187 100644 --- a/nanobot/webui/gateway_tokens.py +++ b/nanobot/webui/gateway_tokens.py @@ -4,6 +4,7 @@ from __future__ import annotations import secrets import time +import uuid from dataclasses import dataclass, field from typing import Any, Literal @@ -19,6 +20,7 @@ class GatewayTokenStore: """Own short-lived WebSocket and WebUI API tokens for one gateway process.""" max_tokens: int = 10_000 + instance_id: str = field(default_factory=lambda: str(uuid.uuid4()), init=False) issued_tokens: dict[str, float] = field(default_factory=dict) issued_token_audiences: dict[str, IssuedTokenAudience] = field(default_factory=dict) api_tokens: dict[str, float] = field(default_factory=dict) diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py index b5b870b82..799546943 100644 --- a/nanobot/webui/ws_http.py +++ b/nanobot/webui/ws_http.py @@ -511,6 +511,8 @@ class GatewayHTTPHandler: # Bootstrap if got == "/webui/bootstrap": return self._handle_bootstrap(connection, request) + if got == "/webui/terminal": + return self._handle_bootstrap(connection, request, terminal_probe=True) # Settings routes (delegated) response = await self.settings_routes.dispatch(connection, request, got) @@ -601,7 +603,9 @@ class GatewayHTTPHandler: # -- Bootstrap ---------------------------------------------------------- - def _handle_bootstrap(self, connection: Any, request: Any) -> Response: + def _handle_bootstrap( + self, connection: Any, request: Any, *, terminal_probe: bool = False, + ) -> Response: secret = self.config.token_issue_secret.strip() or self.config.token.strip() is_local_browser = _is_local_browser_request(connection, request.headers) is_proxy_authenticated = _is_trusted_proxy_authenticated_request( @@ -616,6 +620,11 @@ class GatewayHTTPHandler: elif not is_local_browser: return _http_error(403, "bootstrap is localhost-only") + terminal = {"protocolVersion": 1, "gatewayId": self.tokens.instance_id} + if terminal_probe: + # Capability probing does not allocate credentials or acquire client leases. + return _http_json_response(terminal, extra_headers=_NO_STORE_HEADERS) + if is_proxy_authenticated: payload = { "ws_path": _normalize_config_path(self.config.path), @@ -651,6 +660,7 @@ class GatewayHTTPHandler: expected_path = _normalize_config_path(self.config.path) payload = { "token": token, + "terminal": terminal, "ws_path": expected_path, "ws_url": ws_url, "expires_in": self.config.token_ttl_s, diff --git a/pyproject.toml b/pyproject.toml index c84383946..62788eb8b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -108,6 +108,7 @@ dev = [ [project.scripts] nanobot = "nanobot.cli.entry:main" +nanobot-desktop-tui = "nanobot.cli.desktop_tui:main" # Third-party tool plugins register here. Built-in tools are discovered # automatically via pkgutil scanning in ToolLoader.discover(). diff --git a/tests/cli/test_desktop_target.py b/tests/cli/test_desktop_target.py index e644474fd..13de9617a 100644 --- a/tests/cli/test_desktop_target.py +++ b/tests/cli/test_desktop_target.py @@ -263,10 +263,10 @@ def test_desktop_tui_selection_fails_without_fallback(monkeypatch, capsys) -> No 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"] + assert dispatch_bare_desktop_target([]) == 3 + assert calls == ["status", "tui"] error = capsys.readouterr().err - assert "does not yet provide attach-only terminal chat" in error + assert "unavailable or incompatible" in error assert "No backend was started" in error diff --git a/tests/cli/test_desktop_tui.py b/tests/cli/test_desktop_tui.py new file mode 100644 index 000000000..fbf0a62ec --- /dev/null +++ b/tests/cli/test_desktop_tui.py @@ -0,0 +1,173 @@ +import json +import os +import socket +import subprocess +import sys +from pathlib import Path +from unittest.mock import MagicMock + +import pytest + +from nanobot.cli import desktop_target, desktop_tui, tui_launcher +from nanobot.cli.desktop_target import DesktopReply, DesktopTargetError + +DESKTOP_ID = "d4f6cc96-a3a2-4a68-9a45-cec04b79ab53" +GATEWAY_ID = "d4f6cc96-a3a2-4a68-9a45-cec04b79ab54" + + +def connection(**overrides): + return { + "protocolVersion": 1, "gatewayId": GATEWAY_ID, + "apiUrl": "http://127.0.0.1:8765", "wsUrl": "ws://127.0.0.1:8765/ws", + "wsToken": "synthetic-ws-token", "apiToken": "synthetic-api-token", **overrides, + } + + +def target(**overrides): + value = MagicMock(instance_id=DESKTOP_ID) + value.request.return_value = DesktopReply("ready", frozenset({"tui"}), tui=connection(**overrides)) + return value + + +@pytest.mark.parametrize("overrides", [ + {"protocolVersion": True}, {"protocolVersion": 2}, {"gatewayId": "not-a-uuid"}, + {"wsUrl": "ws://evil.example/ws"}, {"apiUrl": "https://127.0.0.1:8765"}, + {"apiUrl": "http://localhost:8765"}, {"apiUrl": "http://127.0.0.1:0"}, + {"wsUrl": "ws://127.0.0.1:8766/ws"}, {"wsUrl": "ws://127.0.0.1:8765/ws?token=hidden"}, + {"wsUrl": "ws://user@127.0.0.1:8765/ws"}, {"wsUrl": "ws://127.0.0.1:8765/ws#fragment"}, + {"apiUrl": "http://127.0.0.1:8765/api"}, {"apiToken": ""}, {"wsToken": "secret\n"}, +]) +def test_resolver_rejects_unusable_or_unsafe_connection(monkeypatch, overrides): + monkeypatch.setattr(desktop_tui, "discover_desktop_target", lambda: target(**overrides)) + with pytest.raises(DesktopTargetError): + desktop_tui.resolve_request(json.dumps({"instanceId": DESKTOP_ID, "gatewayId": GATEWAY_ID}).encode()) + + +def test_resolver_revalidates_both_instances_for_each_refresh(monkeypatch): + chosen = target() + monkeypatch.setattr(desktop_tui, "discover_desktop_target", lambda: chosen) + request = json.dumps({"instanceId": DESKTOP_ID, "gatewayId": GATEWAY_ID}).encode() + assert desktop_tui.resolve_request(request) == connection() + assert desktop_tui.resolve_request(request) == connection() + assert chosen.request.call_count == 2 + chosen.instance_id = "replacement" + with pytest.raises(DesktopTargetError, match="disconnected"): + desktop_tui.resolve_request(request) + chosen.instance_id = DESKTOP_ID + chosen.request.return_value = DesktopReply("ready", frozenset({"tui"}), tui=connection(gatewayId=DESKTOP_ID)) + with pytest.raises(DesktopTargetError, match="identity changed"): + desktop_tui.resolve_request(request) + + +def test_launcher_has_no_gateway_ownership_and_no_credentials_in_child_env(monkeypatch): + chosen = target() + monkeypatch.setattr(tui_launcher, "resolve_tui_command", lambda: ["terminal-client"]) + monkeypatch.setattr(tui_launcher, "_ensure_gateway", lambda *a, **k: pytest.fail("must not own gateway")) + monkeypatch.setenv("NANOBOT_TUI_GATEWAY_STOP_COMMAND", "forbidden stop") + monkeypatch.setenv("NANOBOT_TUI_BOOTSTRAP_SECRET", "unrelated-bootstrap") + monkeypatch.setenv("NANOBOT_TUI_WS_URL", "ws://unrelated") + monkeypatch.delenv("NANOBOT_DESKTOP_CLIENT_CACHE", raising=False) + calls = [] + process = MagicMock() + process.wait.return_value = 90 + process.poll.return_value = 90 + monkeypatch.setattr(desktop_tui.subprocess, "run", lambda *a, **kw: subprocess.CompletedProcess(a, 0, b"1\n", b"")) + def start(args, **kw): + calls.append((args, kw)) + return process + monkeypatch.setattr(desktop_tui.subprocess, "Popen", start) + assert desktop_tui.launch_desktop_tui(chosen) == 0 + args, options = calls[0] + assert args == ["terminal-client"] + env = options["env"] + assert set(key for key in env if key.startswith("NANOBOT_TUI_")) == { + "NANOBOT_TUI_DESKTOP_TARGET", "NANOBOT_TUI_DESKTOP_RESOLVER", + } + assert "synthetic" not in json.dumps((args, options)) + assert "unrelated-bootstrap" not in json.dumps((args, options)) + assert json.loads(env["NANOBOT_TUI_DESKTOP_TARGET"])["gatewayId"] == GATEWAY_ID + resolver = json.loads(env["NANOBOT_TUI_DESKTOP_RESOLVER"]) + assert resolver[:3] == [sys.executable, "-I", "-S"] + assert resolver[-1] == "--resolve" + process.terminate.assert_not_called() + + +def test_unsupported_desktop_does_not_install_or_launch_a_client(monkeypatch): + chosen = target() + chosen.request.return_value = DesktopReply("ready", frozenset({"webui"})) + monkeypatch.setattr(tui_launcher, "resolve_tui_command", lambda: pytest.fail("unsupported target")) + with pytest.raises(DesktopTargetError): + desktop_tui.launch_desktop_tui(chosen) + + +def test_incompatible_tui_fails_without_fallback(monkeypatch): + monkeypatch.setattr(tui_launcher, "resolve_tui_command", lambda: ["old-client"]) + monkeypatch.setattr(desktop_tui.subprocess, "run", lambda *a, **kw: subprocess.CompletedProcess(a, 1, b"", b"")) + monkeypatch.setattr(desktop_tui.subprocess, "Popen", lambda *a, **kw: pytest.fail("cannot start client")) + with pytest.raises(DesktopTargetError, match="does not support"): + desktop_tui.launch_desktop_tui(target()) + + +def test_bare_command_uses_attachment_and_preserves_return_code(monkeypatch): + chosen = target() + monkeypatch.setattr(desktop_target, "_interactive_shell", lambda: True) + monkeypatch.setattr(desktop_target, "discover_desktop_target", lambda: chosen) + monkeypatch.setattr(desktop_target, "_choose_target", lambda status: "desktop") + monkeypatch.setattr(desktop_tui, "launch_desktop_tui", lambda selected: 17 if selected is chosen else 99) + assert desktop_target.dispatch_bare_desktop_target([]) == 17 + + +def test_standalone_resolver_is_silent_on_invalid_input(tmp_path): + script = str(Path(desktop_tui.__file__).resolve()) + result = subprocess.run([sys.executable, "-I", "-S", script, "--resolve"], + input=b'{"apiToken":"synthetic"}\n', capture_output=True, timeout=5) + assert result.returncode == 3 + assert result.stdout == result.stderr == b"" + with (tmp_path / "not-a-pipe").open("wb") as output: + result = subprocess.run([sys.executable, "-I", "-S", script, "--resolve"], + input=b"{}\n", stdout=output, stderr=subprocess.PIPE, timeout=5) + assert result.returncode == 3 + assert (tmp_path / "not-a-pipe").read_bytes() == b"" + + +@pytest.mark.skipif(os.name != "posix", reason="Bun Unix socket-pair stdout") +def test_resolver_output_accepts_only_anonymous_ipc(tmp_path): + first, second = socket.socketpair() + with first, second: + assert desktop_tui._anonymous_output(first.fileno()) + read_fd, write_fd = os.pipe() + try: + assert desktop_tui._anonymous_output(write_fd) + finally: + os.close(read_fd) + os.close(write_fd) + with (tmp_path / "file").open("wb") as file: + assert not desktop_tui._anonymous_output(file.fileno()) + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener: + listener.bind(("127.0.0.1", 0)) + listener.listen() + with socket.create_connection(listener.getsockname()) as client: + peer, _ = listener.accept() + with peer: + assert not desktop_tui._anonymous_output(client.fileno()) + + +@pytest.mark.parametrize("args", [["--config", "elsewhere"], ["gateway", "stop"], ["--help"], ["webui"]]) +def test_desktop_only_entry_never_forwards_unknown_commands(args, monkeypatch): + monkeypatch.setattr(sys, "argv", ["nanobot-desktop-tui", *args]) + monkeypatch.setattr(desktop_tui, "discover_desktop_target", lambda: pytest.fail("explicit command")) + with pytest.raises(SystemExit) as error: + desktop_tui.main() + assert error.value.code == 2 + + +def test_desktop_cache_avoids_default_python_data_root(monkeypatch, tmp_path): + monkeypatch.setenv("NANOBOT_DESKTOP_CLIENT_CACHE", str(tmp_path)) + observed = [] + def resolve(**kwargs): + observed.append(kwargs) + raise tui_launcher.TuiUnavailableError("not installed") + monkeypatch.setattr(tui_launcher, "resolve_tui_command", resolve) + with pytest.raises(DesktopTargetError): + desktop_tui.launch_desktop_tui(target()) + assert observed == [{"data_dir": tmp_path}] diff --git a/tests/cli/test_tui_launcher.py b/tests/cli/test_tui_launcher.py index 5cc1f4a65..4df9bd24b 100644 --- a/tests/cli/test_tui_launcher.py +++ b/tests/cli/test_tui_launcher.py @@ -18,7 +18,7 @@ from nanobot.cli.tui_launcher import ( _initial_tui_chat_id, _initial_tui_workspace, _resolve_source_tui_command, - _resolve_tui_command, + resolve_tui_command, _websocket_chat_id, launch_tui, ) @@ -103,7 +103,7 @@ def test_launcher_passes_the_canonical_model_preset_to_the_tui( assert wait_for_stop is False released.append(True) - monkeypatch.setattr("nanobot.cli.tui_launcher._resolve_tui_command", lambda: ["nanobot-tui"]) + monkeypatch.setattr("nanobot.cli.tui_launcher.resolve_tui_command", lambda: ["nanobot-tui"]) def ensure_gateway(*args: object, **kwargs: object) -> SimpleNamespace: assert events == ["spawned"] assert kwargs["wait_until_ready"] is False @@ -173,7 +173,7 @@ def test_launcher_terminates_the_tui_when_gateway_start_fails( def fail_gateway(*args: object, **kwargs: object) -> None: raise RuntimeError("gateway failed") - monkeypatch.setattr("nanobot.cli.tui_launcher._resolve_tui_command", lambda: ["nanobot-tui"]) + monkeypatch.setattr("nanobot.cli.tui_launcher.resolve_tui_command", lambda: ["nanobot-tui"]) monkeypatch.setattr( "nanobot.cli.tui_launcher.subprocess.Popen", lambda *args, **kwargs: FakeProcess(), @@ -227,7 +227,7 @@ def test_launcher_keeps_the_tui_alive_while_an_existing_gateway_recovers( return 0 monkeypatch.setattr("nanobot.gateway.GatewayRuntime", FakeRuntime) - monkeypatch.setattr("nanobot.cli.tui_launcher._resolve_tui_command", lambda: ["nanobot-tui"]) + monkeypatch.setattr("nanobot.cli.tui_launcher.resolve_tui_command", lambda: ["nanobot-tui"]) monkeypatch.setattr( "nanobot.cli.tui_launcher.subprocess.Popen", lambda *args, **kwargs: FakeProcess(), @@ -286,7 +286,7 @@ def test_launcher_promotes_the_gateway_when_the_tui_detaches( events.append("waited") return tui_launcher._TUI_DETACH_EXIT_CODE - monkeypatch.setattr("nanobot.cli.tui_launcher._resolve_tui_command", lambda: ["nanobot-tui"]) + monkeypatch.setattr("nanobot.cli.tui_launcher.resolve_tui_command", lambda: ["nanobot-tui"]) def popen(command: list[str], *, env: dict[str, str]) -> FakeProcess: assert command == ["nanobot-tui"] captured.update(env) @@ -325,7 +325,7 @@ def test_explicit_tui_binary_must_exist( missing = tmp_path / "missing" monkeypatch.setenv("NANOBOT_TUI_BIN", str(missing)) with pytest.raises(TuiUnavailableError, match="does not exist"): - _resolve_tui_command() + resolve_tui_command() def test_windows_arm64_fails_instead_of_using_the_classic_prompt( @@ -336,7 +336,7 @@ def test_windows_arm64_fails_instead_of_using_the_classic_prompt( monkeypatch.setattr("nanobot.cli.tui_launcher.platform.machine", lambda: "ARM64") with pytest.raises(TuiUnavailableError, match="Windows ARM64"): - _resolve_tui_command() + resolve_tui_command() def test_source_checkout_does_not_fall_back_to_a_release_tui_without_bun( @@ -357,7 +357,7 @@ def test_source_checkout_does_not_fall_back_to_a_release_tui_without_bun( ) with pytest.raises(TuiUnavailableError, match="source checkout requires Bun"): - _resolve_tui_command() + resolve_tui_command() def test_source_checkout_requires_project_and_tui_markers( diff --git a/tests/webui/test_gateway_terminal.py b/tests/webui/test_gateway_terminal.py new file mode 100644 index 000000000..6ba30d9e0 --- /dev/null +++ b/tests/webui/test_gateway_terminal.py @@ -0,0 +1,30 @@ +"""Terminal capability metadata is authenticated and does not allocate tokens.""" + +import json +from types import SimpleNamespace + +from websockets.datastructures import Headers +from websockets.http11 import Request + +from nanobot.channels.websocket.runtime import WebSocketConfig +from nanobot.webui.gateway_tokens import GatewayTokenStore +from nanobot.webui.ws_http import GatewayHTTPHandler + + +def test_terminal_probe_is_private_stable_and_does_not_issue_credentials(): + handler = object.__new__(GatewayHTTPHandler) + handler.config = WebSocketConfig(token_issue_secret="fixture-secret") + handler.tokens = GatewayTokenStore(max_tokens=0) + connection = SimpleNamespace(remote_address=("127.0.0.1", 10000)) + request = Request("/webui/terminal", Headers({"Host": "127.0.0.1:8765"})) + assert handler._handle_bootstrap(connection, request, terminal_probe=True).status_code == 401 + request.headers["X-Nanobot-Auth"] = "fixture-secret" + for _ in range(3): + response = handler._handle_bootstrap(connection, request, terminal_probe=True) + assert response.status_code == 200 + assert json.loads(response.body) == { + "protocolVersion": 1, "gatewayId": handler.tokens.instance_id, + } + assert "no-store" in response.headers["Cache-Control"] + assert not handler.tokens.api_tokens and not handler.tokens.issued_tokens + assert GatewayTokenStore().instance_id != handler.tokens.instance_id diff --git a/tests/webui/test_gateway_webui_smoke.py b/tests/webui/test_gateway_webui_smoke.py index 6b63f7c44..11b205f00 100644 --- a/tests/webui/test_gateway_webui_smoke.py +++ b/tests/webui/test_gateway_webui_smoke.py @@ -211,6 +211,55 @@ async def test_gateway_webui_bootstrap_message_and_thread_hydration(tmp_path: Pa _stop_gateway(process) +@pytest.mark.asyncio +async def test_desktop_terminal_identity_and_independent_client_lifetime(tmp_path: Path) -> None: + """Two terminal clients exercise real authentication, framing and gateway lifetime.""" + ws_port, gateway_port = _free_port(), _free_port() + workspace = tmp_path / "workspace" + workspace.mkdir() + config_path, log_path = tmp_path / "config.json", tmp_path / "gateway.log" + _write_smoke_config(config_path, workspace=workspace, ws_port=ws_port, gateway_port=gateway_port) + process = _start_gateway(config_path, log_path) + base_url = f"http://127.0.0.1:{ws_port}" + try: + first = _wait_for_bootstrap(base_url, process, log_path) + terminal = first["terminal"] + assert terminal["protocolVersion"] == 1 + unauthenticated = httpx.get(f"{base_url}/webui/terminal", trust_env=False) + assert unauthenticated.status_code == 401 + probe = _get_bootstrap(f"{base_url}/webui/terminal") + assert probe == terminal # Contains no token or config information. + second = _get_bootstrap(f"{base_url}/webui/bootstrap") + assert second["terminal"] == terminal + identity_query = f'&terminal_protocol=1&terminal_instance={terminal["gatewayId"]}' + first_url = f'{first["ws_url"]}?token={first["token"]}&client_id=terminal-one' + # A rejected wrong-instance upgrade must not consume the one-use WS token. + with pytest.raises(websockets.exceptions.InvalidStatus) as wrong: + async with websockets.connect(first_url + "&terminal_protocol=1&terminal_instance=wrong"): + pytest.fail("Wrong gateway identity accepted") + assert wrong.value.response.status_code == 409 + async with websockets.connect(first_url + identity_query) as one: + assert (await _recv_until(one, "ready"))["terminal"] == terminal + second_url = f'{second["ws_url"]}?token={second["token"]}&client_id=terminal-two' + async with websockets.connect(second_url + identity_query) as two: + assert (await _recv_until(two, "ready"))["terminal"] == terminal + await one.close() + await two.send(json.dumps({"type": "new_chat"})) + chat_id = (await _recv_until(two, "attached"))["chat_id"] + await two.send(json.dumps({"type": "message", "chat_id": chat_id, + "content": "/model", "webui": True, "turn_id": "terminal-model"})) + assert "custom/smoke-model" in (await _recv_until(two, "message"))["text"] + await _recv_until(two, "turn_end") + assert process.poll() is None + after = _get_bootstrap(f"{base_url}/webui/bootstrap") + assert after["terminal"] == terminal + # The ordinary WebUI ready frame remains unchanged (no opt-in metadata). + async with websockets.connect(f'{after["ws_url"]}?token={after["token"]}&client_id=browser') as browser: + assert "terminal" not in await _recv_until(browser, "ready") + finally: + _stop_gateway(process) + + def test_gateway_restart_restores_a_completed_answer_without_replaying_model( tmp_path: Path, ) -> None: diff --git a/tui/src/app.ts b/tui/src/app.ts index f243a675a..9c4c965f8 100644 --- a/tui/src/app.ts +++ b/tui/src/app.ts @@ -34,6 +34,7 @@ import { type ConnectionStatusInfo, type FileEditEvent, type GatewayApiConnection, + type GatewayConnection, type HistoryMessage, type InboundEvent, type MentionCandidate, @@ -98,6 +99,8 @@ import { import { configureOpenTuiEnvironment, createTuiHost, type TuiHost } from "./host" interface AppOptions { + resolveConnection?: () => Promise + desktopGatewayId?: string wsUrl?: string bootstrapUrl?: string bootstrapSecret?: string @@ -573,7 +576,7 @@ export class NanobotTui { this.defaultModelPreset = options.modelPreset this.modelName = options.model this.modelPreset = options.modelPreset - this.apiReauthenticator = options.bootstrapUrl + this.apiReauthenticator = options.bootstrapUrl || options.resolveConnection ? (rejectedApiToken) => this.refreshApiConnection(rejectedApiToken) : undefined this.sessionModelPreset = options.chatId ? undefined : null @@ -615,7 +618,13 @@ export class NanobotTui { }, ) this.client = client || new NanobotClient({ - ...(options.bootstrapUrl + ...(options.resolveConnection ? { + resolveConnection: options.resolveConnection, + onConnection: (connection: GatewayConnection) => this.useGatewayConnection(connection.apiUrl, connection.apiToken), + expectedGatewayId: options.desktopGatewayId, + reconnect: false, + targetEndpoint: "Nanobot Desktop", + } : options.bootstrapUrl ? { resolveConnection: () => fetchGatewayConnection( options.bootstrapUrl || "", @@ -636,7 +645,7 @@ export class NanobotTui { } : { url: options.wsUrl }), chatId: options.chatId, - initialWorkspaceScope: { + initialWorkspaceScope: options.desktopGatewayId ? undefined : { project_path: options.workspace, access_mode: options.access.toLocaleLowerCase().includes("full") ? "full" : "restricted", }, @@ -1442,12 +1451,12 @@ export class NanobotTui { return { apiUrl: this.options.apiUrl, apiToken: this.options.apiToken } } if (this.apiRefreshPromise) return this.apiRefreshPromise - const refresh = fetchGatewayConnection( + const refresh = (this.options.resolveConnection ? this.options.resolveConnection() : fetchGatewayConnection( this.options.bootstrapUrl || "", this.options.bootstrapSecret || "", this.options.apiUrl, `tui-${process.pid}`, - ).then((connection) => { + )).then((connection) => { this.updateGatewayApiConnection(connection.apiUrl, connection.apiToken) return connection }) @@ -1468,6 +1477,9 @@ export class NanobotTui { // accurate user-facing state unless the protocol supplied connection diagnostics. if (status === "error" && !info) return this.connectionMessage = connectionStatusText(status, info) + if (this.options.desktopGatewayId && status === "error") { + this.connectionMessage = "Desktop disconnected or incompatible · exit and run nanobot to reconnect" + } if (status === "connected") { this.ready = false this.renderConnectionMessage() diff --git a/tui/src/desktop.test.ts b/tui/src/desktop.test.ts new file mode 100644 index 000000000..5b51dddb0 --- /dev/null +++ b/tui/src/desktop.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, test } from "bun:test" +import { desktopConnectionSource } from "./desktop" + +const instanceId = "b370a67d-1dbb-4b7c-9b22-c5f72ad8f5f0" +const gatewayId = "a277eeea-a422-4691-aac5-2c7348a95140" +const connection = { + protocolVersion: 1, gatewayId, + apiUrl: "http://127.0.0.1:8765", wsUrl: "ws://127.0.0.1:8765/ws", + wsToken: "test-ws-secret", apiToken: "test-api-secret", +} +function source(value: unknown = connection, exitCode = 0) { + // This test helper uses synthetic values only. Production passes no tokens in argv. + const script = `const input = JSON.parse(await Bun.stdin.text()); + if (input.instanceId !== ${JSON.stringify(instanceId)} || input.gatewayId !== ${JSON.stringify(gatewayId)}) process.exit(9); + process.stdout.write(${JSON.stringify(JSON.stringify(value))}); process.exit(${exitCode});` + return desktopConnectionSource({ + NANOBOT_TUI_DESKTOP_RESOLVER: JSON.stringify([process.execPath, "-e", script]), + NANOBOT_TUI_DESKTOP_TARGET: JSON.stringify({ instanceId, gatewayId }), + })! +} + +describe("Desktop credential resolver", () => { + test("does nothing for a normal Python TUI", () => { + expect(desktopConnectionSource({})).toBeUndefined() + }) + test("fails closed for incomplete launcher metadata", () => { + expect(() => desktopConnectionSource({ NANOBOT_TUI_DESKTOP_TARGET: "{}" })).toThrow("Invalid Desktop") + }) + test("refreshes through a pipe and pins the websocket to the chosen gateway", async () => { + const resolver = source() + for (let refresh = 0; refresh < 2; refresh++) { + const result = await resolver.resolve() + const ws = new URL(result.wsUrl) + expect(ws.searchParams.get("terminal_instance")).toBe(gatewayId) + expect(ws.searchParams.get("terminal_protocol")).toBe("1") + expect(ws.searchParams.get("token")).toBe(connection.wsToken) + expect(result.apiToken).toBe(connection.apiToken) + expect(result.apiUrl).toBe(connection.apiUrl) + } + }) + test("accepts equivalent explicit and implicit HTTP default ports", async () => { + const result = await source({ ...connection, apiUrl: "http://127.0.0.1:80", wsUrl: "ws://127.0.0.1/ws" }).resolve() + expect(result.apiUrl).toBe("http://127.0.0.1") + }) + for (const patch of [ + { protocolVersion: 2 }, { gatewayId: instanceId }, { apiToken: "" }, + { wsToken: "unsafe\nvalue" }, { wsUrl: "ws://external.example:8765/ws" }, + { apiUrl: "http://localhost:8765" }, { wsUrl: "ws://127.0.0.1:8766/ws" }, + { wsUrl: "ws://127.0.0.1:8765/ws?token=unexpected" }, + { apiUrl: "http://user:password@127.0.0.1:8765" }, + { apiUrl: "http://127.0.0.1:0" }, { apiUrl: "http://127.0.0.1:8765/api" }, + ]) { + test(`rejects untrusted connection fields: ${Object.keys(patch)[0]} ${JSON.stringify(patch)}`, async () => { + await expect(source({ ...connection, ...patch }).resolve()).rejects.toThrow("Selected Desktop is unavailable") + }) + } + test("does not expose malformed, oversized, or failed helper output", async () => { + for (const resolver of [source("test-secret"), source("x".repeat(9000)), source(connection, 3)]) { + await expect(resolver.resolve()).rejects.toThrow("Selected Desktop is unavailable") + } + }) +}) diff --git a/tui/src/desktop.ts b/tui/src/desktop.ts new file mode 100644 index 000000000..49309440d --- /dev/null +++ b/tui/src/desktop.ts @@ -0,0 +1,87 @@ +import type { GatewayConnection } from "./protocol" + +type Environment = Record + +export interface DesktopConnectionSource { + gatewayId: string + resolve: () => Promise +} + +export function desktopConnectionSource(environment: Environment = process.env): DesktopConnectionSource | undefined { + const rawCommand = environment.NANOBOT_TUI_DESKTOP_RESOLVER + const rawTarget = environment.NANOBOT_TUI_DESKTOP_TARGET + if (!rawCommand && !rawTarget) return undefined + try { + const command: unknown = JSON.parse(rawCommand || "") + const target: unknown = JSON.parse(rawTarget || "") + if (!Array.isArray(command) || command.length < 2 + || !command.every((part): part is string => typeof part === "string" && part.length > 0) + || !record(target) || typeof target.instanceId !== "string" + || !uuid(target.instanceId) || typeof target.gatewayId !== "string" || !uuid(target.gatewayId)) throw new Error() + const gatewayId = target.gatewayId + const request = JSON.stringify({ instanceId: target.instanceId, gatewayId }) + "\n" + if (request.length > 8192) throw new Error() + return { gatewayId, resolve: () => resolveDesktopConnection(command, request, gatewayId) } + } catch { + throw new Error("Invalid Desktop terminal launcher configuration") + } +} + +async function resolveDesktopConnection(command: string[], request: string, gatewayId: string): Promise { + const child = Bun.spawn(command, { + stdin: "pipe", stdout: "pipe", stderr: "ignore", + }) + const timer = setTimeout(() => child.kill(), 8_000) + try { + child.stdin.write(request) + child.stdin.end() + const reader = child.stdout.getReader() + const chunks: Uint8Array[] = [] + let length = 0 + try { + for (;;) { + const next = await reader.read() + if (next.done) break + length += next.value.byteLength + if (length > 8192) throw new Error() + chunks.push(next.value) + } + } finally { reader.releaseLock() } + if (await child.exited !== 0) throw new Error() + const value: unknown = JSON.parse(Buffer.concat(chunks).toString("utf8")) + if (!record(value) || value.protocolVersion !== 1 || value.gatewayId !== gatewayId) throw new Error() + const api = endpoint(value.apiUrl, "http:") + const ws = endpoint(value.wsUrl, "ws:") + if (api.host !== ws.host || api.pathname !== "/" + || !token(value.wsToken) || !token(value.apiToken)) throw new Error() + ws.searchParams.set("token", value.wsToken) + ws.searchParams.set("client_id", `tui-${process.pid}`) + ws.searchParams.set("terminal_protocol", "1") + ws.searchParams.set("terminal_instance", gatewayId) + return { wsUrl: ws.toString(), apiUrl: api.origin, apiToken: value.apiToken } + } catch { + // The helper response contains secrets; never expose its raw errors/output. + throw new Error("Selected Desktop is unavailable or incompatible; reconnect from the terminal") + } finally { + clearTimeout(timer) + child.kill() + await child.exited + } +} + +function record(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value) +} +function uuid(value: string): boolean { + return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(value) +} +function token(value: unknown): value is string { + return typeof value === "string" && /^[\x21-\x7e]{1,2048}$/u.test(value) +} +function endpoint(value: unknown, protocol: string): URL { + if (typeof value !== "string" || /[\s\\\x00-\x1f\x7f]/u.test(value)) throw new Error() + const url = new URL(value) + if (url.protocol !== protocol || !["127.0.0.1", "[::1]"].includes(url.hostname) + || url.port === "0" || url.username || url.password || url.search || url.hash) throw new Error() + return url +} diff --git a/tui/src/index.ts b/tui/src/index.ts index 7060dcf2f..ba7337354 100644 --- a/tui/src/index.ts +++ b/tui/src/index.ts @@ -1,4 +1,11 @@ import { NanobotTui, sessionExitMessage, type AppOptions } from "./app" +import { desktopConnectionSource } from "./desktop" + +if (process.argv.slice(2).join(" ") === "--desktop-protocol") { + process.stdout.write("1\n") + process.exit(0) +} +const desktop = desktopConnectionSource() // Keep in sync with _TUI_DETACH_EXIT_CODE in nanobot/cli/tui_launcher.py. const TUI_DETACH_EXIT_CODE = 90 @@ -15,11 +22,11 @@ const wsUrl = process.env.NANOBOT_TUI_WS_URL?.trim() || "" const healthUrl = process.env.NANOBOT_TUI_HEALTH_URL?.trim() || "" const gatewayStopCommand = process.env.NANOBOT_TUI_GATEWAY_STOP_COMMAND?.trim() || "nanobot gateway stop" -if (!bootstrapUrl && !wsUrl) { +if (!desktop && !bootstrapUrl && !wsUrl) { throw new Error("NANOBOT_TUI_BOOTSTRAP_URL or NANOBOT_TUI_WS_URL is required") } const options: AppOptions = { - ...(bootstrapUrl + ...(desktop ? { resolveConnection: desktop.resolve, desktopGatewayId: desktop.gatewayId } : bootstrapUrl ? { bootstrapUrl, bootstrapSecret: process.env.NANOBOT_TUI_BOOTSTRAP_SECRET?.trim() || "", @@ -38,11 +45,11 @@ const options: AppOptions = { onDetach: (chatId) => { process.exitCode = TUI_DETACH_EXIT_CODE process.stdout.write("Detached; the agent continues in the background.\n") - if (chatId) process.stdout.write(sessionExitMessage(chatId)) - process.stdout.write(`Stop it with: ${gatewayStopCommand}\n`) + if (!desktop && chatId) process.stdout.write(sessionExitMessage(chatId)) + process.stdout.write(desktop ? "Desktop remains running. Reconnect with nanobot.\n" : `Stop it with: ${gatewayStopCommand}\n`) }, onExit: (chatId) => { - process.stdout.write(sessionExitMessage(chatId)) + process.stdout.write(desktop ? "Disconnected from Desktop; its backend remains running.\n" : sessionExitMessage(chatId)) }, } @@ -62,11 +69,11 @@ for (const signal of ["SIGHUP", "SIGINT", "SIGTERM"] as const) { process.once("exit", () => app?.stop()) process.once("uncaughtException", (error) => { shutdown(1) - process.stderr.write(`${error instanceof Error ? error.stack || error.message : String(error)}\n`) + process.stderr.write(desktop ? "Desktop terminal connection failed. No backend was started.\n" : `${error instanceof Error ? error.stack || error.message : String(error)}\n`) }) process.once("unhandledRejection", (error) => { shutdown(1) - process.stderr.write(`${error instanceof Error ? error.stack || error.message : String(error)}\n`) + process.stderr.write(desktop ? "Desktop terminal connection failed. No backend was started.\n" : `${error instanceof Error ? error.stack || error.message : String(error)}\n`) }) app = await NanobotTui.create(options) diff --git a/tui/src/protocol.test.ts b/tui/src/protocol.test.ts index f325e2231..21f53a740 100644 --- a/tui/src/protocol.test.ts +++ b/tui/src/protocol.test.ts @@ -50,6 +50,72 @@ async function waitUntil(predicate: () => boolean, timeout = 1_000): Promise { + const gatewayId = "4d7d6bea-6d4b-4da1-975f-3d835c986c50" + async function fixture(run: (client: NanobotClient, socket: FakeSocket, statuses: ConnectionStatus[], attempts: () => number) => Promise) { + const original = globalThis.WebSocket + let socket: FakeSocket | undefined + let attempts = 0 + const statuses: ConnectionStatus[] = [] + Object.defineProperty(globalThis, "WebSocket", { + configurable: true, + value: class extends FakeSocket { constructor() { super(); socket = this } }, + }) + const client = new NanobotClient({ + expectedGatewayId: gatewayId, reconnect: false, reconnectDelayMs: 1, + resolveConnection: async () => { + attempts++ + return { wsUrl: "ws://127.0.0.1:8765/ws", apiUrl: "http://127.0.0.1:8765", apiToken: "fixture" } + }, + onEvent: () => {}, onStatus: (status) => statuses.push(status), + }) + try { + client.connect() + await waitUntil(() => !!socket) + socket!.emit("open") + await run(client, socket!, statuses, () => attempts) + } finally { + client.close() + Object.defineProperty(globalThis, "WebSocket", { configurable: true, value: original }) + } + } + for (const terminal of [undefined, { protocolVersion: 2, gatewayId }, { protocolVersion: 1, gatewayId: "other" }]) { + test(`rejects missing or changed handshake before any mutation: ${JSON.stringify(terminal)}`, async () => { + await fixture(async (client, socket, statuses, attempts) => { + expect(() => client.newChat()).toThrow("Desktop identity not verified") + await expect(client.updateRecovery("continue", "chat", "recovery")).rejects.toThrow("Desktop identity not verified") + socket.emit("message", { data: JSON.stringify({ event: "ready", chat_id: "", client_id: "test", terminal }) }) + await Bun.sleep(20) + expect(socket.sent).toHaveLength(0) + expect(socket.readyState).toBe(3) + expect(statuses.at(-1)).toBe("error") + expect(attempts()).toBe(1) + }) + }) + } + test("connects once, never replays a task and never reconnects after a disconnect", async () => { + await fixture(async (client, socket, statuses, attempts) => { + socket.emit("message", { data: JSON.stringify({ event: "ready", chat_id: "", client_id: "test", terminal: { protocolVersion: 1, gatewayId } }) }) + expect(socket.sent.map((frame) => JSON.parse(frame).type)).toEqual(["new_chat"]) + socket.emit("message", { data: JSON.stringify({ event: "attached", chat_id: "desktop-chat" }) }) + client.send("one task") + socket.emit("close") + await Bun.sleep(20) + expect(attempts()).toBe(1) + expect(socket.sent.map((frame) => JSON.parse(frame).type)).toEqual(["new_chat", "message"]) + expect(() => client.send("another task")).toThrow() + expect(statuses.at(-1)).toBe("error") + }) + }) + test("explicit client exit sends no lifecycle command", async () => { + await fixture(async (client, socket) => { + client.close() + expect(socket.sent).toHaveLength(0) + expect(socket.readyState).toBe(3) + }) + }) +}) + describe("gateway protocol", () => { test("bootstraps fresh websocket and API credentials", async () => { const original = globalThis.fetch diff --git a/tui/src/protocol.ts b/tui/src/protocol.ts index 3d8601a3b..6eaccfe8a 100644 --- a/tui/src/protocol.ts +++ b/tui/src/protocol.ts @@ -192,6 +192,8 @@ type OutboundEvent = } export interface ClientOptions { + expectedGatewayId?: string + reconnect?: boolean url?: string resolveConnection?: () => Promise checkHealth?: () => Promise @@ -1072,6 +1074,8 @@ export function sanitizeConnectionFailure(error: unknown): string { } export class NanobotClient { + private identityVerified = false + private handshakeTimer: ReturnType | null = null private socket: WebSocket | null = null private chatId = "" private workspaceScope?: WorkspaceScopePayload @@ -1115,6 +1119,7 @@ export class NanobotClient { private async open(): Promise { if (this.socket || this.opening || this.closedByClient) return this.opening = true + this.identityVerified = !this.options.expectedGatewayId this.nextRetryAt = 0 this.connectionAttempt += 1 this.reportConnectionProgress() @@ -1154,6 +1159,9 @@ export class NanobotClient { } let opened = false this.socket = socket + if (this.options.expectedGatewayId) { + this.handshakeTimer = setTimeout(() => this.desktopFailure(), 8_000) + } socket.addEventListener("open", () => { if (this.socket !== socket) return opened = true @@ -1172,6 +1180,7 @@ export class NanobotClient { }) socket.addEventListener("error", () => { if (this.socket !== socket) return + if (this.options.reconnect === false) { this.desktopFailure(); return } this.lastFailure = "connection failed" this.reportRetryState() }) @@ -1183,6 +1192,7 @@ export class NanobotClient { this.options.onStatus("closed") return } + if (this.options.reconnect === false) { this.desktopFailure(); return } if (opened) { this.connectionAttempt = 0 this.reconnectAttempt = 0 @@ -1195,6 +1205,8 @@ export class NanobotClient { } close(): void { + if (this.handshakeTimer) clearTimeout(this.handshakeTimer) + this.handshakeTimer = null this.closedByClient = true if (this.reconnectTimer) clearTimeout(this.reconnectTimer) this.reconnectTimer = null @@ -1271,6 +1283,9 @@ export class NanobotClient { payload: Record = {}, timeoutMs = 20_000, ): Promise { + if (this.options.expectedGatewayId && !this.identityVerified) { + return Promise.reject(new Error("Desktop identity not verified")) + } if (!this.socket || this.socket.readyState !== WebSocket.OPEN) { return Promise.reject(new Error("gateway connection is not open")) } @@ -1314,10 +1329,21 @@ export class NanobotClient { try { value = JSON.parse(raw) as unknown } catch { + if (!this.identityVerified && this.options.expectedGatewayId) { this.desktopFailure(); return } this.options.onStatus("error", "gateway sent invalid JSON") return } const response = decodeWebUIResponse(value) + if (!this.identityVerified) { + if (!isRecord(value) || value.event !== "ready" || !isRecord(value.terminal) + || value.terminal.protocolVersion !== 1 || value.terminal.gatewayId !== this.options.expectedGatewayId) { + this.desktopFailure() + return + } + this.identityVerified = true + if (this.handshakeTimer) clearTimeout(this.handshakeTimer) + this.handshakeTimer = null + } if (response === null) { this.options.onStatus("error", "gateway sent an invalid event") return @@ -1371,6 +1397,7 @@ export class NanobotClient { } private async checkHealthAndScheduleReconnect(): Promise { + if (this.options.reconnect === false) { this.desktopFailure(); return } if (this.options.checkHealth) { try { this.healthStatus = await this.options.checkHealth() @@ -1393,6 +1420,11 @@ export class NanobotClient { } } + private desktopFailure(): void { + this.close() + this.options.onStatus("error", "Desktop disconnected or is incompatible; reconnect from the terminal", this.connectionInfo()) + } + private reportConnectionProgress(): void { if (this.connectedOnce) { this.options.onStatus("reconnecting", this.lastFailure || undefined, this.connectionInfo()) @@ -1429,6 +1461,7 @@ export class NanobotClient { } private write(event: OutboundEvent): void { + if (this.options.expectedGatewayId && !this.identityVerified) throw new Error("Desktop identity not verified") if (!this.socket || this.socket.readyState !== WebSocket.OPEN) { throw new Error("gateway connection is not open") }