@mgcrea/mcp-apple-mail 1.20.1 → 1.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,8 +14,8 @@ const pkg = readPackageIdentity(new URL("../package.json", import.meta.url), {
14
14
  const BUILD_INFO = {
15
15
  name: pkg.name,
16
16
  version: pkg.version,
17
- gitCommit: "a96dda2",
18
- gitCommitDate: "2026-09-09T13:03:18+02:00"
17
+ gitCommit: "78ce002",
18
+ gitCommitDate: "2026-09-11T22:05:33+02:00"
19
19
  };
20
20
  //#endregion
21
21
  //#region src/client/errors.ts
@@ -257,7 +257,10 @@ var MailAxLane = class MailAxLane {
257
257
  * milliseconds.
258
258
  *
259
259
  * The subject is the identity, and requiring a body area with it rejects the
260
- * main window and the drafts list. Counting windows does not work: Mail closes
260
+ * main window and the drafts list. It is an identity only because `compose.ts`
261
+ * refuses when a composer under the same subject was already open before the
262
+ * call: a leftover from an earlier attempt matches here just as well, and is
263
+ * readable first. Counting windows does not work: Mail closes
261
264
  * and reuses windows around a compose, so the count comes back unchanged with
262
265
  * a new composer on screen.
263
266
  */
@@ -327,6 +330,16 @@ var MailAxLane = class MailAxLane {
327
330
  * `matched` rather than the returned length, because the response is byte
328
331
  * capped and a long quoted message will truncate — a fingerprint taken from a
329
332
  * truncated list would compare two different bounds rather than two states.
333
+ *
334
+ * **Null when the body cannot be read at all, and that is the whole point.**
335
+ * This returned -1 for a failed read, and the caller compared it as a count.
336
+ * A composer that CLOSES takes its element handle with it — the driver answers
337
+ * `staleHandle` — so a body that had gone in perfectly read back as -1 and
338
+ * compared unequal to the size before, which is the signature of "something
339
+ * landed that cannot be matched". A reply sent by hand mid-call was reported
340
+ * as a body that never went in, with a warning against the retry that was in
341
+ * fact the safe move. Blind and different are not the same answer, exactly as
342
+ * `bodyText` above insists, and this is where that was forgotten.
330
343
  */
331
344
  async bodySize(body) {
332
345
  try {
@@ -337,7 +350,7 @@ var MailAxLane = class MailAxLane {
337
350
  });
338
351
  return tree.matched ?? (tree.elements ?? []).length;
339
352
  } catch {
340
- return -1;
353
+ return null;
341
354
  }
342
355
  }
343
356
  /**
@@ -359,21 +372,33 @@ var MailAxLane = class MailAxLane {
359
372
  *
360
373
  * The guard itself stays. Posting command-V without knowing where the focus is
361
374
  * types into whatever happens to be in front, and that is the user's window.
375
+ *
376
+ * **A composer that has gone answers false rather than throwing.** Both handles
377
+ * die with the window, so raising or focusing one afterwards is a `staleHandle`
378
+ * — and letting that escape turns a describable failure into a bare channel
379
+ * error with no note attached, on the one path whose whole job is to say what
380
+ * happened. False is the honest answer: the focus was not taken, so nothing was
381
+ * typed.
362
382
  */
363
383
  async paste(ref, focusTimeoutMs = FOCUS_TIMEOUT_MS) {
364
- await this.#call("raise_window", { handle: ref.window });
365
- await this.activate();
366
- const deadline = Date.now() + focusTimeoutMs;
367
- for (;;) {
368
- if ((await this.#call("focus", { handle: ref.body })).focused === true) break;
369
- if (Date.now() >= deadline) return false;
370
- await new Promise((resolve) => setTimeout(resolve, FOCUS_POLL_MS));
384
+ try {
385
+ await this.#call("raise_window", { handle: ref.window });
386
+ await this.activate();
387
+ const deadline = Date.now() + focusTimeoutMs;
388
+ for (;;) {
389
+ if ((await this.#call("focus", { handle: ref.body })).focused === true) break;
390
+ if (Date.now() >= deadline) return false;
391
+ await new Promise((resolve) => setTimeout(resolve, FOCUS_POLL_MS));
392
+ }
393
+ await this.#call("key", {
394
+ key: "v",
395
+ modifiers: ["command"],
396
+ handle: ref.body
397
+ });
398
+ return true;
399
+ } catch {
400
+ return false;
371
401
  }
372
- await this.#call("key", {
373
- key: "v",
374
- modifiers: ["command"]
375
- });
376
- return true;
377
402
  }
378
403
  /**
379
404
  * Send the composer, or save it as a draft.
@@ -391,15 +416,51 @@ var MailAxLane = class MailAxLane {
391
416
  * alternative and is worse — drafts are discovered by subject, so two with the
392
417
  * same one are indistinguishable, on the single path whose named failure is
393
418
  * sending the wrong thing.
419
+ *
420
+ * **The window is raised again first, and the answer says whether that took.**
421
+ * The focus is only known to be in the composer at the moment of the paste;
422
+ * between the read that verifies the body and this keystroke the person at the
423
+ * keyboard can move the foreground, and command-shift-D would then be posted
424
+ * into whatever they moved to. Re-raising costs two round trips and closes
425
+ * that window.
426
+ *
427
+ * The keystroke also names the composer's window, which closes the gap that
428
+ * remains between the re-raise and the key: the desktop server brings Mail
429
+ * forward again and refuses rather than posting into something else.
430
+ *
431
+ * Only `"pressed"` means anything was pressed. The other two answers are both
432
+ * refusals, and they are kept apart because they mean opposite things to the
433
+ * person reading the result:
434
+ *
435
+ * * `"gone"`: the composer could not be raised. Its handle died with the
436
+ * window, so somebody sent or closed it.
437
+ * * `"refused"`: raised, but the keystroke was refused because Mail would
438
+ * not come forward. The composer is still on screen, unsent.
439
+ *
440
+ * Posting a send into an unknown foreground is the one outcome worth refusing
441
+ * outright, which is why neither of them throws.
394
442
  */
395
- async finish(sendNow) {
396
- await this.#call("key", sendNow ? {
397
- key: "d",
398
- modifiers: ["command", "shift"]
399
- } : {
400
- key: "s",
401
- modifiers: ["command"]
402
- });
443
+ async finish(sendNow, ref) {
444
+ try {
445
+ await this.#call("raise_window", { handle: ref.window });
446
+ await this.activate();
447
+ } catch {
448
+ return "gone";
449
+ }
450
+ try {
451
+ await this.#call("key", sendNow ? {
452
+ key: "d",
453
+ modifiers: ["command", "shift"],
454
+ handle: ref.window
455
+ } : {
456
+ key: "s",
457
+ modifiers: ["command"],
458
+ handle: ref.window
459
+ });
460
+ } catch {
461
+ return "refused";
462
+ }
463
+ return "pressed";
403
464
  }
404
465
  /**
405
466
  * Has the composer for this subject gone?
@@ -1413,7 +1474,26 @@ function collectText(el, depth, acc, budget) {
1413
1474
  * ends up in the draft twice with no way to undo it from here.
1414
1475
  */
1415
1476
  function composerBodySize(body) {
1416
- return prop(function () { return body.entireContents().length; }, -1);
1477
+ return prop(function () { return body.entireContents().length; }, null);
1478
+ }
1479
+
1480
+ /**
1481
+ * Did anything at all reach the composer, comparing two fingerprints?
1482
+ *
1483
+ * Three answers, and the third is the one that was missing. "unknown" is a body
1484
+ * that cannot be READ -- which is what a composer that has CLOSED looks like
1485
+ * from the outside, because its reference dies with the window.
1486
+ *
1487
+ * This returned -1 for an unreadable body and the caller compared it as a
1488
+ * length. Two consequences, both wrong and in opposite directions: -1 against a
1489
+ * real count read as "something landed", so a reply sent by hand mid-call was
1490
+ * reported as a body that never went in; and -1 against -1 read as "nothing
1491
+ * landed", which is the branch that DISCARDS the composer -- destroying a body
1492
+ * that may well have been in it.
1493
+ */
1494
+ function landedVerdict(before, after) {
1495
+ if (before === null || after === null) return "unknown";
1496
+ return after === before ? "no" : "yes";
1417
1497
  }
1418
1498
 
1419
1499
  /**
@@ -1778,6 +1858,220 @@ function run(argv) {
1778
1858
  }
1779
1859
  `;
1780
1860
  //#endregion
1861
+ //#region src/client/jxa/read.ts
1862
+ /** Accounts, their UUIDs, on-disk directories and mailbox names. ~0.6s for 4 accounts. */
1863
+ const LIST_ACCOUNTS = script(`
1864
+ var accts = M.accounts();
1865
+ var out = [];
1866
+ for (var i = 0; i < accts.length; i++) {
1867
+ var a = accts[i];
1868
+ out.push({
1869
+ id: prop(function () { return a.id(); }, null),
1870
+ name: prop(function () { return a.name(); }, null),
1871
+ enabled: prop(function () { return a.enabled(); }, null),
1872
+ accountType: prop(function () { return String(a.accountType()); }, null),
1873
+ emailAddresses: prop(function () { return a.emailAddresses(); }, []),
1874
+ fullName: prop(function () { return a.fullName(); }, null),
1875
+ // Path objects need String(); JSON.stringify renders them as {}.
1876
+ directory: prop(function () { return String(a.accountDirectory()); }, null),
1877
+ messageCaching: prop(function () { return String(a.messageCaching()); }, null),
1878
+ mailboxes: prop(function () { return a.mailboxes().map(function (m) { return m.name(); }); }, [])
1879
+ });
1880
+ }
1881
+ return ok(out);
1882
+ `);
1883
+ /**
1884
+ * Mailboxes with counts. Counts come from AppleScript rather than the index
1885
+ * because they are cheap here (76ms unread / 295ms total on a 29k mailbox) and
1886
+ * therefore never need to degrade when Full Disk Access is missing.
1887
+ */
1888
+ const LIST_MAILBOXES = script(`
1889
+ var accts = M.accounts();
1890
+ var out = [];
1891
+ for (var i = 0; i < accts.length; i++) {
1892
+ var a = accts[i];
1893
+ var uuid = prop(function () { return a.id(); }, null);
1894
+ if (p.accountUuids && p.accountUuids.length && p.accountUuids.indexOf(uuid) === -1) continue;
1895
+ var boxes = a.mailboxes();
1896
+ for (var j = 0; j < boxes.length; j++) {
1897
+ var b = boxes[j];
1898
+ var entry = {
1899
+ accountUuid: uuid,
1900
+ accountName: prop(function () { return a.name(); }, null),
1901
+ name: prop(function () { return b.name(); }, null)
1902
+ };
1903
+ if (p.withCounts) {
1904
+ entry.unread = prop(function () { return b.unreadCount(); }, null);
1905
+ entry.total = prop(function () { return b.messages.length; }, null);
1906
+ }
1907
+ out.push(entry);
1908
+ }
1909
+ }
1910
+ return ok(out);
1911
+ `);
1912
+ /** Total and unread for one mailbox. */
1913
+ const COUNT_MAILBOX = script(`
1914
+ var acct = findAccount(M, p.accountUuid);
1915
+ if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
1916
+ var mb = resolveMailbox(acct, p.mailbox);
1917
+ if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
1918
+ return ok({
1919
+ accountUuid: p.accountUuid,
1920
+ mailbox: prop(function () { return mb.name(); }, p.mailbox),
1921
+ total: prop(function () { return mb.messages.length; }, null),
1922
+ unread: prop(function () { return mb.unreadCount(); }, null)
1923
+ });
1924
+ `);
1925
+ /**
1926
+ * The degraded listing lane: newest N of one mailbox, used when the Envelope
1927
+ * Index is unavailable. Costs roughly 130ms + 42ms per message per property,
1928
+ * which is why the caller caps N hard (default 50) instead of paginating.
1929
+ */
1930
+ const LIST_RECENT = script(`
1931
+ var acct = findAccount(M, p.accountUuid);
1932
+ if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
1933
+ var mb = resolveMailbox(acct, p.mailbox);
1934
+ if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
1935
+ var mailboxName = prop(function () { return mb.name(); }, p.mailbox);
1936
+
1937
+ var total = prop(function () { return mb.messages.length; }, 0);
1938
+ var n = Math.min(p.limit || 20, total);
1939
+ if (n <= 0) return ok({ mailbox: mailboxName, total: total, messages: [] });
1940
+
1941
+ // Batch the property reads: one Apple Event per property beats one per message
1942
+ // by roughly 6x. slice() on the message collection keeps it to a range specifier.
1943
+ var slice = mb.messages.slice(0, n);
1944
+ var subjects = prop(function () { return slice.subject(); }, []);
1945
+ var senders = prop(function () { return slice.sender(); }, []);
1946
+ var dates = prop(function () { return slice.dateReceived(); }, []);
1947
+ var reads = prop(function () { return slice.readStatus(); }, []);
1948
+ var flags = prop(function () { return slice.flaggedStatus(); }, []);
1949
+ var ids = prop(function () { return slice.id(); }, []);
1950
+
1951
+ var out = [];
1952
+ for (var i = 0; i < n; i++) {
1953
+ out.push({
1954
+ id: ids[i] === undefined ? null : ids[i],
1955
+ accountUuid: p.accountUuid,
1956
+ mailbox: mailboxName,
1957
+ subject: subjects[i] === undefined ? null : subjects[i],
1958
+ sender: senders[i] === undefined ? null : senders[i],
1959
+ dateReceived: iso(dates[i]),
1960
+ read: reads[i] === undefined ? null : reads[i],
1961
+ flagged: flags[i] === undefined ? null : flags[i]
1962
+ });
1963
+ }
1964
+ return ok({ mailbox: mailboxName, total: total, messages: out });
1965
+ `);
1966
+ /** Resolve a batch of message ids inside one mailbox. ~0.1s even on a 29k mailbox. */
1967
+ const GET_MESSAGES = script(`
1968
+ var acct = findAccount(M, p.accountUuid);
1969
+ if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
1970
+ var mb = resolveMailbox(acct, p.mailbox);
1971
+ if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
1972
+ var mailboxName = prop(function () { return mb.name(); }, p.mailbox);
1973
+
1974
+ var out = [];
1975
+ for (var i = 0; i < p.ids.length; i++) {
1976
+ var id = p.ids[i];
1977
+ try {
1978
+ var m = mb.messages.byId(id);
1979
+ var summary = messageSummary(m, p.accountUuid, mailboxName);
1980
+ if (p.withContent) {
1981
+ summary.content = prop(function () { return m.content(); }, null);
1982
+ }
1983
+ if (p.withSource) {
1984
+ summary.source = prop(function () { return m.source(); }, null);
1985
+ }
1986
+ if (p.withHeaders) {
1987
+ summary.allHeaders = prop(function () { return m.allHeaders(); }, null);
1988
+ }
1989
+ out.push(summary);
1990
+ } catch (e) {
1991
+ out.push({ id: id, found: false, error: String(e && e.message ? e.message : e) });
1992
+ }
1993
+ }
1994
+ return ok(out);
1995
+ `);
1996
+ /**
1997
+ * Did a message with this subject reach Sent, at or after a given instant?
1998
+ *
1999
+ * The question a failed compose cannot answer for itself. When the composer
2000
+ * window is GONE, nothing in the Accessibility lane can say whether it was sent
2001
+ * or discarded — both leave the same empty screen — and getting that wrong in
2002
+ * either direction is expensive: calling a sent reply a failure invites a retry
2003
+ * that sends it twice, and calling a discarded one sent loses the reply.
2004
+ *
2005
+ * ## Where it looks
2006
+ *
2007
+ * The application-level unified mailbox, not the account's. `docs/mail-compose.md`
2008
+ * measured `account.draftsMailbox` answering "Can't get object." on all four
2009
+ * account types while `application.draftsMailbox` resolves to the unified "All
2010
+ * Drafts", and there is no reason to expect `sentMailbox` to differ. The
2011
+ * documented per-account property is still tried first, so this repairs itself
2012
+ * if Apple ever fixes it.
2013
+ *
2014
+ * Unified is the better target anyway: which account Mail actually sends from is
2015
+ * its own decision, and need not be the account the original was read in.
2016
+ *
2017
+ * ## Why `found: false` is deliberately weak
2018
+ *
2019
+ * The newest messages are taken as the head of the collection, the way
2020
+ * LIST_RECENT does. If a mailbox ever came back oldest-first, the head would be
2021
+ * ancient and nothing would match — a FALSE NEGATIVE on a reply that did go,
2022
+ * which is the dangerous direction. So `newest` is reported alongside: a caller
2023
+ * that sees nothing found AND a newest older than its floor knows the listing
2024
+ * never showed it recent mail, and must say "could not tell" rather than "not
2025
+ * sent".
2026
+ */
2027
+ const SENT_SINCE = script(`
2028
+ var box = null;
2029
+ var acct = p.accountUuid ? findAccount(M, p.accountUuid) : null;
2030
+ // name() forces the event: JXA is lazy, so a specifier that will fail does not
2031
+ // fail until something reads through it.
2032
+ if (acct) box = prop(function () { var b = acct.sentMailbox(); b.name(); return b; }, null);
2033
+ if (!box) box = prop(function () { var b = M.sentMailbox(); b.name(); return b; }, null);
2034
+ if (!box) return ok({ checked: false, reason: "NO_SENT_MAILBOX", found: false, messages: [] });
2035
+
2036
+ var mailbox = prop(function () { return box.name(); }, "Sent");
2037
+ var total = prop(function () { return box.messages.length; }, 0);
2038
+ var n = Math.min(p.limit || 25, total);
2039
+ if (n <= 0) return ok({ checked: true, mailbox: mailbox, total: total, found: false, newest: null, messages: [] });
2040
+
2041
+ // One Apple Event per property rather than one per message, as LIST_RECENT.
2042
+ var slice = box.messages.slice(0, n);
2043
+ var subjects = prop(function () { return slice.subject(); }, []);
2044
+ var sent = prop(function () { return slice.dateSent(); }, []);
2045
+ var received = prop(function () { return slice.dateReceived(); }, []);
2046
+
2047
+ var floor = p.sinceMs ? Number(p.sinceMs) : 0;
2048
+ var wanted = String(p.subject == null ? "" : p.subject);
2049
+ var hits = [];
2050
+ var newest = 0;
2051
+ for (var i = 0; i < n; i++) {
2052
+ var when = sent[i] || received[i];
2053
+ var ms = 0;
2054
+ try { ms = when ? when.getTime() : 0; } catch (e) { ms = 0; }
2055
+ if (ms > newest) newest = ms;
2056
+ if (String(subjects[i] === undefined ? "" : subjects[i]) !== wanted) continue;
2057
+ if (ms && ms < floor) continue;
2058
+ hits.push({
2059
+ subject: subjects[i] === undefined ? null : subjects[i],
2060
+ dateSent: iso(sent[i]),
2061
+ dateReceived: iso(received[i])
2062
+ });
2063
+ }
2064
+ return ok({
2065
+ checked: true,
2066
+ mailbox: mailbox,
2067
+ total: total,
2068
+ scanned: n,
2069
+ found: hits.length > 0,
2070
+ newest: newest ? new Date(newest).toISOString() : null,
2071
+ messages: hits
2072
+ });
2073
+ `);
2074
+ //#endregion
1781
2075
  //#region src/client/jxa/write.ts
1782
2076
  /**
1783
2077
  * Mutating scripts.
@@ -2490,9 +2784,11 @@ const REPLY_OR_FORWARD = script(`
2490
2784
  bodyVerified = after !== null && containsText(after, expected);
2491
2785
  if (bodyVerified) {
2492
2786
  verifiedChars = expected.length;
2493
- } else if (composerBodySize(bodyArea) !== sizeBefore) {
2494
- // Something went in that we cannot match. Pasting again would put the
2495
- // reply in the draft twice, and nothing here can undo that.
2787
+ } else if (landedVerdict(sizeBefore, composerBodySize(bodyArea)) !== "no") {
2788
+ // Something went in that we cannot match, or the body can no longer be
2789
+ // read at all. Pasting again would put the reply in the draft twice,
2790
+ // and nothing here can undo that -- so an UNKNOWN reading stops the
2791
+ // retry just as firmly as a changed one.
2496
2792
  break;
2497
2793
  }
2498
2794
  }
@@ -2502,12 +2798,37 @@ const REPLY_OR_FORWARD = script(`
2502
2798
 
2503
2799
  if (!bodyVerified) {
2504
2800
  restore();
2801
+
2802
+ // A composer that has GONE reads exactly like one whose body is
2803
+ // unreadable, and only this tells them apart. Nothing here closes a
2804
+ // composer before this point, so one that is missing was taken by the
2805
+ // person at the keyboard -- and sent and discarded leave the same empty
2806
+ // screen. Saying "the body did not go in" here named the wrong failure and
2807
+ // forbade the wrong retry: the hazard is sending the mail twice, not
2808
+ // pasting it twice.
2809
+ //
2810
+ // The native path (client/compose.ts) goes on to ask Mail whether the
2811
+ // message reached Sent. This one only says where to look -- it is the
2812
+ // fallback for a server not hosted by Cupertino, and a second mailbox scan
2813
+ // inside this script is not worth the surface.
2814
+ if (composerWindow(proc, subject, 0) === null) {
2815
+ return err(
2816
+ "COMPOSER_GONE",
2817
+ "The " + p.mode + " window for \\"" + subject + "\\" is GONE. Nothing here closed it — " +
2818
+ "this path discards a composer only when it is provably empty — so someone using the " +
2819
+ "Mac sent it or closed it while this was running. Whether it went cannot be told from " +
2820
+ "here: LOOK IN SENT for this subject before retrying, because a retry after a send " +
2821
+ "that did go sends it twice."
2822
+ );
2823
+ }
2824
+
2505
2825
  // Take the window back only when it is provably still empty. A paste that
2506
2826
  // landed and could not be READ is a different thing from one that never
2507
2827
  // landed, and closing that one would destroy the reply with no way to get
2508
- // it back -- so it is left on screen for the user to judge.
2509
- var landed = composerBodySize(bodyArea) !== sizeBefore;
2510
- var closedUnverified = landed ? false : discardComposer(M, draft);
2828
+ // it back -- so it is left on screen for the user to judge. An UNKNOWN
2829
+ // reading counts as "may have landed" for exactly the same reason.
2830
+ var landed = landedVerdict(sizeBefore, composerBodySize(bodyArea));
2831
+ var closedUnverified = landed === "no" ? discardComposer(M, draft) : false;
2511
2832
  return err(
2512
2833
  "DRAFT_BODY_NOT_SET",
2513
2834
  "The " + p.mode + " window for \\"" + subject + "\\" was opened and correctly addressed, but the " +
@@ -2515,12 +2836,16 @@ const REPLY_OR_FORWARD = script(`
2515
2836
  "MUST NOT be described to the user as ready. " +
2516
2837
  (closedUnverified
2517
2838
  ? "Nothing had landed in it, so it was closed again without saving and a retry is safe."
2518
- : landed
2839
+ : landed === "yes"
2519
2840
  ? "SOMETHING DID land in it that could not be read back, so it was left open rather " +
2520
2841
  "than discarded — look at it in Mail before retrying, because a retry would paste " +
2521
2842
  "the reply in twice."
2522
- : "It could NOT be closed from here — close it in Mail before retrying, or the retry " +
2523
- "leaves a second draft behind.")
2843
+ : landed === "unknown"
2844
+ ? "The window is still there but its body could not be READ, so whether anything " +
2845
+ "landed is unknown. It was left open rather than discarded — look at it in Mail " +
2846
+ "before retrying, because a retry would paste the reply in twice."
2847
+ : "It could NOT be closed from here — close it in Mail before retrying, or the retry " +
2848
+ "leaves a second draft behind.")
2524
2849
  );
2525
2850
  }
2526
2851
  }
@@ -2686,6 +3011,20 @@ const SEND_TIMEOUT_MS = 5e3;
2686
3011
  * so the top of it is the tell.
2687
3012
  */
2688
3013
  const VERIFY_CHARS = 400;
3014
+ /**
3015
+ * How far back to accept a message in Sent as this call's.
3016
+ *
3017
+ * Generous on purpose. `dateSent` and the moment the row appears are not the
3018
+ * same instant — a real send measured 16s between them — and the cost of the two
3019
+ * errors is lopsided: a window slightly too wide names a message that was
3020
+ * already there, which a reader can see and dismiss; one too narrow reports a
3021
+ * reply that DID go as missing, and invites sending it again.
3022
+ */
3023
+ const SENT_SLACK_MS = 12e4;
3024
+ const compare = (before, after) => {
3025
+ if (before === null || after === null) return "unknown";
3026
+ return after === before ? "no" : "yes";
3027
+ };
2689
3028
  const systemClipboard = {
2690
3029
  async read() {
2691
3030
  try {
@@ -2731,25 +3070,99 @@ const paste = async (lane, clipboard, ref, text, focusTimeoutMs) => {
2731
3070
  const after = await lane.bodyText(ref.body);
2732
3071
  if (after !== null && containsText(after, expected)) return {
2733
3072
  verified: true,
2734
- landed: true
3073
+ landed: "yes"
2735
3074
  };
2736
3075
  }
2737
- if (await lane.bodySize(ref.body) !== sizeBefore) break;
3076
+ if (compare(sizeBefore, await lane.bodySize(ref.body)) !== "no") break;
2738
3077
  }
2739
3078
  return {
2740
3079
  verified: false,
2741
- landed: await lane.bodySize(ref.body) !== sizeBefore
3080
+ landed: compare(sizeBefore, await lane.bodySize(ref.body))
2742
3081
  };
2743
3082
  });
2744
3083
  };
3084
+ /**
3085
+ * What became of a composer that is no longer on screen.
3086
+ *
3087
+ * Nothing in this file closes a composer, so one that has gone was taken by the
3088
+ * person at the keyboard — and sent and discarded look identical from the
3089
+ * Accessibility side. This is the only place that can tell them apart, and it
3090
+ * asks Mail rather than guessing.
3091
+ *
3092
+ * Costs one Apple Event, on a failure path. Deliberately NOT the envelope index:
3093
+ * the index is rebuilt on a schedule and was 47 minutes stale when this bug was
3094
+ * found, so it cannot see a message sent seconds ago.
3095
+ */
3096
+ const sentVerdict = async (runner, accountUuid, subject, since) => {
3097
+ let found;
3098
+ try {
3099
+ found = await runner.run(SENT_SINCE, {
3100
+ accountUuid,
3101
+ subject,
3102
+ sinceMs: since - SENT_SLACK_MS
3103
+ });
3104
+ } catch {
3105
+ return {
3106
+ sent: null,
3107
+ sentence: "Whether it was sent could NOT be checked from here — Mail would not answer for its Sent mailbox. Look there for this subject before retrying: a retry after a send that did go sends it twice."
3108
+ };
3109
+ }
3110
+ if (found.checked !== true) return {
3111
+ sent: null,
3112
+ sentence: "Whether it was sent could NOT be checked from here — no Sent mailbox could be resolved. Look for this subject in Sent before retrying: a retry after a send that did go sends it twice."
3113
+ };
3114
+ if (found.found === true) {
3115
+ const when = found.messages?.[0]?.dateSent ?? found.messages?.[0]?.dateReceived ?? "just now";
3116
+ return {
3117
+ sent: true,
3118
+ sentence: `It WAS SENT: a message with this subject is in ${found.mailbox ?? "Sent"}, dated ${when}. Do NOT send it again. Its body was never read back from the window, so what went out is not verified from here — open it in ${found.mailbox ?? "Sent"} to see what it actually says.`
3119
+ };
3120
+ }
3121
+ const newest = found.newest ? Date.parse(found.newest) : NaN;
3122
+ if (!Number.isNaN(newest) && newest < since - SENT_SLACK_MS) return {
3123
+ sent: null,
3124
+ sentence: `Whether it was sent could NOT be told: the ${found.scanned ?? 0} messages read back from ${found.mailbox ?? "Sent"} are all older than this call (newest ${found.newest}), so that listing never showed recent mail. Check Sent yourself before retrying.`
3125
+ };
3126
+ return {
3127
+ sent: false,
3128
+ sentence: `It does NOT appear to have been sent: no message with this subject is among the ${found.scanned ?? 0} most recent in ${found.mailbox ?? "Sent"}. So it was most likely closed or discarded rather than sent. Confirm in Sent before retrying.`
3129
+ };
3130
+ };
2745
3131
  const replyOrForwardNatively = async (lane, runner, params, opts = {}) => {
2746
3132
  const clipboard = opts.clipboard ?? systemClipboard;
2747
3133
  const composerTimeoutMs = opts.composerTimeoutMs ?? COMPOSER_TIMEOUT_MS;
2748
3134
  const sendTimeoutMs = opts.sendTimeoutMs ?? SEND_TIMEOUT_MS;
2749
3135
  const watch = lane.watch();
3136
+ const startedAt = Date.now();
2750
3137
  const reach = await lane.reach();
2751
3138
  if (!reach.ok) throw new Error(MailAxLane.grantMessage(params.mode));
2752
3139
  const subject = (await runner.run(OPEN_COMPOSER, params)).subject;
3140
+ /**
3141
+ * A composer under this subject was open BEFORE this call opened one.
3142
+ *
3143
+ * The subject is the only identity the native half has, and it stops being
3144
+ * one the moment a composer from an earlier call survives — which is routine,
3145
+ * because nothing here ever closes one. The incident, 2026-09-10: Mail keeps
3146
+ * composers as tabs, the leftover was readable before the new one was, and
3147
+ * the title matched it first. ⌘V went to the composer Mail had in front, the
3148
+ * read-back went to the leftover, and a reply that was fine came back as
3149
+ * "SOMETHING DID land in it that could not be read back". With `sendNow` the
3150
+ * send shortcut would have named the leftover too: the wrong message sent,
3151
+ * which is the one failure this path is built to refuse.
3152
+ *
3153
+ * Refused rather than disambiguated. Handles are minted per call, so there is
3154
+ * nothing to tell the two apart by, and a guess here is a guess about which
3155
+ * message to send. The pre-flight list is the one moment the new composer
3156
+ * provably was not on screen.
3157
+ */
3158
+ if ((reach.windows ?? []).includes(subject)) return {
3159
+ ok: false,
3160
+ subject,
3161
+ bodyVerified: null,
3162
+ verifiedChars: 0,
3163
+ sent: false,
3164
+ note: `A ${params.mode} window titled "${subject}" was already open in Mail before this call, most likely left by an earlier attempt, and this call has now opened another. With two under one title this path cannot tell which one it opened, so nothing was pasted, pressed or sent. The one just opened has no text above the quoted message. Close it, finish or discard the older one, then retry.` + interferenceNote(await watch.check())
3165
+ };
2753
3166
  const ref = await lane.findComposer(subject, composerTimeoutMs);
2754
3167
  if (!ref) return {
2755
3168
  ok: false,
@@ -2759,22 +3172,57 @@ const replyOrForwardNatively = async (lane, runner, params, opts = {}) => {
2759
3172
  sent: false,
2760
3173
  note: `Mail was asked to open a ${params.mode} window for "${subject}" and no such window was readable within ${composerTimeoutMs / 1e3}s, although Mail's other windows read fine — so this is not a permission. Nothing was written. The window may still be on screen: look for an empty ${params.mode} in Mail before retrying, because a retry would leave a second one behind. Windows visible at the time: ${JSON.stringify(reach.windows)}.` + interferenceNote(await watch.check())
2761
3174
  };
3175
+ /**
3176
+ * The composer is no longer on screen, and nothing here closed it.
3177
+ *
3178
+ * Which makes this someone else's doing, and the two things they can have done
3179
+ * — sent it, discarded it — leave exactly the same empty screen. Saying "the
3180
+ * body did not go in" here is what shipped, and it was wrong in every part: it
3181
+ * named the body as the failure when the body was fine, and forbade the retry
3182
+ * on double-paste grounds when the real hazard was sending the mail twice.
3183
+ */
3184
+ const vanished = async (knownBody = null) => {
3185
+ const verdict = await sentVerdict(runner, params.accountUuid, subject, startedAt);
3186
+ return {
3187
+ ok: false,
3188
+ subject,
3189
+ bodyVerified: knownBody?.verified ?? null,
3190
+ verifiedChars: knownBody?.chars ?? 0,
3191
+ sent: verdict.sent,
3192
+ note: `The ${params.mode} window for "${subject}" is GONE. Nothing here closed it — this path never discards a composer — so someone using the Mac sent it or closed it while this was running. ${verdict.sentence}` + interferenceNote(await watch.check())
3193
+ };
3194
+ };
2762
3195
  let bodyVerified = null;
2763
3196
  let verifiedChars = 0;
2764
3197
  if (params.body) {
2765
3198
  const result = await paste(lane, clipboard, ref, params.body, opts.focusTimeoutMs);
2766
3199
  bodyVerified = result.verified;
2767
3200
  verifiedChars = result.verified ? Math.min(params.body.length, VERIFY_CHARS) : 0;
2768
- if (!result.verified) return {
2769
- ok: false,
2770
- subject,
2771
- bodyVerified: false,
2772
- verifiedChars: 0,
2773
- sent: false,
2774
- note: `The ${params.mode} window for "${subject}" was opened and correctly addressed, but the body did not go in: reading the composer back does not show the text that was sent. It MUST NOT be described to the user as ready. ` + (result.landed ? "SOMETHING DID land in it that could not be read back — look at it in Mail before retrying, because a retry would paste the reply in twice." : "Nothing landed in it. It was left open rather than discarded, because closing an unsaved composer raises a save sheet whose buttons are localised. Close it in Mail, then retry.") + interferenceNote(await watch.check())
2775
- };
3201
+ if (!result.verified) {
3202
+ if (await lane.composerGone(subject, 0)) return vanished();
3203
+ return {
3204
+ ok: false,
3205
+ subject,
3206
+ bodyVerified: false,
3207
+ verifiedChars: 0,
3208
+ sent: false,
3209
+ note: `The ${params.mode} window for "${subject}" was opened and correctly addressed, but the body did not go in: reading the composer back does not show the text that was sent. It MUST NOT be described to the user as ready. ` + (result.landed === "no" ? "Nothing landed in it. It was left open rather than discarded, because closing an unsaved composer raises a save sheet whose buttons are localised. Close it in Mail, then retry." : result.landed === "yes" ? "SOMETHING DID land in it that could not be read back — look at it in Mail before retrying, because a retry would paste the reply in twice." : "The window is still there but its body could not be READ, so whether anything landed is unknown — look at it in Mail before retrying, because a retry would paste the reply in twice.") + interferenceNote(await watch.check())
3210
+ };
3211
+ }
2776
3212
  }
2777
- await lane.finish(params.sendNow);
3213
+ const finished = await lane.finish(params.sendNow, ref);
3214
+ if (finished === "gone") return vanished(bodyVerified === true ? {
3215
+ verified: true,
3216
+ chars: verifiedChars
3217
+ } : null);
3218
+ if (finished === "refused") return {
3219
+ ok: false,
3220
+ subject,
3221
+ bodyVerified,
3222
+ verifiedChars,
3223
+ sent: false,
3224
+ note: `The ${params.mode} for "${subject}" was composed, but Mail could not be brought to the front, so nothing was pressed and it was not ${params.sendNow ? "sent" : "saved"}. Its window is still open in Mail. Someone is probably using the Mac; retry once it is free, or finish it in Mail.` + interferenceNote(await watch.check())
3225
+ };
2778
3226
  const sent = params.sendNow ? await lane.composerGone(subject, sendTimeoutMs) : false;
2779
3227
  return {
2780
3228
  ok: params.sendNow ? sent : true,
@@ -3133,142 +3581,6 @@ var EnvelopeIndex = class EnvelopeIndex {
3133
3581
  }
3134
3582
  };
3135
3583
  //#endregion
3136
- //#region src/client/jxa/read.ts
3137
- /** Accounts, their UUIDs, on-disk directories and mailbox names. ~0.6s for 4 accounts. */
3138
- const LIST_ACCOUNTS = script(`
3139
- var accts = M.accounts();
3140
- var out = [];
3141
- for (var i = 0; i < accts.length; i++) {
3142
- var a = accts[i];
3143
- out.push({
3144
- id: prop(function () { return a.id(); }, null),
3145
- name: prop(function () { return a.name(); }, null),
3146
- enabled: prop(function () { return a.enabled(); }, null),
3147
- accountType: prop(function () { return String(a.accountType()); }, null),
3148
- emailAddresses: prop(function () { return a.emailAddresses(); }, []),
3149
- fullName: prop(function () { return a.fullName(); }, null),
3150
- // Path objects need String(); JSON.stringify renders them as {}.
3151
- directory: prop(function () { return String(a.accountDirectory()); }, null),
3152
- messageCaching: prop(function () { return String(a.messageCaching()); }, null),
3153
- mailboxes: prop(function () { return a.mailboxes().map(function (m) { return m.name(); }); }, [])
3154
- });
3155
- }
3156
- return ok(out);
3157
- `);
3158
- /**
3159
- * Mailboxes with counts. Counts come from AppleScript rather than the index
3160
- * because they are cheap here (76ms unread / 295ms total on a 29k mailbox) and
3161
- * therefore never need to degrade when Full Disk Access is missing.
3162
- */
3163
- const LIST_MAILBOXES = script(`
3164
- var accts = M.accounts();
3165
- var out = [];
3166
- for (var i = 0; i < accts.length; i++) {
3167
- var a = accts[i];
3168
- var uuid = prop(function () { return a.id(); }, null);
3169
- if (p.accountUuids && p.accountUuids.length && p.accountUuids.indexOf(uuid) === -1) continue;
3170
- var boxes = a.mailboxes();
3171
- for (var j = 0; j < boxes.length; j++) {
3172
- var b = boxes[j];
3173
- var entry = {
3174
- accountUuid: uuid,
3175
- accountName: prop(function () { return a.name(); }, null),
3176
- name: prop(function () { return b.name(); }, null)
3177
- };
3178
- if (p.withCounts) {
3179
- entry.unread = prop(function () { return b.unreadCount(); }, null);
3180
- entry.total = prop(function () { return b.messages.length; }, null);
3181
- }
3182
- out.push(entry);
3183
- }
3184
- }
3185
- return ok(out);
3186
- `);
3187
- /** Total and unread for one mailbox. */
3188
- const COUNT_MAILBOX = script(`
3189
- var acct = findAccount(M, p.accountUuid);
3190
- if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
3191
- var mb = resolveMailbox(acct, p.mailbox);
3192
- if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
3193
- return ok({
3194
- accountUuid: p.accountUuid,
3195
- mailbox: prop(function () { return mb.name(); }, p.mailbox),
3196
- total: prop(function () { return mb.messages.length; }, null),
3197
- unread: prop(function () { return mb.unreadCount(); }, null)
3198
- });
3199
- `);
3200
- /**
3201
- * The degraded listing lane: newest N of one mailbox, used when the Envelope
3202
- * Index is unavailable. Costs roughly 130ms + 42ms per message per property,
3203
- * which is why the caller caps N hard (default 50) instead of paginating.
3204
- */
3205
- const LIST_RECENT = script(`
3206
- var acct = findAccount(M, p.accountUuid);
3207
- if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
3208
- var mb = resolveMailbox(acct, p.mailbox);
3209
- if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
3210
- var mailboxName = prop(function () { return mb.name(); }, p.mailbox);
3211
-
3212
- var total = prop(function () { return mb.messages.length; }, 0);
3213
- var n = Math.min(p.limit || 20, total);
3214
- if (n <= 0) return ok({ mailbox: mailboxName, total: total, messages: [] });
3215
-
3216
- // Batch the property reads: one Apple Event per property beats one per message
3217
- // by roughly 6x. slice() on the message collection keeps it to a range specifier.
3218
- var slice = mb.messages.slice(0, n);
3219
- var subjects = prop(function () { return slice.subject(); }, []);
3220
- var senders = prop(function () { return slice.sender(); }, []);
3221
- var dates = prop(function () { return slice.dateReceived(); }, []);
3222
- var reads = prop(function () { return slice.readStatus(); }, []);
3223
- var flags = prop(function () { return slice.flaggedStatus(); }, []);
3224
- var ids = prop(function () { return slice.id(); }, []);
3225
-
3226
- var out = [];
3227
- for (var i = 0; i < n; i++) {
3228
- out.push({
3229
- id: ids[i] === undefined ? null : ids[i],
3230
- accountUuid: p.accountUuid,
3231
- mailbox: mailboxName,
3232
- subject: subjects[i] === undefined ? null : subjects[i],
3233
- sender: senders[i] === undefined ? null : senders[i],
3234
- dateReceived: iso(dates[i]),
3235
- read: reads[i] === undefined ? null : reads[i],
3236
- flagged: flags[i] === undefined ? null : flags[i]
3237
- });
3238
- }
3239
- return ok({ mailbox: mailboxName, total: total, messages: out });
3240
- `);
3241
- /** Resolve a batch of message ids inside one mailbox. ~0.1s even on a 29k mailbox. */
3242
- const GET_MESSAGES = script(`
3243
- var acct = findAccount(M, p.accountUuid);
3244
- if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
3245
- var mb = resolveMailbox(acct, p.mailbox);
3246
- if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
3247
- var mailboxName = prop(function () { return mb.name(); }, p.mailbox);
3248
-
3249
- var out = [];
3250
- for (var i = 0; i < p.ids.length; i++) {
3251
- var id = p.ids[i];
3252
- try {
3253
- var m = mb.messages.byId(id);
3254
- var summary = messageSummary(m, p.accountUuid, mailboxName);
3255
- if (p.withContent) {
3256
- summary.content = prop(function () { return m.content(); }, null);
3257
- }
3258
- if (p.withSource) {
3259
- summary.source = prop(function () { return m.source(); }, null);
3260
- }
3261
- if (p.withHeaders) {
3262
- summary.allHeaders = prop(function () { return m.allHeaders(); }, null);
3263
- }
3264
- out.push(summary);
3265
- } catch (e) {
3266
- out.push({ id: id, found: false, error: String(e && e.message ? e.message : e) });
3267
- }
3268
- }
3269
- return ok(out);
3270
- `);
3271
- //#endregion
3272
3584
  //#region src/client/mailbox-map.ts
3273
3585
  var MailboxMap = class {
3274
3586
  #runner;
@@ -4837,7 +5149,7 @@ const registerComposeTools = (server, client) => {
4837
5149
  });
4838
5150
  }));
