feat(update): integrate managed installs and recoverable in-app updates (#6168)

Add owner-aware Stable and Preview updates with explicit consent, verified release plans, protected process handoff and bounded service recovery. Keep configuration and conversations separate from program rollback.

Include the compact About controls, Windows long-path support, native package recovery checks and optional macOS Dock lifecycle integration. Preserve documented guidance for installations owned by other managers.

This code integration does not publish packages, enable signing or advance the public update channel.

Co-authored-by: chengyongru <61816729+chengyongru@users.noreply.github.com>
This commit is contained in:
Xubin Renandchengyongru authored and GitHub committed 2026-10-21 19:16:56 +08:00
1 parent 76da55994b
commit fbb61a373f
216 files changed
+27948 -1084

No files matched your search

+19 -3
View File
@@ -1,3 +1,4 @@
import asyncio
from contextlib import nullcontext
from io import StringIO
from unittest.mock import AsyncMock, MagicMock, call, patch
@@ -9,6 +10,14 @@ from nanobot.cli import stream as stream_mod
from nanobot.cli import terminal
@pytest.fixture(autouse=True)
def isolate_prompt_session(tmp_path, monkeypatch):
"""Keep real parser tests out of user history and other prompt sessions."""
monkeypatch.setattr("nanobot.config.paths.get_cli_history_path", lambda: tmp_path / "history")
monkeypatch.setattr(terminal, "_prompt_session", None)
monkeypatch.setattr(terminal, "_saved_term_attrs", None)
@pytest.fixture
def mock_prompt_session():
"""Mock the global prompt session."""
@@ -105,7 +114,10 @@ async def test_raw_lf_enter_still_submits_like_wsl_terminals():
terminal._init_prompt_session()
session = terminal._prompt_session
pipe_input.send_text("hello\x0aworld\r")
result = await session.prompt_async("> ")
# CI has no user to acknowledge prompt_toolkit's exception prompt.
result = await asyncio.wait_for(
session.prompt_async("> ", set_exception_handler=False), timeout=10,
)
assert result == "hello"
@@ -122,7 +134,9 @@ async def test_alt_enter_inserts_newline_on_lf_terminals():
terminal._init_prompt_session()
session = terminal._prompt_session
pipe_input.send_text("foo\x1b\x0abar\r")
result = await session.prompt_async("> ")
result = await asyncio.wait_for(
session.prompt_async("> ", set_exception_handler=False), timeout=10,
)
assert result == "foo\nbar"
@@ -139,7 +153,9 @@ async def test_csi_u_shift_enter_inserts_newline_not_raw_escape():
terminal._init_prompt_session()
session = terminal._prompt_session
pipe_input.send_text("foo\x1b[13;2ubar\r")
result = await session.prompt_async("> ")
result = await asyncio.wait_for(
session.prompt_async("> ", set_exception_handler=False), timeout=10,
)
# A newline is inserted and no raw escape bytes leak into the result.
assert result == "foo\nbar"
+86 -17
View File
@@ -3,8 +3,9 @@ import json
import re
import shutil
import signal
import sys
import urllib.error
from contextlib import contextmanager, suppress
from contextlib import contextmanager, nullcontext, suppress
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
@@ -48,6 +49,8 @@ runner = CliRunner()
def mock_webui_bundle(monkeypatch) -> MagicMock:
prepare_bundle = MagicMock()
monkeypatch.setattr(cli_webui, "_prepare_webui_bundle_for_gateway", prepare_bundle)
monkeypatch.setattr(cli_webui, "dock_icon", lambda *_args, **_kwargs: nullcontext())
monkeypatch.setattr(cli_webui, "request_gateway_icon", lambda *_args, **_kwargs: None)
return prepare_bundle
@@ -93,6 +96,10 @@ class _GatewayAgentContractStub:
tools = ToolRegistry()
subagents = MagicMock(spec=SubagentManager)
@contextmanager
def maintenance(self):
yield
async def discard_session(self, _session_key: str) -> None:
pass
@@ -1717,7 +1724,7 @@ def test_agent_uses_workspace_directory_for_cron_store(monkeypatch, tmp_path: Pa
monkeypatch.setattr("nanobot.bus.queue.MessageBus", lambda: object())
class _FakeCron:
def __init__(self, store_path: Path) -> None:
def __init__(self, store_path: Path, *, admission=None) -> None:
seen["cron_store"] = store_path
class _FakeAgentLoop:
@@ -1767,7 +1774,7 @@ def test_agent_workspace_override_does_not_migrate_legacy_cron(
monkeypatch.setattr("nanobot.config.paths.get_cron_dir", lambda: legacy_dir)
class _FakeCron:
def __init__(self, store_path: Path) -> None:
def __init__(self, store_path: Path, *, admission=None) -> None:
seen["cron_store"] = store_path
class _FakeAgentLoop:
@@ -1823,7 +1830,7 @@ def test_agent_custom_config_workspace_does_not_migrate_legacy_cron(
monkeypatch.setattr("nanobot.config.paths.get_cron_dir", lambda: legacy_dir)
class _FakeCron:
def __init__(self, store_path: Path) -> None:
def __init__(self, store_path: Path, *, admission=None) -> None:
seen["cron_store"] = store_path
class _FakeAgentLoop:
@@ -1853,9 +1860,8 @@ def test_agent_custom_config_workspace_does_not_migrate_legacy_cron(
assert not (custom_workspace / "cron" / "jobs.json").exists()
def test_agent_overrides_workspace_path(mock_agent_runtime):
workspace_path = Path("/tmp/agent-workspace")
@pytest.mark.parametrize("workspace_path", [Path("/tmp/agent-workspace"), Path("relative-agent-workspace")])
def test_agent_overrides_workspace_path(mock_agent_runtime, workspace_path):
result = runner.invoke(app, ["agent", "-m", "hello", "-w", str(workspace_path)])
assert result.exit_code == 0
@@ -2174,7 +2180,7 @@ def test_heartbeat_empty_response_is_not_evaluated(
return [{"key": "telegram:u1"}]
class _FakeCron:
def __init__(self, _store_path: Path) -> None:
def __init__(self, _store_path: Path, *, admission=None) -> None:
self.on_job = None
seen["cron"] = self
@@ -2367,6 +2373,36 @@ def test_webui_background_points_to_the_single_persistent_gateway_command(
assert not config_file.exists()
@pytest.mark.parametrize("managed", [False, True], ids=["explicit-detach", "fresh-installer"])
@pytest.mark.parametrize("no_dock", [False, True])
def test_webui_detached_gateway_does_not_retain_launcher_lease(monkeypatch, tmp_path, managed, no_dock):
config = tmp_path / "config.json"
_patch_webui_provider_ready(monkeypatch)
_patch_gateway_ports_free(monkeypatch)
seen = _patch_webui_managed_gateway(monkeypatch)
requested = []
monkeypatch.setattr(cli_webui, "request_gateway_icon",
lambda instance, *, enabled: requested.append((instance, enabled)))
if managed:
prefix = tmp_path / "managed"
prefix.mkdir()
(prefix / "nanobot-install.json").write_text(json.dumps({
"schema_version": 1, "owner": "nanobot-installer", "environment": str(prefix), "extras": [],
}))
monkeypatch.setattr(sys, "prefix", str(prefix))
result = runner.invoke(app, ["webui", "--config", str(config), "--yes", "--no-open",
*([] if managed else ["--detach"]),
*(["--no-dock"] if no_dock else [])])
assert result.exit_code == 0, result.output
assert "start_options" in seen
assert "attached_runtime" not in seen
assert "lease_release_wait_for_stop" not in seen
assert "Stop nanobot" in result.stdout
assert len(requested) == 1
assert requested[0][0].parent == tmp_path / "run"
assert requested[0][1] is not no_dock
def test_webui_dev_starts_vite_sidecar_and_gateway(monkeypatch, tmp_path: Path) -> None:
config_file = tmp_path / "config.json"
config_file.write_text("{}", encoding="utf-8")
@@ -2725,6 +2761,35 @@ def test_launch_browser_uses_unix_launcher_on_linux(monkeypatch) -> None:
assert opened == ["http://127.0.0.1:8765/"]
@pytest.mark.parametrize("no_dock", [False, True])
def test_webui_dock_lifetime_wraps_the_attached_client(monkeypatch, tmp_path, no_dock):
config_file = tmp_path / "config.json"
config_file.write_text("{}")
_patch_gateway_ports_free(monkeypatch)
_patch_webui_provider_ready(monkeypatch)
_patch_webui_managed_gateway(monkeypatch)
events = []
@contextmanager
def desktop(url, *, instance, enabled):
assert url.startswith("http://127.0.0.1:")
assert instance.parent == tmp_path / "run"
assert enabled is not no_dock
events.append("icon attached")
try:
yield
finally:
events.append("icon detached")
monkeypatch.setattr(cli_webui, "dock_icon", desktop)
monkeypatch.setattr(cli_webui, "_attach_to_background_gateway",
lambda *_args, **_kwargs: events.append("gateway attached"))
result = runner.invoke(app, ["webui", "--config", str(config_file), "--no-open", "--yes",
*(["--no-dock"] if no_dock else [])])
assert result.exit_code == 0, result.output
assert events == ["icon attached", "gateway attached", "icon detached"]
def test_webui_foreground_attaches_to_existing_managed_gateway(monkeypatch, tmp_path: Path) -> None:
config_file = tmp_path / "config.json"
config_file.write_text("{}")
@@ -3151,7 +3216,7 @@ def test_gateway_uses_workspace_directory_for_cron_store(monkeypatch, tmp_path:
seen: dict[str, Path] = {}
class _StopCron:
def __init__(self, store_path: Path) -> None:
def __init__(self, store_path: Path, *, admission=None) -> None:
seen["cron_store"] = store_path
raise _StopGatewayError("stop")
@@ -3221,7 +3286,7 @@ def test_gateway_unbound_agent_cron_is_skipped(
monkeypatch.setattr("nanobot.session.manager.SessionManager", _FakeSessionManager)
class _FakeCron:
def __init__(self, _store_path: Path) -> None:
def __init__(self, _store_path: Path, *, admission=None) -> None:
self.on_job = None
seen["cron"] = self
@@ -3334,7 +3399,7 @@ def test_gateway_bound_cron_runs_as_session_turn(
monkeypatch.setattr("nanobot.session.manager.SessionManager", _FakeSessionManager)
class _FakeCron:
def __init__(self, _store_path: Path) -> None:
def __init__(self, _store_path: Path, *, admission=None) -> None:
self.on_job = None
seen["cron"] = self
@@ -3526,7 +3591,7 @@ def test_gateway_local_trigger_queue_submits_agent_turns(
config,
message_bus=lambda: bus,
session_manager=lambda _workspace: _FakeSessionManager(),
cron_service=lambda _store_path: _FakeCronService(),
cron_service=lambda _store_path, **_kwargs: _FakeCronService(),
)
class _FakeMemory:
@@ -3687,7 +3752,7 @@ def test_gateway_workspace_override_does_not_migrate_legacy_cron(
seen: dict[str, Path] = {}
class _StopCron:
def __init__(self, store_path: Path) -> None:
def __init__(self, store_path: Path, *, admission=None) -> None:
seen["cron_store"] = store_path
raise _StopGatewayError("stop")
@@ -3726,7 +3791,7 @@ def test_gateway_custom_config_workspace_does_not_migrate_legacy_cron(
seen: dict[str, Path] = {}
class _StopCron:
def __init__(self, store_path: Path) -> None:
def __init__(self, store_path: Path, *, admission=None) -> None:
seen["cron_store"] = store_path
raise _StopGatewayError("stop")
@@ -3879,7 +3944,7 @@ def test_gateway_health_endpoint_binds_and_serves_expected_responses(
return None
class _FakeCronService:
def __init__(self, _store_path: Path) -> None:
def __init__(self, _store_path: Path, *, admission=None) -> None:
self.on_job = None
async def start(self) -> None:
@@ -3971,6 +4036,10 @@ def test_gateway_health_endpoint_binds_and_serves_expected_responses(
assert health_writer.closed is True
assert "HTTP/1.0 200 OK" in health_response
health_body = json.loads(health_response.split("\r\n\r\n", 1)[1])
assert health_body.pop("maintenance") is False
identity = health_body.pop("runtime")
assert identity["version"] == cli_commands.__version__
assert identity["instance_id"] and identity["run_id"]
assert health_body == {
"status": "ok",
"process": "alive",
@@ -4114,7 +4183,7 @@ def test_gateway_agent_task_owns_initial_mcp_provider_close(
seen["channels_stopped"] = True
class _FakeCronService:
def __init__(self, _store_path: Path) -> None:
def __init__(self, _store_path: Path, *, admission=None) -> None:
self.on_job = None
async def start(self) -> None:
@@ -4251,7 +4320,7 @@ def test_gateway_shutdown_event_exits_forever_runtime_tasks(
await asyncio.wait_for(channel_finished.wait(), timeout=1)
class _FakeCronService:
def __init__(self, _store_path: Path) -> None:
def __init__(self, _store_path: Path, *, admission=None) -> None:
self.on_job = None
async def start(self) -> None:
+333
View File
@@ -0,0 +1,333 @@
"""The Dock shortcut never owns gateway execution, data, or credentials on disk."""
import asyncio
import os
import socket
import sys
import tempfile
import threading
from contextlib import contextmanager
from pathlib import Path
import pytest
from nanobot.cli import dock
from nanobot.cli._macos_dock import _Clients, _serve, is_local_browser_url
@pytest.mark.parametrize("platform", ["linux", "win32"])
def test_other_platforms_do_not_prepare_or_launch_an_icon(monkeypatch, tmp_path, platform):
monkeypatch.setattr(dock.sys, "platform", platform)
monkeypatch.setattr(dock, "_attach", lambda *_: pytest.fail("must not launch"))
with dock.dock_icon("http://127.0.0.1:8765/", instance=tmp_path / "gateway.json"):
pass
assert list(tmp_path.iterdir()) == []
def test_explicit_opt_out_and_ssh_do_not_launch(monkeypatch, tmp_path):
monkeypatch.setattr(dock.sys, "platform", "darwin")
monkeypatch.setattr(dock, "_attach", lambda *_: pytest.fail("must not launch"))
with dock.dock_icon("http://127.0.0.1:8765/", instance=tmp_path, enabled=False):
pass
monkeypatch.setenv("SSH_CONNECTION", "test")
with dock.dock_icon("http://127.0.0.1:8765/", instance=tmp_path):
pass
def test_optional_failure_does_not_swallow_webui_failure_or_log_credentials(monkeypatch, tmp_path):
warnings = []
monkeypatch.setattr(dock, "_desktop_available", lambda: True)
monkeypatch.setattr(dock, "_directory", lambda *_: tmp_path)
monkeypatch.setattr(dock.logger, "warning", warnings.append)
def unavailable(*_):
raise OSError("sensitive-url-fragment")
monkeypatch.setattr(dock, "_attach", unavailable)
with pytest.raises(RuntimeError, match="gateway failure"):
with dock.dock_icon("http://127.0.0.1:8765/", instance=tmp_path):
raise RuntimeError("gateway failure")
assert len(warnings) == 1
assert "sensitive" not in warnings[0]
def test_context_releases_its_connection_even_when_the_launcher_is_interrupted(monkeypatch, tmp_path):
first, other = socket.socketpair()
monkeypatch.setattr(dock, "_desktop_available", lambda: True)
monkeypatch.setattr(dock, "_directory", lambda *_: tmp_path)
monkeypatch.setattr(dock, "_attach", lambda *_: first)
with other, pytest.raises(KeyboardInterrupt):
try:
with dock.dock_icon("http://127.0.0.1:8765/", instance=tmp_path):
raise KeyboardInterrupt
finally:
other.settimeout(1)
assert other.recv(1) == b""
@pytest.mark.skipif(sys.platform == "win32", reason="Darwin/Unix helper startup contract")
def test_interrupt_during_handshake_closes_connection_and_stops_new_helper(monkeypatch):
from unittest.mock import MagicMock
connection = MagicMock()
connection.recv.side_effect = KeyboardInterrupt
process = MagicMock()
process.poll.return_value = None
attempts = iter((None, connection))
monkeypatch.setattr(dock, "_connect", lambda *_: next(attempts))
monkeypatch.setattr(dock, "_bundle", lambda *_: Path("unused-test-interpreter"))
monkeypatch.setattr(dock.subprocess, "Popen", lambda *_args, **_kwargs: process)
with tempfile.TemporaryDirectory(prefix="nb-dock-") as name, pytest.raises(KeyboardInterrupt):
dock._attach(Path(name), "http://127.0.0.1:8765/")
connection.close.assert_called_once()
process.terminate.assert_called_once()
@pytest.mark.skipif(sys.platform == "win32", reason="Darwin/Unix helper startup contract")
def test_cold_helper_startup_keeps_the_connection_until_ready(monkeypatch, tmp_path):
# Native AppKit startup was measured at 1.928s after an update, already at
# the old 2s socket deadline. Exercise a cold start without requiring a GUI.
helper = tmp_path / "slow-helper.py"
helper.write_text("""import socket, sys, time
listener = socket.socket(fileno=int(sys.argv[1]))
time.sleep(2.5)
connection, _ = listener.accept()
with connection:
assert connection.recv(8192).endswith(b'\\n')
connection.sendall(b'1')
assert connection.recv(1) == b''
listener.close()
""")
spawned = []
popen = dock.subprocess.Popen
def launch(*args, **kwargs):
process = popen(*args, **kwargs)
spawned.append(process)
return process
monkeypatch.setattr(dock, "_WORKER", helper)
monkeypatch.setattr(dock, "_bundle", lambda _: Path(sys.executable))
monkeypatch.setattr(dock.subprocess, "Popen", launch)
with tempfile.TemporaryDirectory(prefix="nb-dock-") as name:
try:
connection = dock._attach(Path(name), "http://127.0.0.1:8765/")
connection.close()
assert spawned[0].wait(timeout=3) == 0
finally:
for process in spawned:
if process.poll() is None:
process.terminate()
process.wait(timeout=3)
@pytest.mark.skipif(sys.platform == "win32", reason="macOS private-directory contract")
def test_private_cache_rejects_symlink_and_shared_directory(tmp_path):
shared = tmp_path / "shared"
shared.mkdir(mode=0o755)
shared.chmod(0o755)
with pytest.raises(PermissionError):
dock._private_directory(shared)
private = tmp_path / "private"
dock._private_directory(private)
link = tmp_path / "link"
link.symlink_to(private, target_is_directory=True)
with pytest.raises(PermissionError):
dock._private_directory(link)
@pytest.mark.parametrize("url, valid", [
("http://127.0.0.1:8765/#/?bootstrapSecret=test", True),
("http://localhost:8765/", True),
("http://[::1]:5173/", True),
("http://example.com:8765/", False),
("http://127.0.0.1.example.com:8765/", False),
("http://user:pass@127.0.0.1:8765/", False),
("file:///tmp/index.html", False),
("http://127.0.0.1:8765/\n", False),
("http://127.0.0.1:99999/", False),
])
def test_private_socket_only_accepts_local_browser_urls(url, valid):
assert is_local_browser_url(url) is valid
@contextmanager
def _server():
# macOS has a short AF_UNIX address limit; pytest's nested tmp_path can exceed it.
with tempfile.TemporaryDirectory(prefix="nb-dock-") as name:
address = Path(name) / "s"
listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
listener.bind(str(address))
listener.listen()
clients = _Clients()
stopped = threading.Event()
# Keep startup serialized just like the launcher: first connect before release.
from filelock import FileLock
with FileLock(str(address.parent / "start.lock")):
thread = threading.Thread(target=_serve, args=(listener, address, clients, stopped.set))
thread.start()
first = _join(address, "http://127.0.0.1:8765/#/first")
try:
yield address, first, clients, stopped
finally:
first.close()
assert stopped.wait(3)
thread.join(timeout=1)
def _join(address, url):
connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
connection.settimeout(2)
connection.connect(str(address))
connection.sendall(url.encode() + b"\n")
assert connection.recv(1) == b"1"
return connection
@pytest.mark.skipif(sys.platform == "win32", reason="Darwin/Unix socket lifetime contract")
def test_shared_icon_survives_first_launcher_and_stops_after_last():
with _server() as (address, first, clients, stopped):
second = _join(address, "http://127.0.0.1:8765/#/second")
try:
assert clients.current_url().endswith("/second")
first.close()
assert not stopped.wait(0.15)
assert address.exists()
finally:
second.close()
assert stopped.wait(3)
assert not address.exists()
assert clients.current_url() is None
@pytest.mark.skipif(sys.platform == "win32", reason="Darwin/Unix socket lifetime contract")
def test_rejected_peer_does_not_replace_live_url_or_stop_the_icon():
with _server() as (address, first, clients, stopped):
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as invalid:
invalid.settimeout(2)
invalid.connect(str(address))
invalid.sendall(b"https://example.com/\n")
assert invalid.recv(1) == b""
assert clients.current_url().endswith("/first")
assert not stopped.is_set()
first.close()
@pytest.mark.skipif(sys.platform == "win32", reason="Darwin/Unix socket lifetime contract")
def test_new_launcher_can_join_while_the_previous_launcher_exits():
from filelock import FileLock
with _server() as (address, first, _clients, stopped):
with FileLock(str(address.parent / "start.lock")):
first.close()
assert not stopped.wait(0.15)
second = _join(address, "http://127.0.0.1:8765/#/next")
try:
assert not stopped.wait(0.15)
finally:
second.close()
@pytest.mark.skipif(sys.platform == "win32", reason="macOS interpreter wrapper")
def test_bundle_uses_current_python_and_never_contains_the_login_url(tmp_path):
import plistlib
executable = dock._bundle(tmp_path)
assert executable.is_symlink()
assert os.readlink(executable) == sys.executable
info = plistlib.loads((executable.parent.parent / "Info.plist").read_bytes())
assert info["CFBundleDisplayName"] == "nanobot"
assert (executable.parent.parent / "Resources" / "dock-icon.png").read_bytes() == dock._ICON.read_bytes()
assert len([path for path in tmp_path.rglob("*") if path.is_file()]) == 3
async def test_background_presence_waits_for_activation_and_remembers_explicit_requests(monkeypatch, tmp_path):
monkeypatch.setattr(dock, "_desktop_available", lambda: True)
instance = tmp_path / "run" / "gateway.json"
entered, closed = threading.Event(), threading.Event()
@contextmanager
def icon(url, **_kwargs):
assert url == "http://127.0.0.1:8765/"
entered.set()
try:
yield
finally:
closed.set()
monkeypatch.setattr(dock, "dock_icon", icon)
dock.request_gateway_icon(instance, enabled=True)
intent = instance.with_suffix(".dock").read_text()
assert intent.startswith("show:") and "http" not in intent
activated = asyncio.Event()
watcher = asyncio.create_task(dock.watch_gateway_icon(
"http://127.0.0.1:8765/", instance=instance, activated=activated,
))
try:
await asyncio.sleep(0)
assert not entered.is_set()
activated.set()
assert await asyncio.to_thread(entered.wait, 2)
dock.request_gateway_icon(instance, enabled=False)
assert await asyncio.to_thread(closed.wait, 2)
entered.clear()
closed.clear()
dock.request_gateway_icon(instance, enabled=True)
assert await asyncio.to_thread(entered.wait, 2)
finally:
watcher.cancel()
with pytest.raises(asyncio.CancelledError):
await watcher
assert closed.is_set()
# A new gateway generation, including a protected update restart, reads the
# same intent without rewriting configuration or learning an updater protocol.
entered.clear()
watcher = asyncio.create_task(dock.watch_gateway_icon(
"http://127.0.0.1:8765/", instance=instance, activated=activated,
))
try:
assert await asyncio.to_thread(entered.wait, 2)
finally:
watcher.cancel()
with pytest.raises(asyncio.CancelledError):
await watcher
async def test_cancelled_gateway_joins_pending_dock_startup_before_releasing_it(monkeypatch, tmp_path):
monkeypatch.setattr(dock, "_desktop_available", lambda: True)
started, release, closed = threading.Event(), threading.Event(), threading.Event()
@contextmanager
def slow_icon(*_args, **_kwargs):
started.set()
assert release.wait(3)
try:
yield
finally:
closed.set()
monkeypatch.setattr(dock, "dock_icon", slow_icon)
instance = tmp_path / "gateway.json"
dock.request_gateway_icon(instance, enabled=True)
activated = asyncio.Event()
activated.set()
watcher = asyncio.create_task(dock.watch_gateway_icon(
"http://127.0.0.1:8765/", instance=instance, activated=activated,
))
try:
assert await asyncio.to_thread(started.wait, 2)
watcher.cancel()
await asyncio.sleep(0)
assert not watcher.done()
finally:
release.set()
with pytest.raises(asyncio.CancelledError):
await watcher
assert closed.is_set()
def test_background_preference_failure_never_blocks_the_launcher(monkeypatch, tmp_path):
monkeypatch.setattr(dock, "_desktop_available", lambda: True)
not_directory = tmp_path / "file"
not_directory.write_text("test")
dock.request_gateway_icon(not_directory / "gateway.json", enabled=True)
+69 -2
View File
@@ -7,6 +7,7 @@ import pytest
from nanobot.cli import entry
from nanobot.cli.entry import _agent_invocation_args, _native_tui_candidate
from nanobot.installation_lock import InstallationBusyError, installation_access, installation_id
def test_root_command_routes_to_agent_without_copying_agent_options() -> None:
@@ -70,7 +71,7 @@ def test_root_alias_dispatches_the_shared_agent_command(monkeypatch) -> None:
"set_cli_process_identity",
lambda args: calls.__setitem__("identity", args),
)
monkeypatch.setattr(entry, "_configure_windows_console", lambda: None)
monkeypatch.setattr(entry, "configure_windows_console", lambda: None)
monkeypatch.setattr(
entry,
"_run_agent",
@@ -91,7 +92,7 @@ def test_desktop_handled_bare_invocation_does_not_start_python(monkeypatch) -> N
monkeypatch.setattr(entry.sys, "argv", ["nanobot"])
monkeypatch.setattr(entry, "set_cli_process_identity", lambda _args: None)
monkeypatch.setattr(entry, "_configure_windows_console", lambda: None)
monkeypatch.setattr(entry, "configure_windows_console", lambda: None)
monkeypatch.setattr(desktop_target, "dispatch_bare_desktop_target", lambda _args: 0)
monkeypatch.setattr(
entry,
@@ -114,3 +115,69 @@ def test_classic_and_one_shot_agent_invocations_keep_the_full_cli_entrypoint() -
assert not _native_tui_candidate(["agent", "-mhello"])
assert not _native_tui_candidate(["agent", "--message=hello"])
assert not _native_tui_candidate(["status"])
def test_entry_refuses_dispatch_during_update(tmp_path, monkeypatch, capsys):
monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
monkeypatch.setattr(sys, "prefix", str(tmp_path / "environment"))
monkeypatch.setattr(sys, "argv", ["nanobot", "gateway"])
monkeypatch.setattr(entry, "_dispatch", lambda: pytest.fail("Runtime dispatched during update"))
with installation_access(updating=True):
with pytest.raises(SystemExit) as result:
entry.main()
assert result.value.code == 1
assert "being updated" in capsys.readouterr().err
@pytest.mark.parametrize("args", [["update"], ["--home", "/test", "update"], ["--home=/test", "update"]])
def test_update_command_can_reach_its_own_lease_and_recovery(tmp_path, monkeypatch, args):
monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
monkeypatch.setattr(sys, "prefix", str(tmp_path / "environment"))
monkeypatch.setattr(sys, "argv", ["nanobot", *args])
called = []
monkeypatch.setattr(entry, "_dispatch", lambda: called.append(True))
with installation_access(updating=True):
entry.main()
assert called == [True]
@pytest.mark.parametrize("args", [["update", "--job", "saved-id"],
["--home=/test", "update", "--job=saved-id", "--retry-handoff"]])
def test_saved_update_recovery_owns_runtime_before_application_imports(tmp_path, monkeypatch, args):
monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
monkeypatch.setattr(sys, "prefix", str(tmp_path / "environment"))
monkeypatch.setattr(sys, "argv", ["nanobot", *args])
entered = []
def dispatch():
with pytest.raises(InstallationBusyError):
with installation_access(updating=True):
pytest.fail("Recovery imported without a runtime lease")
entered.append(True)
monkeypatch.setattr(entry, "_dispatch", dispatch)
entry.main()
assert entered == [True]
with installation_access(updating=True):
with pytest.raises(SystemExit):
entry.main()
assert entered == [True]
@pytest.mark.parametrize("action,allowed", [("stop", True), ("status", True), ("logs", True), ("restart", False)])
def test_interrupted_installation_keeps_stop_commands_usable(tmp_path, monkeypatch, action, allowed):
monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
monkeypatch.setattr(sys, "prefix", str(tmp_path / "environment"))
pending = tmp_path / ".nanobot/run" / f"update-{installation_id()[:16]}.pending"
pending.parent.mkdir(parents=True)
pending.write_text("incomplete")
monkeypatch.setattr(sys, "argv", ["nanobot", "--home", str(tmp_path / "profile"), "gateway", action])
called = []
monkeypatch.setattr(entry, "_dispatch", lambda: called.append(True))
if allowed:
entry.main()
assert called == [True]
else:
with pytest.raises(SystemExit):
entry.main()
assert not called
+1
View File
@@ -139,6 +139,7 @@ def _test_app(
config: Config,
*,
port: int | None = None,
verbose: bool = False,
webui_bundle_mode: str | None = None,
unconfigured_provider_error: str | None = None,
gateway_instance: GatewayInstance | None = None,
+9 -3
View File
@@ -356,13 +356,16 @@ def test_source_checkout_does_not_fall_back_to_a_release_tui_without_bun(
"nanobot.cli.tui_launcher._source_checkout_tui_dir",
lambda: source_dir,
)
monkeypatch.setattr("nanobot.cli.tui_launcher.shutil.which", lambda _name: None)
def unavailable():
raise tui_launcher.BunUnavailableError("Bun download failed")
monkeypatch.setattr(tui_launcher, "ensure_bun", unavailable)
monkeypatch.setattr(
"nanobot.cli.tui_launcher._download_release_tui",
lambda _asset: pytest.fail("a source checkout must not download a release TUI"),
)
with pytest.raises(TuiUnavailableError, match="source checkout requires Bun"):
with pytest.raises(TuiUnavailableError, match="Bun download failed"):
resolve_tui_command()
@@ -539,6 +542,7 @@ def test_source_checkout_refreshes_locked_tui_dependencies(
source_dir.mkdir()
(source_dir / "node_modules" / "@opentui" / "core").mkdir(parents=True)
bun = str(tmp_path / "bun")
Path(bun).write_bytes(b"runtime")
def install(command: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
assert command == [bun, "install", "--frozen-lockfile"]
@@ -563,13 +567,15 @@ def test_source_checkout_fails_when_locked_dependencies_cannot_be_refreshed(
) -> None:
source_dir = tmp_path / "tui"
source_dir.mkdir()
bun = tmp_path / "bun"
bun.write_bytes(b"runtime")
monkeypatch.setattr(
"nanobot.cli.tui_launcher.subprocess.run",
lambda *args, **kwargs: subprocess.CompletedProcess(args, 1, "", "lockfile mismatch"),
)
with pytest.raises(TuiUnavailableError, match="lockfile mismatch"):
_resolve_source_tui_command(source_dir, "bun")
_resolve_source_tui_command(source_dir, str(bun))
def test_release_tui_is_verified_and_cached(
+191
View File
@@ -7,6 +7,7 @@ import json
import runpy
import stat
import struct
import subprocess
import tarfile
import tomllib
import zipfile
@@ -17,6 +18,13 @@ import pytest
from nanobot.cli import tui_launcher
from scripts import build_tui_wheels as packager
from scripts import release_candidate
from scripts.release_candidate import (
retain_candidate,
verify_candidate,
write_install_guide,
write_manifest,
)
@pytest.fixture
@@ -186,3 +194,186 @@ def test_installed_tui_never_downloads_or_requires_bun(tmp_path, monkeypatch, sy
cache = tmp_path / "empty-cache"
assert tui_launcher.resolve_tui_command(data_dir=cache) == [str(binary)]
assert not cache.exists()
@pytest.fixture
def complete_candidate(tmp_path, candidate):
"""Actual checkout payload, with synthetic native binaries (not native execution)."""
from hatch_build import WebUIBuildHook
root = tmp_path / "checkout"
subprocess.run(["git", "clone", "--shared", str(packager.ROOT), str(root)],
check=True, capture_output=True)
commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=root, text=True).strip()
metadata = tomllib.loads((root / "pyproject.toml").read_text())["project"]
wheel, info = candidate
with zipfile.ZipFile(wheel) as archive:
files = {name: archive.read(name) for name in archive.namelist()}
tracked = subprocess.check_output(["git", "ls-files", "-z", "--", "nanobot"], cwd=root).decode().split("\0")
for name in filter(None, tracked):
parts = name.split("/")
if len(parts) > 3 and parts[1] == "channels" and parts[3] == "tests":
continue
files[name] = (root / name).read_bytes()
hook = WebUIBuildHook(str(root), {}, None, {}, "", "wheel",
SimpleNamespace(display_info=lambda message: None))
hook.initialize("editable", {})
references = root / "nanobot/skills/nanobot-document/references"
documentation = {}
for reference in references.rglob("*.md"):
files[reference.relative_to(root).as_posix()] = reference.read_bytes()
name = "docs/" + reference.relative_to(references).as_posix()
documentation[name] = (root / name).read_bytes()
files[f"{info}/METADATA"] += f'Requires-Python: {metadata["requires-python"]}\n'.encode()
files["nanobot/_build_commit.txt"] = f"{commit}\n".encode()
files["nanobot/web/dist/index.html"] = b"<html>compiled fixture</html>"
record = io.StringIO()
writer = csv.writer(record)
for name, content in files.items():
if not name.endswith("/RECORD"):
writer.writerow((name, packager._digest(content), len(content)))
writer.writerow((f"{info}/RECORD", "", ""))
files[f"{info}/RECORD"] = record.getvalue().encode()
with zipfile.ZipFile(wheel, "w") as archive:
for name, content in files.items():
archive.writestr(name, content)
artifacts = tmp_path / "artifacts"
artifacts.mkdir()
for target in packager.PLATFORMS:
make_bundle(artifacts, target)
packager.build_wheel(wheel, artifacts, artifacts, target, root=root)
version = metadata["version"]
source_files = {
"PKG-INFO": files[f"{info}/METADATA"],
"pyproject.toml": (root / "pyproject.toml").read_bytes(),
**documentation,
**{name: data for name, data in files.items() if name.startswith("nanobot/")},
}
with tarfile.open(artifacts / f"nanobot_ai-{version}.tar.gz", "w:gz") as archive:
for name, data in source_files.items():
member = tarfile.TarInfo(f"nanobot_ai-{version}/{name}")
member.size = len(data)
archive.addfile(member, io.BytesIO(data))
return root, commit, artifacts
def test_complete_manifest_binds_wheels_sdist_and_fallback_archives(tmp_path, complete_candidate):
"""Real archive/RECORD checks, with synthetic binaries (not native execution)."""
root, commit, artifacts = complete_candidate
manifest = verify_candidate(root, artifacts, source_commit=commit)
assert len(manifest.artifacts) == 16
assert manifest.candidate_commit == commit
output = artifacts / "release-manifest.json"
write_manifest(manifest, output)
original = output.read_bytes()
write_manifest(verify_candidate(root, artifacts, source_commit=commit), output)
assert output.read_bytes() == original
with pytest.raises(FileExistsError):
write_manifest(manifest.model_copy(update={"source_commit": "f" * 40}), output)
guide = tmp_path / "install.md"
write_install_guide(root, artifacts, guide, source_commit=commit)
original_guide = guide.read_bytes()
write_install_guide(root, artifacts, guide, source_commit=commit)
assert guide.read_bytes() == original_guide
assert commit.encode() in original_guide
assert len(list(artifacts.iterdir())) == 17 # 16 artifacts and the manifest, no guide.
with pytest.raises(ValueError, match="outside"):
write_install_guide(root, artifacts, artifacts / "install.md", source_commit=commit)
guide.write_text("previous reviewed handoff\n")
with pytest.raises(FileExistsError, match="overwrite"):
write_install_guide(root, artifacts, guide, source_commit=commit)
assert guide.read_text() == "previous reviewed handoff\n"
recorded = json.loads(original)
recorded["artifacts"][0]["sha256"] = "f" * 64
output.write_text(json.dumps(recorded))
with pytest.raises(ValueError, match="recorded release manifest"):
write_install_guide(root, artifacts, tmp_path / "unverified.md", source_commit=commit)
assert not (tmp_path / "unverified.md").exists()
output.write_bytes(original)
damaged = artifacts / "nanobot-tui-linux-x64.zip.sha256"
damaged.write_text("0" * 64 + " nanobot-tui-linux-x64.zip\n")
with pytest.raises(ValueError, match="checksum mismatch"):
verify_candidate(root, artifacts, source_commit=commit)
with pytest.raises(ValueError, match="checksum mismatch"):
write_install_guide(root, artifacts, tmp_path / "damaged.md", source_commit=commit)
assert not (tmp_path / "damaged.md").exists()
def test_retained_candidate_keeps_checked_bytes_and_independent_source(tmp_path, complete_candidate):
root, commit, artifacts = complete_candidate
manifest = verify_candidate(root, artifacts, source_commit=commit)
write_manifest(manifest, artifacts / "release-manifest.json")
(root / "private-untracked.txt").write_text("not release input")
output = tmp_path / "retained"
retain_candidate(root, artifacts, output, source_commit=commit)
identity = json.loads((output / "handoff.json").read_text())
assert identity["candidate_commit"] == commit and identity["published"] is False
assert identity["manifest_sha256"] == hashlib.sha256((artifacts / "release-manifest.json").read_bytes()).hexdigest()
assert verify_candidate(root, output / "artifacts", source_commit=commit) == manifest
for original in artifacts.iterdir():
assert (output / "artifacts" / original.name).read_bytes() == original.read_bytes()
independent = tmp_path / "independent"
subprocess.run(["git", "clone", "--no-local", str(output / "source.git"), str(independent)],
check=True, capture_output=True)
assert subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=independent, text=True).strip() == commit
assert not (independent / "private-untracked.txt").exists()
assert not (output / "source.git/objects/info/alternates").exists()
assert str(root) not in (output / "source.git/config").read_text()
assert verify_candidate(independent, output / "artifacts", source_commit=commit) == manifest
with pytest.raises(FileExistsError):
retain_candidate(root, artifacts, output, source_commit=commit)
def test_interrupted_retention_has_no_accepted_handoff(tmp_path, complete_candidate, monkeypatch):
root, commit, artifacts = complete_candidate
write_manifest(verify_candidate(root, artifacts, source_commit=commit), artifacts / "release-manifest.json")
def interrupted_copy(source, target):
raise OSError("controlled interrupted copy")
monkeypatch.setattr(release_candidate.shutil, "copyfile", interrupted_copy)
output = tmp_path / "interrupted"
with pytest.raises(OSError, match="interrupted copy"):
retain_candidate(root, artifacts, output, source_commit=commit)
assert not (output / "handoff.json").exists()
@pytest.mark.parametrize("mutation", ["wheel-code", "wheel-webui", "source-code", "source-missing", "source-extra"])
def test_complete_candidate_rejects_mixed_or_incomplete_application_payload(tmp_path, complete_candidate, mutation):
root, commit, artifacts = complete_candidate
# These are intact archives with valid versions/commit markers and RECORDs.
# A stale intermediate or a stray local file can still be packaged correctly.
if mutation.startswith("wheel-"):
wheel = next(artifacts.glob("*-macosx_13_0_arm64.whl"))
with zipfile.ZipFile(wheel) as archive:
entries = archive.infolist()
files = {entry.filename: archive.read(entry) for entry in entries}
name = "nanobot/__init__.py" if mutation == "wheel-code" else "nanobot/web/dist/index.html"
files[name] += b"\n# stale build\n"
record_name = next(name for name in files if name.endswith(".dist-info/RECORD"))
record = io.StringIO()
writer = csv.writer(record)
for name, data in files.items():
writer.writerow((name, "", "") if name == record_name else (name, packager._digest(data), len(data)))
files[record_name] = record.getvalue().encode()
with zipfile.ZipFile(wheel, "w") as archive:
for entry in entries:
archive.writestr(entry, files[entry.filename])
else:
source = next(artifacts.glob("nanobot_ai-*.tar.gz"))
files = packager.source_files(source.read_bytes())
module = next(name for name in files if name.endswith("/nanobot/agent/loop.py"))
if mutation == "source-code":
files[module] += b"\n# stale build\n"
elif mutation == "source-missing":
del files[module]
else:
files[module.split("/", 1)[0] + "/nanobot/local-settings.json"] = b'{"local": true}'
with tarfile.open(source, "w:gz") as archive:
for name, data in files.items():
member = tarfile.TarInfo(name)
member.size = len(data)
archive.addfile(member, io.BytesIO(data))
with pytest.raises(ValueError, match="application payload"):
verify_candidate(root, artifacts, source_commit=commit)
assert not (artifacts / "release-manifest.json").exists()
+3 -2
View File
@@ -71,11 +71,12 @@ Test-Trace 'PowerShell started'
result = subprocess.run(
["powershell.exe", "-NoProfile", "-NonInteractive", "-STA", "-EncodedCommand",
base64.b64encode(script.encode("utf-16-le")).decode("ascii")],
input=base64.b64encode(content) + b"\n", capture_output=True, timeout=15,
# Cold C# compilation on a Windows runner is not the acknowledgement deadline.
input=base64.b64encode(content) + b"\n", capture_output=True, timeout=60,
)
except subprocess.TimeoutExpired as exc:
stages = (exc.stderr or b"").decode("utf-8", errors="replace")
pytest.fail(f"Windows handoff exceeded 15s. Native stages:\n{stages}", pytrace=False)
pytest.fail(f"Windows handoff exceeded 60s. Native stages:\n{stages}", pytrace=False)
assert result.returncode == (0 if opens else 1), result.stderr
assert result.stdout == b"private;" + (b"1" if opens else b"") + b"removed=True"