Skip to content

The agent that grows with you

refactor(email): schedule the pre-fetch gate via safe_schedule_threadsafe

kshitijk4poor7e6762b6fd3f
diff --git a/plugins/platforms/email/adapter.py b/plugins/platforms/email/adapter.py
index e523fbce957..1922fcf8443 100644
--- a/plugins/platforms/email/adapter.py
+++ b/plugins/platforms/email/adapter.py
@@ -22,6 +22,7 @@ from email import encoders
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple
+from agent.async_utils import safe_schedule_threadsafe
from agent.i18n import t
from gateway.platforms.base import (
BasePlatformAdapter, SendResult,
@@ -623,7 +624,10 @@ class EmailAdapter(BasePlatformAdapter):
def gate(candidate: Dict[str, Any]) -> bool:
# Authorization reads profile-scoped policy and pairing state on the adapter's event loop;
# the blocking IMAP worker waits for that verdict before asking the server for RFC822.
- return asyncio.run_coroutine_threadsafe(authorize_on_loop(candidate), loop).result()
+ # A closed loop (stop race) yields None: fail closed without leaking the coroutine.
+ fut = safe_schedule_threadsafe(authorize_on_loop(candidate), loop, logger=logger,
+ log_message="[Email] Could not schedule sender authorization")
+ return fut is not None and fut.result()
messages = await asyncio.to_thread(self._fetch_new_messages, gate)
# Dispatch partial results BEFORE escalating a failure — a mid-batch exception returns what was fetched (already marked seen).
diff --git a/tests/gateway/test_email.py b/tests/gateway/test_email.py
index 8bfbda3c41a..c859726acee 100644
--- a/tests/gateway/test_email.py
+++ b/tests/gateway/test_email.py
@@ -770,6 +770,8 @@ class TestPollLoop(unittest.TestCase):
return ("NO", [])
mock_imap.uid.side_effect = uid_handler
+ gates, fetch = [], adapter._fetch_new_messages
+ adapter._fetch_new_messages = lambda gate: (gates.append(gate), fetch(gate))[1]
with patch.dict(os.environ, {
"EMAIL_ALLOWED_USERS": "[email protected]",
"EMAIL_ALLOW_ALL_USERS": "",
@@ -789,6 +791,8 @@ class TestPollLoop(unittest.TestCase):
self.assertTrue(all(f"<0.{_MAX_PREAUTH_HEADER_BYTES + 1}>" in spec for spec in header_specs))
extract_attachments.assert_called_once()
self.assertTrue({b"9", b"10", b"11"}.issubset(adapter._seen_uids))
+ # Once the poll's loop is closed (stop race) the gate fails closed instead of raising.
+ self.assertFalse(gates[0](dispatched[0]))
def test_check_inbox_notifies_fatal_error_on_fetch_failure(self):
"""A failed IMAP check must surface through the fatal-error hook so