Skip to content

Autonomous AI sales agent powered by Claude Code or Codex. Finds prospects, writes cold emails, sends campaigns, handles replies, books meetings. No API keys needed — runs on your Claude or Codex subscriptions.

Fail closed on incomplete Microsoft inbox reads and follow all pages

Ethan9fa37a135728
diff --git a/docs/microsoft365.md b/docs/microsoft365.md
index a38adc5..3af4585 100644
--- a/docs/microsoft365.md
+++ b/docs/microsoft365.md
@@ -99,7 +99,7 @@ To make sure nobody else in the tenant can use the app, go to
prospect's own message, so `In-Reply-To` and `References` are correct. If
that message was deleted, the reply goes out as a new email.
- **Your inbox is left alone.** Each cycle, Harvey reads the last 7 days of
- the inbox, newest first, and skips your own mail. It never marks anything
+ the inbox, newest first, all of it (page by page), and skips your own mail. It never marks anything
read, moves it or deletes it. It keeps its own record of what it has
handled.
- **It only acts as the right mailbox.** If the signed-in mailbox isn't
@@ -109,7 +109,8 @@ To make sure nobody else in the tenant can use the app, go to
- **Failures hold sending.** If the inbox can't be read (expired login,
Graph outage, throttling), the cycle sends nothing. A reply nobody read
can't have stopped its follow-ups. Graph throttling (429/503 with a short
- `Retry-After`) is retried once.
+ `Retry-After`) is retried once. A read that fails part-way through counts
+ as a failed read: Harvey never acts on part of the inbox.
- **Unsent drafts are cleaned up.** If a send fails, its draft is deleted
so it doesn't sit in your Drafts folder.
- **The sender name is the mailbox's.** Mail goes out under the mailbox's
@@ -149,7 +150,32 @@ delete the app registration. Then delete `data/m365_token.json`.
`get_replies` **raises** `GraphError` when the inbox can't be read, instead
of returning `[]`. The handler turns that into a failed read, and the
-heartbeat holds sending.
+heartbeat holds sending. It returns the whole 7-day window or nothing:
+
+- **Every page.** `limit` is only the page size (`$top`). Harvey follows
+ `@odata.nextLink` until Graph stops sending one, using the link exactly
+ as given, without re-adding the first request's parameters or touching
+ `$skip`, as Microsoft asks. Messages repeated across pages (new mail
+ shifts `$skip` mid-read) are returned once.
+- **Links are checked before the token is attached.** A `nextLink` must be
+ `https://graph.microsoft.com` (default port), on the path
+ `/v1.0/me/mailFolders/inbox/messages`, with a query, and no credentials,
+ fragment, backslash or control characters. A link that repeats an earlier
+ page is a loop. Either way the read fails without sending the request.
+- **Bounded.** More than `MAX_INBOX_PAGES` (40) pages, i.e. 2,000 messages
+ in a week at the default page size, fails the read rather than truncating.
+- **Malformed data fails.** Any Graph response must be a JSON object; only
+ `202`/`204` (send, delete) may be empty. A page whose `value` is missing
+ or isn't a list, or a message with the wrong shape (no `id`, `from` or
+ `body` not an object, non-string fields, headers not a list) raises. A
+ message with no sender address is skipped, as before.
+
+Limitations: a mailbox with more than 2,000 inbox messages in 7 days holds
+sending every cycle until the volume drops (raise `MAX_INBOX_PAGES` or the
+page size). If Graph ever returns a `nextLink` in another shape (say
+`/users/{id}/...`), reads fail closed until the check is widened. Mail that
+arrives while pages are being read can shift `$skip` so one message is
+missed that cycle; the next cycle reads it, since the window is 7 days.
The loopback callback server listens on both `127.0.0.1` and `::1`, because
`localhost` resolves to both and browsers differ in which one they try.
diff --git a/harvey/integrations/microsoft.py b/harvey/integrations/microsoft.py
index 4dfdfae..c958d82 100644
--- a/harvey/integrations/microsoft.py
+++ b/harvey/integrations/microsoft.py
@@ -47,6 +47,12 @@ logger = logging.getLogger("harvey.microsoft")
TOKEN_FILE = PROJECT_ROOT / "data" / "m365_token.json"
GRAPH = "https://graph.microsoft.com/v1.0"
+GRAPH_HOST = "graph.microsoft.com"
+INBOX_MESSAGES = "/me/mailFolders/inbox/messages"
+INBOX_MESSAGES_PATH = "/v1.0" + INBOX_MESSAGES
+# Inbox pages read per cycle (limit messages each). More than this and the
+# read fails, and sending is held, rather than acting on a partial inbox.
+MAX_INBOX_PAGES = 40
LOGIN = "https://login.microsoftonline.com"
SCOPE = (
"offline_access https://graph.microsoft.com/Mail.ReadWrite "
@@ -143,16 +149,22 @@ class MicrosoftProvider(MailProvider):
raise GraphError("token refresh returned no access token")
return self._access_token
- async def _request(self, method: str, path: str, *, headers=None, **kwargs) -> dict:
+ async def _request(self, method: str, path: str, **kwargs) -> dict:
+ return await self._request_url(method, f"{GRAPH}{path}", **kwargs)
+
+ async def _request_url(self, method: str, url: str, *, headers=None, **kwargs) -> dict:
"""One Graph call. Raises GraphError on failure; retries once when
- Graph asks to slow down (429/503 with a short Retry-After)."""
+ Graph asks to slow down (429/503 with a short Retry-After). The
+ result is always a JSON object; only 202/204 may be empty (send,
+ delete), and come back as {}."""
+ path = url[len(GRAPH):] if url.startswith(GRAPH) else url
token = await self._token()
all_headers = {"Authorization": f"Bearer {token}", **(headers or {})}
for attempt in (1, 2):
try:
async with self._client() as client:
resp = await client.request(
- method, f"{GRAPH}{path}", headers=all_headers, **kwargs
+ method, url, headers=all_headers, **kwargs
)
except httpx.HTTPError as e:
raise GraphError(f"{method} {path} failed: {e}") from e
@@ -168,11 +180,19 @@ class MicrosoftProvider(MailProvider):
if resp.status_code >= 400:
raise GraphError(f"Graph {resp.status_code} on {method} {path}: {resp.text[:200]}")
if not resp.content:
- return {}
+ if resp.status_code in (202, 204):
+ return {}
+ raise GraphError(f"Graph {resp.status_code} on {method} {path}: empty response")
try:
- return resp.json()
- except ValueError:
- return {}
+ data = resp.json()
+ except ValueError as e:
+ raise GraphError(f"Graph {resp.status_code} on {method} {path}: malformed JSON") from e
+ if not isinstance(data, dict):
+ raise GraphError(
+ f"Graph {resp.status_code} on {method} {path}: expected a JSON object, "
+ f"got {type(data).__name__}"
+ )
+ return data
async def _my_address(self) -> str:
if not self._me:
@@ -246,49 +266,92 @@ class MicrosoftProvider(MailProvider):
async def get_replies(self, limit: int = 50) -> list[InboundMessage]:
"""The last week of the inbox, newest first, minus your own mail.
- Raises on failure: the heartbeat then holds sends, because an unread
- reply can't have stopped its follow-ups."""
+ Every page is read (``limit`` is only the page size), following
+ Graph's @odata.nextLink as-is. Raises on any failure, including a
+ later page: the heartbeat then holds sends, because an unread reply
+ can't have stopped its follow-ups. Never returns a partial inbox."""
me = await self._check_identity()
since = (datetime.now(timezone.utc) - timedelta(days=REPLY_WINDOW_DAYS))
- data = await self._request(
- "GET", "/me/mailFolders/inbox/messages",
- params={
- "$filter": f"receivedDateTime ge {since.strftime('%Y-%m-%dT%H:%M:%SZ')}",
- "$orderby": "receivedDateTime desc",
- "$top": str(limit),
- "$select": _SELECT,
- },
- headers={"Prefer": 'outlook.body-content-type="text"'},
- )
+ url = str(httpx.URL(f"{GRAPH}{INBOX_MESSAGES}", params={
+ "$filter": f"receivedDateTime ge {since.strftime('%Y-%m-%dT%H:%M:%SZ')}",
+ "$orderby": "receivedDateTime desc",
+ "$top": str(max(1, int(limit))),
+ "$select": _SELECT,
+ }))
+ seen_urls = {url}
+ seen_ids = set()
out = []
- for item in data.get("value", []):
- msg = self._parse_message(item)
- if msg and msg.from_email != me:
- out.append(msg)
- return out
+ for page in range(1, MAX_INBOX_PAGES + 1):
+ data = await self._request_url(
+ "GET", url, headers={"Prefer": 'outlook.body-content-type="text"'},
+ )
+ items = data.get("value")
+ if not isinstance(items, list):
+ raise GraphError(f"inbox page {page}: 'value' is missing or not a list")
+ for item in items:
+ msg = self._parse_message(item)
+ # A message can repeat across pages if mail arrives mid-read.
+ if msg and msg.from_email != me and msg.provider_id not in seen_ids:
+ seen_ids.add(msg.provider_id)
+ out.append(msg)
+ next_link = data.get("@odata.nextLink")
+ if next_link is None:
+ return out
+ url = _checked_next_link(next_link)
+ if url in seen_urls:
+ raise GraphError(f"inbox page {page}: @odata.nextLink repeats an earlier page")
+ seen_urls.add(url)
+ raise GraphError(
+ f"inbox has more than {MAX_INBOX_PAGES} pages; refusing a partial read"
+ )
@staticmethod
- def _parse_message(item: dict) -> InboundMessage | None:
- sender = ((item.get("from") or {}).get("emailAddress") or {})
- from_email = (sender.get("address") or "").strip().lower()
+ def _parse_message(item) -> InboundMessage | None:
+ """One Graph message. A message with no sender address is skipped;
+ one with fields of the wrong shape raises GraphError."""
+ def obj(value, what) -> dict:
+ if value is None:
+ return {}
+ if not isinstance(value, dict):
+ raise GraphError(f"malformed inbox message: {what} is not an object")
+ return value
+
+ def text(value, what) -> str:
+ if value is None:
+ return ""
+ if not isinstance(value, str):
+ raise GraphError(f"malformed inbox message: {what} is not a string")
+ return value
+
+ if not isinstance(item, dict):
+ raise GraphError("malformed inbox message: not an object")
+ msg_id = text(item.get("id"), "id")
+ if not msg_id:
+ raise GraphError("malformed inbox message: no id")
+ sender = obj(obj(item.get("from"), "from").get("emailAddress"), "from.emailAddress")
+ from_email = text(sender.get("address"), "sender address").strip().lower()
if not from_email:
return None
- subject = item.get("subject") or ""
- headers = {
- (h.get("name") or "").lower(): h.get("value") or ""
- for h in item.get("internetMessageHeaders") or []
- }
- body = ((item.get("body") or {}).get("content") or "")
+ subject = text(item.get("subject"), "subject")
+ raw_headers = item.get("internetMessageHeaders") or []
+ if not isinstance(raw_headers, list):
+ raise GraphError("malformed inbox message: internetMessageHeaders is not a list")
+ headers = {}
+ for h in raw_headers:
+ h = obj(h, "header")
+ headers[text(h.get("name"), "header name").lower()] = text(
+ h.get("value"), "header value")
+ body = text(obj(item.get("body"), "body").get("content"), "body content")
return InboundMessage(
- provider_id=item.get("id", ""),
+ provider_id=msg_id,
from_email=from_email,
subject=subject,
body=body[:5000],
- message_id=item.get("internetMessageId", ""),
+ message_id=text(item.get("internetMessageId"), "internetMessageId"),
in_reply_to=headers.get("in-reply-to", ""),
# The Graph id: what createReply needs to answer this message.
- thread_ref=item.get("id", ""),
- date=item.get("receivedDateTime", ""),
+ thread_ref=msg_id,
+ date=text(item.get("receivedDateTime"), "receivedDateTime"),
is_bounce=looks_like_bounce(from_email, subject),
headers=headers,
)
@@ -309,6 +372,33 @@ class MicrosoftProvider(MailProvider):
return True, f"Connected as {me}"
+def _checked_next_link(link) -> str:
+ """Graph's @odata.nextLink, used whole (Microsoft: don't rebuild or
+ edit $skip). It gets the bearer token, so it must point back at the
+ inbox listing on Graph itself: https, graph.microsoft.com, the same
+ path, no credentials, no fragment. Anything else raises GraphError."""
+ if not isinstance(link, str) or not link:
+ raise GraphError("@odata.nextLink is not a URL")
+ if any(c in link for c in "#\\") or any(c.isspace() or ord(c) < 32 for c in link):
+ raise GraphError("@odata.nextLink rejected: unexpected characters")
+ try:
+ url = httpx.URL(link)
+ except (httpx.InvalidURL, ValueError) as e:
+ raise GraphError(f"@odata.nextLink rejected: {e}") from e
+ path = url.raw_path.split(b"?", 1)[0].decode("ascii", "replace")
+ if (
+ url.scheme != "https"
+ or url.host != GRAPH_HOST
+ or url.port not in (None, 443)
+ or url.userinfo
+ or url.fragment
+ or path.lower() != INBOX_MESSAGES_PATH.lower()
+ or not url.query
+ ):
+ raise GraphError("@odata.nextLink rejected: not the Graph inbox listing")
+ return link
+
+
def _pkce_pair() -> tuple[str, str]:
verifier = secrets.token_urlsafe(64)[:96]
challenge = base64.urlsafe_b64encode(
diff --git a/tests/test_microsoft.py b/tests/test_microsoft.py
index 65dc192..2426399 100644
--- a/tests/test_microsoft.py
+++ b/tests/test_microsoft.py
@@ -23,6 +23,8 @@ class Graph:
self.inbox = []
self.fail = {} # (method, path suffix) -> status
self.drafts = 0
+ self.pages = {} # inbox page number -> httpx.Response, or a dict
+ # merged into that page's normal JSON body
def __call__(self, request: httpx.Request):
self.requests.append(request)
@@ -56,13 +58,41 @@ class Graph:
if path.endswith("/send"):
return httpx.Response(202)
if path == "/v1.0/me/mailFolders/inbox/messages":
- return httpx.Response(200, json={"value": self.inbox})
+ return self._inbox_page(request)
return httpx.Response(404, json={"error": {"code": "notFound"}})
+ def _inbox_page(self, request):
+ """Pages like Graph: $top per page, then an opaque nextLink whose
+ query carries only $skip (and a token) — not the first page's params."""
+ params = request.url.params
+ top = int(params.get("$top") or params.get("t") or 50)
+ skip = int(params.get("$skip", 0))
+ page = skip // top + 1
+ body = {"value": self.inbox[skip:skip + top]}
+ if skip + top < len(self.inbox):
+ body["@odata.nextLink"] = (
+ "https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages"
+ f"?%24skip={skip + top}&t={top}&%24skiptoken=opaque{page}"
+ )
+ override = self.pages.get(page)
+ if isinstance(override, httpx.Response):
+ return override
+ return httpx.Response(200, json={**body, **(override or {})})
+
def calls(self):
return [(r.method, r.url.path) for r in self.requests
if r.url.host == "graph.microsoft.com"]
+ def inbox_requests(self):
+ return [r for r in self.requests if r.url.path.endswith("/inbox/messages")]
+
+
+def message(i, sender="[email protected]", body="hello"):
+ return {"id": f"m{i}", "subject": f"note {i}",
+ "from": {"emailAddress": {"address": sender}},
+ "body": {"content": body}, "internetMessageId": f"<{i}@elsewhere.example>",
+ "receivedDateTime": "2026-10-14T15:00:00Z"}
+
@pytest.fixture
def graph(tmp_path, monkeypatch):
@@ -253,3 +283,260 @@ def test_pkce_challenge_matches_verifier():
assert 43 <= len(verifier) <= 128
expected = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest())
assert challenge == expected.decode().rstrip("=")
+
+
+# ── Pagination and malformed responses: never a partial inbox ──
+
+
+async def test_every_page_of_the_week_is_read(graph):
+ graph.inbox = [message(i) for i in range(120)]
+ replies = await provider(graph).get_replies()
+
+ assert [m.provider_id for m in replies] == [f"m{i}" for i in range(120)]
+ first, *later = graph.inbox_requests()
+ assert len(later) == 2
+ assert first.url.params["$top"] == "50"
+ for request in later:
+ # The nextLink is followed exactly, with no initial params re-added,
+ # and still gets the same Prefer header.
+ assert "$filter" not in request.url.params and "$top" not in request.url.params
+ assert request.headers["Prefer"] == 'outlook.body-content-type="text"'
+ assert str(later[0].url) == (
+ "https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages"
+ "?%24skip=50&t=50&%24skiptoken=opaque1"
+ )
+
+
+async def test_limit_is_only_the_page_size(graph):
+ graph.inbox = [message(i) for i in range(7)]
+ replies = await provider(graph).get_replies(limit=3)
+
+ assert len(replies) == 7
+ assert len(graph.inbox_requests()) == 3
+
+
+async def test_empty_inbox_is_an_empty_list(graph):
+ assert await provider(graph).get_replies() == []
+ assert len(graph.inbox_requests()) == 1
+
+
[email protected]("response", [
+ httpx.Response(200, content=b"<html>not json</html>"),
+ httpx.Response(200, content=b'{"value": ['),
+ httpx.Response(200, json=[{"id": "m1"}]),
+ httpx.Response(200, json="value"),
+ httpx.Response(200, json={}),
+ httpx.Response(200, json={"value": None}),
+ httpx.Response(200, json={"value": {"id": "m1"}}),
+ httpx.Response(200),
+], ids=["html", "truncated", "list", "string", "no-value", "null-value",
+ "object-value", "empty-200"])
+async def test_malformed_first_page_raises(graph, response):
+ graph.pages[1] = response
+ with pytest.raises(GraphError):
+ await provider(graph).get_replies()
+
+
[email protected]("override", [
+ httpx.Response(500, json={"error": {"code": "boom"}}),
+ httpx.Response(200, content=b"not json"),
+ httpx.Response(200, json=["m51"]),
+ {"value": None},
+ {"value": [message(50), "not a message"]},
+ {"value": [{**message(50), "id": None}]},
+ {"value": [{**message(50), "from": "[email protected]"}]},
+ {"value": [{**message(50), "from": {"emailAddress": {"address": 7}}}]},
+ {"value": [{**message(50), "body": "text"}]},
+ {"value": [{**message(50), "internetMessageHeaders": {"In-Reply-To": "x"}}]},
+ {"value": [{**message(50), "internetMessageHeaders": [{"name": 1}]}]},
+ {"@odata.nextLink": 42},
+ {"@odata.nextLink": ""},
+], ids=["http-500", "not-json", "list", "null-value", "non-object-message",
+ "no-id", "from-string", "address-number", "body-string", "headers-object",
+ "header-name-number", "nextlink-number", "nextlink-empty"])
+async def test_a_bad_later_page_fails_the_whole_read(graph, override):
+ graph.inbox = [message(i) for i in range(120)]
+ graph.pages[2] = override
+ with pytest.raises(GraphError):
+ await provider(graph).get_replies()
+
+
+ "http://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?%24skip=50",
+ "https://evil.example/v1.0/me/mailFolders/inbox/messages?%24skip=50",
+ "https://graph.microsoft.com.evil.example/v1.0/me/mailFolders/inbox/messages?%24skip=50",
+ "https://[email protected]/v1.0/me/mailFolders/inbox/messages?%24skip=50",
+ "https://user:[email protected]/v1.0/me/mailFolders/inbox/messages?%24skip=50",
+ "https://graph.microsoft.com:8443/v1.0/me/mailFolders/inbox/messages?%24skip=50",
+ "https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?%24skip=50#frag",
+ "https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?%24skip=50#",
+ "https://graph.microsoft.com\\@evil.example/v1.0/me/mailFolders/inbox/messages?x=1",
+ "https://graph.microsoft.com/v1.0/me/messages?%24skip=50",
+ "https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages/m1/send?x=1",
+ "https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages/../../../sendMail?x=1",
+ "https://graph.microsoft.com/v1.0/me/mailFolders/inbox%2Fmessages?x=1",
+ "https://graph.microsoft.com/beta/me/mailFolders/inbox/messages?%24skip=50",
+ "https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages",
+ "/v1.0/me/mailFolders/inbox/messages?%24skip=50",
+ "https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?a=1\r\nX-Evil: 1",
+], ids=["http", "off-origin", "suffix-host", "userinfo-host", "credentials", "port",
+ "fragment", "empty-fragment", "backslash", "other-path", "send-path",
+ "dot-segments", "encoded-slash", "beta", "no-query", "relative", "crlf"])
+async def test_hostile_next_link_is_refused_before_any_request(graph, link):
+ graph.inbox = [message(i) for i in range(60)]
+ graph.pages[1] = {"@odata.nextLink": link}
+ with pytest.raises(GraphError, match="nextLink"):
+ await provider(graph).get_replies()
+
+ # Only the first page went out; nothing (and no token) followed the link.
+ assert len(graph.inbox_requests()) == 1
+ assert all(r.url.host in ("graph.microsoft.com", "login.microsoftonline.com")
+ for r in graph.requests)
+ graph_requests = [r for r in graph.requests if r.url.host == "graph.microsoft.com"]
+ assert [r.url.path for r in graph_requests] == [
+ "/v1.0/me", "/v1.0/me/mailFolders/inbox/messages"]
+
+
+async def test_next_link_loop_is_refused(graph):
+ graph.inbox = [message(i) for i in range(120)]
+ loop = "https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?%24skip=50&t=50"
+ graph.pages[1] = {"@odata.nextLink": loop}
+ graph.pages[2] = {"@odata.nextLink": loop}
+ with pytest.raises(GraphError, match="repeats"):
+ await provider(graph).get_replies()
+ assert len(graph.inbox_requests()) == 2
+
+
+async def test_next_link_back_to_the_first_page_is_refused(graph):
+ def self_link(request):
+ if request.url.path.endswith("/inbox/messages"):
+ graph.requests.append(request)
+ return httpx.Response(200, json={
+ "value": [message(0)], "@odata.nextLink": str(request.url)})
+ return graph(request)
+
+ p = MicrosoftProvider(config=None, env=Env(), transport=httpx.MockTransport(self_link))
+ with pytest.raises(GraphError, match="repeats"):
+ await p.get_replies()
+ assert len(graph.inbox_requests()) == 1
+
+
+async def test_too_many_pages_fails_closed(graph, monkeypatch):
+ monkeypatch.setattr(microsoft, "MAX_INBOX_PAGES", 3)
+ graph.inbox = [message(i) for i in range(10)]
+ with pytest.raises(GraphError, match="more than 3 pages"):
+ await provider(graph).get_replies(limit=3)
+ assert len(graph.inbox_requests()) == 3
+
+ graph.requests.clear()
+ graph.inbox = graph.inbox[:9] # exactly 3 pages is fine
+ assert len(await provider(graph).get_replies(limit=3)) == 9
+
+
+async def test_message_repeated_across_pages_is_returned_once(graph):
+ graph.inbox = [message(i) for i in range(60)]
+ graph.inbox[50] = message(49) # shifted by new mail arriving mid-read
+ replies = await provider(graph).get_replies()
+ assert [m.provider_id for m in replies].count("m49") == 1
+ assert len(replies) == 59
+
+
+async def test_message_without_a_sender_is_skipped(graph):
+ graph.inbox = [{**message(0), "from": None}, message(1)]
+ assert [m.provider_id for m in await provider(graph).get_replies()] == ["m1"]
+
+
+# ── Empty responses: fine for send/delete, not for anything with a body ──
+
+
+async def test_empty_202_and_204_are_success(graph):
+ p = provider(graph)
+ assert await p._request("POST", "/me/messages/draft1/send") == {}
+ assert await p._request("DELETE", "/me/messages/draft1") == {}
+
+
+async def test_malformed_draft_response_fails_the_send(graph):
+ def bad_draft(request):
+ if request.method == "POST" and request.url.path == "/v1.0/me/messages":
+ graph.requests.append(request)
+ return httpx.Response(201, content=b"<html>oops</html>")
+ return graph(request)
+
+ p = MicrosoftProvider(config=None, env=Env(), transport=httpx.MockTransport(bad_draft))
+ result = await p.send_email("[email protected]", "booking", "Hi.")
+ assert not result.ok and "malformed JSON" in result.error
+ assert not any(path.endswith("/send") for _, path in graph.calls())
+
+
+async def test_malformed_identity_response_raises(graph):
+ def not_json(request):
+ if request.url.path == "/v1.0/me":
+ return httpx.Response(200, content=b"nope")
+ return graph(request)
+
+ p = MicrosoftProvider(config=None, env=Env(), transport=httpx.MockTransport(not_json))
+ with pytest.raises(GraphError, match="malformed JSON"):
+ await p.get_replies()
+
+
+# ── With the handler: later pages count, and a bad later page holds sends ──
+
+
+async def _handler_with_prospect(tmp_path, graph):
+ import os
+ from harvey.state import StateManager
+ from tests.test_outbox_native import _now_iso, make_handler, seed_prospect
+
+ state = StateManager(os.path.join(tmp_path, "t.db"))
+ await state.init_db()
+ pid = await seed_prospect(state, email="[email protected]", status="contacted")
+ await state.add_outbox_item(
+ prospect_id=pid, to_email="[email protected]", subject="s2", body="b",
+ send_at=_now_iso(), status="approved", campaign_id="c1", step=2,
+ )
+ return state, pid, make_handler(state, provider(graph))
+
+
+async def test_unsubscribe_on_a_later_page_is_honored(graph, tmp_path):
+ graph.inbox = [message(i) for i in range(60)]
+ graph.inbox[55] = message(55, sender="[email protected]", body="Please unsubscribe me.")
+ state, pid, handler = await _handler_with_prospect(tmp_path, graph)
+
+ assert await handler.run() is True
+ assert len(graph.inbox_requests()) == 2
+ assert (await state.get_prospect(pid)).status == "opted_out"
+ assert len(await state.get_outbox(status="cancelled")) == 1
+
+
[email protected]("override", [
+ httpx.Response(503, headers={"Retry-After": "60"}),
+ httpx.Response(200, content=b"not json"),
+ {"value": "nope"},
+], ids=["outage", "not-json", "bad-value"])
+async def test_bad_later_page_holds_sends_and_handles_nothing(graph, tmp_path, override):
+ graph.inbox = [message(i) for i in range(60)]
+ graph.inbox[3] = message(3, sender="[email protected]", body="Please unsubscribe me.")
+ graph.pages[2] = override
+ state, pid, handler = await _handler_with_prospect(tmp_path, graph)
+
+ assert await handler.run() is False
+ # Page 1 was readable, but nothing from a partial inbox is acted on.
+ assert not await state.is_reply_processed("m3")
+ assert (await state.get_prospect(pid)).status == "contacted"
+ assert len(await state.get_outbox(status="approved")) == 1