Skip to content

fix: verify actual saved recipients from a draft reply - #92

Closed
proscar87 wants to merge 4 commits into
patrickfreyer:mainfrom
proscar87:fix/70-verify-recipients-from-saved-draft
Closed

proscar87 wants to merge 4 commits into
patrickfreyer:mainfrom
proscar87:fix/70-verify-recipients-from-saved-draft

Conversation

@proscar87

@proscar87 proscar87 commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Builds on #91. This branch is stacked on #91's head, so until #91 is merged the diff here also shows #91's commit (fix: verify a saved reply lands outside Mail's quoted original). Only the last commit is new in this PR.

Refs #70 (Bcc, draft_id and thread headers are not covered yet). reply_to_email's own AppleScript reports success by echoing "To: " & messageSender — the original message's sender — unconditionally. That's correct for a plain reply, but doesn't reflect what actually landed in the saved draft when reply_to_all, cc, or from_address changes the real recipients/sender.

This extends the existing #71 read-back mechanism (get_email_source re-reading the just-saved draft) to also verify the real To/Cc/From headers, sharing the same round-trip already used to verify the reply body landed outside the quote.

  • New verify_recipients() in reply_verification.py: parses the saved draft's RFC 822 source and checks that every requested cc address actually made it into the saved Cc header (subset check — extra addresses Mail adds via reply-to-all are not a mismatch), and that a requested from_address override actually landed in the saved From header.
  • Bcc is deliberately not checked — whether an unsent draft's RFC 822 source even retains Bcc (vs. only applying it at send time) isn't something I could determine without a live draft to inspect, and I didn't want a check that always silently reports "not found" to be mistaken for a real verification. Documented in the docstring rather than guessed at.
  • _verify_saved_reply_body now runs both checks off the single get_email_source fetch and appends a Recipients (PASSED|FAILED): ... line only when cc or from_address was actually requested — a plain reply with neither gets no extra line.

Testing

  • 8 new unit tests for verify_recipients/_extract_addresses in tests/test_reply_verification.py (exact match, missing requested CC, reply-to-all extra CC tolerated, from-mismatch, no headers present, etc.)
  • 5 new integration tests in tests/test_compose_tools.py::ReplyDraftVerificationTests exercising the full reply_to_email → readback path for: no-expectations (no Recipients line), CC actually saved (PASSED), CC silently dropped (FAILED), from_address honored (PASSED), from_address not applied (FAILED)
  • Mutation-tested: reverted the expected_cc=cc, expected_from=sender_override pass-through and confirmed exactly the 4 new recipient-specific tests fail (others unaffected)
  • Full suite: 148 passed on this branch, vs 135 on fix: verify a saved reply lands outside Mail's quoted original (#71) #91 and 120 on main
  • Ran the whole suite with subprocess.run instrumented at the process level to confirm zero real AppleScript calls escape mocking — same isolation check used for bug: prevent reply bodies from being saved inside quoted text #71, since this wiring runs through the same draft-mode code path

🤖 Generated with Claude Code

proscar87 and others added 2 commits August 20, 2026 08:39
…ckfreyer#71)

`reply_to_email` inserts the new body via a blind clipboard paste into
Mail's native reply composer, which already contains the quoted original
thread. That paste is never read back through `content of replyMessage` --
Mail's GUI editor buffer is decoupled from that scriptable property, so a
read-back there always reports the pre-paste value even after a
successful paste (documented in the existing comment above the keystroke
step). The tool therefore reported success from the AppleScript completing
without error, with no check on where the pasted text actually landed.

`reply_verification.py` adds that check: parse the saved draft's RFC 822
source (via the existing `get_email_source` tool, no new AppleScript) and
verify the reply body is present in the region preceding Mail's quote
container -- HTML `<blockquote type="cite">` or a plain-text `>`-quoted
block. If the body ends up inside the quote instead of above it (the bug
patrickfreyer#71 describes), or isn't found at all (a different, pre-existing failure
mode -- see the focus-polling comment in `compose.py`), the tool now says
so instead of reporting the same "saved!" text either way.

