@mgcrea/mcp-apple-mail 1.20.1 → 1.21.0

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: "0281ea0",
18
+ gitCommitDate: "2026-09-10T16:16:14+02:00"
19
19
  };
20
20
  //#endregion
21
21
  //#region src/client/errors.ts
@@ -327,6 +327,16 @@ var MailAxLane = class MailAxLane {
327
327
  * `matched` rather than the returned length, because the response is byte
328
328
  * capped and a long quoted message will truncate — a fingerprint taken from a
329
329
  * truncated list would compare two different bounds rather than two states.
330
+ *
331
+ * **Null when the body cannot be read at all, and that is the whole point.**
332
+ * This returned -1 for a failed read, and the caller compared it as a count.
333
+ * A composer that CLOSES takes its element handle with it — the driver answers
334
+ * `staleHandle` — so a body that had gone in perfectly read back as -1 and
335
+ * compared unequal to the size before, which is the signature of "something
336
+ * landed that cannot be matched". A reply sent by hand mid-call was reported
337
+ * as a body that never went in, with a warning against the retry that was in
338
+ * fact the safe move. Blind and different are not the same answer, exactly as
339
+ * `bodyText` above insists, and this is where that was forgotten.
330
340
  */
331
341
  async bodySize(body) {
332
342
  try {
@@ -337,7 +347,7 @@ var MailAxLane = class MailAxLane {
337
347
  });
338
348
  return tree.matched ?? (tree.elements ?? []).length;
339
349
  } catch {
340
- return -1;
350
+ return null;
341
351
  }
342
352
  }
343
353
  /**
@@ -359,21 +369,33 @@ var MailAxLane = class MailAxLane {
359
369
  *
360
370
  * The guard itself stays. Posting command-V without knowing where the focus is
361
371
  * types into whatever happens to be in front, and that is the user's window.
372
+ *
373
+ * **A composer that has gone answers false rather than throwing.** Both handles
374
+ * die with the window, so raising or focusing one afterwards is a `staleHandle`
375
+ * — and letting that escape turns a describable failure into a bare channel
376
+ * error with no note attached, on the one path whose whole job is to say what
377
+ * happened. False is the honest answer: the focus was not taken, so nothing was
378
+ * typed.
362
379
  */
363
380
  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));
381
+ try {
382
+ await this.#call("raise_window", { handle: ref.window });
383
+ await this.activate();
384
+ const deadline = Date.now() + focusTimeoutMs;
385
+ for (;;) {
386
+ if ((await this.#call("focus", { handle: ref.body })).focused === true) break;
387
+ if (Date.now() >= deadline) return false;
388
+ await new Promise((resolve) => setTimeout(resolve, FOCUS_POLL_MS));
389
+ }
390
+ await this.#call("key", {
391
+ key: "v",
392
+ modifiers: ["command"],
393
+ handle: ref.body
394
+ });
395
+ return true;
396
+ } catch {
397
+ return false;
371
398
  }
372
- await this.#call("key", {
373
- key: "v",
374
- modifiers: ["command"]
375
- });
376
- return true;
377
399
  }
378
400
  /**
379
401
  * Send the composer, or save it as a draft.
@@ -391,15 +413,51 @@ var MailAxLane = class MailAxLane {
391
413
  * alternative and is worse — drafts are discovered by subject, so two with the
392
414
  * same one are indistinguishable, on the single path whose named failure is
393
415
  * sending the wrong thing.
416
+ *
417
+ * **The window is raised again first, and the answer says whether that took.**
418
+ * The focus is only known to be in the composer at the moment of the paste;
419
+ * between the read that verifies the body and this keystroke the person at the
420
+ * keyboard can move the foreground, and command-shift-D would then be posted
421
+ * into whatever they moved to. Re-raising costs two round trips and closes
422
+ * that window.
423
+ *
424
+ * The keystroke also names the composer's window, which closes the gap that
425
+ * remains between the re-raise and the key: the desktop server brings Mail
426
+ * forward again and refuses rather than posting into something else.
427
+ *
428
+ * Only `"pressed"` means anything was pressed. The other two answers are both
429
+ * refusals, and they are kept apart because they mean opposite things to the
430
+ * person reading the result:
431
+ *
432
+ * * `"gone"`: the composer could not be raised. Its handle died with the
433
+ * window, so somebody sent or closed it.
434
+ * * `"refused"`: raised, but the keystroke was refused because Mail would
435
+ * not come forward. The composer is still on screen, unsent.
436
+ *
437
+ * Posting a send into an unknown foreground is the one outcome worth refusing
438
+ * outright, which is why neither of them throws.
394
439
  */
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
- });
440
+ async finish(sendNow, ref) {
441
+ try {
442
+ await this.#call("raise_window", { handle: ref.window });
443
+ await this.activate();
444
+ } catch {
445
+ return "gone";
446
+ }
447
+ try {
448
+ await this.#call("key", sendNow ? {
449
+ key: "d",
450
+ modifiers: ["command", "shift"],
451
+ handle: ref.window
452
+ } : {
453
+ key: "s",
454
+ modifiers: ["command"],
455
+ handle: ref.window
456
+ });
457
+ } catch {
458
+ return "refused";
459
+ }
460
+ return "pressed";
403
461
  }
