fix(webui): refresh pairing prompts on gateway changes (#6401)
This commit is contained in:
1 parent
9e9e22d331
commit
8af6313c56
26 files changed
+630
-82
No files matched your search
@@ -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.
|
`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)):
|
**`attached`** — confirmation for `new_chat` / `attach` inbound envelopes (see [Multi-chat multiplexing](#multi-chat-multiplexing)):
|
||||||
|
|
||||||
```json
|
```json
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ from nanobot.pairing import (
|
|||||||
is_approved,
|
is_approved,
|
||||||
record_delivery,
|
record_delivery,
|
||||||
)
|
)
|
||||||
|
from nanobot.pairing.events import PairingChanged
|
||||||
|
|
||||||
|
|
||||||
class BaseChannel(ABC):
|
class BaseChannel(ABC):
|
||||||
@@ -275,6 +276,9 @@ class BaseChannel(ABC):
|
|||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def _pairing_changed(self) -> None:
|
||||||
|
self.bus.publish_nowait(PairingChanged())
|
||||||
|
|
||||||
async def _handle_message(
|
async def _handle_message(
|
||||||
self,
|
self,
|
||||||
sender_id: str,
|
sender_id: str,
|
||||||
@@ -299,7 +303,7 @@ class BaseChannel(ABC):
|
|||||||
if not self.is_allowed(permission_id):
|
if not self.is_allowed(permission_id):
|
||||||
if is_dm:
|
if is_dm:
|
||||||
try:
|
try:
|
||||||
code = generate_code(self.name, str(sender_id))
|
code = generate_code(self.name, str(sender_id), on_change=self._pairing_changed)
|
||||||
except OSError:
|
except OSError:
|
||||||
# Transient pairing-store I/O failure: skip the pairing
|
# Transient pairing-store I/O failure: skip the pairing
|
||||||
# reply for this message rather than crash the handler.
|
# reply for this message rather than crash the handler.
|
||||||
@@ -307,7 +311,7 @@ class BaseChannel(ABC):
|
|||||||
"Pairing store unavailable; dropping DM from {}", sender_id
|
"Pairing store unavailable; dropping DM from {}", sender_id
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
record_delivery(code, "sending")
|
record_delivery(code, "sending", on_change=self._pairing_changed)
|
||||||
try:
|
try:
|
||||||
await self.send(
|
await self.send(
|
||||||
OutboundMessage(
|
OutboundMessage(
|
||||||
@@ -318,9 +322,9 @@ class BaseChannel(ABC):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
record_delivery(code, "failed")
|
record_delivery(code, "failed", on_change=self._pairing_changed)
|
||||||
raise
|
raise
|
||||||
record_delivery(code, "sent")
|
record_delivery(code, "sent", on_change=self._pairing_changed)
|
||||||
self.logger.info(
|
self.logger.info(
|
||||||
"Sent pairing code {} to sender {} in chat {}",
|
"Sent pairing code {} to sender {} in chat {}",
|
||||||
code, sender_id, chat_id,
|
code, sender_id, chat_id,
|
||||||
|
|||||||
@@ -625,7 +625,7 @@ async def test_on_message_unauthorized_dm_sends_pairing_code(monkeypatch) -> Non
|
|||||||
channel._running = True
|
channel._running = True
|
||||||
monkeypatch.setattr("nanobot.channels.base.is_approved", lambda _ch, _sid: False)
|
monkeypatch.setattr("nanobot.channels.base.is_approved", lambda _ch, _sid: False)
|
||||||
monkeypatch.setattr(
|
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)
|
await channel._on_message(message)
|
||||||
|
|||||||
@@ -250,7 +250,7 @@ class MattermostChannel(BaseChannel):
|
|||||||
|
|
||||||
if not await self._is_allowed(sender_id, channel_id, channel_type):
|
if not await self._is_allowed(sender_id, channel_id, channel_type):
|
||||||
if is_dm and self.config.dm.enabled:
|
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(
|
await self.send(
|
||||||
OutboundMessage(
|
OutboundMessage(
|
||||||
channel=self.name,
|
channel=self.name,
|
||||||
|
|||||||
@@ -2462,7 +2462,7 @@ async def test_forward_command_pairs_unauthorized_private_user(monkeypatch) -> N
|
|||||||
)
|
)
|
||||||
_install_ready_app(channel)
|
_install_ready_app(channel)
|
||||||
monkeypatch.setattr(
|
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)
|
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 = _make_telegram_update(text="/start", chat_type="private")
|
||||||
update.message.reply_text = AsyncMock()
|
update.message.reply_text = AsyncMock()
|
||||||
monkeypatch.setattr(
|
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)
|
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 = _make_telegram_update(text="/help", chat_type="private")
|
||||||
update.message.reply_text = AsyncMock()
|
update.message.reply_text = AsyncMock()
|
||||||
monkeypatch.setattr(
|
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)
|
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._add_reaction = AsyncMock(return_value=None)
|
||||||
channel._download_message_media = AsyncMock(return_value=([], []))
|
channel._download_message_media = AsyncMock(return_value=([], []))
|
||||||
monkeypatch.setattr(
|
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)
|
await channel._on_message(_make_telegram_update(text="hello", chat_type="private"), None)
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ from nanobot.bus.queue import MessageBus
|
|||||||
from nanobot.channels.base import BaseChannel
|
from nanobot.channels.base import BaseChannel
|
||||||
from nanobot.channels.websocket.binary_http import BinaryHTTPBridge
|
from nanobot.channels.websocket.binary_http import BinaryHTTPBridge
|
||||||
from nanobot.config_base import Base
|
from nanobot.config_base import Base
|
||||||
|
from nanobot.pairing.events import PairingChanged
|
||||||
from nanobot.runtime_admission import RuntimeMaintenanceError
|
from nanobot.runtime_admission import RuntimeMaintenanceError
|
||||||
from nanobot.session.webui_turns import (
|
from nanobot.session.webui_turns import (
|
||||||
clear_websocket_turn_if_current,
|
clear_websocket_turn_if_current,
|
||||||
@@ -816,11 +817,13 @@ class WebSocketChannel(BaseChannel):
|
|||||||
if self._server is server:
|
if self._server is server:
|
||||||
self._server = None
|
self._server = None
|
||||||
|
|
||||||
|
disconnect_pairing = self.bus.subscribe(self._queue_pairing_changed, PairingChanged)
|
||||||
task = asyncio.create_task(runner())
|
task = asyncio.create_task(runner())
|
||||||
self._server_task = task
|
self._server_task = task
|
||||||
try:
|
try:
|
||||||
await task
|
await task
|
||||||
finally:
|
finally:
|
||||||
|
disconnect_pairing()
|
||||||
prune_task.cancel()
|
prune_task.cancel()
|
||||||
await asyncio.gather(prune_task, return_exceptions=True)
|
await asyncio.gather(prune_task, return_exceptions=True)
|
||||||
self._uploads.store.clear()
|
self._uploads.store.clear()
|
||||||
@@ -1552,6 +1555,14 @@ class WebSocketChannel(BaseChannel):
|
|||||||
for connection in conns:
|
for connection in conns:
|
||||||
await self._safe_send_to(connection, raw, label=" user_message ")
|
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(
|
async def send_runtime_model_updated(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ from nanobot.channels.websocket.runtime import (
|
|||||||
)
|
)
|
||||||
from nanobot.config.loader import load_config, save_config
|
from nanobot.config.loader import load_config, save_config
|
||||||
from nanobot.config.schema import Config, ModelAPIConfig, ModelPresetConfig
|
from nanobot.config.schema import Config, ModelAPIConfig, ModelPresetConfig
|
||||||
|
from nanobot.pairing.events import PairingChanged
|
||||||
from nanobot.providers.base import LLMUsage
|
from nanobot.providers.base import LLMUsage
|
||||||
from nanobot.runtime_context import RUNTIME_CONTEXT_INPUT_META, WEBUI_QUOTE_SOURCE
|
from nanobot.runtime_context import RUNTIME_CONTEXT_INPUT_META, WEBUI_QUOTE_SOURCE
|
||||||
from nanobot.security.workspace_access import WORKSPACE_SCOPE_METADATA_KEY
|
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"]
|
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
|
@pytest.mark.asyncio
|
||||||
async def test_send_broadcasts_runtime_model_updates() -> None:
|
async def test_send_broadcasts_runtime_model_updates() -> None:
|
||||||
bus = MessageBus()
|
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.list_pending", lambda: list(pending))
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"nanobot.webui.settings_routes.approve_code",
|
"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(
|
monkeypatch.setattr(
|
||||||
"nanobot.webui.settings_routes.deny_code",
|
"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())
|
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
|
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
|
@pytest.mark.asyncio
|
||||||
async def test_nanobot_feature_remote_install_requires_opt_in(
|
async def test_nanobot_feature_remote_install_requires_opt_in(
|
||||||
bus: MagicMock,
|
bus: MagicMock,
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import pytest
|
|||||||
|
|
||||||
from nanobot.bus.queue import MessageBus
|
from nanobot.bus.queue import MessageBus
|
||||||
from nanobot.channels.websocket.runtime import WebSocketChannel
|
from nanobot.channels.websocket.runtime import WebSocketChannel
|
||||||
|
from nanobot.pairing.events import PairingChanged
|
||||||
|
|
||||||
|
|
||||||
class _FakeSocket:
|
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 exc_info.value is bind_error
|
||||||
assert channel.is_running is False
|
assert channel.is_running is False
|
||||||
|
await channel.bus.publish(PairingChanged())
|
||||||
|
assert channel.bus.outbound_size == 0
|
||||||
assert not any(
|
assert not any(
|
||||||
call.args and call.args[0] == "WebSocket server listening on {}"
|
call.args and call.args[0] == "WebSocket server listening on {}"
|
||||||
for call in channel.logger.info.call_args_list
|
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
|
break
|
||||||
await asyncio.sleep(0)
|
await asyncio.sleep(0)
|
||||||
assert channel.is_running is True
|
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
|
first.socket.open = False
|
||||||
for _ in range(50):
|
for _ in range(50):
|
||||||
@@ -129,3 +136,5 @@ async def test_websocket_restarts_only_its_listener_after_serving_socket_is_lost
|
|||||||
await start_task
|
await start_task
|
||||||
|
|
||||||
assert second.closed is True
|
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._get_typing_ticket = AsyncMock(return_value="")
|
||||||
channel._send_text = AsyncMock()
|
channel._send_text = AsyncMock()
|
||||||
monkeypatch.setattr(
|
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(
|
await channel._process_message(
|
||||||
|
|||||||
@@ -798,7 +798,7 @@ async def test_unauthorized_voice_message_does_not_download_or_transcribe(
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_unauthorized_dm_uses_base_pairing_flow(monkeypatch) -> None:
|
async def test_unauthorized_dm_uses_base_pairing_flow(monkeypatch) -> None:
|
||||||
_patch_neonize_api(monkeypatch)
|
_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)
|
monkeypatch.setattr("nanobot.channels.base.is_approved", lambda _ch, _sid: False)
|
||||||
client = SimpleNamespace(send_message=AsyncMock(), download_any=AsyncMock())
|
client = SimpleNamespace(send_message=AsyncMock(), download_any=AsyncMock())
|
||||||
ch = WhatsAppChannel({"enabled": True, "allowFrom": []}, MagicMock())
|
ch = WhatsAppChannel({"enabled": True, "allowFrom": []}, MagicMock())
|
||||||
|
|||||||
@@ -939,8 +939,12 @@ async def cmd_goal(ctx: CommandContext) -> InboundMessage | OutboundMessage:
|
|||||||
async def cmd_pairing(ctx: CommandContext) -> OutboundMessage:
|
async def cmd_pairing(ctx: CommandContext) -> OutboundMessage:
|
||||||
"""List, approve, deny or revoke pairing requests."""
|
"""List, approve, deny or revoke pairing requests."""
|
||||||
from nanobot.pairing import PAIRING_COMMAND_META_KEY, handle_pairing_command
|
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(
|
return OutboundMessage(
|
||||||
channel=ctx.msg.channel,
|
channel=ctx.msg.channel,
|
||||||
chat_id=ctx.msg.chat_id,
|
chat_id=ctx.msg.chat_id,
|
||||||
|
|||||||
@@ -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
@@ -12,6 +12,7 @@ import secrets
|
|||||||
import string
|
import string
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
|
from collections.abc import Callable
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Literal, cast
|
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))
|
_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:
|
def _gc_pending(data: dict[str, Any]) -> None:
|
||||||
"""Remove expired pending entries in-place."""
|
"""Remove expired pending entries in-place."""
|
||||||
now = time.time()
|
now = time.time()
|
||||||
@@ -114,6 +125,8 @@ def generate_code(
|
|||||||
channel: str,
|
channel: str,
|
||||||
sender_id: str,
|
sender_id: str,
|
||||||
ttl: int = _TTL_DEFAULT_S,
|
ttl: int = _TTL_DEFAULT_S,
|
||||||
|
*,
|
||||||
|
on_change: Callable[[], object] | None = None,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Return an active pairing code for *sender_id* on *channel*.
|
"""Return an active pairing code for *sender_id* on *channel*.
|
||||||
|
|
||||||
@@ -138,10 +151,14 @@ def generate_code(
|
|||||||
}
|
}
|
||||||
_save(data)
|
_save(data)
|
||||||
logger.info("Generated pairing code {} for {}@{}", code, sender_id, channel)
|
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.
|
"""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.
|
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()
|
data = _load()
|
||||||
_gc_pending(data)
|
_gc_pending(data)
|
||||||
info = data["pending"].get(code)
|
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
|
return
|
||||||
info["delivery_status"] = status
|
info["delivery_status"] = status
|
||||||
_save(data)
|
_save(data)
|
||||||
except OSError:
|
except OSError:
|
||||||
logger.warning("Could not persist pairing reply delivery status")
|
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.
|
"""Approve a pending pairing code.
|
||||||
|
|
||||||
Returns ``(channel, sender_id)`` on success, or ``None`` if the 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)
|
data.setdefault("approved", {}).setdefault(channel, set()).add(sender_id)
|
||||||
_save(data)
|
_save(data)
|
||||||
logger.info("Approved pairing code {} for {}@{}", code, sender_id, channel)
|
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.
|
"""Reject and discard a pending pairing code.
|
||||||
|
|
||||||
Returns ``True`` if the code existed and was removed.
|
Returns ``True`` if the code existed and was removed.
|
||||||
@@ -191,12 +213,13 @@ def deny_code(code: str) -> bool:
|
|||||||
data = _load()
|
data = _load()
|
||||||
_gc_pending(data)
|
_gc_pending(data)
|
||||||
pending: dict[str, Any] = data.get("pending", {})
|
pending: dict[str, Any] = data.get("pending", {})
|
||||||
if code in pending:
|
if code not in pending:
|
||||||
del pending[code]
|
return False
|
||||||
_save(data)
|
del pending[code]
|
||||||
logger.info("Denied pairing code {}", code)
|
_save(data)
|
||||||
return True
|
logger.info("Denied pairing code {}", code)
|
||||||
return False
|
_notify_changed(on_change)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
def is_approved(channel: str, sender_id: str) -> bool:
|
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*.
|
"""Remove an approved sender from *channel*.
|
||||||
|
|
||||||
Returns ``True`` if the sender was present and removed.
|
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", {})
|
approved: dict[str, set[str]] = data.get("approved", {})
|
||||||
users = approved.get(channel, set())
|
users = approved.get(channel, set())
|
||||||
sid = str(sender_id)
|
sid = str(sender_id)
|
||||||
if sid in users:
|
if sid not in users:
|
||||||
users.discard(sid)
|
return False
|
||||||
if not users:
|
users.discard(sid)
|
||||||
del approved[channel]
|
if not users:
|
||||||
_save(data)
|
del approved[channel]
|
||||||
logger.info("Revoked {} from {}", sid, channel)
|
_save(data)
|
||||||
return True
|
logger.info("Revoked {} from {}", sid, channel)
|
||||||
return False
|
_notify_changed(on_change)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
def revoke_channel(channel: str) -> int:
|
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"
|
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.
|
"""Execute a pairing subcommand and return the reply text.
|
||||||
|
|
||||||
This is a pure function (no side effects other than store mutations)
|
CLI and agent commands share the same mutations. The optional notifier runs
|
||||||
so it can be used from both the CLI and the agent CommandRouter.
|
only after a successful persistent change, without changing the reply text.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
return _handle_pairing_subcommand(channel, subcommand_text)
|
return _handle_pairing_subcommand(channel, subcommand_text, on_change=on_change)
|
||||||
except OSError:
|
except OSError:
|
||||||
# Mutations fail loudly on a transient I/O error instead of lying
|
# Mutations fail loudly on a transient I/O error instead of lying
|
||||||
# ("invalid code") or silently rewriting the store from an empty view.
|
# ("invalid code") or silently rewriting the store from an empty view.
|
||||||
return "The pairing store is temporarily unavailable. Please try again."
|
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()
|
parts = subcommand_text.split()
|
||||||
sub = parts[0] if parts else "list"
|
sub = parts[0] if parts else "list"
|
||||||
arg = parts[1] if len(parts) > 1 else None
|
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":
|
elif sub == "approve":
|
||||||
if arg is None:
|
if arg is None:
|
||||||
return "Usage: `/pairing approve <code>`"
|
return "Usage: `/pairing approve <code>`"
|
||||||
result = approve_code(arg)
|
result = approve_code(arg, on_change=on_change)
|
||||||
if result is None:
|
if result is None:
|
||||||
return f"Invalid or expired pairing code: `{arg}`"
|
return f"Invalid or expired pairing code: `{arg}`"
|
||||||
ch, sid = result
|
ch, sid = result
|
||||||
@@ -362,7 +392,7 @@ def _handle_pairing_subcommand(channel: str, subcommand_text: str) -> str:
|
|||||||
elif sub == "deny":
|
elif sub == "deny":
|
||||||
if arg is None:
|
if arg is None:
|
||||||
return "Usage: `/pairing deny <code>`"
|
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"Denied pairing code `{arg}`"
|
||||||
return f"Pairing code `{arg}` not found or already expired"
|
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:
|
if len(parts) == 2:
|
||||||
return (
|
return (
|
||||||
f"Revoked {arg} from {channel}"
|
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}"
|
else f"{arg} was not in the approved list for {channel}"
|
||||||
)
|
)
|
||||||
if len(parts) == 3:
|
if len(parts) == 3:
|
||||||
return (
|
return (
|
||||||
f"Revoked {parts[2]} from {arg}"
|
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}"
|
else f"{parts[2]} was not in the approved list for {arg}"
|
||||||
)
|
)
|
||||||
return "Usage: `/pairing revoke <user_id>` or `/pairing revoke <channel> <user_id>`"
|
return "Usage: `/pairing revoke <user_id>` or `/pairing revoke <channel> <user_id>`"
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ from nanobot.bus.outbound_events import (
|
|||||||
UserInputEvent,
|
UserInputEvent,
|
||||||
)
|
)
|
||||||
from nanobot.bus.runtime_events import SubagentTaskChanged
|
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.session.webui_turns import clear_websocket_turn_if_current
|
||||||
from nanobot.webui.metadata import (
|
from nanobot.webui.metadata import (
|
||||||
WEBSOCKET_TURN_OWNER_METADATA_KEY,
|
WEBSOCKET_TURN_OWNER_METADATA_KEY,
|
||||||
@@ -45,6 +46,8 @@ class WebUIOutboundTransport(Protocol):
|
|||||||
|
|
||||||
def webui_subscribers(self, chat_id: str) -> tuple[ServerConnection, ...]: ...
|
def webui_subscribers(self, chat_id: str) -> tuple[ServerConnection, ...]: ...
|
||||||
|
|
||||||
|
async def send_pairing_changed(self) -> None: ...
|
||||||
|
|
||||||
async def send_runtime_model_updated(
|
async def send_runtime_model_updated(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
@@ -138,6 +141,9 @@ class WebUIOutboundProjector:
|
|||||||
|
|
||||||
async def send(self, msg: OutboundMessage) -> None:
|
async def send(self, msg: OutboundMessage) -> None:
|
||||||
event = msg.event
|
event = msg.event
|
||||||
|
if isinstance(event, PairingChanged):
|
||||||
|
await self._transport.send_pairing_changed()
|
||||||
|
return
|
||||||
if isinstance(event, RetryWaitEvent):
|
if isinstance(event, RetryWaitEvent):
|
||||||
return
|
return
|
||||||
progress_event = event if isinstance(event, ProgressEvent) else None
|
progress_event = event if isinstance(event, ProgressEvent) else None
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import asyncio
|
|||||||
import html
|
import html
|
||||||
import json
|
import json
|
||||||
from collections.abc import Awaitable, Callable, Mapping
|
from collections.abc import Awaitable, Callable, Mapping
|
||||||
|
from functools import partial
|
||||||
from typing import Any, cast
|
from typing import Any, cast
|
||||||
|
|
||||||
from websockets.http11 import Request as WsRequest
|
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.registry import load_channel_plugin
|
||||||
from nanobot.channels.validation import validate_channel_config
|
from nanobot.channels.validation import validate_channel_config
|
||||||
from nanobot.pairing import approve_code, deny_code, list_pending
|
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_capabilities as capability_domain
|
||||||
from nanobot.webui import settings_contracts as contracts
|
from nanobot.webui import settings_contracts as contracts
|
||||||
from nanobot.webui import settings_models as model_domain
|
from nanobot.webui import settings_models as model_domain
|
||||||
@@ -541,6 +543,9 @@ class WebUISettingsRouter:
|
|||||||
reload_image=self._reload_image_generation_runtime,
|
reload_image=self._reload_image_generation_runtime,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def _pairing_changed(self) -> None:
|
||||||
|
self.bus.publish_nowait(PairingChanged())
|
||||||
|
|
||||||
def _system_operations(self) -> system_domain.SystemSettingsOperations:
|
def _system_operations(self) -> system_domain.SystemSettingsOperations:
|
||||||
return system_domain.SystemSettingsOperations(
|
return system_domain.SystemSettingsOperations(
|
||||||
update_runtime_config=update_runtime_config_settings,
|
update_runtime_config=update_runtime_config_settings,
|
||||||
@@ -552,8 +557,8 @@ class WebUISettingsRouter:
|
|||||||
validate_channel_config=validate_channel_config,
|
validate_channel_config=validate_channel_config,
|
||||||
load_channel_plugin=load_channel_plugin,
|
load_channel_plugin=load_channel_plugin,
|
||||||
list_pending=list_pending,
|
list_pending=list_pending,
|
||||||
approve_code=approve_code,
|
approve_code=partial(approve_code, on_change=self._pairing_changed),
|
||||||
deny_code=deny_code,
|
deny_code=partial(deny_code, on_change=self._pairing_changed),
|
||||||
mcp_presets_action=mcp_presets_settings_action,
|
mcp_presets_action=mcp_presets_settings_action,
|
||||||
reload_mcp=self._reload_mcp_runtime,
|
reload_mcp=self._reload_mcp_runtime,
|
||||||
mcp_runtime_status=self._mcp_runtime_status,
|
mcp_runtime_status=self._mcp_runtime_status,
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ def test_is_allowed_pairing_fallback(monkeypatch) -> None:
|
|||||||
async def test_handle_message_dm_sends_pairing_code(monkeypatch) -> None:
|
async def test_handle_message_dm_sends_pairing_code(monkeypatch) -> None:
|
||||||
channel = _DummyChannel({"allowFrom": []}, MessageBus())
|
channel = _DummyChannel({"allowFrom": []}, MessageBus())
|
||||||
monkeypatch.setattr(
|
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(
|
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
|
assert bus.inbound_size == 0
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
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")
|
||||||
@@ -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
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
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]
|
||||||
@@ -264,7 +264,7 @@ class TestPairingCommandDispatch:
|
|||||||
) -> None:
|
) -> None:
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"nanobot.pairing.store.approve_code",
|
"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"
|
fake_msg.content = "/pairing approve ABCD-EFGH"
|
||||||
ctx = CommandContext(
|
ctx = CommandContext(
|
||||||
@@ -286,7 +286,7 @@ class TestPairingCommandDispatch:
|
|||||||
) -> None:
|
) -> None:
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"nanobot.pairing.store.revoke",
|
"nanobot.pairing.store.revoke",
|
||||||
lambda ch, sid: sid == "123",
|
lambda ch, sid, *, on_change=None: sid == "123",
|
||||||
)
|
)
|
||||||
fake_msg.content = "/pairing revoke 123"
|
fake_msg.content = "/pairing revoke 123"
|
||||||
ctx = CommandContext(
|
ctx = CommandContext(
|
||||||
|
|||||||
@@ -441,3 +441,75 @@ class TestTransientReadFailure:
|
|||||||
|
|
||||||
assert "unavailable" in reply.lower()
|
assert "unavailable" in reply.lower()
|
||||||
assert store.approve_code(code) == ("telegram", "123")
|
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")
|
||||||
@@ -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([]);
|
||||||
|
});
|
||||||
|
}
|
||||||
+44
-26
@@ -1281,6 +1281,7 @@ function Shell({
|
|||||||
const [pairingBusyCode, setPairingBusyCode] = useState<string | null>(null);
|
const [pairingBusyCode, setPairingBusyCode] = useState<string | null>(null);
|
||||||
const [pairingError, setPairingError] = useState<string | null>(null);
|
const [pairingError, setPairingError] = useState<string | null>(null);
|
||||||
const pairingRefreshRef = useRef<Promise<number> | null>(null);
|
const pairingRefreshRef = useRef<Promise<number> | null>(null);
|
||||||
|
const pairingRefreshPendingRef = useRef(false);
|
||||||
const [snoozedPairingCodes, setSnoozedPairingCodes] = useState<Map<string, {
|
const [snoozedPairingCodes, setSnoozedPairingCodes] = useState<Map<string, {
|
||||||
until: number;
|
until: number;
|
||||||
deliveryStatus: PairingRequestInfo["delivery_status"];
|
deliveryStatus: PairingRequestInfo["delivery_status"];
|
||||||
@@ -1473,32 +1474,41 @@ function Shell({
|
|||||||
}, [updatedChatIds]);
|
}, [updatedChatIds]);
|
||||||
|
|
||||||
const refreshPairingRequests = useCallback((): Promise<number> => {
|
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 () => {
|
const request = (async () => {
|
||||||
try {
|
let requestCount: number;
|
||||||
const payload = await fetchPairingRequests(getToken());
|
do {
|
||||||
const requests = Array.isArray(payload.requests) ? payload.requests : [];
|
pairingRefreshPendingRef.current = false;
|
||||||
setPairingRequests(requests);
|
try {
|
||||||
setSnoozedPairingCodes((current) => {
|
const payload = await fetchPairingRequests(getToken());
|
||||||
if (current.size === 0) return current;
|
const requests = Array.isArray(payload.requests) ? payload.requests : [];
|
||||||
const activeRequests = new Map(requests.map((request) => [request.code, request]));
|
setPairingRequests(requests);
|
||||||
const now = Date.now();
|
setSnoozedPairingCodes((current) => {
|
||||||
const next = new Map(
|
if (current.size === 0) return current;
|
||||||
Array.from(current).filter(
|
const activeRequests = new Map(requests.map((request) => [request.code, request]));
|
||||||
([code, snooze]) => activeRequests.has(code)
|
const now = Date.now();
|
||||||
&& snooze.until > now
|
const next = new Map(
|
||||||
&& activeRequests.get(code)?.delivery_status === snooze.deliveryStatus,
|
Array.from(current).filter(
|
||||||
),
|
([code, snooze]) => activeRequests.has(code)
|
||||||
);
|
&& snooze.until > now
|
||||||
return next.size === current.size ? current : next;
|
&& activeRequests.get(code)?.delivery_status === snooze.deliveryStatus,
|
||||||
});
|
),
|
||||||
return requests.length;
|
);
|
||||||
} catch {
|
return next.size === current.size ? current : next;
|
||||||
// Pairing is an opportunistic WebUI affordance. The slash command path
|
});
|
||||||
// remains available if this polling request fails.
|
requestCount = requests.length;
|
||||||
return 0;
|
} 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 = () => {
|
const clearRequest = () => {
|
||||||
if (pairingRefreshRef.current === request) pairingRefreshRef.current = null;
|
if (pairingRefreshRef.current === request) pairingRefreshRef.current = null;
|
||||||
@@ -1516,17 +1526,24 @@ function Shell({
|
|||||||
const poll = async () => {
|
const poll = async () => {
|
||||||
const requestCount = await refreshPairingRequests();
|
const requestCount = await refreshPairingRequests();
|
||||||
if (disposed) return;
|
if (disposed) return;
|
||||||
|
if (timer !== null) window.clearTimeout(timer);
|
||||||
timer = window.setTimeout(
|
timer = window.setTimeout(
|
||||||
() => void poll(),
|
() => void poll(),
|
||||||
requestCount > 0 ? PAIRING_POLL_INTERVAL_MS : PAIRING_IDLE_POLL_INTERVAL_MS,
|
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();
|
void poll();
|
||||||
return () => {
|
return () => {
|
||||||
disposed = true;
|
disposed = true;
|
||||||
|
pairingRefreshPendingRef.current = false;
|
||||||
if (timer !== null) window.clearTimeout(timer);
|
if (timer !== null) window.clearTimeout(timer);
|
||||||
|
unsubscribePairing();
|
||||||
|
unsubscribeReady();
|
||||||
};
|
};
|
||||||
}, [pageVisible, refreshPairingRequests]);
|
}, [client, pageVisible, refreshPairingRequests]);
|
||||||
|
|
||||||
const activeSession = useMemo<ChatSummary | null>(() => {
|
const activeSession = useMemo<ChatSummary | null>(() => {
|
||||||
if (!activeKey) return null;
|
if (!activeKey) return null;
|
||||||
@@ -2465,9 +2482,10 @@ function Shell({
|
|||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setPairingError((e as Error).message);
|
setPairingError((e as Error).message);
|
||||||
void refreshPairingRequests();
|
|
||||||
} finally {
|
} finally {
|
||||||
setPairingBusyCode(null);
|
setPairingBusyCode(null);
|
||||||
|
// A mutation reply can be older than an already-delivered notification.
|
||||||
|
void refreshPairingRequests();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[client, refreshPairingRequests],
|
[client, refreshPairingRequests],
|
||||||
|
|||||||
@@ -87,6 +87,7 @@ type SessionUpdateHandler = (
|
|||||||
workspaceScope?: WorkspaceScopePayload,
|
workspaceScope?: WorkspaceScopePayload,
|
||||||
) => void;
|
) => void;
|
||||||
type SidebarStateUpdateHandler = (state: SidebarStatePayload) => void;
|
type SidebarStateUpdateHandler = (state: SidebarStatePayload) => void;
|
||||||
|
type PairingChangeHandler = () => void;
|
||||||
type RunStatusHandler = (chatId: string, state: RunState) => void;
|
type RunStatusHandler = (chatId: string, state: RunState) => void;
|
||||||
|
|
||||||
/** Structured errors surfaced to the UI.
|
/** Structured errors surfaced to the UI.
|
||||||
@@ -238,6 +239,8 @@ export class NanobotClient {
|
|||||||
private runCompletionHandlers = new Set<RunCompletionHandler>();
|
private runCompletionHandlers = new Set<RunCompletionHandler>();
|
||||||
private errorHandlers = new Set<ErrorHandler>();
|
private errorHandlers = new Set<ErrorHandler>();
|
||||||
private taskNoticeHandlers = new Set<(notice: TaskNotice) => void>();
|
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 chatHandlers = new Map<string, Set<EventHandler>>();
|
||||||
private transcriptHandlers = new Map<string, { handler: EventHandler }>();
|
private transcriptHandlers = new Map<string, { handler: EventHandler }>();
|
||||||
/** Inbound frames received while the transcript owner is absent, regardless of observers. */
|
/** 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 {
|
onSidebarStateUpdate(handler: SidebarStateUpdateHandler): Unsubscribe {
|
||||||
this.sidebarStateUpdateHandlers.add(handler);
|
this.sidebarStateUpdateHandlers.add(handler);
|
||||||
return () => {
|
return () => {
|
||||||
@@ -966,6 +979,9 @@ export class NanobotClient {
|
|||||||
this.upload = uploadCapability(parsed.upload);
|
this.upload = uploadCapability(parsed.upload);
|
||||||
this.readyChatId = parsed.chat_id;
|
this.readyChatId = parsed.chat_id;
|
||||||
this.knownChats.add(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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -987,6 +1003,13 @@ export class NanobotClient {
|
|||||||
return;
|
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") {
|
if (parsed.event === "runtime_model_updated") {
|
||||||
this.emitRuntimeModelUpdate(parsed.model_name || null, parsed.model_preset ?? null);
|
this.emitRuntimeModelUpdate(parsed.model_name || null, parsed.model_preset ?? null);
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -1572,6 +1572,7 @@ export type InboundEvent =
|
|||||||
/** Legacy persisted transcripts may carry the final reasoning text here. */
|
/** Legacy persisted transcripts may carry the final reasoning text here. */
|
||||||
text?: string;
|
text?: string;
|
||||||
} & InboundTurnMetadata)
|
} & InboundTurnMetadata)
|
||||||
|
| { event: "pairing_changed" }
|
||||||
| {
|
| {
|
||||||
event: "runtime_model_updated";
|
event: "runtime_model_updated";
|
||||||
model_name: string;
|
model_name: string;
|
||||||
|
|||||||
@@ -44,6 +44,8 @@ const sessionUpdateHandlers = new Set<(
|
|||||||
workspaceScope?: WorkspaceScopePayload,
|
workspaceScope?: WorkspaceScopePayload,
|
||||||
) => void>();
|
) => void>();
|
||||||
const sidebarStateUpdateHandlers = new Set<(state: SidebarStatePayload) => void>();
|
const sidebarStateUpdateHandlers = new Set<(state: SidebarStatePayload) => void>();
|
||||||
|
const pairingChangeHandlers = new Set<() => void>();
|
||||||
|
const readyHandlers = new Set<() => void>();
|
||||||
let mockSessions: ChatSummary[] = [];
|
let mockSessions: ChatSummary[] = [];
|
||||||
const HERO_GREETING_PATTERN =
|
const HERO_GREETING_PATTERN =
|
||||||
/What should we work on\?|Where should we start\?|What are we building today\?|What should we tackle together\?/;
|
/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);
|
return () => statusHandlers.delete(handler);
|
||||||
};
|
};
|
||||||
onRuntimeModelUpdate = () => () => {};
|
onRuntimeModelUpdate = () => () => {};
|
||||||
|
onPairingChange = (handler: () => void) => {
|
||||||
|
pairingChangeHandlers.add(handler);
|
||||||
|
return () => pairingChangeHandlers.delete(handler);
|
||||||
|
};
|
||||||
|
onReady = (handler: () => void) => {
|
||||||
|
readyHandlers.add(handler);
|
||||||
|
return () => readyHandlers.delete(handler);
|
||||||
|
};
|
||||||
onError = () => () => {};
|
onError = () => () => {};
|
||||||
onChat = () => () => {};
|
onChat = () => () => {};
|
||||||
onTranscript = () => () => {};
|
onTranscript = () => () => {};
|
||||||
@@ -348,6 +358,8 @@ describe("App layout", () => {
|
|||||||
runStatusHandlers.clear();
|
runStatusHandlers.clear();
|
||||||
sessionUpdateHandlers.clear();
|
sessionUpdateHandlers.clear();
|
||||||
sidebarStateUpdateHandlers.clear();
|
sidebarStateUpdateHandlers.clear();
|
||||||
|
pairingChangeHandlers.clear();
|
||||||
|
readyHandlers.clear();
|
||||||
window.history.replaceState(null, "", "/");
|
window.history.replaceState(null, "", "/");
|
||||||
sessionStorage.removeItem("nanobot.remote-instance");
|
sessionStorage.removeItem("nanobot.remote-instance");
|
||||||
Reflect.deleteProperty(window, "nanobotHost");
|
Reflect.deleteProperty(window, "nanobotHost");
|
||||||
@@ -4435,6 +4447,141 @@ describe("App layout", () => {
|
|||||||
unmount();
|
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) => {
|
it.each(["sending", "failed"])("explains an undelivered pairing reply (%s) without empty code slots", async (delivery_status) => {
|
||||||
mockFetchRoutes({ "/api/settings/pairing": { requests: [{
|
mockFetchRoutes({ "/api/settings/pairing": { requests: [{
|
||||||
code: "ABCD-EFGH", channel: "feishu", sender_id: "alice", delivery_status,
|
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();
|
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;
|
let resolvePairing!: (response: Response) => void;
|
||||||
const pendingPairing = new Promise<Response>((resolve) => {
|
const pendingPairing = new Promise<Response>((resolve) => {
|
||||||
resolvePairing = resolve;
|
resolvePairing = resolve;
|
||||||
});
|
});
|
||||||
const fetchMock = vi.fn((input: RequestInfo | URL) => (
|
let reads = 0;
|
||||||
String(input) === "/api/settings/pairing"
|
const fetchMock = vi.fn((input: RequestInfo | URL) => {
|
||||||
? pendingPairing
|
if (String(input) !== "/api/settings/pairing") return Promise.resolve({ ok: false, status: 404 } as Response);
|
||||||
: 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);
|
vi.stubGlobal("fetch", fetchMock);
|
||||||
const visibilityDescriptor = Object.getOwnPropertyDescriptor(document, "visibilityState");
|
const visibilityDescriptor = Object.getOwnPropertyDescriptor(document, "visibilityState");
|
||||||
|
|
||||||
@@ -4550,6 +4699,8 @@ describe("App layout", () => {
|
|||||||
resolvePairing(jsonResponse({ requests: [] }));
|
resolvePairing(jsonResponse({ requests: [] }));
|
||||||
await pendingPairing;
|
await pendingPairing;
|
||||||
});
|
});
|
||||||
|
expect(screen.getByRole("dialog", { name: "Pair account" })).toBeVisible();
|
||||||
|
expect(reads).toBe(2);
|
||||||
} finally {
|
} finally {
|
||||||
if (visibilityDescriptor) {
|
if (visibilityDescriptor) {
|
||||||
Object.defineProperty(document, "visibilityState", visibilityDescriptor);
|
Object.defineProperty(document, "visibilityState", visibilityDescriptor);
|
||||||
|
|||||||
@@ -71,6 +71,45 @@ afterEach(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("NanobotClient", () => {
|
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", () => {
|
it("emits live task notices without mounted chats, not when the chat replays", () => {
|
||||||
const client = new NanobotClient({ url: "ws://test", reconnect: false,
|
const client = new NanobotClient({ url: "ws://test", reconnect: false,
|
||||||
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
|
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
|
||||||
|
|||||||
Reference in new issue
Block a user