fix: preserve delivery failures across channel boundaries

This commit is contained in:
chengyongru authored and chengyongru committed 2026-11-09 11:41:57 +08:00
1 parent f62dfe0ee8
commit d789e1bfc7
10 files changed
+616 -68

No files matched your search

+8 -3
View File
@@ -323,9 +323,13 @@ class BaseChannel(ABC):
authorization_id: str | None = None,
require_existing_session: bool = False,
session_generation: str | None = None,
) -> None:
) -> bool:
"""Handle a message after checking its authorization subject.
Return True only after the inbound bus accepts the message. Return False
for a denied message, including when a pairing reply was sent. Delivery
errors propagate; callers must not acknowledge on an exception.
``sender_id`` is the identity recorded on the inbound message. Channels
where access is scoped to another entity (for example, a group or room)
can pass that entity as ``authorization_id`` without changing the
@@ -342,7 +346,7 @@ class BaseChannel(ABC):
self.logger.warning(
"Pairing store unavailable; dropping DM from {}", sender_id
)
return
return False
record_delivery(code, "sending", on_change=self._pairing_changed)
try:
await self.send(
@@ -367,7 +371,7 @@ class BaseChannel(ABC):
"Add them to allowFrom list in config to grant access.",
sender_id,
)
return
return False
meta = metadata or {}
if self.supports_streaming:
@@ -386,6 +390,7 @@ class BaseChannel(ABC):
)
await self.bus.publish_inbound(msg)
return True
@classmethod
def default_config(cls) -> dict[str, Any]:
+114 -11
View File
@@ -163,8 +163,33 @@ class EmailChannel(BaseChannel):
self._last_subject_by_chat: dict[str, str] = {}
self._last_message_id_by_chat: dict[str, str] = {}
self._processed_uids: set[str] = set()
self._uidvalidity: bytes | None = None
self._pending_seen: set[str] = set()
self._deferred_post_actions: set[str] = set()
self._MAX_PROCESSED_UIDS = 100000
@staticmethod
async def _imap_thread(func: Any, *args: Any) -> Any:
# Wait for the worker on cancellation before a poller can be restarted.
task = asyncio.create_task(asyncio.to_thread(func, *args))
try:
return await asyncio.shield(task)
except asyncio.CancelledError as cancellation:
while not task.done():
try:
await asyncio.shield(task)
except asyncio.CancelledError:
continue
except BaseException:
break
try:
task.result()
except asyncio.CancelledError:
pass
except BaseException as exc:
raise cancellation from exc
raise
async def start(self) -> None:
"""Start polling IMAP for inbound emails."""
if not self.config.consent_granted:
@@ -189,9 +214,24 @@ class EmailChannel(BaseChannel):
poll_seconds = max(5, int(self.config.poll_interval_seconds))
while self._running:
try:
inbound_items, skipped_uids = await asyncio.to_thread(self._fetch_new_messages)
# Retry only the idempotent acknowledgement, never bus delivery.
for uid in sorted(self._pending_seen):
try:
await self._imap_thread(self._mark_seen_batch, [uid])
except Exception:
self.logger.exception("Error retrying seen acknowledgement for UID {}", uid)
else:
self._pending_seen.discard(uid)
ready = self._deferred_post_actions - self._pending_seen
if ready:
# Remove before sending: MOVE/COPY may succeed even if the
# connection or this task fails before receiving a reply.
self._deferred_post_actions.difference_update(ready)
await self._imap_thread(self._apply_post_actions_batch, sorted(ready))
inbound_items, skipped_uids = await self._imap_thread(self._fetch_new_messages)
should_apply_post_action = self._should_apply_post_action()
post_actions_uids: set[str] = set()
delivered_uids: set[str] = set()
for item in inbound_items:
sender = item["sender"]
subject = item.get("subject", "")
@@ -203,7 +243,7 @@ class EmailChannel(BaseChannel):
self._last_message_id_by_chat[sender] = message_id
try:
await self._handle_message(
delivered = await self._handle_message(
sender_id=sender,
chat_id=sender,
content=item["content"],
@@ -213,18 +253,43 @@ class EmailChannel(BaseChannel):
except Exception:
self.logger.exception("Error delivering email from {}", sender)
continue
if not delivered:
continue
metadata = item.get("metadata")
metadata_data = cast(dict[str, Any], metadata) if isinstance(metadata, dict) else {}
uid = str(metadata_data.get("uid") or "")
if uid and should_apply_post_action:
post_actions_uids.add(uid)
if uid:
# Bus acceptance precedes deduplication and IMAP acknowledgement.
self._remember_processed_uid(uid, True, set())
delivered_uids.add(uid)
if self.config.mark_seen:
self._pending_seen.add(uid)
if should_apply_post_action:
# Persist before the next delivery can be cancelled.
self._deferred_post_actions.add(uid)
if self.config.mark_seen and delivered_uids:
try:
await self._imap_thread(self._mark_seen_batch, sorted(delivered_uids))
except Exception:
# Delivery succeeded; retain the acknowledgement for retry.
self.logger.exception("Error marking delivered emails seen")
else:
self._pending_seen.difference_update(delivered_uids)
if should_apply_post_action and not self.config.post_action_ignore_skipped:
post_actions_uids.update(skipped_uids)
if post_actions_uids:
await asyncio.to_thread(self._apply_post_actions_batch, sorted(post_actions_uids))
# Do not remove/move a message while its seen acknowledgement
# is pending: otherwise retry could target a vanished message.
self._deferred_post_actions.update(post_actions_uids)
ready = self._deferred_post_actions - self._pending_seen
if ready:
# Once sent, MOVE/COPY has an uncertain outcome on failure or
# cancellation; do not blindly retry it.
self._deferred_post_actions.difference_update(ready)
await self._imap_thread(self._apply_post_actions_batch, sorted(ready))
except Exception:
self.logger.exception("Polling error")
@@ -438,6 +503,7 @@ class EmailChannel(BaseChannel):
messages,
skipped_uids,
cycle_uids,
allow_epoch_switch=(attempt == 0),
)
return messages, skipped_uids
except Exception as exc:
@@ -456,6 +522,8 @@ class EmailChannel(BaseChannel):
messages: list[dict[str, Any]],
skipped_uids: set[str],
cycle_uids: set[str],
*,
allow_epoch_switch: bool = False,
) -> list[dict[str, Any]] | None:
mailbox = self.config.imap_mailbox or "INBOX"
@@ -464,6 +532,8 @@ class EmailChannel(BaseChannel):
return messages
try:
if dedupe:
self._check_uidvalidity(client, establish=True, allow_epoch_switch=allow_epoch_switch)
status, data = client.uid("SEARCH", None, *search_criteria)
if status != "OK" or not data or not data[0]:
return messages
@@ -584,21 +654,53 @@ class EmailChannel(BaseChannel):
}
)
self._remember_processed_uid(uid, dedupe, cycle_uids)
# Avoid duplicates within an IMAP reconnect, but do not acknowledge
# accepted mail until the asynchronous bus delivery succeeds.
cycle_uids.add(uid)
finally:
self._close_imap_client(client)
if mark_seen:
features = self._mark_seen_uid(client, uid, features)
def _mark_seen_batch(self, uids: list[str]) -> None:
client = self._open_imap_client(mailbox=self.config.imap_mailbox or "INBOX")
if client is None:
raise RuntimeError("Cannot select mailbox to mark messages seen")
try:
self._check_uidvalidity(client)
features: _ServerFeatures | None = None
for uid in uids:
features = self._mark_seen_uid(client, uid, features, require_success=True)
finally:
self._close_imap_client(client)
def _mark_seen_uid(
self, client: Any, uid: str, features: _ServerFeatures | None
self, client: Any, uid: str, features: _ServerFeatures | None, *, require_success: bool = False
) -> _ServerFeatures:
if features is None:
features = self._server_features(client)
self._uid_store_flag(client, uid, "\\Seen", features)
if not self._uid_store_flag(client, uid, "\\Seen", features) and require_success:
raise RuntimeError(f"Could not mark UID {uid} seen")
return features
def _check_uidvalidity(
self, client: Any, *, establish: bool = False, allow_epoch_switch: bool = False
) -> None:
_, values = client.response("UIDVALIDITY")
value = values[0] if values else None
if not isinstance(value, bytes) or not value.isdigit() or int(value) == 0:
raise RuntimeError("IMAP UIDVALIDITY missing or invalid; refusing UID operations")
if self._uidvalidity is None and establish:
self._uidvalidity = value
if self._uidvalidity != value:
if establish and allow_epoch_switch:
# Only a fresh fetch may switch epochs, never a reconnect within
# a partial batch or an acknowledgement/post-action session.
self._processed_uids.clear()
self._pending_seen.clear()
self._deferred_post_actions.clear()
self._uidvalidity = value
else:
raise RuntimeError("IMAP UIDVALIDITY changed or unknown; refusing UID operations")
def _open_imap_client(self, mailbox: str, *, missing_mailbox_ok: bool = False) -> Any | None:
if self.config.imap_use_ssl:
client: Any = imaplib.IMAP4_SSL(self.config.imap_host, self.config.imap_port)
@@ -684,6 +786,7 @@ class EmailChannel(BaseChannel):
return
try:
self._check_uidvalidity(client)
features = self._server_features(client)
# Apply all post-actions in one IMAP session. `features` also carries
# session-learned behavior (e.g. UID STORE support) so later UIDs can
@@ -91,10 +91,10 @@ def test_fetch_unknown_charset_falls_back_to_utf8(monkeypatch, multipart, subtyp
assert "Hello 世界" in items[0]["content"]
assert "<p>" not in items[0]["content"]
assert skipped_uids == set()
assert ("STORE", "123", "+FLAGS", "(\\Seen)") in fake.uid_calls
assert ("STORE", "123", "+FLAGS", "(\\Seen)") not in fake.uid_calls
def test_fetch_new_messages_parses_unseen_and_marks_seen(monkeypatch) -> None:
def test_fetch_new_messages_parses_unseen_without_acknowledging(monkeypatch) -> None:
raw = _make_raw_email(subject="Invoice", body="Please pay")
fake = _make_fake_imap(raw, uid=b"123")
@@ -107,7 +107,7 @@ def test_fetch_new_messages_parses_unseen_and_marks_seen(monkeypatch) -> None:
assert items[0]["sender"] == "alice@example.com"
assert items[0]["subject"] == "Invoice"
assert "Please pay" in items[0]["content"]
assert ("STORE", "123", "+FLAGS", "(\\Seen)") in fake.uid_calls
assert ("STORE", "123", "+FLAGS", "(\\Seen)") not in fake.uid_calls
assert [call for call in fake.uid_calls if call[0] == "FETCH"] == [
("FETCH", "123", "(BODY.PEEK[HEADER])"),
("FETCH", "123", "(BODY.PEEK[])"),
@@ -115,9 +115,9 @@ def test_fetch_new_messages_parses_unseen_and_marks_seen(monkeypatch) -> None:
assert skipped_uids == set()
items_again, skipped_again = channel._fetch_new_messages()
assert items_again == []
assert len(items_again) == 1
assert skipped_again == set()
assert len([call for call in fake.uid_calls if call[0] == "FETCH"]) == 2
assert len([call for call in fake.uid_calls if call[0] == "FETCH"]) == 4
def test_fetch_new_messages_returns_accepted_and_skipped_uids(monkeypatch) -> None:
@@ -170,6 +170,9 @@ def test_apply_post_actions_batch_delete_uses_one_connection(monkeypatch) -> Non
def login(self, _user: str, _pw: str):
return "OK", [b"logged in"]
def response(self, _code: str):
return "UIDVALIDITY", [b"1"]
def select(self, _mailbox: str):
return "OK", [b"1"]
@@ -208,6 +211,7 @@ def test_apply_post_actions_batch_delete_uses_one_connection(monkeypatch) -> Non
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda _h, _p: fake)
channel = EmailChannel(_make_config(post_action="delete"), MessageBus())
channel._uidvalidity = b"1"
channel._apply_post_actions_batch(["123", "124"])
assert fake.store_calls == []
@@ -231,6 +235,9 @@ def test_apply_post_actions_batch_move_copies_then_deletes(monkeypatch) -> None:
def login(self, _user: str, _pw: str):
return "OK", [b"logged in"]
def response(self, _code: str):
return "UIDVALIDITY", [b"1"]
def select(self, _mailbox: str):
return "OK", [b"1"]
@@ -268,6 +275,7 @@ def test_apply_post_actions_batch_move_copies_then_deletes(monkeypatch) -> None:
_make_config(post_action="move", post_action_move_mailbox="Processed"),
MessageBus(),
)
channel._uidvalidity = b"1"
channel._apply_post_actions_batch(["123"])
assert fake.uid_calls == [
@@ -287,6 +295,9 @@ def test_apply_post_actions_batch_move_prefers_uid_move_when_supported(monkeypat
def login(self, _user: str, _pw: str):
return "OK", [b"logged in"]
def response(self, _code: str):
return "UIDVALIDITY", [b"1"]
def select(self, _mailbox: str):
return "OK", [b"1"]
@@ -309,6 +320,7 @@ def test_apply_post_actions_batch_move_prefers_uid_move_when_supported(monkeypat
_make_config(post_action="move", post_action_move_mailbox="Processed"),
MessageBus(),
)
channel._uidvalidity = b"1"
channel._apply_post_actions_batch(["123"])
assert fake.uid_calls == [("MOVE", "123", "Processed")]
@@ -325,6 +337,9 @@ def test_apply_post_actions_batch_fallback_caches_uid_store_failure(monkeypatch)
def login(self, _user: str, _pw: str):
return "OK", [b"logged in"]
def response(self, _code: str):
return "UIDVALIDITY", [b"1"]
def select(self, _mailbox: str):
return "OK", [b"2"]
@@ -360,6 +375,7 @@ def test_apply_post_actions_batch_fallback_caches_uid_store_failure(monkeypatch)
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda _h, _p: fake)
channel = EmailChannel(_make_config(post_action="delete"), MessageBus())
channel._uidvalidity = b"1"
channel._apply_post_actions_batch(["123", "124"])
assert [call for call in fake.uid_calls if call[0] == "STORE"] == [("STORE", "123", "+FLAGS", "(\\Deleted)")]
@@ -378,6 +394,9 @@ def test_apply_post_actions_batch_delete_with_post_action_expunge_true_no_uidplu
def login(self, _user: str, _pw: str):
return "OK", [b"logged in"]
def response(self, _code: str):
return "UIDVALIDITY", [b"1"]
def select(self, _mailbox: str):
return "OK", [b"2"]
@@ -411,6 +430,7 @@ def test_apply_post_actions_batch_delete_with_post_action_expunge_true_no_uidplu
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda _h, _p: fake)
channel = EmailChannel(_make_config(post_action="delete", post_action_expunge=True), MessageBus())
channel._uidvalidity = b"1"
channel._apply_post_actions_batch(["123", "124"])
assert fake.store_calls == [(b"1", "+FLAGS", "\\Deleted"), (b"2", "+FLAGS", "\\Deleted")]
@@ -439,6 +459,7 @@ async def test_start_applies_post_action_only_after_delivery(monkeypatch) -> Non
async def _fake_handle_message(**_kwargs):
calls.append("delivered")
return True
def _fake_batch(actions):
assert calls == ["delivered"]
@@ -447,6 +468,7 @@ async def test_start_applies_post_action_only_after_delivery(monkeypatch) -> Non
monkeypatch.setattr(channel, "_fetch_new_messages", _fake_fetch)
monkeypatch.setattr(channel, "_handle_message", _fake_handle_message)
monkeypatch.setattr(channel, "_mark_seen_batch", lambda _uids: None)
monkeypatch.setattr(channel, "_apply_post_actions_batch", _fake_batch)
await channel.start()
@@ -481,6 +503,7 @@ async def test_start_skips_post_action_when_delivery_fails(monkeypatch) -> None:
monkeypatch.setattr(channel, "_fetch_new_messages", _fake_fetch)
monkeypatch.setattr(channel, "_handle_message", _fake_handle_message)
monkeypatch.setattr(channel, "_mark_seen_batch", lambda _uids: None)
monkeypatch.setattr(channel, "_apply_post_actions_batch", _fake_batch)
await channel.start()
@@ -517,12 +540,14 @@ async def test_start_keeps_post_actions_for_successful_emails_when_later_deliver
async def _fake_handle_message(**kwargs):
if kwargs["chat_id"] == "bob@example.com":
raise RuntimeError("delivery failed")
return True
def _fake_batch(actions):
called_actions.extend(actions)
monkeypatch.setattr(channel, "_fetch_new_messages", _fake_fetch)
monkeypatch.setattr(channel, "_handle_message", _fake_handle_message)
monkeypatch.setattr(channel, "_mark_seen_batch", lambda _uids: None)
monkeypatch.setattr(channel, "_apply_post_actions_batch", _fake_batch)
await channel.start()
@@ -598,6 +623,9 @@ def test_fetch_new_messages_retries_once_when_imap_connection_goes_stale(monkeyp
def login(self, _user: str, _pw: str):
return "OK", [b"logged in"]
def response(self, _code: str):
return "UIDVALIDITY", [b"1"]
def select(self, _mailbox: str):
return "OK", [b"1"]
@@ -647,6 +675,9 @@ def test_fetch_new_messages_keeps_messages_collected_before_stale_retry(monkeypa
def login(self, _user: str, _pw: str):
return "OK", [b"logged in"]
def response(self, _code: str):
return "UIDVALIDITY", [b"1"]
def select(self, _mailbox: str):
return "OK", [b"2"]
@@ -680,6 +711,9 @@ def test_fetch_new_messages_skips_missing_mailbox(monkeypatch) -> None:
def login(self, _user: str, _pw: str):
return "OK", [b"logged in"]
def response(self, _code: str):
return "UIDVALIDITY", [b"1"]
def select(self, _mailbox: str):
raise imaplib.IMAP4.error("Mailbox doesn't exist")
@@ -994,6 +1028,9 @@ def test_fetch_messages_between_dates_uses_imap_since_before_without_mark_seen(m
def login(self, _user: str, _pw: str):
return "OK", [b"logged in"]
def response(self, _code: str):
return "UIDVALIDITY", [b"1"]
def select(self, _mailbox: str):
return "OK", [b"1"]
@@ -1039,6 +1076,9 @@ def _make_fake_imap(raw: bytes, uid: bytes = b"500"):
def login(self, _user: str, _pw: str):
return "OK", [b"logged in"]
def response(self, _code: str):
return "UIDVALIDITY", [b"1"]
def select(self, _mailbox: str):
return "OK", [b"1"]
@@ -1919,3 +1959,328 @@ async def test_send_with_media_and_reply_subject_and_in_reply_to(tmp_path, monke
attachment_parts.append(part)
assert len(attachment_parts) == 1
assert attachment_parts[0].get_filename() == "summary.pdf"
@pytest.mark.asyncio
@pytest.mark.parametrize("mark_seen", [False, True])
@pytest.mark.parametrize("cancel", [False, True])
async def test_real_poll_retries_after_bus_failure_or_cancellation(monkeypatch, mark_seen, cancel):
import asyncio
fake = _make_fake_imap(_make_raw_email(), uid=b"123")
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda *_: fake)
bus = MessageBus()
channel = EmailChannel(_make_config(mark_seen=mark_seen, post_action="delete"), bus)
post_actions = []
monkeypatch.setattr(channel, "_apply_post_actions_batch", lambda uids: post_actions.extend(uids))
publish = bus.publish_inbound
attempts = 0
async def flaky_publish(msg):
nonlocal attempts
attempts += 1
channel._running = False
if attempts == 1:
if cancel:
raise asyncio.CancelledError()
raise RuntimeError("bus unavailable")
await publish(msg)
monkeypatch.setattr(bus, "publish_inbound", flaky_publish)
if cancel:
with pytest.raises(asyncio.CancelledError):
await channel.start()
else:
await channel.start()
assert bus.inbound_size == 0
assert "123" not in channel._processed_uids
assert not post_actions
assert not any(call[0] == "STORE" for call in fake.uid_calls)
await channel.start()
assert bus.inbound_size == 1
assert "123" in channel._processed_uids
assert post_actions == ["123"]
assert any(call[0] == "STORE" for call in fake.uid_calls) == mark_seen
assert channel._fetch_new_messages() == ([], set())
@pytest.mark.asyncio
async def test_poll_retries_seen_without_redelivery(monkeypatch):
fake = _make_fake_imap(_make_raw_email(), uid=b"123")
original_uid = fake.uid
failures = 0
def uid(command, *args):
nonlocal failures
if command == "STORE" and failures == 0:
failures += 1
raise OSError("connection lost")
return original_uid(command, *args)
fake.uid = uid
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda *_: fake)
bus = MessageBus()
channel = EmailChannel(_make_config(), bus)
publish = bus.publish_inbound
async def stop_after_delivery(message):
await publish(message)
channel._running = False
monkeypatch.setattr(bus, "publish_inbound", stop_after_delivery)
await channel.start()
assert bus.inbound_size == 1
assert channel._pending_seen == {"123"}
# Stop after the next fetch, allowing the pending acknowledgement to run.
fetch = channel._fetch_new_messages
def stop_after_fetch():
result = fetch()
channel._running = False
return result
monkeypatch.setattr(channel, "_fetch_new_messages", stop_after_fetch)
await channel.start()
assert bus.inbound_size == 1
assert not channel._pending_seen
assert ("STORE", "123", "+FLAGS", "(\\Seen)") in fake.uid_calls
@pytest.mark.asyncio
@pytest.mark.parametrize("validity", [b"2", None])
async def test_poll_refuses_ack_and_post_action_on_unverified_mailbox(monkeypatch, validity):
first = _make_fake_imap(_make_raw_email(), uid=b"123")
second = _make_fake_imap(_make_raw_email(), uid=b"123")
second.response = lambda _: ("UIDVALIDITY", [validity])
clients = iter([first, second, second])
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda *_: next(clients))
bus = MessageBus()
channel = EmailChannel(_make_config(post_action="delete"), bus)
publish = bus.publish_inbound
async def stop_after_delivery(message):
await publish(message)
channel._running = False
monkeypatch.setattr(bus, "publish_inbound", stop_after_delivery)
await channel.start()
assert bus.inbound_size == 1
assert channel._pending_seen == {"123"}
assert not second.uid_calls
@pytest.mark.asyncio
async def test_uncertain_move_is_not_retried_after_disconnect(monkeypatch):
fake = _make_fake_imap(_make_raw_email(), uid=b"123")
fake.capability = lambda: ("OK", [b"IMAP4rev1 MOVE"])
original_uid = fake.uid
moves = []
def uid(command, *args):
if command == "MOVE":
moves.append(args)
raise OSError("connection lost after MOVE")
return original_uid(command, *args)
fake.uid = uid
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda *_: fake)
bus = MessageBus()
channel = EmailChannel(_make_config(post_action="move", post_action_move_mailbox="Archive"), bus)
publish = bus.publish_inbound
async def stop_after_delivery(message):
await publish(message)
channel._running = False
monkeypatch.setattr(bus, "publish_inbound", stop_after_delivery)
await channel.start()
fetch = channel._fetch_new_messages
def stop_after_fetch():
result = fetch()
channel._running = False
return result
monkeypatch.setattr(channel, "_fetch_new_messages", stop_after_fetch)
await channel.start()
assert bus.inbound_size == 1
assert moves == [("123", "Archive")]
def test_reconnect_rejects_changed_uidvalidity_before_mixing_results(monkeypatch):
first = _make_fake_imap(_make_raw_email(), uid=b"123")
second = _make_fake_imap(_make_raw_email(), uid=b"123")
original = first.uid
def broken(command, *args):
if command == "SEARCH":
return "OK", [b"123 124"]
if command == "FETCH" and args[0] == "124":
raise imaplib.IMAP4.abort("socket error")
return original(command, *args)
first.uid = broken
second.response = lambda _: ("UIDVALIDITY", [b"2"])
clients = iter([first, second])
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda *_: next(clients))
channel = EmailChannel(_make_config(), MessageBus())
with pytest.raises(RuntimeError, match="UIDVALIDITY changed"):
channel._fetch_new_messages()
assert not second.uid_calls
assert not channel._processed_uids
@pytest.mark.asyncio
async def test_seen_failure_defers_move_until_acknowledged(monkeypatch):
fake = _make_fake_imap(_make_raw_email(), uid=b"123")
fake.capability = lambda: ("OK", [b"IMAP4rev1 MOVE"])
original = fake.uid
failed = False
def uid(command, *args):
nonlocal failed
if command == "STORE" and not failed:
failed = True
raise OSError("connection lost")
return original(command, *args)
fake.uid = uid
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda *_: fake)
bus = MessageBus()
channel = EmailChannel(_make_config(post_action="move", post_action_move_mailbox="Archive"), bus)
publish = bus.publish_inbound
async def stop_after_delivery(message):
await publish(message)
channel._running = False
monkeypatch.setattr(bus, "publish_inbound", stop_after_delivery)
await channel.start()
assert not any(call[0] == "MOVE" for call in fake.uid_calls)
assert channel._deferred_post_actions == {"123"}
fetch = channel._fetch_new_messages
def stop_after_fetch():
result = fetch()
channel._running = False
return result
monkeypatch.setattr(channel, "_fetch_new_messages", stop_after_fetch)
await channel.start()
assert not channel._pending_seen
assert not channel._deferred_post_actions
assert sum(call[0] == "MOVE" for call in fake.uid_calls) == 1
assert bus.inbound_size == 1
def test_fresh_poll_switches_uidvalidity_and_discards_old_epoch(monkeypatch):
fake = _make_fake_imap(_make_raw_email(), uid=b"123")
fake.response = lambda _: ("UIDVALIDITY", [b"2"])
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda *_: fake)
channel = EmailChannel(_make_config(), MessageBus())
channel._uidvalidity = b"1"
channel._processed_uids.add("123")
channel._pending_seen.add("123")
channel._deferred_post_actions.add("123")
messages, _ = channel._fetch_new_messages()
assert len(messages) == 1
assert channel._uidvalidity == b"2"
assert not channel._processed_uids and not channel._pending_seen and not channel._deferred_post_actions
assert not any(call[0] in {"STORE", "MOVE", "COPY"} for call in fake.uid_calls)
@pytest.mark.asyncio
async def test_cancel_later_delivery_preserves_earlier_post_action(monkeypatch):
import asyncio
fake = _make_fake_imap(_make_raw_email(), uid=b"1 2")
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda *_: fake)
bus = MessageBus()
channel = EmailChannel(_make_config(mark_seen=False, post_action="move", post_action_move_mailbox="Archive"), bus)
publish = bus.publish_inbound
calls = 0
async def deliver(message):
nonlocal calls
calls += 1
if calls == 2:
raise asyncio.CancelledError()
await publish(message)
monkeypatch.setattr(bus, "publish_inbound", deliver)
with pytest.raises(asyncio.CancelledError):
await channel.start()
assert bus.inbound_size == 1
assert channel._deferred_post_actions == {"1"}
actions = []
monkeypatch.setattr(channel, "_apply_post_actions_batch", lambda uids: actions.extend(uids))
def finish_fetch():
channel._running = False
return [], set()
monkeypatch.setattr(channel, "_fetch_new_messages", finish_fetch)
await channel.start()
assert actions == ["1"]
assert not channel._deferred_post_actions
@pytest.mark.asyncio
async def test_imap_thread_drains_after_repeated_cancellation():
import asyncio
import threading
started = threading.Event()
release = threading.Event()
finished = threading.Event()
def worker():
started.set()
release.wait(5)
finished.set()
task = asyncio.create_task(EmailChannel._imap_thread(worker))
try:
assert await asyncio.to_thread(started.wait, 2)
task.cancel()
await asyncio.sleep(0)
task.cancel()
await asyncio.sleep(0)
assert not task.done()
release.set()
with pytest.raises(asyncio.CancelledError):
await task
assert finished.is_set()
finally:
release.set()
@pytest.mark.asyncio
async def test_poll_switches_epoch_without_writing_old_uids(monkeypatch):
fake = _make_fake_imap(_make_raw_email(), uid=b"123")
fake.response = lambda _: ("UIDVALIDITY", [b"2"])
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda *_: fake)
bus = MessageBus()
channel = EmailChannel(_make_config(mark_seen=False, post_action="move", post_action_move_mailbox="Archive"), bus)
channel._uidvalidity = b"1"
channel._processed_uids.add("123")
channel._pending_seen.add("123")
channel._deferred_post_actions.add("123")
publish = bus.publish_inbound
async def deliver(message):
await publish(message)
channel._running = False
monkeypatch.setattr(bus, "publish_inbound", deliver)
await channel.start()
assert bus.inbound_size == 1
assert channel._uidvalidity == b"2"
# Only the newly delivered message can be moved, never the old pending UID.
assert sum(call[0] == "COPY" for call in fake.uid_calls) == 1
search_index = next(i for i, call in enumerate(fake.uid_calls) if call[0] == "SEARCH")
assert not any(call[0] in {"STORE", "MOVE", "COPY"} for call in fake.uid_calls[:search_index])
@pytest.mark.asyncio
@pytest.mark.parametrize("mark_seen", [False, True])
async def test_revocation_between_fetch_and_delivery_does_not_acknowledge(monkeypatch, tmp_path, mark_seen):
from nanobot.pairing import store
monkeypatch.setattr(store, "_store_path", lambda: tmp_path / "pairing.json")
code = store.generate_code("email", "alice@example.com")
store.approve_code(code)
fake = _make_fake_imap(_make_raw_email(), uid=b"123")
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda *_: fake)
bus = MessageBus()
channel = EmailChannel(_make_config(allow_from=[], mark_seen=mark_seen, post_action="delete"), bus)
fetch = channel._fetch_new_messages
def fetch_then_revoke():
result = fetch()
assert len(result[0]) == 1
assert store.revoke("email", "alice@example.com")
channel._running = False
return result
monkeypatch.setattr(channel, "_fetch_new_messages", fetch_then_revoke)
await channel.start()
assert bus.inbound_size == 0
assert "123" not in channel._processed_uids
assert not channel._pending_seen
assert not channel._deferred_post_actions
assert not any(call[0] in {"STORE", "MOVE", "COPY"} for call in fake.uid_calls)
+14 -26
View File
@@ -503,12 +503,8 @@ class MattermostChannel(BaseChannel):
file_ids: list[str] = []
for media_path in msg.media or []:
try:
fid = await self._upload_file(chat_id, media_path)
if fid:
file_ids.append(fid)
except Exception:
self.logger.exception("Failed to upload file {}", media_path)
fid = await self._upload_file(chat_id, media_path)
file_ids.append(fid)
if msg.content or file_ids:
text = msg.content or " "
@@ -669,27 +665,19 @@ class MattermostChannel(BaseChannel):
body["file_ids"] = file_ids
return await self._api_post("/api/v4/posts", body)
async def _upload_file(self, channel_id: str, file_path: str) -> str | None:
async def _upload_file(self, channel_id: str, file_path: str) -> str:
path = Path(file_path)
if not path.exists():
self.logger.warning("file not found: {}", file_path)
return None
try:
files = {"files": (path.name, path.read_bytes())}
resp = await self._require_http_client().post(
"/api/v4/files",
data={"channel_id": channel_id},
files=files,
)
resp.raise_for_status()
data = cast(dict[str, Any], resp.json())
infos = cast(list[dict[str, Any]], data.get("file_infos", []))
if infos:
return infos[0].get("id")
except Exception as e:
self.logger.warning("file upload failed for {}: {}", file_path, e)
return None
files = {"files": (path.name, path.read_bytes())}
resp = await self._require_http_client().post(
"/api/v4/files", data={"channel_id": channel_id}, files=files,
)
resp.raise_for_status()
data = cast(dict[str, Any], resp.json())
infos = cast(list[dict[str, Any]], data.get("file_infos", []))
file_id = infos[0].get("id") if infos else None
if not isinstance(file_id, str) or not file_id:
raise ValueError(f"Mattermost upload returned no file id for {file_path}")
return file_id
async def _download_file(self, file_id: str) -> str | None:
try:
@@ -1035,3 +1035,18 @@ def test_message_splitting():
chunks = split_message(long_text, MATTERMOST_MAX_MESSAGE_LEN)
assert all(len(c) <= MATTERMOST_MAX_MESSAGE_LEN for c in chunks)
assert "".join(chunks) == long_text
@pytest.mark.asyncio
@pytest.mark.parametrize("failure", ["missing", "http", "no_id"])
async def test_upload_failure_propagates_before_any_post(tmp_path, failure):
channel, fake = _make_channel()
path = tmp_path / "file.txt"
if failure != "missing":
path.write_text("data")
if failure == "http":
fake.post = AsyncMock(side_effect=httpx.ConnectError("offline"))
elif failure == "no_id":
fake.set_post_response("/api/v4/files", {"file_infos": [{}]})
with pytest.raises((OSError, httpx.ConnectError, ValueError)):
await channel.send(OutboundMessage("mattermost", "chan", "text", media=[str(path)]))
assert not [c for c in fake.post_calls if c["path"] == "/api/v4/posts"]
+5 -3
View File
@@ -398,7 +398,7 @@ class SignalChannel(BaseChannel):
return True
return False
async def _handle_message(
async def _publish_policy_checked_message(
self,
sender_id: str,
chat_id: str,
@@ -411,8 +411,10 @@ class SignalChannel(BaseChannel):
require_existing_session: bool = False,
session_generation: str | None = None,
) -> None:
"""Handle an inbound message whose policy has already been checked.
"""Publish only an inbound message whose Signal policy has already been checked.
This is not the base ``_handle_message`` authorization contract; never
call it for a message that has not passed ``_check_inbound_policy``.
``_check_inbound_policy`` is the authoritative gate for DM/group
access, so we skip the base-class ``is_allowed()`` check and publish
directly to the bus. The denied-DM pairing path calls
@@ -764,7 +766,7 @@ class SignalChannel(BaseChannel):
await self._start_typing(chat_id)
try:
await self._handle_message(
await self._publish_policy_checked_message(
sender_id=sender_id,
chat_id=chat_id,
content=content,
@@ -53,7 +53,7 @@ class _FakeHTTPClient:
def _make_channel_with_capture(**overrides) -> tuple[SignalChannel, list[dict]]:
"""Build a SignalChannel with _handle_message captured into a list and a
"""Build a SignalChannel with _publish_policy_checked_message captured into a list and a
no-op _start_typing, used by every receive-flow test class.
"""
ch = _make_channel(**overrides)
@@ -65,7 +65,7 @@ def _make_channel_with_capture(**overrides) -> tuple[SignalChannel, list[dict]]:
async def noop_typing(chat_id):
pass
ch._handle_message = capture # type: ignore[method-assign]
ch._publish_policy_checked_message = capture # type: ignore[method-assign]
ch._start_typing = noop_typing # type: ignore[method-assign]
return ch, handled
@@ -488,9 +488,9 @@ class TestIsAllowed:
class TestEndToEndDMRouting:
"""End-to-end tests that keep the real _handle_message chain (no mock),
verifying that _check_inbound_policy + _handle_message work together
correctly for DM routing. The override of _handle_message publishes
"""End-to-end tests that keep the real policy-checked publish chain (no mock),
verifying that _check_inbound_policy + publish work together
correctly for DM routing. The policy-checked helper publishes
directly to bus (policy already checked); denied DMs call
super()._handle_message which issues a pairing code.
"""
@@ -803,7 +803,7 @@ class TestHandleDataMessageDM:
async def capture(**kwargs):
handled.append(kwargs)
ch._handle_message = capture # type: ignore[method-assign]
ch._publish_policy_checked_message = capture # type: ignore[method-assign]
async def noop_typing(chat_id):
pass
@@ -890,7 +890,7 @@ class TestHandleDataMessageDM:
async def record_stop(chat_id, **kwargs):
typing_stopped.append(chat_id)
ch._handle_message = fail_handle # type: ignore[method-assign]
ch._publish_policy_checked_message = fail_handle # type: ignore[method-assign]
ch._start_typing = noop_typing # type: ignore[method-assign]
ch._stop_typing = record_stop # type: ignore[method-assign]
@@ -918,7 +918,7 @@ class TestHandleDataMessageGroup:
async def test_group_disabled_rejected(self):
ch = _make_channel(group_enabled=False)
handled: list[dict] = []
ch._handle_message = lambda **kw: handled.append(kw) # type: ignore[method-assign]
ch._publish_policy_checked_message = lambda **kw: handled.append(kw) # type: ignore[method-assign]
params = _group_envelope(group_id="grp==", message="hi")
await ch._handle_receive_notification(params)
assert handled == []
@@ -1010,7 +1010,7 @@ class TestHandleDataMessageGroup:
async def test_bot_account_alias_learned_from_incoming(self):
ch, handled = self._make_group_channel(require_mention=False)
params = _dm_envelope(source_number="+10000000000", source_uuid="new-bot-uuid")
ch._handle_message = lambda **kw: handled.append(kw) # type: ignore[method-assign]
ch._publish_policy_checked_message = lambda **kw: handled.append(kw) # type: ignore[method-assign]
ch._start_typing = lambda chat_id: None # type: ignore[method-assign]
await ch._handle_receive_notification(params)
assert ch._id_matches_account("new-bot-uuid")
@@ -1339,7 +1339,7 @@ async def test_send_request_raises_when_not_connected() -> None:
async def test_handle_notification_sync_message_does_not_forward() -> None:
ch = _make_channel(dm_enabled=True, dm_policy="open")
handled: list[dict] = []
ch._handle_message = lambda **kw: handled.append(kw) # type: ignore[method-assign]
ch._publish_policy_checked_message = lambda **kw: handled.append(kw) # type: ignore[method-assign]
notification = {
"envelope": {
@@ -1360,7 +1360,7 @@ async def test_handle_notification_sync_message_does_not_forward() -> None:
async def test_handle_notification_no_source_skipped() -> None:
ch = _make_channel(dm_enabled=True, dm_policy="open")
handled: list[dict] = []
ch._handle_message = lambda **kw: handled.append(kw) # type: ignore[method-assign]
ch._publish_policy_checked_message = lambda **kw: handled.append(kw) # type: ignore[method-assign]
notification = {"envelope": {"dataMessage": {"message": "ghost"}}}
await ch._handle_receive_notification(notification)
+19 -1
View File
@@ -73,10 +73,11 @@ async def test_handle_message_dm_sends_pairing_code(monkeypatch) -> None:
"nanobot.channels.base.generate_code", lambda _ch, sid, **_kwargs: "ABCD-EFGH"
)
await channel._handle_message(
delivered = await channel._handle_message(
sender_id="stranger", chat_id="chat1", content="hello", is_dm=True
)
assert delivered is False
assert len(channel._sent) == 1
msg = channel._sent[0]
assert "ABCD-EFGH" in msg.content
@@ -185,3 +186,20 @@ async def test_dm_publishes_pairing_changes_without_a_file_watcher(monkeypatch,
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")
@pytest.mark.asyncio
async def test_handle_message_reports_bus_acceptance_and_denial(monkeypatch) -> None:
bus = MessageBus()
channel = _DummyChannel({"allowFrom": ["alice"]}, bus)
monkeypatch.setattr("nanobot.channels.base.is_approved", lambda *_: False)
assert await channel._handle_message("alice", "chat", "hello") is True
assert await channel._handle_message("stranger", "chat", "hello") is False
assert bus.inbound_size == 1
async def fail(_message):
raise RuntimeError("bus unavailable")
monkeypatch.setattr(bus, "publish_inbound", fail)
with pytest.raises(RuntimeError, match="bus unavailable"):
await channel._handle_message("alice", "chat", "hello")
+16 -8
View File
@@ -100,6 +100,7 @@ export function UpdateFlowProvider({ client, token, enabled, canSettleHandoff =
};
const refresh = async (manual = false) => {
const feedback = manual ? new Promise(resolve => setTimeout(resolve, 600)) : Promise.resolve();
let readingReview = false;
try {
// API tokens belong to a gateway process. Let the client's authenticated
// reconnect replace them before reading the new process's update journal.
@@ -116,9 +117,11 @@ export function UpdateFlowProvider({ client, token, enabled, canSettleHandoff =
setRecovery(next.recovery_command);
try { sessionStorage.setItem(RECOVERY_KEY, JSON.stringify({ id: next.id, command: next.recovery_command, automatic: next.automatic_recovery === true })); } catch { /* Still available until reload. */ }
}
setOffline(false);
setDelayed(false);
missingSince = 0;
if (next.recorded_phase !== "ready" || next.execution_confirmation_id) {
setOffline(false);
setDelayed(false);
missingSince = 0;
}
setError("");
if (next.recorded_phase === "ready" && approved.current === next.id) {
await execute(next.id);
@@ -129,10 +132,14 @@ export function UpdateFlowProvider({ client, token, enabled, canSettleHandoff =
&& !(next.service_restored && next.running_version !== next.previous_version)) return;
// A refresh can recover files already staged, but not installation consent.
if (next.recorded_phase === "ready" && !next.execution_confirmation_id) {
try {
const restored = await readUpdateReview(token, next.id);
if (active) setReview(restored);
} catch { if (active) setError(t("updates.reviewFailed")); }
readingReview = true;
const restored = await readUpdateReview(token, next.id);
if (active) {
setReview(restored);
setOffline(false);
setDelayed(false);
missingSince = 0;
}
}
} catch (reason) {
if (!active) return;
@@ -142,9 +149,10 @@ export function UpdateFlowProvider({ client, token, enabled, canSettleHandoff =
approved.current = null;
setOffline(false);
setDelayed(false);
setError(t("updates.statusFailed"));
setError(t(readingReview ? "updates.reviewFailed" : "updates.statusFailed"));
return;
}
if (readingReview) setError(t("updates.reviewFailed"));
reconnecting();
} finally {
if (manual) {
+44
View File
@@ -370,6 +370,50 @@ describe("Real update consent and recovery", () => {
fireEvent.click(screen.getByRole("button", { name: "Update & restart" }));
await waitFor(() => expect(api.executeUpdate).toHaveBeenCalledOnce());
});
it("stops polling a forbidden restored review and allows a manual retry", async () => {
vi.useFakeTimers();
sessionStorage.setItem("nanobot.pending-update.v1", id);
vi.mocked(api.readUpdateReview).mockRejectedValueOnce(new api.ApiError(403, "Forbidden"));
render(view());
await act(async () => {});
expect(screen.getByText(/Could not verify this update/)).toBeVisible();
await act(async () => { await vi.advanceTimersByTimeAsync(4500); });
expect(api.readUpdateReview).toHaveBeenCalledTimes(1);
expect(api.readUpdateJob).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByRole("button", { name: "Check again" }));
await act(async () => { await vi.advanceTimersByTimeAsync(600); });
expect(api.readUpdateReview).toHaveBeenCalledTimes(2);
expect(screen.getByRole("button", { name: "Update & restart" })).toBeEnabled();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("retries a transient restored review failure and recovers without consent", async () => {
vi.useFakeTimers();
sessionStorage.setItem("nanobot.pending-update.v1", id);
vi.mocked(api.readUpdateReview).mockRejectedValueOnce(new Error("offline"));
render(view());
await act(async () => {});
expect(api.readUpdateReview).toHaveBeenCalledTimes(1);
await act(async () => { await vi.advanceTimersByTimeAsync(1500); });
expect(api.readUpdateReview).toHaveBeenCalledTimes(2);
expect(screen.getByRole("button", { name: "Update & restart" })).toBeEnabled();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("offers a manual check and delayed recovery after repeated review failures", async () => {
vi.useFakeTimers();
sessionStorage.setItem("nanobot.pending-update.v1", id);
sessionStorage.setItem("nanobot.pending-update-recovery.v1", JSON.stringify({ id, command: "recover safely" }));
vi.mocked(api.readUpdateReview).mockRejectedValue(new Error("offline"));
render(view());
await act(async () => {});
expect(screen.getByRole("button", { name: "Check again" })).toBeEnabled();
await act(async () => { await vi.advanceTimersByTimeAsync(123_000); });
expect(screen.getByDisplayValue("recover safely")).toBeVisible();
vi.mocked(api.readUpdateReview).mockResolvedValue(review);
fireEvent.click(screen.getByRole("button", { name: "Check again" }));
await act(async () => { await vi.advanceTimersByTimeAsync(600); });
expect(screen.getByRole("button", { name: "Update & restart" })).toBeEnabled();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("waits for the restored review before enabling confirmation", async () => {
sessionStorage.setItem("nanobot.pending-update.v1", id);
let resolveReview!: (value: api.UpdateReviewResponse) => void;