fix(webui): refresh pairing prompts on gateway changes (#6401)

This commit is contained in:
chengyongru authored and GitHub committed 2026-10-25 20:16:51 +08:00
1 parent 9e9e22d331
commit 8af6313c56
26 files changed
+630 -82

No files matched your search

+11
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.pairing.events import PairingChanged
from nanobot.runtime_admission import RuntimeMaintenanceError
from nanobot.session.webui_turns import (
clear_websocket_turn_if_current,
@@ -816,11 +817,13 @@ class WebSocketChannel(BaseChannel):
if self._server is server:
self._server = None
disconnect_pairing = self.bus.subscribe(self._queue_pairing_changed, PairingChanged)
task = asyncio.create_task(runner())
self._server_task = task
try:
await task
finally:
disconnect_pairing()
prune_task.cancel()
await asyncio.gather(prune_task, return_exceptions=True)
self._uploads.store.clear()
@@ -1552,6 +1555,14 @@ class WebSocketChannel(BaseChannel):
for connection in conns:
await self._safe_send_to(connection, raw, label=" user_message ")
async def _queue_pairing_changed(self, event: PairingChanged) -> None:
await self.bus.publish_event(event, channel=self.name, chat_id="*")
async def send_pairing_changed(self) -> None:
"""Project invalidation only to bootstrap-authenticated WebUI clients."""
for connection in tuple(self._webui_connections):
await self._send_event(connection, "pairing_changed")
async def send_runtime_model_updated(
self,
*,
@@ -50,6 +50,7 @@ from nanobot.channels.websocket.runtime import (
)
from nanobot.config.loader import load_config, save_config
from nanobot.config.schema import Config, ModelAPIConfig, ModelPresetConfig
from nanobot.pairing.events import PairingChanged
from nanobot.providers.base import LLMUsage
from nanobot.runtime_context import RUNTIME_CONTEXT_INPUT_META, WEBUI_QUOTE_SOURCE
from nanobot.security.workspace_access import WORKSPACE_SCOPE_METADATA_KEY
@@ -2371,6 +2372,21 @@ async def test_send_delivers_json_message_with_media_and_reply() -> None:
assert payload["media"] == ["/tmp/a.png"]
@pytest.mark.asyncio
async def test_pairing_invalidation_reaches_only_authenticated_webui_connections() -> None:
bus = MessageBus()
channel = _ch(bus)
webui, ordinary = AsyncMock(), AsyncMock()
channel._attach(webui, "chat-1")
channel._attach(ordinary, "chat-1")
channel._webui_connections.add(webui)
await channel.send(OutboundMessage(
channel="websocket", chat_id="*", content="", event=PairingChanged(),
))
assert json.loads(webui.send.call_args[0][0]) == {"event": "pairing_changed"}
ordinary.send.assert_not_awaited()
@pytest.mark.asyncio
async def test_send_broadcasts_runtime_model_updates() -> None:
bus = MessageBus()
@@ -1230,11 +1230,11 @@ async def test_pairing_routes_require_token_and_approve_or_deny(
monkeypatch.setattr("nanobot.webui.settings_routes.list_pending", lambda: list(pending))
monkeypatch.setattr(
"nanobot.webui.settings_routes.approve_code",
lambda code: approved.append(code) or ("feishu", "ou_123") if code == "ABCD-EFGH" else None,
lambda code, **_kwargs: approved.append(code) or ("feishu", "ou_123") if code == "ABCD-EFGH" else None,
)
monkeypatch.setattr(
"nanobot.webui.settings_routes.deny_code",
lambda code: denied.append(code) or code == "ABCD-EFGH",
lambda code, **_kwargs: denied.append(code) or code == "ABCD-EFGH",
)
channel = _ch(bus, session_manager=_seed_session(tmp_path), port=_free_port())
@@ -1291,6 +1291,28 @@ async def test_pairing_routes_require_token_and_approve_or_deny(
assert "Missing pairing code" in missing_code.text
@pytest.mark.asyncio
@pytest.mark.parametrize("action", ["approve", "deny"])
async def test_pairing_mutation_publishes_committed_snapshot(action, tmp_path, monkeypatch):
from nanobot.bus.queue import MessageBus
from nanobot.pairing import store
from nanobot.pairing.events import PairingChanged
monkeypatch.setattr(store, "_store_path", lambda: tmp_path / "pairing.json")
code = store.generate_code("telegram", "alice")
bus = MessageBus()
snapshots = []
bus.subscribe(lambda _event: snapshots.append(store.list_pending()), PairingChanged)
channel = _ch(bus, session_manager=_seed_session(tmp_path), port=_free_port())
result = await _webui_mutate(channel, f"settings.pairing.{action}", {"code": code})
await bus.drain()
assert result.status_code == 200 and snapshots == [[]]
assert store.is_approved("telegram", "alice") == (action == "approve")
missing = await _webui_mutate(channel, f"settings.pairing.{action}", {"code": code})
await bus.drain()
assert missing.status_code == 404 and snapshots == [[]]
@pytest.mark.asyncio
async def test_nanobot_feature_remote_install_requires_opt_in(
bus: MagicMock,
@@ -8,6 +8,7 @@ import pytest
from nanobot.bus.queue import MessageBus
from nanobot.channels.websocket.runtime import WebSocketChannel
from nanobot.pairing.events import PairingChanged
class _FakeSocket:
@@ -70,6 +71,8 @@ async def test_websocket_does_not_report_running_before_bind_succeeds(monkeypatc
assert exc_info.value is bind_error
assert channel.is_running is False
await channel.bus.publish(PairingChanged())
assert channel.bus.outbound_size == 0
assert not any(
call.args and call.args[0] == "WebSocket server listening on {}"
for call in channel.logger.info.call_args_list
@@ -112,6 +115,10 @@ async def test_websocket_restarts_only_its_listener_after_serving_socket_is_lost
break
await asyncio.sleep(0)
assert channel.is_running is True
await channel.bus.publish(PairingChanged())
notification = await channel.bus.consume_outbound()
assert notification.channel == "websocket" and notification.chat_id == "*"
assert isinstance(notification.event, PairingChanged)
first.socket.open = False
for _ in range(50):
@@ -129,3 +136,5 @@ async def test_websocket_restarts_only_its_listener_after_serving_socket_is_lost
await start_task
assert second.closed is True
await channel.bus.publish(PairingChanged())
assert channel.bus.outbound_size == 0