404
462
  /**
405
463
  * Has the composer for this subject gone?
@@ -1413,7 +1471,26 @@ function collectText(el, depth, acc, budget) {
1413
1471
  * ends up in the draft twice with no way to undo it from here.
1414
1472
  */
1415
1473
  function composerBodySize(body) {
1416
- return prop(function () { return body.entireContents().length; }, -1);
1474
+ return prop(function () { return body.entireContents().length; }, null);
1475
+ }
1476
+
1477
+ /**
1478
+ * Did anything at all reach the composer, comparing two fingerprints?
1479
+ *
1480
+ * Three answers, and the third is the one that was missing. "unknown" is a body
1481
+ * that cannot be READ -- which is what a composer that has CLOSED looks like
1482
+ * from the outside, because its reference dies with the window.
1483
+ *
1484
+ * This returned -1 for an unreadable body and the caller compared it as a
1485
+ * length. Two consequences, both wrong and in opposite directions: -1 against a
1486
+ * real count read as "something landed", so a reply sent by hand mid-call was
1487
+ * reported as a body that never went in; and -1 against -1 read as "nothing
1488
+ * landed", which is the branch that DISCARDS the composer -- destroying a body
1489
+ * that may well have been in it.
1490
+ */
1491
+ function landedVerdict(before, after) {
1492
+ if (before === null || after === null) return "unknown";
1493
+ return after === before ? "no" : "yes";
1417
1494
  }
1418
1495
 
1419
1496
  /**
@@ -1778,6 +1855,220 @@ function run(argv) {
1778
1855
  }
1779
1856
  `;
1780
1857
  //#endregion
1858
+ //#region src/client/jxa/read.ts
1859
+ /** Accounts, their UUIDs, on-disk directories and mailbox names. ~0.6s for 4 accounts. */
1860
+ const LIST_ACCOUNTS = script(`
1861
+ var accts = M.accounts();
1862
+ var out = [];
1863
+ for (var i = 0; i < accts.length; i++) {
1864
+ var a = accts[i];
1865
+ out.push({
1866
+ id: prop(function () { return a.id(); }, null),
1867
+ name: prop(function () { return a.name(); }, null),
1868
+ enabled: prop(function () { return a.enabled(); }, null),
1869
+ accountType: prop(function () { return String(a.accountType()); }, null),
1870
+ emailAddresses: prop(function () { return a.emailAddresses(); }, []),
1871
+ fullName: prop(function () { return a.fullName(); }, null),
1872
+ // Path objects need String(); JSON.stringify renders them as {}.
1873
+ directory: prop(function () { return String(a.accountDirectory()); }, null),
1874
+ messageCaching: prop(function () { return String(a.messageCaching()); }, null),
1875
+ mailboxes: prop(function () { return a.mailboxes().map(function (m) { return m.name(); }); }, [])
1876
+ });
1877
+ }
1878
+ return ok(out);
1879
+ `);
1880
+ /**
1881
+ * Mailboxes with counts. Counts come from AppleScript rather than the index
1882
+ * because they are cheap here (76ms unread / 295ms total on a 29k mailbox) and
1883
+ * therefore never need to degrade when Full Disk Access is missing.
1884
+ */
1885
+ const LIST_MAILBOXES = script(`
1886
+ var accts = M.accounts();
1887
+ var out = [];
1888
+ for (var i = 0; i < accts.length; i++) {
1889
+ var a = accts[i];
1890
+ var uuid = prop(function () { return a.id(); }, null);
1891
+ if (p.accountUuids && p.accountUuids.length && p.accountUuids.indexOf(uuid) === -1) continue;
1892
+ var boxes = a.mailboxes();
1893
+ for (var j = 0; j < boxes.length; j++) {
1894
+ var b = boxes[j];
1895
+ var entry = {
1896
+ accountUuid: uuid,
1897
+ accountName: prop(function () { return a.name(); }, null),
1898
+ name: prop(function () { return b.name(); }, null)
1899
+ };
1900
+ if (p.withCounts) {
1901
+ entry.unread = prop(function () { return b.unreadCount(); }, null);
1902
+ entry.total = prop(function () { return b.messages.length; }, null);
1903
+ }
1904
+ out.push(entry);
1905
+ }
1906
+ }
1907
+ return ok(out);
1908
+ `);
1909
+ /** Total and unread for one mailbox. */
1910
+ const COUNT_MAILBOX = script(`
1911
+ var acct = findAccount(M, p.accountUuid);
1912
+ if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
1913
+ var mb = resolveMailbox(acct, p.mailbox);
1914
+ if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
1915
+ return ok({
1916
+ accountUuid: p.accountUuid,
1917
+ mailbox: prop(function () { return mb.name(); }, p.mailbox),
1918
+ total: prop(function () { return mb.messages.length; }, null),
1919
+ unread: prop(function () { return mb.unreadCount(); }, null)
1920
+ });
1921
+ `);
1922
+ /**
1923
+ * The degraded listing lane: newest N of one mailbox, used when the Envelope
1924
+ * Index is unavailable. Costs roughly 130ms + 42ms per message per property,
1925
+ * which is why the caller caps N hard (default 50) instead of paginating.
1926
+ */
1927
+ const LIST_RECENT = script(`
1928
+ var acct = findAccount(M, p.accountUuid);
1929
+ if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
1930
+ var mb = resolveMailbox(acct, p.mailbox);
1931
+ if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
1932
+ var mailboxName = prop(function () { return mb.name(); }, p.mailbox);
1933
+
1934
+ var total = prop(function () { return mb.messages.length; }, 0);
1935
+ var n = Math.min(p.limit || 20, total);
1936
+ if (n <= 0) return ok({ mailbox: mailboxName, total: total, messages: [] });
1937
+
1938
+ // Batch the property reads: one Apple Event per property beats one per message
1939
+ // by roughly 6x. slice() on the message collection keeps it to a range specifier.
1940
+ var slice = mb.messages.slice(0, n);
1941
+ var subjects = prop(function () { return slice.subject(); }, []);
1942
+ var senders = prop(function () { return slice.sender(); }, []);
1943
+ var dates = prop(function () { return slice.dateReceived(); }, []);
1944
+ var reads = prop(function () { return slice.readStatus(); }, []);
1945
+ var flags = prop(function () { return slice.flaggedStatus(); }, []);
1946
+ var ids = prop(function () { return slice.id(); }, []);
1947
+
1948
+ var out = [];
1949
+ for (var i = 0; i < n; i++) {
1950
+ out.push({
1951
+ id: ids[i] === undefined ? null : ids[i],
1952
+ accountUuid: p.accountUuid,
1953
+ mailbox: mailboxName,
1954
+ subject: subjects[i] === undefined ? null : subjects[i],
1955
+ sender: senders[i] === undefined ? null : senders[i],
1956
+ dateReceived: iso(dates[i]),
1957
+ read: reads[i] === undefined ? null : reads[i],
1958
+ flagged: flags[i] === undefined ? null : flags[i]
1959
+ });
1960
+ }
1961
+ return ok({ mailbox: mailboxName, total: total, messages: out });
1962
+ `);
1963
+ /** Resolve a batch of message ids inside one mailbox. ~0.1s even on a 29k mailbox. */
1964
+ const GET_MESSAGES = script(`
1965
+ var acct = findAccount(M, p.accountUuid);
1966
+ if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
1967
+ var mb = resolveMailbox(acct, p.mailbox);
1968
+ if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
1969
+ var mailboxName = prop(function () { return mb.name(); }, p.mailbox);
1970
+
1971
+ var out = [];
1972
+ for (var i = 0; i < p.ids.length; i++) {
1973
+ var id = p.ids[i];
1974
+ try {
1975
+ var m = mb.messages.byId(id);
1976
+ var summary = messageSummary(m, p.accountUuid, mailboxName);
1977
+ if (p.withContent) {
1978
+ summary.content = prop(function () { return m.content(); }, null);
1979
+ }
1980
+ if (p.withSource) {
1981
+ summary.source = prop(function () { return m.source(); }, null);
1982
+ }
1983
+ if (p.withHeaders) {
1984
+ summary.allHeaders = prop(function () { return m.allHeaders(); }, null);
1985
+ }
1986
+ out.push(summary);
1987
+ } catch (e) {
1988
+ out.push({ id: id, found: false, error: String(e && e.message ? e.message : e) });
1989
+ }
1990
+ }
1991
+ return ok(out);
1992
+ `);
1993
+ /**
1994
+ * Did a message with this subject reach Sent, at or after a given instant?
1995
+ *
1996
+ * The question a failed compose cannot answer for itself. When the composer
1997
+ * window is GONE, nothing in the Accessibility lane can say whether it was sent
1998
+ * or discarded — both leave the same empty screen — and getting that wrong in
1999
+ * either direction is expensive: calling a sent reply a failure invites a retry
2000
+ * that sends it twice, and calling a discarded one sent loses the reply.
2001
+ *
2002
+ * ## Where it looks
2003
+ *
2004
+ * The application-level unified mailbox, not the account's. `docs/mail-compose.md`
2005
+ * measured `account.draftsMailbox` answering "Can't get object." on all four
2006
+ * account types while `application.draftsMailbox` resolves to the unified "All
2007
+ * Drafts", and there is no reason to expect `sentMailbox` to differ. The
2008
+ * documented per-account property is still tried first, so this repairs itself
2009
+ * if Apple ever fixes it.
2010
+ *
2011
+ * Unified is the better target anyway: which account Mail actually sends from is
2012
+ * its own decision, and need not be the account the original was read in.
2013
+ *
2014
+ * ## Why `found: false` is deliberately weak
2015
+ *
2016
+ * The newest messages are taken as the head of the collection, the way
2017
+ * LIST_RECENT does. If a mailbox ever came back oldest-first, the head would be
2018
+ * ancient and nothing would match — a FALSE NEGATIVE on a reply that did go,
2019
+ * which is the dangerous direction. So `newest` is reported alongside: a caller
2020
+ * that sees nothing found AND a newest older than its floor knows the listing
2021
+ * never showed it recent mail, and must say "could not tell" rather than "not
2022
+ * sent".
2023
+ */
2024
+ const SENT_SINCE = script(`
2025
+ var box = null;
2026
+ var acct = p.accountUuid ? findAccount(M, p.accountUuid) : null;
2027
+ // name() forces the event: JXA is lazy, so a specifier that will fail does not
2028
+ // fail until something reads through it.
2029
+ if (acct) box = prop(function () { var b = acct.sentMailbox(); b.name(); return b; }, null);
2030
+ if (!box) box = prop(function () { var b = M.sentMailbox(); b.name(); return b; }, null);
2031
+ if (!box) return ok({ checked: false, reason: "NO_SENT_MAILBOX", found: false, messages: [] });
2032
+
2033
+ var mailbox = prop(function () { return box.name(); }, "Sent");
2034
+ var total = prop(function () { return box.messages.length; }, 0);
2035
+ var n = Math.min(p.limit || 25, total);
2036
+ if (n <= 0) return ok({ checked: true, mailbox: mailbox, total: total, found: false, newest: null, messages: [] });
2037
+
2038
+ // One Apple Event per property rather than one per message, as LIST_RECENT.
2039
+ var slice = box.messages.slice(0, n);
2040
+ var subjects = prop(function () { return slice.subject(); }, []);
2041
+ var sent = prop(function () { return slice.dateSent(); }, []);
2042
+ var received = prop(function () { return slice.dateReceived(); }, []);
2043
+
2044
+ var floor = p.sinceMs ? Number(p.sinceMs) : 0;
2045
+ var wanted = String(p.subject == null ? "" : p.subject);
2046
+ var hits = [];
2047
+ var newest = 0;
2048
+ for (var i = 0; i < n; i++) {
2049
+ var when = sent[i] || received[i];
2050
+ var ms = 0;
2051
+ try { ms = when ? when.getTime() : 0; } catch (e) { ms = 0; }
2052
+ if (ms > newest) newest = ms;
2053
+ if (String(subjects[i] === undefined ? "" : subjects[i]) !== wanted) continue;
2054
+ if (ms && ms < floor) continue;
2055
+ hits.push({
2056
+ subject: subjects[i] === undefined ? null : subjects[i],
2057
+ dateSent: iso(sent[i]),
2058
+ dateReceived: iso(received[i])
2059
+ });
2060
+ }
2061
+ return ok({
2062
+ checked: true,
2063
+ mailbox: mailbox,
2064
+ total: total,
2065
+ scanned: n,
2066
+ found: hits.length > 0,
2067
+ newest: newest ? new Date(newest).toISOString() : null,
2068
+ messages: hits
2069
+ });
2070
+ `);
2071
+ //#endregion
1781
2072
  //#region src/client/jxa/write.ts
1782
2073
  /**
1783
2074
  * Mutating scripts.
@@ -2490,9 +2781,11 @@ const REPLY_OR_FORWARD = script(`
2490
2781
  bodyVerified = after !== null && containsText(after, expected);
2491
2782
  if (bodyVerified) {
2492
2783
  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.
2784
+ } else if (landedVerdict(sizeBefore, composerBodySize(bodyArea)) !== "no") {
2785
+ // Something went in that we cannot match, or the body can no longer be
2786
+ // read at all. Pasting again would put the reply in the draft twice,
2787
+ // and nothing here can undo that -- so an UNKNOWN reading stops the
2788
+ // retry just as firmly as a changed one.
2496
2789
  break;
2497
2790
  }
2498
2791
  }
@@ -2502,12 +2795,37 @@ const REPLY_OR_FORWARD = script(`
2502
2795
 
2503
2796
  if (!bodyVerified) {
2504
2797
  restore();
2798
+
2799
+ // A composer that has GONE reads exactly like one whose body is
2800
+ // unreadable, and only this tells them apart. Nothing here closes a
2801
+ // composer before this point, so one that is missing was taken by the
2802
+ // person at the keyboard -- and sent and discarded leave the same empty
2803
+ // screen. Saying "the body did not go in" here named the wrong failure and
2804
+ // forbade the wrong retry: the hazard is sending the mail twice, not
2805
+ // pasting it twice.
2806
+ //
2807
+ // The native path (client/compose.ts) goes on to ask Mail whether the
2808
+ // message reached Sent. This one only says where to look -- it is the
2809
+ // fallback for a server not hosted by Cupertino, and a second mailbox scan
2810
+ // inside this script is not worth the surface.
2811
+ if (composerWindow(proc, subject, 0) === null) {
2812
+ return err(
2813
+ "COMPOSER_GONE",
2814
+ "The " + p.mode + " window for \\"" + subject + "\\" is GONE. Nothing here closed it — " +
2815
+ "this path discards a composer only when it is provably empty — so someone using the " +
2816
+ "Mac sent it or closed it while this was running. Whether it went cannot be told from " +
2817
+ "here: LOOK IN SENT for this subject before retrying, because a retry after a send " +
2818
+ "that did go sends it twice."
2819
+ );
2820
+ }
2821
+
2505
2822
  // Take the window back only when it is provably still empty. A paste that
2506
2823
  // landed and could not be READ is a different thing from one that never
2507
2824
  // 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);
2825
+ // it back -- so it is left on screen for the user to judge. An UNKNOWN
2826
+ // reading counts as "may have landed" for exactly the same reason.
2827
+ var landed = landedVerdict(sizeBefore, composerBodySize(bodyArea));
2828
+ var closedUnverified = landed === "no" ? discardComposer(M, draft) : false;
2511
2829
  return err(
2512
2830
  "DRAFT_BODY_NOT_SET",
2513
2831
  "The " + p.mode + " window for \\"" + subject + "\\" was opened and correctly addressed, but the " +
@@ -2515,12 +2833,16 @@ const REPLY_OR_FORWARD = script(`
2515
2833
  "MUST NOT be described to the user as ready. " +
2516
2834
  (closedUnverified
2517
2835
  ? "Nothing had landed in it, so it was closed again without saving and a retry is safe."
2518
- : landed
2836
+ : landed === "yes"
2519
2837
  ? "SOMETHING DID land in it that could not be read back, so it was left open rather " +
2520
2838
  "than discarded — look at it in Mail before retrying, because a retry would paste " +
2521
2839
  "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.")
2840
+ : landed === "unknown"
2841
+ ? "The window is still there but its body could not be READ, so whether anything " +
2842
+ "landed is unknown. It was left open rather than discarded — look at it in Mail " +
2843
+ "before retrying, because a retry would paste the reply in twice."
2844
+ : "It could NOT be closed from here — close it in Mail before retrying, or the retry " +
2845
+ "leaves a second draft behind.")
2524
2846
  );
2525
2847
  }
2526
2848
  }
@@ -2686,6 +3008,20 @@ const SEND_TIMEOUT_MS = 5e3;
2686
3008
  * so the top of it is the tell.
2687
3009
  */
2688
3010
  const VERIFY_CHARS = 400;
3011
+ /**
3012
+ * How far back to accept a message in Sent as this call's.
3013
+ *
3014
+ * Generous on purpose. `dateSent` and the moment the row appears are not the
3015
+ * same instant — a real send measured 16s between them — and the cost of the two
3016
+ * errors is lopsided: a window slightly too wide names a message that was
3017
+ * already there, which a reader can see and dismiss; one too narrow reports a
3018
+ * reply that DID go as missing, and invites sending it again.
3019
+ */
3020
+ const SENT_SLACK_MS = 12e4;
3021
+ const compare = (before, after) => {
3022
+ if (before === null || after === null) return "unknown";
3023
+ return after === before ? "no" : "yes";
3024
+ };
2689
3025
  const systemClipboard = {
2690
3026
  async read() {
2691
3027
  try {
@@ -2731,22 +3067,70 @@ const paste = async (lane, clipboard, ref, text, focusTimeoutMs) => {
2731
3067
  const after = await lane.bodyText(ref.body);
2732
3068
  if (after !== null && containsText(after, expected)) return {
2733
3069
  verified: true,
2734
- landed: true
3070
+ landed: "yes"
2735
3071
  };
2736
3072
  }
2737
- if (await lane.bodySize(ref.body) !== sizeBefore) break;
3073
+ if (compare(sizeBefore, await lane.bodySize(ref.body)) !== "no") break;
2738
3074
  }
2739
3075
  return {
2740
3076
  verified: false,
2741
- landed: await lane.bodySize(ref.body) !== sizeBefore
3077
+ landed: compare(sizeBefore, await lane.bodySize(ref.body))
2742
3078
  };
2743
3079
  });