Wired into `reply_to_email` for `mode="draft"` only. That's the one case
where the message is guaranteed to already be sitting in Drafts by the
time the AppleScript that saved it returns, so re-reading it is safe and
synchronous. "send" moves the message to Sent before a read-back could
happen; "open" leaves it unsaved in a compose window with nothing in a
mailbox yet. Neither is covered here -- flagged as a natural follow-up
rather than solved in this PR.

Found and fixed two bugs in my own first pass, before opening anything:

1. Gating the read-back on `not output_text.startswith("Error")` misses
   "No email found matching: <keyword>" -- a different failure with no
   saved draft to verify, that also doesn't start with "Error". Switched
   to checking for the AppleScript's own positive success marker instead
   of the absence of one particular negative one. A test written against
   the *intended* behaviour caught this before it shipped: reverting to
   the negative check is exactly the mutation
   `test_applescript_error_does_not_attempt_verification` exists to catch,
   and it does.

2. My first version of this integration made the existing sender-override
   tests issue real, unmocked AppleScript against whatever machine runs
   the suite (a fast "does this account exist" check that failed quickly
   since "Work" isn't a real account there, but real execution
   nonetheless). `reply_to_email`'s existing tests using `send=False`
   didn't anticipate a second read-back call, since there wasn't one
   before this change. Fixed by mocking `get_email_source` in those two
   tests too, and confirmed with a `subprocess.run`-tracking wrapper
   around the *entire* suite that zero real calls occur anywhere in it,
   not just in the tests I touched.

Verification:
- 9 new unit tests for the parsing/detection logic in isolation (HTML and
  plain-text quote markers, body-inside-quote, body-missing-entirely
  distinguished from body-inside-quote, multi-div HTML wrapping, no quote
  block at all, empty body, no recognizable body part).
- 6 new integration tests for the `reply_to_email` wiring (pass, fail,
  get_email_source error, and that send/open/no-draft-saved paths do not
  attempt verification at all).
- Mutation-tested three points in the detection logic (blockquote
  detection, HTML tag stripping, '>' marker detection) and the gating
  condition: each breaks exactly the test built to catch it, no others.
- Full suite: 135 passed (was 120), matching CI's `PYTHONPATH=plugin`
  invocation. Zero real `subprocess.run` calls anywhere in the suite,
  confirmed by wrapping it for the entire run, not just the new tests.
- `scripts/check_versions.py` (CI's version-drift guard): clean.

What I could not verify: live behaviour against a real Mail.app draft.
Everything above is against synthetic RFC 822 fixtures and mocked
AppleScript output.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
)

reply_to_email's AppleScript always echoed the original message's
sender as "To:", regardless of what reply-to-all, a cc override, or a
from_address override actually produced in the saved draft. Extend the
existing patrickfreyer#71 read-back (verify_reply_body_outside_quote) to also check
the real saved To/Cc/From headers against what was requested, sharing
the same get_email_source round-trip.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@patrickfreyer

Copy link
Copy Markdown
Owner

This review was written by Claude (AI assistant) on Patrick's behalf.

Thanks @proscar87, this is a solid step toward #70 (and it carries #91, which closes #71). 148 tests pass, and it merges cleanly with #101.

Recipient check nits:

Body-placement nits from #91 (see that PR for details): locate the exact draft rather than first subject match, fix the three false FAILs (tag stripping, HTML bodies, whitespace), and surface a failure as a structured result rather than a trailing line.

Heads-up: #98 also rewrites reply_to_email and conflicts here in compose.py and tests/test_compose_tools.py. Whichever lands second will need a rebase.

proscar87 and others added 2 commits October 14, 2026 19:10
Review feedback on patrickfreyer#91 and patrickfreyer#92:
- The draft is identified by Message-ID: Drafts IDs are snapshotted
  before the reply is created, and only one new draft with the exact
  reply subject is accepted. No subject fallback; an ambiguous or missing
  identity is reported as a failure.
- Body placement: markup is only stripped from an actual HTML body, the
  HTML that was sent is checked instead of its plain fallback, and
  whitespace is normalized on both sides, so wrapped plain bodies pass.
- The result leads with 'Status: VERIFIED' or 'Status: FAILED — <why>'
  instead of a trailing line after 'Reply saved as draft!'.
- Cc/From are parsed with email.utils.getaddresses and compared as
  lowercased addresses.
