from datetime import datetime, timezone
from types import SimpleNamespace
import pytest
from bson import ObjectId
from app.services.handoff_delivery import enqueue_handoff_delivery
from app.services.handoff_mirror_policy import (
GENERATED_BY_AGENT,
GENERATED_BY_HANDOFF_BRIDGE,
MESSAGE_ORIGIN_AGENT,
MESSAGE_ORIGIN_HUMAN_OWNER,
RELAY_STATUS_BLOCKED,
should_mirror_to_human,
)
from app.services import human_handoff_service
from app.services.human_handoff_service import (
MESSAGE_SCOPE_EXTERNAL,
MESSAGE_SCOPE_HANDOFF,
build_handoff_subject,
maybe_trigger_handoff,
process_human_reply,
resolve_handoff_from_inbound,
)
from app.services.mailbox_scope import apply_external_scope
from app.services.external_reply_service import build_external_reply_plan
class FakeCursor:
def __init__(self, items):
self.items = items
def sort(self, *_args, **_kwargs):
return self
async def to_list(self, length=None):
return list(self.items)[:length]
class FakeCollection:
def __init__(self, items=None):
self.items = list(items or [])
self.inserted = []
self.updated = []
async def find_one(self, query, projection=None):
for item in self.items:
if _matches(item, query):
return item
return None
def find(self, query=None):
query = query or {}
return FakeCursor([item for item in self.items if _matches(item, query)])
async def insert_one(self, document):
document = dict(document)
document.setdefault("_id", ObjectId())
self.items.append(document)
self.inserted.append(document)
return SimpleNamespace(inserted_id=document["_id"])
async def update_one(self, query, update, upsert=False):
self.updated.append((query, update, upsert))
existing = await self.find_one(query)
if existing is None and upsert:
inserted = {"_id": ObjectId(), **query, **update.get("$setOnInsert", {})}
self.items.append(inserted)
return SimpleNamespace(upserted_id=inserted["_id"], modified_count=0)
if existing is not None:
existing.update(update.get("$set", {}))
return SimpleNamespace(upserted_id=None, modified_count=1)
return SimpleNamespace(upserted_id=None, modified_count=0)
async def find_one_and_update(self, query, update, **kwargs):
existing = await self.find_one(query)
if existing is None:
return None
existing.update(update.get("$set", {}))
return existing
def _matches(document, query):
for key, expected in query.items():
if key == "$or":
if not any(_matches(document, clause) for clause in expected):
return False
continue
if key == "$ne":
continue
actual = document.get(key)
if isinstance(expected, dict):
if "$ne" in expected and actual == expected["$ne"]:
return False
if "$in" in expected and actual not in expected["$in"]:
return False
continue
if actual != expected:
return False
return True
def test_external_mailbox_filter_excludes_handoff_scope():
match = {"account_id": "account-1", "mailbox": "inbox"}
apply_external_scope(match)
assert match["$or"] == [
{"message_scope": "EXTERNAL"},
{"message_scope": {"$exists": False}},
]
def test_bridge_plan_never_references_private_ids():
customer = {
"_id": ObjectId(),
"internet_message_id": "",
"message_id": "",
"message_scope": MESSAGE_SCOPE_EXTERNAL,
"references": [],
"subject": "Invoice 42",
}
private_id = "