2744
3080
  };
3081
+ /**
3082
+ * What became of a composer that is no longer on screen.
3083
+ *
3084
+ * Nothing in this file closes a composer, so one that has gone was taken by the
3085
+ * person at the keyboard — and sent and discarded look identical from the
3086
+ * Accessibility side. This is the only place that can tell them apart, and it
3087
+ * asks Mail rather than guessing.
3088
+ *
3089
+ * Costs one Apple Event, on a failure path. Deliberately NOT the envelope index:
3090
+ * the index is rebuilt on a schedule and was 47 minutes stale when this bug was
3091
+ * found, so it cannot see a message sent seconds ago.
3092
+ */
3093
+ const sentVerdict = async (runner, accountUuid, subject, since) => {
3094
+ let found;
3095
+ try {
3096
+ found = await runner.run(SENT_SINCE, {
3097
+ accountUuid,
3098
+ subject,
3099
+ sinceMs: since - SENT_SLACK_MS
3100
+ });
3101
+ } catch {
3102
+ return {
3103
+ sent: null,
3104
+ 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."
3105
+ };
3106
+ }
3107
+ if (found.checked !== true) return {
3108
+ sent: null,
3109
+ 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."
3110
+ };
3111
+ if (found.found === true) {
3112
+ const when = found.messages?.[0]?.dateSent ?? found.messages?.[0]?.dateReceived ?? "just now";
3113
+ return {
3114
+ sent: true,
3115
+ 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.`
3116
+ };
3117
+ }
3118
+ const newest = found.newest ? Date.parse(found.newest) : NaN;
3119
+ if (!Number.isNaN(newest) && newest < since - SENT_SLACK_MS) return {
3120
+ sent: null,
3121
+ 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.`
3122
+ };
3123
+ return {
3124
+ sent: false,
3125
+ 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.`
3126
+ };
3127
+ };
2745
3128
  const replyOrForwardNatively = async (lane, runner, params, opts = {}) => {
2746
3129
  const clipboard = opts.clipboard ?? systemClipboard;
2747
3130
  const composerTimeoutMs = opts.composerTimeoutMs ?? COMPOSER_TIMEOUT_MS;
2748
3131
  const sendTimeoutMs = opts.sendTimeoutMs ?? SEND_TIMEOUT_MS;
2749
3132
  const watch = lane.watch();
3133
+ const startedAt = Date.now();
2750
3134
  const reach = await lane.reach();
2751
3135
  if (!reach.ok) throw new Error(MailAxLane.grantMessage(params.mode));
2752
3136
  const subject = (await runner.run(OPEN_COMPOSER, params)).subject;
@@ -2759,22 +3143,57 @@ const replyOrForwardNatively = async (lane, runner, params, opts = {}) => {
2759
3143
  sent: false,
2760
3144
  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
3145
  };
3146
+ /**
3147
+ * The composer is no longer on screen, and nothing here closed it.
3148
+ *
3149
+ * Which makes this someone else's doing, and the two things they can have done
3150
+ * — sent it, discarded it — leave exactly the same empty screen. Saying "the
3151
+ * body did not go in" here is what shipped, and it was wrong in every part: it
3152
+ * named the body as the failure when the body was fine, and forbade the retry
3153
+ * on double-paste grounds when the real hazard was sending the mail twice.
3154
+ */
3155
+ const vanished = async (knownBody = null) => {
3156
+ const verdict = await sentVerdict(runner, params.accountUuid, subject, startedAt);
3157
+ return {
3158
+ ok: false,
3159
+ subject,
3160
+ bodyVerified: knownBody?.verified ?? null,
3161
+ verifiedChars: knownBody?.chars ?? 0,
3162
+ sent: verdict.sent,
3163
+ 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())
3164
+ };
3165
+ };
2762
3166
  let bodyVerified = null;
2763
3167
  let verifiedChars = 0;
2764
3168
  if (params.body) {
2765
3169
  const result = await paste(lane, clipboard, ref, params.body, opts.focusTimeoutMs);
2766
3170
  bodyVerified = result.verified;
2767
3171
  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
- };
3172
+ if (!result.verified) {
3173
+ if (await lane.composerGone(subject, 0)) return vanished();
3174
+ return {
3175
+ ok: false,
3176
+ subject,
3177
+ bodyVerified: false,
3178
+ verifiedChars: 0,
3179
+ sent: false,
3180
+ 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())
3181
+ };
3182
+ }
2776
3183
  }
2777
- await lane.finish(params.sendNow);
3184
+ const finished = await lane.finish(params.sendNow, ref);
3185
+ if (finished === "gone") return vanished(bodyVerified === true ? {
3186
+ verified: true,
3187
+ chars: verifiedChars
3188
+ } : null);
3189
+ if (finished === "refused") return {
3190
+ ok: false,
3191
+ subject,
3192
+ bodyVerified,
3193
+ verifiedChars,
3194
+ sent: false,
3195
+ 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())
3196
+ };
2778
3197
  const sent = params.sendNow ? await lane.composerGone(subject, sendTimeoutMs) : false;
2779
3198
  return {
2780
3199
  ok: params.sendNow ? sent : true,
@@ -3133,142 +3552,6 @@ var EnvelopeIndex = class EnvelopeIndex {
3133
3552
  }
3134
3553
  };
3135
3554
  //#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
3555
  //#region src/client/mailbox-map.ts
3273
3556
  var MailboxMap = class {
3274
3557
  #runner;
@@ -4837,7 +5120,7 @@ const registerComposeTools = (server, client) => {
4837
5120
  });
4838
5121
  }));
4839
5122
  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.",
5123
+ 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
5124
  inputSchema: {
4842
5125
  ref: messageRefArg,
4843
5126
  body: bodyArg,
@@ -5288,4 +5571,4 @@ const createServer = (opts) => {
5288
5571
  //#endregion
5289
5572
  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
5573
 
5291
- //# sourceMappingURL=server-DdKWlMP9.js.map
5574
+ //# sourceMappingURL=server-CcHy5Pw4.js.map