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

+21 -1
View File
@@ -29,6 +29,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.channels.websocket.binary_http import BinaryHTTPBridge
from nanobot.config_base import Base
from nanobot.runtime_admission import RuntimeMaintenanceError
from nanobot.session.webui_turns import (
clear_websocket_turn_if_current,
mark_websocket_turn_transcript_persistence_failed,
@@ -705,6 +706,15 @@ class WebSocketChannel(BaseChannel):
async def handler(connection: ServerConnection) -> None:
await self._connection_loop(connection)
from aiohttp import web
async def handle_binary(request: web.BaseRequest) -> web.StreamResponse:
try:
with self.bus.admission.activity():
return await self._uploads.handle(request)
except RuntimeMaintenanceError:
return web.json_response({"error": "Gateway update is being verified"}, status=503)
async def prune_uploads() -> None:
while not stop_event.is_set():
self._uploads.store.prune()
@@ -720,7 +730,7 @@ class WebSocketChannel(BaseChannel):
failures = 0
while not stop_event.is_set():
server: Server | None = None
bridge = BinaryHTTPBridge(self._uploads.handle)
bridge = BinaryHTTPBridge(handle_binary)
was_serving = False
started_at = 0.0
try:
@@ -969,6 +979,16 @@ class WebSocketChannel(BaseChannel):
name=f"websocket-outbound-{id(connection):x}",
)
@property
def has_pending_delivery(self) -> bool:
# send() only enqueues a frame. buffered_bytes includes the frame that
# a writer has removed from its queue but has not finished transmitting.
return bool(self._outbound_retire_tasks) or any(
state.buffered_bytes or not state.queue.empty()
or (state.writer is not None and not state.writer.done())
for state in self._connection_outbound.values()
)
async def _drain_connection_outbound(
self,
connection: ServerConnection,
@@ -1,6 +1,7 @@
"""Production listener regressions for HTTP upload + small WS references."""
import asyncio
import json
import threading
from pathlib import Path
import aiohttp
@@ -9,6 +10,8 @@ from websockets.asyncio.client import connect
from nanobot.bus.queue import MessageBus
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
from nanobot.config.loader import load_config
from nanobot.runtime_admission import RuntimeBusyError
from nanobot.session.manager import SessionManager
from nanobot.webui.gateway_services import build_gateway_services
@@ -48,6 +51,134 @@ async def event(ws, name):
return payload
@pytest.mark.parametrize("finish", [True, False], ids=["complete", "disconnect"])
async def test_streaming_upload_blocks_maintenance_until_written_or_cleaned(gateway, finish):
channel, bus, http_url, ws_url = gateway
port = int(http_url.rsplit(":", 1)[1])
store = channel.gateway.uploads.store
async with connect(ws_url) as ws:
capability = (await event(ws, "ready"))["upload"]
reader, writer = await asyncio.open_connection("127.0.0.1", port)
try:
writer.write((
f"POST {capability['path']} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n"
f"Authorization: Bearer {capability['token']}\r\n"
"Content-Type: image/png\r\nContent-Length: 8\r\n\r\npart"
).encode())
await writer.drain()
async with asyncio.timeout(3):
while store._active == 0:
await asyncio.sleep(.01)
with pytest.raises(RuntimeBusyError):
with bus.admission.pause_if_idle(lambda: False):
pytest.fail("Maintenance ignored an in-progress binary write")
assert not bus.admission.paused
if finish:
writer.write(b"done")
await writer.drain()
response = await asyncio.wait_for(reader.read(), timeout=3)
assert response.startswith(b"HTTP/1.1 201"), response
else:
writer.close()
await writer.wait_closed()
async with asyncio.timeout(3):
while store._active:
await asyncio.sleep(.01)
with bus.admission.pause_if_idle(lambda: False):
assert bus.admission.paused
if not finish:
assert not tuple(store._journal.iterdir())
finally:
writer.close()
await writer.wait_closed()
async def test_threaded_settings_write_stays_busy_after_browser_disconnect(gateway, monkeypatch):
channel, bus, _, ws_url = gateway
entered, release = threading.Event(), threading.Event()
settings = channel.gateway.settings
original = settings.config.run_serialized
def delayed_save(*args, **kwargs):
entered.set()
assert release.wait(10), "Test did not release the settings writer"
return original(*args, **kwargs)
monkeypatch.setattr(settings.config, "run_serialized", delayed_save)
def connection_url():
token = channel.gateway.tokens.issue_token(300, audience="webui")
return ws_url.replace("test-secret", token)
def request(identifier, value):
return json.dumps({"type": "webui_request", "request_id": identifier,
"action": "settings.runtime_config.update",
"payload": {"values": {"agents.defaults.max_tool_iterations": value}}})
try:
async with connect(connection_url()) as ws:
await event(ws, "ready")
await ws.send(request("slow-write", 31))
assert await asyncio.to_thread(entered.wait, 3)
with pytest.raises(RuntimeBusyError):
with bus.admission.pause_if_idle(lambda: False):
pytest.fail("Maintenance ignored a threaded settings write")
# Existing mutation ownership deliberately survives a lost browser;
# losing its delivery task must not make the gateway appear idle.
with pytest.raises(RuntimeBusyError):
with bus.admission.pause_if_idle(lambda: False):
pytest.fail("Browser disconnect released an unfinished write")
operation = channel._commands.request_operations["slow-write"].task
release.set()
result = await asyncio.wait_for(asyncio.shield(operation), timeout=5)
assert result.status is None, result
assert load_config(settings.config.path).agents.defaults.max_tool_iterations == 31
async with connect(connection_url()) as ws:
await event(ws, "ready")
with bus.admission.pause_if_idle(lambda: False):
await ws.send(request("blocked-write", 32))
rejected = await event(ws, "webui_response")
assert rejected["error"]["status"] == 503
assert load_config(settings.config.path).agents.defaults.max_tool_iterations == 31
await ws.send(request("after-abort", 33))
assert (await event(ws, "webui_response"))["ok"] is True
assert load_config(settings.config.path).agents.defaults.max_tool_iterations == 33
finally:
release.set()
async def test_http_route_is_busy_until_its_async_work_finishes(gateway, monkeypatch):
channel, bus, http_url, _ = gateway
entered, release = asyncio.Event(), asyncio.Event()
route = channel.gateway.http._dispatch_resolved
async def delayed_route(*args, **kwargs):
entered.set()
await release.wait()
return await route(*args, **kwargs)
monkeypatch.setattr(channel.gateway.http, "_dispatch_resolved", delayed_route)
async with aiohttp.ClientSession(headers={"Authorization": "Bearer test-secret"}) as http:
request = asyncio.create_task(http.get(http_url + "/webui/bootstrap"))
try:
await asyncio.wait_for(entered.wait(), timeout=3)
with pytest.raises(RuntimeBusyError):
with bus.admission.pause_if_idle(lambda: False):
pytest.fail("Maintenance ignored a running HTTP handler")
release.set()
async with await asyncio.wait_for(request, timeout=3) as response:
assert response.status == 200
await response.read()
with bus.admission.pause_if_idle(lambda: False):
async with http.get(http_url + "/webui/bootstrap") as response:
assert response.status == 503
async with http.get(http_url + "/webui/bootstrap") as response:
assert response.status == 200
finally:
release.set()
await asyncio.gather(request, return_exceptions=True)
@pytest.mark.parametrize("mime,name", [
("image/png", "image.png"), ("text/csv", "report.csv"), ("video/webm", "clip.webm"),
])
@@ -16,6 +16,7 @@ from nanobot.channels.manager import ChannelManager
from nanobot.channels.websocket import runtime
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
from nanobot.config.schema import Config
from nanobot.runtime_admission import RuntimeBusyError
from nanobot.webui.gateway_services import build_gateway_services
@@ -64,7 +65,7 @@ class _RecordingConnection:
def _channel() -> WebSocketChannel:
bus = MagicMock(spec=MessageBus)
bus = MessageBus()
config = WebSocketConfig(
enabled=True,
allow_from=["*"],
@@ -129,9 +130,24 @@ async def test_message_bus_delivers_to_ten_tuis_with_one_blocked_connection() ->
assert await _next_text(connection) == "first"
assert await _next_text(connection) == "last"
assert connections[0].sent.empty()
async with asyncio.timeout(2):
while manager._outbound_tasks or bus.outbound_size:
await asyncio.sleep(0)
# The manager's send has finished; the physical transport still owns
# its final frames. A shutdown idle check must include that second queue.
assert channel.has_pending_delivery
with pytest.raises(RuntimeBusyError):
with bus.admission.pause_if_idle(lambda: False):
pytest.fail("The blocked WebSocket transport was missed")
assert not bus.admission.paused
connections[0].release_send.set()
assert await _next_text(connections[0]) == "first"
assert await _next_text(connections[0]) == "last"
async with asyncio.timeout(2):
while manager.has_pending_delivery:
await asyncio.sleep(0)
with bus.admission.pause_if_idle(lambda: False):
assert bus.admission.paused
finally:
dispatcher.cancel()
await asyncio.gather(dispatcher, return_exceptions=True)
@@ -142,6 +158,26 @@ async def test_message_bus_delivers_to_ten_tuis_with_one_blocked_connection() ->
assert not channel._connection_outbound
@pytest.mark.asyncio
async def test_delivery_remains_busy_until_timed_out_transport_is_retired(monkeypatch) -> None:
monkeypatch.setattr(runtime, "_OUTBOUND_SEND_TIMEOUT_S", 0.02)
channel = _channel()
connection = _RecordingConnection(block_first_send=True, block_close=True)
channel._attach(cast(Any, connection), "chat-retiring")
try:
await channel.send(_message("chat-retiring", "reply"))
await asyncio.wait_for(connection.closed.wait(), 2)
assert connection.send_cancelled.is_set()
assert channel.has_pending_delivery
connection.release_close.set()
await asyncio.wait_for(_wait_for_retire_tasks(channel), 2)
assert not channel.has_pending_delivery
finally:
connection.release_send.set()
connection.release_close.set()
await channel._cleanup_connection(cast(Any, connection))
@pytest.mark.asyncio
async def test_slow_tui_does_not_block_a_different_topic() -> None:
channel = _channel()