- The saved To/Cc/From are always reported, including reply-all without
  overrides.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Found on a real Mail.app draft: a cc of "Name <>" was saved as
`Cc: Name`, and the check passed because getaddresses yields an empty
address for that entry, which was filtered out before comparing.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@proscar87

Copy link
Copy Markdown
Contributor Author

Thanks, all addressed here (#91's points too, since they land together): c7ce288 and 82d7a07. I also changed "Closes #70" to "Refs #70".

Body placement (#91):

  • Exact draft: Drafts IDs are snapshotted before the reply is created, and only one new draft with the exact reply subject is accepted. Its RFC Message-ID is then read back through get_email_source(message_id=...). There is no subject fallback: a missing or ambiguous identity is reported as a failure.
  • False FAILs: markup is only stripped from an actual HTML body ("use tag" and "R&D" survive in plain text), the HTML that was sent is checked instead of its plain fallback, and whitespace is normalized on both sides, so wrapped bodies pass.
  • Structured result: the output now leads with Status: VERIFIED or Status: FAILED — <reason>. It no longer trails after "Reply saved as draft!".

Recipients (#92):

  • Cc/From are parsed with email.utils.getaddresses and compared as lowercased addresses.
  • The saved To/Cc/From are always reported, including reply-all with no overrides.

Checked on real Mail.app drafts (saved as drafts, never sent, then deleted):

  • The new-draft identity resolved to the right draft by Message-ID every time.
  • cc="Prueba Copia <PRUEBA@EXAMPLE.COM>, otra@Example.com" was saved with both addresses and passed.
  • That run also found a false PASS, now fixed in 82d7a07. A cc of "Name <>" was saved as Cc: Name, and the check passed because getaddresses returns an empty address for it, which was being filtered out. It's now reported as "has no valid address".
  • Not validated: a real PASS for body placement. From my session the Cmd+V paste didn't land in the reply (no keyboard focus or Accessibility permission), so every real draft I made had no body, and the check correctly said FAILED. The PASS path is covered by tests on recorded sources only.

159 tests pass. Each new test fails against the code before its fix.

@proscar87

Copy link
Copy Markdown
Contributor Author

One more observation from those real drafts (a Gmail account). After each run I deleted the verified draft by its Message-ID, but other copies with the same "Re:" subject were left in Drafts: six across four runs, some with identical timestamps. They're probably autosave versions or Gmail-sync copies. In every run the new-draft lookup still resolved exactly one Message-ID, and verification read the right draft. But if those copies can appear before the lookup runs, it would see more than one new draft and report "could not uniquely identify the saved draft". That's a FAILED, not a wrong PASS, so it fails safe, but worth knowing. I cleaned up all the test drafts.

@patrickfreyer

Copy link
Copy Markdown
Owner

This review was written by Claude (AI assistant) on Patrick's behalf.

Thanks @proscar87, this is great work, and checking it on real drafts is much appreciated. Everything from both reviews is addressed: 161 tests pass on current main and it merges cleanly with #87 and #101 (both now merged).

One thing before we merge:

  • compose.py:864: the Drafts snapshot runs inside the main try, so on an account without a mailbox literally named "Drafts", draft-mode reply_to_email now fails before the reply is created (on main it saves fine). Could you wrap the snapshot in its own try and leave priorDraftIDs empty on failure? Verification would then report FAILED while the draft still saves.

Optional: on the duplicate Gmail copies, agreed it fails safe. If the new candidates all share one Message-ID, treating them as one draft would avoid that spurious FAILED.

Once that's in we'll merge this and close #91 as superseded.

@patrickfreyer

Copy link
Copy Markdown
Owner

This comment was written by Claude (AI assistant) on Patrick's behalf.

Thanks @proscar87! To keep things moving, we carried this over in #114 with your commits preserved (authorship intact), plus one small follow-up: the Drafts snapshot now has its own try, and Gmail autosave copies sharing one Message-ID count as one draft. #114 is now merged, so closing this in favour of it. Really appreciate the careful real-mailbox verification.

patrickfreyer added a commit that referenced this pull request Oct 15, 2026
ZiyadDiab pushed a commit to ZiyadDiab/apple-mail-mcp that referenced this pull request Nov 6, 2026
…aved reply drafts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants