Skip to content

Your lightweight open-source personal agent.

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

chengyongru8af6313c560b
diff --git a/docs/websocket.md b/docs/websocket.md
index ce7f28971..7efd00ea2 100644
--- a/docs/websocket.md
+++ b/docs/websocket.md
@@ -190,6 +190,14 @@ Reasoning frames only flow when the channel's `showReasoning` is `true` (default
`model_preset` is omitted when no named preset is active. WebUI clients use this event to refresh model settings after default-runtime and config changes. `/model <preset>` is session-scoped; its selection is reflected through `session_updated` and the session row's `model_preset` field instead of this global event.
+**`pairing_changed`** — sent only to authenticated WebUI connections after an in-process pairing change:
+
+```json
+{"event":"pairing_changed"}
+```
+
+The event contains no pairing codes or account data. Read the current state from `GET /api/settings/pairing`; notifications are not replayed, so read a fresh snapshot on initial connection and reconnect. Existing polling continues to discover changes made by another process and expired requests. Approval, denial and authentication checks are unchanged.
+
**`attached`** — confirmation for `new_chat` / `attach` inbound envelopes (see [Multi-chat multiplexing](#multi-chat-multiplexing)):
```json
diff --git a/nanobot/channels/base.py b/nanobot/channels/base.py
index bd455965f..b0a7f6770 100644
--- a/nanobot/channels/base.py
+++ b/nanobot/channels/base.py
@@ -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,
diff --git a/nanobot/channels/discord/tests/test_discord_channel.py b/nanobot/channels/discord/tests/test_discord_channel.py
index 47d1ff2cc..281376cab 100644
--- a/nanobot/channels/discord/tests/test_discord_channel.py
+++ b/nanobot/channels/discord/tests/test_discord_channel.py
@@ -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)
diff --git a/nanobot/channels/mattermost/runtime.py b/nanobot/channels/mattermost/runtime.py
index 580f1e630..0f8b06263 100644
--- a/nanobot/channels/mattermost/runtime.py
+++ b/nanobot/channels/mattermost/runtime.py
@@ -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,
diff --git a/nanobot/channels/telegram/tests/test_telegram_channel.py b/nanobot/channels/telegram/tests/test_telegram_channel.py
index cb96ac85f..f8f7d8724 100644
--- a/nanobot/channels/telegram/tests/test_telegram_channel.py
+++ b/nanobot/channels/telegram/tests/test_telegram_channel.py
@@ -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)
diff --git a/nanobot/channels/websocket/runtime.py b/nanobot/channels/websocket/runtime.py
index e4c4f0301..db8a767cc 100644
--- a/nanobot/channels/websocket/runtime.py
+++ b/nanobot/channels/websocket/runtime.py
@@ -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,
*,
diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.py
index 283e904fb..ada6c9ad1 100644
--- a/nanobot/channels/websocket/tests/test_websocket_channel.py
+++ b/nanobot/channels/websocket/tests/test_websocket_channel.py
@@ -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"]
+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()
diff --git a/nanobot/channels/websocket/tests/test_websocket_http_routes.py b/nanobot/channels/websocket/tests/test_websocket_http_routes.py
index e4c3554a3..f428f9324 100644
--- a/nanobot/channels/websocket/tests/test_websocket_http_routes.py
+++ b/nanobot/channels/websocket/tests/test_websocket_http_routes.py
@@ -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
[email protected]("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,
diff --git a/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.py b/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.py
index 340521bfa..d91263e10 100644
--- a/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.py
+++ b/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.py
@@ -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
diff --git a/nanobot/channels/weixin/tests/test_weixin_channel.py b/nanobot/channels/weixin/tests/test_weixin_channel.py
index bd86a4861..c73bb0fe2 100644
--- a/nanobot/channels/weixin/tests/test_weixin_channel.py
+++ b/nanobot/channels/weixin/tests/test_weixin_channel.py
@@ -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(
diff --git a/nanobot/channels/whatsapp/tests/test_whatsapp_channel.py b/nanobot/channels/whatsapp/tests/test_whatsapp_channel.py
index 5ab946cca..4e06cd5ec 100644
--- a/nanobot/channels/whatsapp/tests/test_whatsapp_channel.py
+++ b/nanobot/channels/whatsapp/tests/test_whatsapp_channel.py
@@ -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())
diff --git a/nanobot/command/builtin.py b/nanobot/command/builtin.py
index 3736ed19b..d4ff11a0f 100644
--- a/nanobot/command/builtin.py
+++ b/nanobot/command/builtin.py
@@ -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,
diff --git a/nanobot/pairing/events.py b/nanobot/pairing/events.py
new file mode 100644
index 000000000..292fca988
--- /dev/null
+++ b/nanobot/pairing/events.py
@@ -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."""
diff --git a/nanobot/pairing/store.py b/nanobot/pairing/store.py
index c7e9e95a2..3bcce157c 100644
--- a/nanobot/pairing/store.py
+++ b/nanobot/pairing/store.py
@@ -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>`"
diff --git a/nanobot/webui/outbound_projection.py b/nanobot/webui/outbound_projection.py
index e44596f4f..0a6a4a2b6 100644
--- a/nanobot/webui/outbound_projection.py
+++ b/nanobot/webui/outbound_projection.py
@@ -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
diff --git a/nanobot/webui/settings_routes.py b/nanobot/webui/settings_routes.py
index 8c1fa870f..77906a96f 100644
--- a/nanobot/webui/settings_routes.py
+++ b/nanobot/webui/settings_routes.py
@@ -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,
diff --git a/tests/channels/test_base_channel.py b/tests/channels/test_base_channel.py
index 7605c6aeb..00e685ae6 100644
--- a/tests/channels/test_base_channel.py
+++ b/tests/channels/test_base_channel.py
@@ -70,7 +70,7 @@ def test_is_allowed_pairing_fallback(monkeypatch) -> None:
async def test_handle_message_dm_sends_pairing_code(monkeypatch) -> None:
channel = _DummyChannel({"allowFrom": []}, MessageBus())
monkeypatch.setattr(
- "nanobot.channels.base.generate_code", lambda _ch, sid: "ABCD-EFGH"
+ "nanobot.channels.base.generate_code", lambda _ch, sid, **_kwargs: "ABCD-EFGH"
)
await channel._handle_message(
@@ -168,3 +168,20 @@ async def test_handle_message_rejects_when_authorization_id_is_not_allowed() ->
assert bus.inbound_size == 0
+
+
+async def test_dm_publishes_pairing_changes_without_a_file_watcher(monkeypatch, tmp_path) -> None:
+ from nanobot.pairing import store
+ from nanobot.pairing.events import PairingChanged
+
+ monkeypatch.setattr(store, "_store_path", lambda: tmp_path / "pairing.json")
+ bus = MessageBus()
+ observed = []
+ bus.subscribe(lambda _event: observed.append(store.list_pending()), PairingChanged)
+ channel = _DummyChannel({"allowFrom": []}, bus)
+ await channel._handle_message("alice", "dm", "hello", is_dm=True)
+ await bus.drain()
+ assert observed and observed[-1][0]["delivery_status"] == "sent"
+ assert observed[-1][0]["code"] in channel._sent[0].content
+ assert not store.is_approved("dummy", "alice")
diff --git a/tests/command/test_pairing_command.py b/tests/command/test_pairing_command.py
new file mode 100644
index 000000000..814f27e6b
--- /dev/null
+++ b/tests/command/test_pairing_command.py
@@ -0,0 +1,31 @@
+from unittest.mock import MagicMock
+
+import pytest
+
+from nanobot.bus.events import InboundMessage
+from nanobot.bus.queue import MessageBus
+from nanobot.command.builtin import cmd_pairing
+from nanobot.command.router import CommandContext
+from nanobot.pairing import store
+from nanobot.pairing.events import PairingChanged
+
+
+async def test_pairing_command_notifies_after_persistence_without_a_file_watcher(tmp_path, monkeypatch):
+ monkeypatch.setattr(store, "_store_path", lambda: tmp_path / "pairing.json")
+ code = store.generate_code("telegram", "alice")
+ bus = MessageBus()
+ approved = []
+ bus.subscribe(lambda _event: approved.append(store.is_approved("telegram", "alice")), PairingChanged)
+ loop = MagicMock(bus=bus)
+ msg = InboundMessage(channel="cli", sender_id="owner", chat_id="direct", content=f"/pairing approve {code}")
+ ctx = CommandContext(msg=msg, session=None, key=msg.session_key, raw=msg.content, args=f"approve {code}", loop=loop)
+ result = await cmd_pairing(ctx)
+ await bus.drain()
+ assert "Approved" in result.content and approved == [True]
+ ctx.args = "approve invalid"
+ await cmd_pairing(ctx)
+ ctx.args = "list"
+ await cmd_pairing(ctx)
+ await bus.drain()
+ assert approved == [True]
diff --git a/tests/command/test_router_dispatchable.py b/tests/command/test_router_dispatchable.py
index 9604b1972..3d791470b 100644
--- a/tests/command/test_router_dispatchable.py
+++ b/tests/command/test_router_dispatchable.py
@@ -264,7 +264,7 @@ class TestPairingCommandDispatch:
) -> None:
monkeypatch.setattr(
"nanobot.pairing.store.approve_code",
- lambda code: ("telegram", "123") if code == "ABCD-EFGH" else None,
+ lambda code, *, on_change=None: ("telegram", "123") if code == "ABCD-EFGH" else None,
)
fake_msg.content = "/pairing approve ABCD-EFGH"
ctx = CommandContext(
@@ -286,7 +286,7 @@ class TestPairingCommandDispatch:
) -> None:
monkeypatch.setattr(
"nanobot.pairing.store.revoke",
- lambda ch, sid: sid == "123",
+ lambda ch, sid, *, on_change=None: sid == "123",
)
fake_msg.content = "/pairing revoke 123"
ctx = CommandContext(
diff --git a/tests/pairing/test_store.py b/tests/pairing/test_store.py
index 331759143..8c749d212 100644
--- a/tests/pairing/test_store.py
+++ b/tests/pairing/test_store.py
@@ -441,3 +441,75 @@ class TestTransientReadFailure:
assert "unavailable" in reply.lower()
assert store.approve_code(code) == ("telegram", "123")
+
+
+class TestChangeNotifications:
+ def test_changes_are_committed_and_unlocked_before_notification(self):
+ snapshots = []
+
+ def changed():
+ unlocked = store._LOCK.acquire(blocking=False)
+ if unlocked:
+ store._LOCK.release()
+ snapshots.append(store.list_pending())
+
+ code = store.generate_code("telegram", "alice", on_change=changed)
+ assert len(snapshots) == 1 and snapshots[-1][0]["code"] == code
+ assert store.generate_code("telegram", "alice", on_change=changed) == code
+ assert len(snapshots) == 1
+ store.record_delivery(code, "sending", on_change=changed)
+ assert snapshots[-1][0]["delivery_status"] == "sending"
+ store.record_delivery(code, "sending", on_change=changed)
+ assert len(snapshots) == 2
+ store.record_delivery(code, "sent", on_change=changed)
+ store.record_delivery(code, "failed", on_change=changed)
+ assert len(snapshots) == 3 and snapshots[-1][0]["delivery_status"] == "sent"
+ assert store.approve_code(code, on_change=changed) == ("telegram", "alice")
+ assert snapshots[-1] == [] and len(snapshots) == 4
+ assert store.approve_code(code, on_change=changed) is None
+ assert not store.deny_code(code, on_change=changed)
+ assert len(snapshots) == 4
+
+ def test_commands_notify_only_after_changes(self):
+ changes = []
+
+ def changed():
+ changes.append(json.loads(store._store_path().read_text()))
+
+ code = store.generate_code("telegram", "alice")
+ assert "Approved" in store.handle_pairing_command("cli", f"approve {code}", on_change=changed)
+ assert changes[-1]["approved"] == {"telegram": ["alice"]}
+ store.handle_pairing_command("cli", "list", on_change=changed)
+ store.handle_pairing_command("cli", "approve invalid", on_change=changed)
+ assert len(changes) == 1
+ store.handle_pairing_command("cli", "revoke telegram alice", on_change=changed)
+ store.handle_pairing_command("cli", "revoke telegram alice", on_change=changed)
+ code = store.generate_code("telegram", "bob")
+ store.handle_pairing_command("cli", f"deny {code}", on_change=changed)
+ code = store.generate_code("telegram", "carol")
+ store.handle_pairing_command("cli", f"approve {code}", on_change=changed)
+ store.handle_pairing_command("cli", "revoke telegram carol", on_change=changed)
+ assert len(changes) == 5 and changes[-1] == {"approved": {}, "pending": {}}
+
+ def test_failed_persistence_does_not_notify(self, monkeypatch):
+ code = store.generate_code("telegram", "alice")
+ before = store._store_path().read_bytes()
+ changes = []
+
+ def failed_write(_data):
+ raise OSError("fixture disk failure")
+
+ monkeypatch.setattr(store, "_save", failed_write)
+ with pytest.raises(OSError, match="disk failure"):
+ store.generate_code("telegram", "bob", on_change=lambda: changes.append(True))
+ store.record_delivery(code, "sent", on_change=lambda: changes.append(True))
+ assert changes == [] and store._store_path().read_bytes() == before
+
+ def test_notification_failure_does_not_report_persisted_mutation_as_failure(self):
+ def failed_notify():
+ raise RuntimeError("fixture observer failure")
+
+ code = store.generate_code("telegram", "alice", on_change=failed_notify)
+ assert store.list_pending()[0]["code"] == code
+ assert store.approve_code(code, on_change=failed_notify) == ("telegram", "alice")
+ assert store.is_approved("telegram", "alice")
diff --git a/webui/browser/pairing-refresh.spec.ts b/webui/browser/pairing-refresh.spec.ts
new file mode 100644
index 000000000..0a4f34685
--- /dev/null
+++ b/webui/browser/pairing-refresh.spec.ts
@@ -0,0 +1,71 @@
+import { expect, test, type WebSocketRoute } from "@playwright/test";
+
+for (const width of [1440, 390]) {
+ test(`pairing appears on the real client's event 1s after an empty read at ${width}px`, async ({ page }) => {
+ await page.setViewportSize({ width, height: 900 });
+ await page.addInitScript(() => localStorage.setItem("nanobot.locale", "en"));
+ await page.clock.install();
+ const errors: string[] = [];
+ page.on("pageerror", error => errors.push(error.message));
+ const sockets: WebSocketRoute[] = [];
+ let reads = 0;
+ let requests: Record<string, unknown>[] = [];
+ await page.route("**/webui/bootstrap*", route => route.fulfill({ json: {
+ token: "fixture-token", api_token: "fixture-api-token", ws_path: "/pairing-events-fixture", expires_in: 300,
+ terminal: { webui: { capabilities: ["webui.core.v1"] } },
+ } }));
+ await page.route("**/api/**", route => {
+ const path = new URL(route.request().url()).pathname;
+ if (path === "/api/settings/pairing") {
+ expect(route.request().headers().authorization).toBe("Bearer fixture-api-token");
+ reads += 1;
+ return route.fulfill({ json: { requests } });
+ }
+ if (path === "/api/sessions") return route.fulfill({ json: { sessions: [] } });
+ if (path === "/api/skills") return route.fulfill({ json: { skills: [] } });
+ if (path === "/api/webui/sidebar-state") return route.fulfill({ json: {} });
+ if (path === "/api/remote-instances") return route.fulfill({ status: 403, json: {} });
+ return route.fulfill({ status: 404, json: {} });
+ });
+ await page.routeWebSocket("**/pairing-events-fixture*", ws => {
+ expect(new URL(ws.url()).searchParams.get("token")).toBe("fixture-token");
+ sockets.push(ws);
+ });
+ await page.goto("/");
+ const composer = page.getByRole("textbox", { name: "Message input" });
+ await expect(composer).toBeVisible();
+ await expect.poll(() => reads).toBe(1);
+ await expect.poll(() => sockets.length).toBe(1);
+ // The first ready snapshot closes the pre-connection gap without replacing polling.
+ sockets[0].send(JSON.stringify({ event: "ready", chat_id: "fixture-chat" }));
+ await expect.poll(() => reads).toBe(2);
+ await composer.fill("Keep this draft during pairing and reconnect");
+ await page.clock.fastForward(1_000);
+ expect(reads).toBe(2);
+ requests = [{ code: "ABCD-EFGH", channel: "feishu", sender_id: "fixture-user", delivery_status: "sent" }];
+ expect(sockets).toHaveLength(1);
+ sockets[0].send(JSON.stringify({ event: "pairing_changed" }));
+ const popup = page.getByRole("dialog", { name: "Pair account" });
+ await expect(popup).toBeVisible();
+ await expect(popup.getByRole("textbox", { name: "Pairing code" })).toBeEnabled();
+ await expect.poll(() => reads).toBe(3);
+ requests = [];
+ sockets[0].close({ code: 1012, reason: "pairing fixture reconnect" });
+ await page.clock.fastForward(1_000);
+ await expect.poll(() => sockets.length).toBe(2);
+ sockets[1].send(JSON.stringify({ event: "ready", chat_id: "fixture-chat" }));
+ await expect.poll(() => reads).toBe(4);
+ await expect(popup).toBeHidden();
+ // Changes from another process and expiry need no same-gateway notification.
+ requests = [{ code: "IJKL-MNOP", channel: "feishu", sender_id: "fixture-user", delivery_status: "sent" }];
+ await page.clock.runFor(15_000);
+ await expect(popup).toBeVisible();
+ await expect.poll(() => reads).toBe(5);
+ requests = [];
+ await page.clock.runFor(5_000);
+ await expect(popup).toBeHidden();
+ await expect.poll(() => reads).toBe(6);
+ await expect(composer).toHaveValue("Keep this draft during pairing and reconnect");
+ expect(errors).toEqual([]);
+ });
+}
diff --git a/webui/src/App.tsx b/webui/src/App.tsx
index 6f96a0aa0..a95fedef3 100644
--- a/webui/src/App.tsx
+++ b/webui/src/App.tsx
@@ -1281,6 +1281,7 @@ function Shell({
const [pairingBusyCode, setPairingBusyCode] = useState<string | null>(null);
const [pairingError, setPairingError] = useState<string | null>(null);
const pairingRefreshRef = useRef<Promise<number> | null>(null);
+ const pairingRefreshPendingRef = useRef(false);
const [snoozedPairingCodes, setSnoozedPairingCodes] = useState<Map<string, {
until: number;
deliveryStatus: PairingRequestInfo["delivery_status"];
@@ -1473,32 +1474,41 @@ function Shell({
}, [updatedChatIds]);
const refreshPairingRequests = useCallback((): Promise<number> => {
- if (pairingRefreshRef.current) return pairingRefreshRef.current;
+ if (pairingRefreshRef.current) {
+ // An earlier snapshot may predate the notice or completed mutation.
+ pairingRefreshPendingRef.current = true;
+ return pairingRefreshRef.current;
+ }
const request = (async () => {
- try {
- const payload = await fetchPairingRequests(getToken());
- const requests = Array.isArray(payload.requests) ? payload.requests : [];
- setPairingRequests(requests);
- setSnoozedPairingCodes((current) => {
- if (current.size === 0) return current;
- const activeRequests = new Map(requests.map((request) => [request.code, request]));
- const now = Date.now();
- const next = new Map(
- Array.from(current).filter(
- ([code, snooze]) => activeRequests.has(code)
- && snooze.until > now
- && activeRequests.get(code)?.delivery_status === snooze.deliveryStatus,
- ),
- );
- return next.size === current.size ? current : next;
- });
- return requests.length;
- } catch {
- // Pairing is an opportunistic WebUI affordance. The slash command path
- // remains available if this polling request fails.
- return 0;
- }
+ let requestCount: number;
+ do {
+ pairingRefreshPendingRef.current = false;
+ try {
+ const payload = await fetchPairingRequests(getToken());
+ const requests = Array.isArray(payload.requests) ? payload.requests : [];
+ setPairingRequests(requests);
+ setSnoozedPairingCodes((current) => {
+ if (current.size === 0) return current;
+ const activeRequests = new Map(requests.map((request) => [request.code, request]));
+ const now = Date.now();
+ const next = new Map(
+ Array.from(current).filter(
+ ([code, snooze]) => activeRequests.has(code)
+ && snooze.until > now
+ && activeRequests.get(code)?.delivery_status === snooze.deliveryStatus,
+ ),
+ );
+ return next.size === current.size ? current : next;
+ });
+ requestCount = requests.length;
+ } catch {
+ // Pairing is an opportunistic WebUI affordance. The slash command path
+ // remains available if this polling request fails.
+ requestCount = 0;
+ }
+ } while (pairingRefreshPendingRef.current);
+ return requestCount;
})();
const clearRequest = () => {
if (pairingRefreshRef.current === request) pairingRefreshRef.current = null;
@@ -1516,17 +1526,24 @@ function Shell({
const poll = async () => {
const requestCount = await refreshPairingRequests();
if (disposed) return;
+ if (timer !== null) window.clearTimeout(timer);
timer = window.setTimeout(
() => void poll(),
requestCount > 0 ? PAIRING_POLL_INTERVAL_MS : PAIRING_IDLE_POLL_INTERVAL_MS,
);
};
+ const requestRefresh = () => { void poll(); };
+ const unsubscribePairing = client.onPairingChange(requestRefresh);
+ const unsubscribeReady = client.onReady(requestRefresh);
void poll();
return () => {
disposed = true;
+ pairingRefreshPendingRef.current = false;
if (timer !== null) window.clearTimeout(timer);
+ unsubscribePairing();
+ unsubscribeReady();
};
- }, [pageVisible, refreshPairingRequests]);
+ }, [client, pageVisible, refreshPairingRequests]);
const activeSession = useMemo<ChatSummary | null>(() => {
if (!activeKey) return null;
@@ -2465,9 +2482,10 @@ function Shell({
});
} catch (e) {
setPairingError((e as Error).message);
- void refreshPairingRequests();
} finally {
setPairingBusyCode(null);
+ // A mutation reply can be older than an already-delivered notification.
+ void refreshPairingRequests();
}
},
[client, refreshPairingRequests],
diff --git a/webui/src/lib/nanobot-client.ts b/webui/src/lib/nanobot-client.ts
index 56c7d753f..1141d2093 100644
--- a/webui/src/lib/nanobot-client.ts
+++ b/webui/src/lib/nanobot-client.ts
@@ -87,6 +87,7 @@ type SessionUpdateHandler = (
workspaceScope?: WorkspaceScopePayload,
) => void;
type SidebarStateUpdateHandler = (state: SidebarStatePayload) => void;
+type PairingChangeHandler = () => void;
type RunStatusHandler = (chatId: string, state: RunState) => void;
/** Structured errors surfaced to the UI.
@@ -238,6 +239,8 @@ export class NanobotClient {
private runCompletionHandlers = new Set<RunCompletionHandler>();
private errorHandlers = new Set<ErrorHandler>();
private taskNoticeHandlers = new Set<(notice: TaskNotice) => void>();
+ private pairingChangeHandlers = new Set<PairingChangeHandler>();
+ private readyHandlers = new Set<() => void>();
private chatHandlers = new Map<string, Set<EventHandler>>();
private transcriptHandlers = new Map<string, { handler: EventHandler }>();
/** Inbound frames received while the transcript owner is absent, regardless of observers. */
@@ -317,6 +320,16 @@ export class NanobotClient {
};
}
+ onPairingChange(handler: PairingChangeHandler): Unsubscribe {
+ this.pairingChangeHandlers.add(handler);
+ return () => { this.pairingChangeHandlers.delete(handler); };
+ }
+
+ onReady(handler: () => void): Unsubscribe {
+ this.readyHandlers.add(handler);
+ return () => { this.readyHandlers.delete(handler); };
+ }
+
onSidebarStateUpdate(handler: SidebarStateUpdateHandler): Unsubscribe {
this.sidebarStateUpdateHandlers.add(handler);
return () => {
@@ -966,6 +979,9 @@ export class NanobotClient {
this.upload = uploadCapability(parsed.upload);
this.readyChatId = parsed.chat_id;
this.knownChats.add(parsed.chat_id);
+ for (const handler of this.readyHandlers) {
+ try { handler(); } catch { /* One listener must not block another ready consumer. */ }
+ }
return;
}
@@ -987,6 +1003,13 @@ export class NanobotClient {
return;
}
+ if (parsed.event === "pairing_changed") {
+ for (const handler of this.pairingChangeHandlers) {
+ try { handler(); } catch { /* One listener must not block another pairing refresh. */ }
+ }
+ return;
+ }
+
if (parsed.event === "runtime_model_updated") {
this.emitRuntimeModelUpdate(parsed.model_name || null, parsed.model_preset ?? null);
return;
diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts
index 700810958..399fb9417 100644
--- a/webui/src/lib/types.ts
+++ b/webui/src/lib/types.ts
@@ -1572,6 +1572,7 @@ export type InboundEvent =
/** Legacy persisted transcripts may carry the final reasoning text here. */
text?: string;
} & InboundTurnMetadata)
+ | { event: "pairing_changed" }
| {
event: "runtime_model_updated";
model_name: string;
diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsx
index aff32a1d3..635962c11 100644
--- a/webui/src/tests/app-layout.test.tsx
+++ b/webui/src/tests/app-layout.test.tsx
@@ -44,6 +44,8 @@ const sessionUpdateHandlers = new Set<(
workspaceScope?: WorkspaceScopePayload,
) => void>();
const sidebarStateUpdateHandlers = new Set<(state: SidebarStatePayload) => void>();
+const pairingChangeHandlers = new Set<() => void>();
+const readyHandlers = new Set<() => void>();
let mockSessions: ChatSummary[] = [];
const HERO_GREETING_PATTERN =
/What should we work on\?|Where should we start\?|What are we building today\?|What should we tackle together\?/;
@@ -261,6 +263,14 @@ vi.mock("@/lib/nanobot-client", async (importOriginal) => {
return () => statusHandlers.delete(handler);
};
onRuntimeModelUpdate = () => () => {};
+ onPairingChange = (handler: () => void) => {
+ pairingChangeHandlers.add(handler);
+ return () => pairingChangeHandlers.delete(handler);
+ };
+ onReady = (handler: () => void) => {
+ readyHandlers.add(handler);
+ return () => readyHandlers.delete(handler);
+ };
onError = () => () => {};
onChat = () => () => {};
onTranscript = () => () => {};
@@ -348,6 +358,8 @@ describe("App layout", () => {
runStatusHandlers.clear();
sessionUpdateHandlers.clear();
sidebarStateUpdateHandlers.clear();
+ pairingChangeHandlers.clear();
+ readyHandlers.clear();
window.history.replaceState(null, "", "/");
sessionStorage.removeItem("nanobot.remote-instance");
Reflect.deleteProperty(window, "nanobotHost");
@@ -4435,6 +4447,141 @@ describe("App layout", () => {
unmount();
});
+ it("refreshes pairing immediately on notices and ready, only while visible", async () => {
+ vi.useFakeTimers();
+ let requests: Record<string, unknown>[] = [];
+ mockFetchRoutes({ "/api/settings/pairing": () => ({ requests }) });
+ const { unmount } = render(<App />);
+ await act(async () => {});
+ const pairingReads = () => vi.mocked(fetch).mock.calls.filter(([input]) => String(input) === "/api/settings/pairing").length;
+ expect(pairingReads()).toBe(1);
+ await act(async () => { await vi.advanceTimersByTimeAsync(1_000); });
+ requests = [{ code: "ABCD-EFGH", channel: "feishu", sender_id: "alice", delivery_status: "sent" }];
+ await act(async () => { for (const handler of pairingChangeHandlers) handler(); });
+ expect(screen.getByRole("dialog", { name: "Pair account" })).toBeVisible();
+ expect(pairingReads()).toBe(2);
+ requests = [];
+ await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
+ expect(pairingReads()).toBe(3);
+ expect(screen.queryByRole("dialog", { name: "Pair account" })).not.toBeInTheDocument();
+
+ const visibilityDescriptor = Object.getOwnPropertyDescriptor(document, "visibilityState");
+ const setVisibility = (state: DocumentVisibilityState) => {
+ Object.defineProperty(document, "visibilityState", { configurable: true, value: state });
+ document.dispatchEvent(new Event("visibilitychange"));
+ };
+ try {
+ act(() => setVisibility("hidden"));
+ requests = [];
+ await act(async () => {
+ for (const handler of pairingChangeHandlers) handler();
+ for (const handler of readyHandlers) handler();
+ await vi.advanceTimersByTimeAsync(15_000);
+ });
+ expect(pairingReads()).toBe(3);
+ await act(async () => setVisibility("visible"));
+ expect(pairingReads()).toBe(4);
+ expect(screen.queryByRole("dialog", { name: "Pair account" })).not.toBeInTheDocument();
+
+ requests = [{ code: "IJKL-MNOP", channel: "feishu", sender_id: "bob", delivery_status: "sent" }];
+ await act(async () => { for (const handler of readyHandlers) handler(); });
+ expect(screen.getByRole("dialog", { name: "Pair account" })).toBeVisible();
+ expect(pairingReads()).toBe(5);
+ unmount();
+ await act(async () => {
+ for (const handler of pairingChangeHandlers) handler();
+ for (const handler of readyHandlers) handler();
+ await vi.advanceTimersByTimeAsync(15_000);
+ });
+ expect(pairingReads()).toBe(5);
+ } finally {
+ if (visibilityDescriptor) Object.defineProperty(document, "visibilityState", visibilityDescriptor);
+ else Reflect.deleteProperty(document, "visibilityState");
+ }
+ });
+
+ it("polls for cross-process pairing changes and expiry without a notice", async () => {
+ vi.useFakeTimers();
+ let requests: Record<string, unknown>[] = [];
+ mockFetchRoutes({ "/api/settings/pairing": () => ({ requests }) });
+ render(<App />);
+ await act(async () => {});
+ requests = [{ code: "ABCD-EFGH", channel: "feishu", sender_id: "alice", expires_in_seconds: 5 }];
+ await act(async () => { await vi.advanceTimersByTimeAsync(14_999); });
+ expect(screen.queryByRole("dialog", { name: "Pair account" })).not.toBeInTheDocument();
+ await act(async () => { await vi.advanceTimersByTimeAsync(1); });
+ expect(screen.getByRole("dialog", { name: "Pair account" })).toHaveTextContent("Code expires 5s.");
+ requests = [];
+ await act(async () => { await vi.advanceTimersByTimeAsync(4_999); });
+ expect(screen.getByRole("dialog", { name: "Pair account" })).toBeVisible();
+ await act(async () => { await vi.advanceTimersByTimeAsync(1); });
+ expect(screen.queryByRole("dialog", { name: "Pair account" })).not.toBeInTheDocument();
+ });
+
+ it.each([false, true])("coalesces notices during an older pairing read and pauses while hidden (%s)", async (hide) => {
+ let finishOldRead!: (value: unknown) => void;
+ const oldSnapshot = new Promise((resolve) => { finishOldRead = resolve; });
+ let reads = 0;
+ mockFetchRoutes({ "/api/settings/pairing": () => ++reads === 1 ? oldSnapshot : { requests: [{
+ code: "ABCD-EFGH", channel: "feishu", sender_id: "alice", delivery_status: "sent",
+ }] } });
+ const visibilityDescriptor = Object.getOwnPropertyDescriptor(document, "visibilityState");
+ const setVisibility = (state: DocumentVisibilityState) => {
+ Object.defineProperty(document, "visibilityState", { configurable: true, value: state });
+ document.dispatchEvent(new Event("visibilitychange"));
+ };
+ const { unmount } = render(<App />);
+ try {
+ await waitFor(() => expect(reads).toBe(1));
+ act(() => {
+ for (let notice = 0; notice < 3; notice += 1) {
+ for (const handler of pairingChangeHandlers) handler();
+ }
+ if (hide) setVisibility("hidden");
+ });
+ expect(reads).toBe(1);
+ await act(async () => { finishOldRead({ requests: [] }); });
+ if (hide) {
+ expect(reads).toBe(1);
+ await act(async () => setVisibility("visible"));
+ }
+ expect(screen.getByRole("dialog", { name: "Pair account" })).toBeVisible();
+ expect(reads).toBe(2);
+ } finally {
+ unmount();
+ if (visibilityDescriptor) Object.defineProperty(document, "visibilityState", visibilityDescriptor);
+ else Reflect.deleteProperty(document, "visibilityState");
+ }
+ });
+
+ it.each(["success", "failure"])("reconciles a late pairing mutation after a notice shows a newer request (%s)", async (outcome) => {
+ let requests = [{
+ code: "ABCD-EFGH", channel: "feishu", sender_id: "alice", expires_in_seconds: 120,
+ }];
+ mockFetchRoutes({ "/api/settings/pairing": () => ({ requests }) });
+ let reply!: (payload: unknown) => void;
+ let fail!: (error: Error) => void;
+ requestMutationSpy.mockImplementationOnce(() => new Promise((resolve, reject) => { reply = resolve; fail = reject; }));
+ render(<App />);
+ const popup = await screen.findByRole("dialog", { name: "Pair account" });
+ fireEvent.change(within(popup).getByRole("textbox", { name: "Pairing code" }), {
+ target: { value: "ABCD-EFGH" },
+ });
+ expect(requestMutationSpy).toHaveBeenCalledWith("settings.pairing.approve", { code: "ABCD-EFGH" }, expect.any(Number));
+ requests = [{
+ code: "IJKL-MNOP", channel: "feishu.second", sender_id: "bob", expires_in_seconds: 240,
+ }];
+ await act(async () => { for (const handler of pairingChangeHandlers) handler(); });
+ expect(popup).toHaveTextContent("Code expires 4 min.");
+ await act(async () => {
+ if (outcome === "success") reply({ requests: [] });
+ else fail(new Error("Approval unavailable"));
+ });
+ expect(screen.getByRole("dialog", { name: "Pair account" })).toHaveTextContent("Code expires 4 min.");
+ expect(vi.mocked(fetch).mock.calls.filter(([input]) => String(input) === "/api/settings/pairing")).toHaveLength(3);
+ expect(requestMutationSpy).toHaveBeenCalledTimes(1);
+ });
+
it.each(["sending", "failed"])("explains an undelivered pairing reply (%s) without empty code slots", async (delivery_status) => {
mockFetchRoutes({ "/api/settings/pairing": { requests: [{
code: "ABCD-EFGH", channel: "feishu", sender_id: "alice", delivery_status,
@@ -4511,16 +4658,18 @@ describe("App layout", () => {
expect(screen.queryByRole("dialog", { name: "Pair account" })).not.toBeInTheDocument();
});
- it("reuses an in-flight pairing poll when the page becomes visible again", async () => {
+ it("reuses an in-flight pairing poll then reads current requests on visible return", async () => {
let resolvePairing!: (response: Response) => void;
const pendingPairing = new Promise<Response>((resolve) => {
resolvePairing = resolve;
});
- const fetchMock = vi.fn((input: RequestInfo | URL) => (
- String(input) === "/api/settings/pairing"
- ? pendingPairing
- : Promise.resolve({ ok: false, status: 404 } as Response)
- ));
+ let reads = 0;
+ const fetchMock = vi.fn((input: RequestInfo | URL) => {
+ if (String(input) !== "/api/settings/pairing") return Promise.resolve({ ok: false, status: 404 } as Response);
+ return ++reads === 1 ? pendingPairing : Promise.resolve(jsonResponse({ requests: [{
+ code: "ABCD-EFGH", channel: "feishu", sender_id: "alice", delivery_status: "sent",
+ }] }));
+ });
vi.stubGlobal("fetch", fetchMock);
const visibilityDescriptor = Object.getOwnPropertyDescriptor(document, "visibilityState");
@@ -4550,6 +4699,8 @@ describe("App layout", () => {
resolvePairing(jsonResponse({ requests: [] }));
await pendingPairing;
});
+ expect(screen.getByRole("dialog", { name: "Pair account" })).toBeVisible();
+ expect(reads).toBe(2);
} finally {
if (visibilityDescriptor) {
Object.defineProperty(document, "visibilityState", visibilityDescriptor);
diff --git a/webui/src/tests/nanobot-client.test.ts b/webui/src/tests/nanobot-client.test.ts
index c917d2a80..260df4cc3 100644
--- a/webui/src/tests/nanobot-client.test.ts
+++ b/webui/src/tests/nanobot-client.test.ts
@@ -71,6 +71,45 @@ afterEach(() => {
});
describe("NanobotClient", () => {
+ it("notifies ready consumers after server ready frames, including reconnects", async () => {
+ const client = new NanobotClient({ url: "ws://test?token=fixture-token", socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
+ const ready = vi.fn();
+ const unsubscribe = client.onReady(ready);
+ client.connect();
+ lastSocket().fakeOpen();
+ expect(ready).not.toHaveBeenCalled();
+ lastSocket().fakeMessage({ event: "ready", chat_id: "first" });
+ expect(ready).toHaveBeenCalledTimes(1);
+ expect(client.defaultChatId).toBe("first");
+ lastSocket().close();
+ await vi.advanceTimersByTimeAsync(1_000);
+ lastSocket().fakeOpen();
+ lastSocket().fakeMessage({ event: "ready", chat_id: "second" });
+ expect(ready).toHaveBeenCalledTimes(2);
+ expect(client.defaultChatId).toBe("second");
+ unsubscribe();
+ lastSocket().fakeMessage({ event: "ready", chat_id: "third" });
+ expect(client.defaultChatId).toBe("third");
+ expect(ready).toHaveBeenCalledTimes(2);
+ client.close();
+ });
+
+ it("delivers payload-free pairing changes, isolates listeners and unsubscribes", () => {
+ const client = new NanobotClient({ url: "ws://test", socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
+ const pairing = vi.fn();
+ client.onPairingChange(() => { throw new Error("view failed"); });
+ const unsubscribe = client.onPairingChange(pairing);
+ client.connect();
+ lastSocket().fakeOpen();
+ lastSocket().fakeMessage({ event: "pairing_changed" });
+ expect(pairing).toHaveBeenCalledTimes(1);
+ expect(pairing).toHaveBeenCalledWith();
+ unsubscribe();
+ lastSocket().fakeMessage({ event: "pairing_changed" });
+ expect(pairing).toHaveBeenCalledTimes(1);
+ client.close();
+ });
+
it("emits live task notices without mounted chats, not when the chat replays", () => {
const client = new NanobotClient({ url: "ws://test", reconnect: false,
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });