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

+8 -4
View File
@@ -18,6 +18,7 @@ from nanobot.pairing import (
is_approved,
record_delivery,
)
from nanobot.pairing.events import PairingChanged
class BaseChannel(ABC):
@@ -275,6 +276,9 @@ class BaseChannel(ABC):
return True
return False
def _pairing_changed(self) -> None:
self.bus.publish_nowait(PairingChanged())
async def _handle_message(
self,
sender_id: str,
@@ -299,7 +303,7 @@ class BaseChannel(ABC):
if not self.is_allowed(permission_id):
if is_dm:
try:
code = generate_code(self.name, str(sender_id))
code = generate_code(self.name, str(sender_id), on_change=self._pairing_changed)
except OSError:
# Transient pairing-store I/O failure: skip the pairing
# reply for this message rather than crash the handler.
@@ -307,7 +311,7 @@ class BaseChannel(ABC):
"Pairing store unavailable; dropping DM from {}", sender_id
)
return
record_delivery(code, "sending")
record_delivery(code, "sending", on_change=self._pairing_changed)
try:
await self.send(
OutboundMessage(
@@ -318,9 +322,9 @@ class BaseChannel(ABC):
)
)
except Exception:
record_delivery(code, "failed")
record_delivery(code, "failed", on_change=self._pairing_changed)
raise
record_delivery(code, "sent")
record_delivery(code, "sent", on_change=self._pairing_changed)
self.logger.info(
"Sent pairing code {} to sender {} in chat {}",
code, sender_id, chat_id,
@@ -625,7 +625,7 @@ async def test_on_message_unauthorized_dm_sends_pairing_code(monkeypatch) -> Non
channel._running = True
monkeypatch.setattr("nanobot.channels.base.is_approved", lambda _ch, _sid: False)
monkeypatch.setattr(
"nanobot.channels.base.generate_code", lambda _ch, _sid: "ABCD-EFGH"
"nanobot.channels.base.generate_code", lambda _ch, _sid, *, on_change=None: "ABCD-EFGH"
)
await channel._on_message(message)
+1 -1
View File
@@ -250,7 +250,7 @@ class MattermostChannel(BaseChannel):
if not await self._is_allowed(sender_id, channel_id, channel_type):
if is_dm and self.config.dm.enabled:
code = generate_code(self.name, str(sender_id))
code = generate_code(self.name, str(sender_id), on_change=self._pairing_changed)
await self.send(
OutboundMessage(
channel=self.name,
@@ -2462,7 +2462,7 @@ async def test_forward_command_pairs_unauthorized_private_user(monkeypatch) -> N
)
_install_ready_app(channel)
monkeypatch.setattr(
"nanobot.channels.base.generate_code", lambda _ch, _sid: "ABCD-EFGH"
"nanobot.channels.base.generate_code", lambda _ch, _sid, *, on_change=None: "ABCD-EFGH"
)
await channel._forward_command(_make_telegram_update(text="/new", chat_type="private"), None)
@@ -2689,7 +2689,7 @@ async def test_on_start_sends_pairing_code_to_unauthorized_private_user(monkeypa
update = _make_telegram_update(text="/start", chat_type="private")
update.message.reply_text = AsyncMock()
monkeypatch.setattr(
"nanobot.channels.base.generate_code", lambda _ch, _sid: "ABCD-EFGH"
"nanobot.channels.base.generate_code", lambda _ch, _sid, *, on_change=None: "ABCD-EFGH"
)
await channel._on_start(update, None)
@@ -2709,7 +2709,7 @@ async def test_on_help_sends_pairing_code_to_unauthorized_private_user(monkeypat
update = _make_telegram_update(text="/help", chat_type="private")
update.message.reply_text = AsyncMock()
monkeypatch.setattr(
"nanobot.channels.base.generate_code", lambda _ch, _sid: "ABCD-EFGH"
"nanobot.channels.base.generate_code", lambda _ch, _sid, *, on_change=None: "ABCD-EFGH"
)
await channel._on_help(update, None)
@@ -2733,7 +2733,7 @@ async def test_on_message_pairs_unauthorized_private_user_before_side_effects(
channel._add_reaction = AsyncMock(return_value=None)
channel._download_message_media = AsyncMock(return_value=([], []))
monkeypatch.setattr(
"nanobot.channels.base.generate_code", lambda _ch, _sid: "ABCD-EFGH"
"nanobot.channels.base.generate_code", lambda _ch, _sid, *, on_change=None: "ABCD-EFGH"
)
await channel._on_message(_make_telegram_update(text="hello", chat_type="private"), None)
+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
@@ -351,7 +351,7 @@ async def test_process_message_pairs_unauthorized_sender_before_media_side_effec
channel._get_typing_ticket = AsyncMock(return_value="")
channel._send_text = AsyncMock()
monkeypatch.setattr(
"nanobot.channels.base.generate_code", lambda _ch, _sid: "ABCD-EFGH"
"nanobot.channels.base.generate_code", lambda _ch, _sid, *, on_change=None: "ABCD-EFGH"
)
await channel._process_message(
@@ -798,7 +798,7 @@ async def test_unauthorized_voice_message_does_not_download_or_transcribe(
@pytest.mark.asyncio
async def test_unauthorized_dm_uses_base_pairing_flow(monkeypatch) -> None:
_patch_neonize_api(monkeypatch)
monkeypatch.setattr("nanobot.channels.base.generate_code", lambda _ch, _sid: "ABCD-EFGH")
monkeypatch.setattr("nanobot.channels.base.generate_code", lambda _ch, _sid, *, on_change=None: "ABCD-EFGH")
monkeypatch.setattr("nanobot.channels.base.is_approved", lambda _ch, _sid: False)
client = SimpleNamespace(send_message=AsyncMock(), download_any=AsyncMock())
ch = WhatsAppChannel({"enabled": True, "allowFrom": []}, MagicMock())
+5 -1
View File
@@ -939,8 +939,12 @@ async def cmd_goal(ctx: CommandContext) -> InboundMessage | OutboundMessage:
async def cmd_pairing(ctx: CommandContext) -> OutboundMessage:
"""List, approve, deny or revoke pairing requests."""
from nanobot.pairing import PAIRING_COMMAND_META_KEY, handle_pairing_command
from nanobot.pairing.events import PairingChanged
reply = handle_pairing_command(ctx.msg.channel, ctx.args)
def changed() -> None:
ctx.loop.bus.publish_nowait(PairingChanged())
reply = handle_pairing_command(ctx.msg.channel, ctx.args, on_change=changed)
return OutboundMessage(
channel=ctx.msg.channel,
chat_id=ctx.msg.chat_id,
+10
View File
@@ -0,0 +1,10 @@
"""Transport-independent pairing snapshot invalidation."""
from dataclasses import dataclass
from nanobot.events import AgentEvent
@dataclass(frozen=True)
class PairingChanged(AgentEvent):
"""Pairing state may have changed; consumers must read the current store."""
+60 -30
View File
@@ -12,6 +12,7 @@ import secrets
import string
import threading
import time
from collections.abc import Callable
from pathlib import Path
from typing import Any, Literal, cast
@@ -85,6 +86,16 @@ def _save(data: dict[str, Any]) -> None:
_write_text_atomic(path, json.dumps(payload, indent=2, ensure_ascii=False))
def _notify_changed(on_change: Callable[[], object] | None) -> None:
# Notification is best-effort and runs outside the domain lock. A consumer
# failure must not make an already-persisted mutation appear to have failed.
if on_change is not None:
try:
on_change()
except Exception:
logger.exception("Could not publish pairing change")
def _gc_pending(data: dict[str, Any]) -> None:
"""Remove expired pending entries in-place."""
now = time.time()
@@ -114,6 +125,8 @@ def generate_code(
channel: str,
sender_id: str,
ttl: int = _TTL_DEFAULT_S,
*,
on_change: Callable[[], object] | None = None,
) -> str:
"""Return an active pairing code for *sender_id* on *channel*.
@@ -138,10 +151,14 @@ def generate_code(
}
_save(data)
logger.info("Generated pairing code {} for {}@{}", code, sender_id, channel)
return code
_notify_changed(on_change)
return code
def record_delivery(code: str, status: Literal["sending", "sent", "failed"]) -> None:
def record_delivery(
code: str, status: Literal["sending", "sent", "failed"],
*, on_change: Callable[[], object] | None = None,
) -> None:
"""Record a reply outcome without changing approval or reviving a stale request.
Once a code has been sent, a failed concurrent retry must not hide it.
@@ -153,15 +170,19 @@ def record_delivery(code: str, status: Literal["sending", "sent", "failed"]) ->
data = _load()
_gc_pending(data)
info = data["pending"].get(code)
if info is None or info.get("delivery_status") == "sent":
if info is None or info.get("delivery_status") in ("sent", status):
return
info["delivery_status"] = status
_save(data)
except OSError:
logger.warning("Could not persist pairing reply delivery status")
return
_notify_changed(on_change)
def approve_code(code: str) -> tuple[str, str] | None:
def approve_code(
code: str, *, on_change: Callable[[], object] | None = None,
) -> tuple[str, str] | None:
"""Approve a pending pairing code.
Returns ``(channel, sender_id)`` on success, or ``None`` if the code
@@ -179,10 +200,11 @@ def approve_code(code: str) -> tuple[str, str] | None:
data.setdefault("approved", {}).setdefault(channel, set()).add(sender_id)
_save(data)
logger.info("Approved pairing code {} for {}@{}", code, sender_id, channel)
return channel, sender_id
_notify_changed(on_change)
return channel, sender_id
def deny_code(code: str) -> bool:
def deny_code(code: str, *, on_change: Callable[[], object] | None = None) -> bool:
"""Reject and discard a pending pairing code.
Returns ``True`` if the code existed and was removed.
@@ -191,12 +213,13 @@ def deny_code(code: str) -> bool:
data = _load()
_gc_pending(data)
pending: dict[str, Any] = data.get("pending", {})
if code in pending:
del pending[code]
_save(data)
logger.info("Denied pairing code {}", code)
return True
return False
if code not in pending:
return False
del pending[code]
_save(data)
logger.info("Denied pairing code {}", code)
_notify_changed(on_change)
return True
def is_approved(channel: str, sender_id: str) -> bool:
@@ -226,7 +249,9 @@ def list_pending() -> list[dict[str, Any]]:
]
def revoke(channel: str, sender_id: str) -> bool:
def revoke(
channel: str, sender_id: str, *, on_change: Callable[[], object] | None = None,
) -> bool:
"""Remove an approved sender from *channel*.
Returns ``True`` if the sender was present and removed.
@@ -236,14 +261,15 @@ def revoke(channel: str, sender_id: str) -> bool:
approved: dict[str, set[str]] = data.get("approved", {})
users = approved.get(channel, set())
sid = str(sender_id)
if sid in users:
users.discard(sid)
if not users:
del approved[channel]
_save(data)
logger.info("Revoked {} from {}", sid, channel)
return True
return False
if sid not in users:
return False
users.discard(sid)
if not users:
del approved[channel]
_save(data)
logger.info("Revoked {} from {}", sid, channel)
_notify_changed(on_change)
return True
def revoke_channel(channel: str) -> int:
@@ -319,21 +345,25 @@ def format_expiry(expires_at: float) -> str:
return f"{remaining}s" if remaining > 0 else "expired"
def handle_pairing_command(channel: str, subcommand_text: str) -> str:
def handle_pairing_command(
channel: str, subcommand_text: str, *, on_change: Callable[[], object] | None = None,
) -> str:
"""Execute a pairing subcommand and return the reply text.
This is a pure function (no side effects other than store mutations)
so it can be used from both the CLI and the agent CommandRouter.
CLI and agent commands share the same mutations. The optional notifier runs
only after a successful persistent change, without changing the reply text.
"""
try:
return _handle_pairing_subcommand(channel, subcommand_text)
return _handle_pairing_subcommand(channel, subcommand_text, on_change=on_change)
except OSError:
# Mutations fail loudly on a transient I/O error instead of lying
# ("invalid code") or silently rewriting the store from an empty view.
return "The pairing store is temporarily unavailable. Please try again."
def _handle_pairing_subcommand(channel: str, subcommand_text: str) -> str:
def _handle_pairing_subcommand(
channel: str, subcommand_text: str, *, on_change: Callable[[], object] | None,
) -> str:
parts = subcommand_text.split()
sub = parts[0] if parts else "list"
arg = parts[1] if len(parts) > 1 else None
@@ -353,7 +383,7 @@ def _handle_pairing_subcommand(channel: str, subcommand_text: str) -> str:
elif sub == "approve":
if arg is None:
return "Usage: `/pairing approve <code>`"
result = approve_code(arg)
result = approve_code(arg, on_change=on_change)
if result is None:
return f"Invalid or expired pairing code: `{arg}`"
ch, sid = result
@@ -362,7 +392,7 @@ def _handle_pairing_subcommand(channel: str, subcommand_text: str) -> str:
elif sub == "deny":
if arg is None:
return "Usage: `/pairing deny <code>`"
if deny_code(arg):
if deny_code(arg, on_change=on_change):
return f"Denied pairing code `{arg}`"
return f"Pairing code `{arg}` not found or already expired"
@@ -370,13 +400,13 @@ def _handle_pairing_subcommand(channel: str, subcommand_text: str) -> str:
if len(parts) == 2:
return (
f"Revoked {arg} from {channel}"
if revoke(channel, parts[1])
if revoke(channel, parts[1], on_change=on_change)
else f"{arg} was not in the approved list for {channel}"
)
if len(parts) == 3:
return (
f"Revoked {parts[2]} from {arg}"
if revoke(parts[1], parts[2])
if revoke(parts[1], parts[2], on_change=on_change)
else f"{parts[2]} was not in the approved list for {arg}"
)
return "Usage: `/pairing revoke <user_id>` or `/pairing revoke <channel> <user_id>`"
+6
View File
@@ -21,6 +21,7 @@ from nanobot.bus.outbound_events import (
UserInputEvent,
)
from nanobot.bus.runtime_events import SubagentTaskChanged
from nanobot.pairing.events import PairingChanged
from nanobot.session.webui_turns import clear_websocket_turn_if_current
from nanobot.webui.metadata import (
WEBSOCKET_TURN_OWNER_METADATA_KEY,
@@ -45,6 +46,8 @@ class WebUIOutboundTransport(Protocol):
def webui_subscribers(self, chat_id: str) -> tuple[ServerConnection, ...]: ...
async def send_pairing_changed(self) -> None: ...
async def send_runtime_model_updated(
self,
*,
@@ -138,6 +141,9 @@ class WebUIOutboundProjector:
async def send(self, msg: OutboundMessage) -> None:
event = msg.event
if isinstance(event, PairingChanged):
await self._transport.send_pairing_changed()
return
if isinstance(event, RetryWaitEvent):
return
progress_event = event if isinstance(event, ProgressEvent) else None
+7 -2
View File
@@ -6,6 +6,7 @@ import asyncio
import html
import json
from collections.abc import Awaitable, Callable, Mapping
from functools import partial
from typing import Any, cast
from websockets.http11 import Request as WsRequest
@@ -17,6 +18,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.registry import load_channel_plugin
from nanobot.channels.validation import validate_channel_config
from nanobot.pairing import approve_code, deny_code, list_pending
from nanobot.pairing.events import PairingChanged
from nanobot.webui import settings_capabilities as capability_domain
from nanobot.webui import settings_contracts as contracts
from nanobot.webui import settings_models as model_domain
@@ -541,6 +543,9 @@ class WebUISettingsRouter:
reload_image=self._reload_image_generation_runtime,
)
def _pairing_changed(self) -> None:
self.bus.publish_nowait(PairingChanged())
def _system_operations(self) -> system_domain.SystemSettingsOperations:
return system_domain.SystemSettingsOperations(
update_runtime_config=update_runtime_config_settings,
@@ -552,8 +557,8 @@ class WebUISettingsRouter:
validate_channel_config=validate_channel_config,
load_channel_plugin=load_channel_plugin,
list_pending=list_pending,
approve_code=approve_code,
deny_code=deny_code,
approve_code=partial(approve_code, on_change=self._pairing_changed),
deny_code=partial(deny_code, on_change=self._pairing_changed),
mcp_presets_action=mcp_presets_settings_action,
reload_mcp=self._reload_mcp_runtime,
mcp_runtime_status=self._mcp_runtime_status,