4839
5151
  server.registerTool("apple_mail_reply_to_message", {
4840
- description: "Reply to a message. By default it opens a draft in Mail with the original quoted beneath your text, for the user to review. Pass replyToAll to include every original recipient. Only pass sendNow: true (with confirm: true) when explicitly asked to send now. Success means the body was read back out of the composer window and matched; an error means the draft is EMPTY and must not be described to the user as ready. Filling the composer brings Mail to the front for a moment and borrows the clipboard, both of which are put back.",
5152
+ description: "Reply to a message. By default it opens a draft in Mail with the original quoted beneath your text, for the user to review. Pass replyToAll to include every original recipient. Only pass sendNow: true (with confirm: true) when explicitly asked to send now. Success means the body was read back out of the composer window and matched, and only then may it be described to the user as ready. A failure is NOT automatically an empty draft: read the note, which says what was actually found — including that the composer was taken by someone using the Mac, in which case the reply may already have been SENT and a retry would send it twice. Filling the composer brings Mail to the front for a moment and borrows the clipboard, both of which are put back.",
4841
5153
  inputSchema: {
4842
5154
  ref: messageRefArg,
4843
5155
  body: bodyArg,
@@ -5288,4 +5600,4 @@ const createServer = (opts) => {
5288
5600
  //#endregion
5289
5601
  export { WritesDisabledError as A, MessageNotFoundError as C, ProtocolError as D, PreconditionError as E, SchemaDriftError as O, MailNotRunningError as S, PlatformError as T, locateEnvelopeIndex as _, loadConfig as a, MAIL_SURFACE as b, decodeRef as c, assertStaticScript as d, createOsascriptRunner as f, inspectFile as g, MailboxMap as h, registerTools as i, BUILD_INFO as j, TccDeniedError as k, encodeRef as l, withBusyRetry as m, SERVER_VERSION as n, AppleMailClient as o, mapOsaError as p, createServer as r, REF_VERSION as s, SERVER_NAME as t, groupRefsByMailbox as u, AppleMailError as v, OsascriptTimeoutError as w, MailBusyError as x, IndexUnavailableError as y };
5290
5602
 
5291
- //# sourceMappingURL=server-DdKWlMP9.js.map
5603
+ //# sourceMappingURL=server-Bk26ykNa.js.map