@mgcrea/mcp-apple-mail 1.20.0 → 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: "33c4728",
18
- gitCommitDate: "2026-09-08T22:33:17+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?
@@ -667,15 +725,32 @@ const parsePart = (buf) => {
667
725
  const splitMultipart = (body, boundary) => {
668
726
  const text = body.toString("latin1");
669
727
  const marker = `--${boundary}`;
728
+ /**
729
+ * RFC 2046: a delimiter starts a line, and nothing follows it but the closing
730
+ * `--` or the end of that line. Both halves earn their keep. Without the
731
+ * first, a body that merely quotes the delimiter splits the part it sits in.
732
+ * Without the second, `--B` also matches inside `--B2`, which flattened a
733
+ * nested multipart into its parent's sibling list — harmless while only one
734
+ * part was ever read, and a doubled body the moment the parts are joined.
735
+ */
736
+ const isDelimiter = (at) => {
737
+ if (at !== 0 && text[at - 1] !== "\n") return false;
738
+ const after = text[at + marker.length];
739
+ return after === void 0 || after === "\r" || after === "\n" || after === "-";
740
+ };
741
+ const find = (from) => {
742
+ let at = text.indexOf(marker, from);
743
+ while (at !== -1 && !isDelimiter(at)) at = text.indexOf(marker, at + 1);
744
+ return at;
745
+ };
670
746
  const segments = [];
671
- let index = text.indexOf(marker);
747
+ let index = find(0);
672
748
  if (index === -1) return [];
673
749
  while (index !== -1) {
674
750
  const afterMarker = index + marker.length;
675
751
  if (text.startsWith("--", afterMarker)) break;
676
- const start = afterMarker;
677
- const next = text.indexOf(marker, start);
678
- segments.push(text.slice(start, next === -1 ? void 0 : next).replace(/^\r?\n/, ""));
752
+ const next = find(afterMarker);
753
+ segments.push(text.slice(afterMarker, next === -1 ? void 0 : next).replace(/^\r?\n/, ""));
679
754
  if (next === -1) break;
680
755
  index = next;
681
756
  }
@@ -696,37 +771,97 @@ const partBytes = (part) => {
696
771
  /** Decode one leaf part's body into text. */
697
772
  const partText = (part) => decodeCharset(partBytes(part), part.charset);
698
773
  /** Very small HTML-to-text pass: enough to read a marketing email, not a renderer. */
699
- const htmlToText = (html) => html.replaceAll(/<(script|style)[^>]*>[\s\S]*?<\/\1>/gi, "").replaceAll(/<br\s*\/?>/gi, "\n").replaceAll(/<\/(p|div|tr|h[1-6]|li)>/gi, "\n").replaceAll(/<li[^>]*>/gi, "- ").replaceAll(/<[^>]+>/g, "").replaceAll("&nbsp;", " ").replaceAll("&amp;", "&").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", "\"").replaceAll("&#39;", "'").replaceAll(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d))).replaceAll(/[ \t]+\n/g, "\n").replaceAll(/\n{3,}/g, "\n\n").trim();
774
+ const htmlToText = (html) => html.replaceAll(/<(script|style)[^>]*>[\s\S]*?<\/\1>/gi, "").replaceAll(/<(script|style)[^>]*>[\s\S]*$/gi, "").replaceAll(/<br\s*\/?>/gi, "\n").replaceAll(/<\/(p|div|tr|h[1-6]|li)>/gi, "\n").replaceAll(/<li[^>]*>/gi, "- ").replaceAll(/<[^>]+>/g, "").replaceAll(/<\/?[a-zA-Z][^>]*$/g, "").replaceAll("&nbsp;", " ").replaceAll("&amp;", "&").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", "\"").replaceAll("&#39;", "'").replaceAll(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d))).replaceAll(/[ \t]+\n/g, "\n").replaceAll(/\n{3,}/g, "\n\n").trim();
700
775
  const walk = (part, visit) => {
701
776
  visit(part);
702
777
  for (const child of part.parts) walk(child, visit);
703
778
  };
704
779
  /**
705
- * Pick the body a person would want to read: the first text/plain that is not
706
- * an attachment, else the first text/html converted to text.
780
+ * Is this part a file rather than something to read?
781
+ *
782
+ * Deliberately shared with `listAttachments`. The two used to disagree — this
783
+ * one excluded only `disposition: attachment`, that one also counted any
784
+ * non-multipart part carrying a filename — and the disagreement was harmless
785
+ * only because a single part was ever chosen as the body. Joining the parts
786
+ * made it visible, as an attached notes.txt landing in the mail it came with.
707
787
  */
708
- const bestBody = (root) => {
709
- let plain = null;
710
- let html = null;
711
- walk(root, (p) => {
712
- if (p.disposition === "attachment") return;
713
- if (!plain && p.contentType === "text/plain") plain = p;
714
- if (!html && p.contentType === "text/html") html = p;
715
- });
716
- if (plain) return {
717
- text: partText(plain).trim(),
788
+ const isAttachmentPart = (p) => p.disposition === "attachment" || p.filename !== null && !p.contentType.startsWith("multipart/");
789
+ const NOTHING = {
790
+ segments: [],
791
+ from: "none"
792
+ };
793
+ const hasText = (r) => r.segments.some((s) => s.kind === "text" && s.text.trim() !== "");
794
+ /** `[image: shot.png]` — house style is the truncation marker's: label, colon, fact. */
795
+ const markerFor = (p) => ({
796
+ kind: "marker",
797
+ text: `[${p.contentType.startsWith("image/") ? "image" : "attachment"}: ${p.filename ?? p.contentType}]`
798
+ });
799
+ /**
800
+ * Resolve one subtree to the runs a person would read, in document order.
801
+ *
802
+ * The container decides. `multipart/alternative` children are competing
803
+ * renderings of one thing, so exactly one is taken; every other multipart holds
804
+ * sequential content, so the children are spliced in order. A flat walk that
805
+ * gathered all the text parts would read the interleaved message correctly and
806
+ * emit a plain+html alternative twice.
807
+ */
808
+ const resolveBody = (part, isFile) => {
809
+ if (part.contentType.startsWith("multipart/")) {
810
+ if (part.parts.length === 0) return NOTHING;
811
+ const children = part.parts.map((child) => resolveBody(child, isFile));
812
+ if (part.contentType === "multipart/alternative") return children.find((c) => c.from === "text/plain" && hasText(c)) ?? children.find((c) => c.from === "text/html" && hasText(c)) ?? NOTHING;
813
+ const contributing = children.filter(hasText);
814
+ return {
815
+ segments: children.flatMap((c) => c.segments),
816
+ from: contributing.some((c) => c.from === "text/html") ? "text/html" : contributing.some((c) => c.from === "text/plain") ? "text/plain" : "none"
817
+ };
818
+ }
819
+ if (isFile(part)) return {
820
+ segments: [markerFor(part)],
821
+ from: "none"
822
+ };
823
+ if (part.contentType === "text/plain") return {
824
+ segments: [{
825
+ kind: "text",
826
+ text: partText(part).trim()
827
+ }],
718
828
  from: "text/plain"
719
829
  };
720
- if (html) return {
721
- text: htmlToText(partText(html)),
830
+ if (part.contentType === "text/html") return {
831
+ segments: [{
832
+ kind: "text",
833
+ text: htmlToText(partText(part))
834
+ }],
722
835
  from: "text/html"
723
836
  };
724
837
  return {
725
- text: "",
838
+ segments: [markerFor(part)],
726
839
  from: "none"
727
840
  };
728
841
  };
729
842
  /**
843
+ * The body a person would want to read: every run of it, in order.
844
+ *
845
+ * `from` reports the worst provenance of the runs that contributed, not the
846
+ * first. It is the caller's only warning that the text went through
847
+ * `htmlToText`, and a concatenation that is half derived must not claim to be
848
+ * text/plain just because its first run was.
849
+ */
850
+ const bestBody = (root) => {
851
+ const strict = resolveBody(root, isAttachmentPart);
852
+ const resolved = hasText(strict) ? strict : resolveBody(root, (p) => p.disposition === "attachment");
853
+ const kept = resolved.segments.filter((s) => s.kind === "marker" || s.text.trim() !== "");
854
+ let first = 0;
855
+ let last = kept.length;
856
+ while (first < last && kept[first].kind === "marker") first += 1;
857
+ while (last > first && kept[last - 1].kind === "marker") last -= 1;
858
+ const text = kept.slice(first, last).map((s) => s.text).join("\n\n").trim();
859
+ return {
860
+ text,
861
+ from: text === "" ? "none" : resolved.from
862
+ };
863
+ };
864
+ /**
730
865
  * Does a decoded part carry actual content?
731
866
  *
732
867
  * Stripping an attachment out to the sidecar tree leaves the part's delimiter
@@ -741,7 +876,7 @@ const hasContent = (bytes) => {
741
876
  const listAttachments = (root) => {
742
877
  const found = [];
743
878
  walk(root, (p) => {
744
- if (!(p.disposition === "attachment" || p.filename !== null && !p.contentType.startsWith("multipart/")) || p.contentType.startsWith("multipart/")) return;
879
+ if (!isAttachmentPart(p) || p.contentType.startsWith("multipart/")) return;
745
880
  const decoded = partBytes(p);
746
881
  const present = hasContent(decoded);
747
882
  found.push({
@@ -1336,7 +1471,26 @@ function collectText(el, depth, acc, budget) {
1336
1471
  * ends up in the draft twice with no way to undo it from here.
1337
1472
  */
1338
1473
  function composerBodySize(body) {
1339
- 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";
1340
1494
  }
1341
1495
 
1342
1496
  /**
@@ -1701,6 +1855,220 @@ function run(argv) {
1701
1855
  }
1702
1856
  `;
1703
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
1704
2072
  //#region src/client/jxa/write.ts
1705
2073
  /**
1706
2074
  * Mutating scripts.
@@ -2413,9 +2781,11 @@ const REPLY_OR_FORWARD = script(`
2413
2781
  bodyVerified = after !== null && containsText(after, expected);
2414
2782
  if (bodyVerified) {
2415
2783
  verifiedChars = expected.length;
2416
- } else if (composerBodySize(bodyArea) !== sizeBefore) {
2417
- // Something went in that we cannot match. Pasting again would put the
2418
- // 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.
2419
2789
  break;
2420
2790
  }
2421
2791
  }
@@ -2425,12 +2795,37 @@ const REPLY_OR_FORWARD = script(`
2425
2795
 
2426
2796
  if (!bodyVerified) {
2427
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
+
2428
2822
  // Take the window back only when it is provably still empty. A paste that
2429
2823
  // landed and could not be READ is a different thing from one that never
2430
2824
  // landed, and closing that one would destroy the reply with no way to get
2431
- // it back -- so it is left on screen for the user to judge.
2432
- var landed = composerBodySize(bodyArea) !== sizeBefore;
2433
- 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;
2434
2829
  return err(
2435
2830
  "DRAFT_BODY_NOT_SET",
2436
2831
  "The " + p.mode + " window for \\"" + subject + "\\" was opened and correctly addressed, but the " +
@@ -2438,12 +2833,16 @@ const REPLY_OR_FORWARD = script(`
2438
2833
  "MUST NOT be described to the user as ready. " +
2439
2834
  (closedUnverified
2440
2835
  ? "Nothing had landed in it, so it was closed again without saving and a retry is safe."
2441
- : landed
2836
+ : landed === "yes"
2442
2837
  ? "SOMETHING DID land in it that could not be read back, so it was left open rather " +
2443
2838
  "than discarded — look at it in Mail before retrying, because a retry would paste " +
2444
2839
  "the reply in twice."
2445
- : "It could NOT be closed from here — close it in Mail before retrying, or the retry " +
2446
- "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.")
2447
2846
  );
2448
2847
  }
2449
2848
  }
@@ -2609,6 +3008,20 @@ const SEND_TIMEOUT_MS = 5e3;
2609
3008
  * so the top of it is the tell.
2610
3009
  */
2611
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
+ };
2612
3025
  const systemClipboard = {
2613
3026
  async read() {
2614
3027
  try {
@@ -2654,22 +3067,70 @@ const paste = async (lane, clipboard, ref, text, focusTimeoutMs) => {
2654
3067
  const after = await lane.bodyText(ref.body);
2655
3068
  if (after !== null && containsText(after, expected)) return {
2656
3069
  verified: true,
2657
- landed: true
3070
+ landed: "yes"
2658
3071
  };
2659
3072
  }
2660
- if (await lane.bodySize(ref.body) !== sizeBefore) break;
3073
+ if (compare(sizeBefore, await lane.bodySize(ref.body)) !== "no") break;
2661
3074
  }
2662
3075
  return {
2663
3076
  verified: false,
2664
- landed: await lane.bodySize(ref.body) !== sizeBefore
3077
+ landed: compare(sizeBefore, await lane.bodySize(ref.body))
2665
3078
  };
2666
3079
  });
2667
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
+ };
2668
3128
  const replyOrForwardNatively = async (lane, runner, params, opts = {}) => {
2669
3129
  const clipboard = opts.clipboard ?? systemClipboard;
2670
3130
  const composerTimeoutMs = opts.composerTimeoutMs ?? COMPOSER_TIMEOUT_MS;
2671
3131
  const sendTimeoutMs = opts.sendTimeoutMs ?? SEND_TIMEOUT_MS;
2672
3132
  const watch = lane.watch();
3133
+ const startedAt = Date.now();
2673
3134
  const reach = await lane.reach();
2674
3135
  if (!reach.ok) throw new Error(MailAxLane.grantMessage(params.mode));
2675
3136
  const subject = (await runner.run(OPEN_COMPOSER, params)).subject;
@@ -2682,22 +3143,57 @@ const replyOrForwardNatively = async (lane, runner, params, opts = {}) => {
2682
3143
  sent: false,
2683
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())
2684
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
+ };
2685
3166
  let bodyVerified = null;
2686
3167
  let verifiedChars = 0;
2687
3168
  if (params.body) {
2688
3169
  const result = await paste(lane, clipboard, ref, params.body, opts.focusTimeoutMs);
2689
3170
  bodyVerified = result.verified;
2690
3171
  verifiedChars = result.verified ? Math.min(params.body.length, VERIFY_CHARS) : 0;
2691
- if (!result.verified) return {
2692
- ok: false,
2693
- subject,
2694
- bodyVerified: false,
2695
- verifiedChars: 0,
2696
- sent: false,
2697
- 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())
2698
- };
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
+ }
2699
3183
  }
2700
- 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
+ };
2701
3197
  const sent = params.sendNow ? await lane.composerGone(subject, sendTimeoutMs) : false;
2702
3198
  return {
2703
3199
  ok: params.sendNow ? sent : true,
@@ -3056,142 +3552,6 @@ var EnvelopeIndex = class EnvelopeIndex {
3056
3552
  }
3057
3553
  };
3058
3554
  //#endregion
3059
- //#region src/client/jxa/read.ts
3060
- /** Accounts, their UUIDs, on-disk directories and mailbox names. ~0.6s for 4 accounts. */
3061
- const LIST_ACCOUNTS = script(`
3062
- var accts = M.accounts();
3063
- var out = [];
3064
- for (var i = 0; i < accts.length; i++) {
3065
- var a = accts[i];
3066
- out.push({
3067
- id: prop(function () { return a.id(); }, null),
3068
- name: prop(function () { return a.name(); }, null),
3069
- enabled: prop(function () { return a.enabled(); }, null),
3070
- accountType: prop(function () { return String(a.accountType()); }, null),
3071
- emailAddresses: prop(function () { return a.emailAddresses(); }, []),
3072
- fullName: prop(function () { return a.fullName(); }, null),
3073
- // Path objects need String(); JSON.stringify renders them as {}.
3074
- directory: prop(function () { return String(a.accountDirectory()); }, null),
3075
- messageCaching: prop(function () { return String(a.messageCaching()); }, null),
3076
- mailboxes: prop(function () { return a.mailboxes().map(function (m) { return m.name(); }); }, [])
3077
- });
3078
- }
3079
- return ok(out);
3080
- `);
3081
- /**
3082
- * Mailboxes with counts. Counts come from AppleScript rather than the index
3083
- * because they are cheap here (76ms unread / 295ms total on a 29k mailbox) and
3084
- * therefore never need to degrade when Full Disk Access is missing.
3085
- */
3086
- const LIST_MAILBOXES = script(`
3087
- var accts = M.accounts();
3088
- var out = [];
3089
- for (var i = 0; i < accts.length; i++) {
3090
- var a = accts[i];
3091
- var uuid = prop(function () { return a.id(); }, null);
3092
- if (p.accountUuids && p.accountUuids.length && p.accountUuids.indexOf(uuid) === -1) continue;
3093
- var boxes = a.mailboxes();
3094
- for (var j = 0; j < boxes.length; j++) {
3095
- var b = boxes[j];
3096
- var entry = {
3097
- accountUuid: uuid,
3098
- accountName: prop(function () { return a.name(); }, null),
3099
- name: prop(function () { return b.name(); }, null)
3100
- };
3101
- if (p.withCounts) {
3102
- entry.unread = prop(function () { return b.unreadCount(); }, null);
3103
- entry.total = prop(function () { return b.messages.length; }, null);
3104
- }
3105
- out.push(entry);
3106
- }
3107
- }
3108
- return ok(out);
3109
- `);
3110
- /** Total and unread for one mailbox. */
3111
- const COUNT_MAILBOX = script(`
3112
- var acct = findAccount(M, p.accountUuid);
3113
- if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
3114
- var mb = resolveMailbox(acct, p.mailbox);
3115
- if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
3116
- return ok({
3117
- accountUuid: p.accountUuid,
3118
- mailbox: prop(function () { return mb.name(); }, p.mailbox),
3119
- total: prop(function () { return mb.messages.length; }, null),
3120
- unread: prop(function () { return mb.unreadCount(); }, null)
3121
- });
3122
- `);
3123
- /**
3124
- * The degraded listing lane: newest N of one mailbox, used when the Envelope
3125
- * Index is unavailable. Costs roughly 130ms + 42ms per message per property,
3126
- * which is why the caller caps N hard (default 50) instead of paginating.
3127
- */
3128
- const LIST_RECENT = script(`
3129
- var acct = findAccount(M, p.accountUuid);
3130
- if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
3131
- var mb = resolveMailbox(acct, p.mailbox);
3132
- if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
3133
- var mailboxName = prop(function () { return mb.name(); }, p.mailbox);
3134
-
3135
- var total = prop(function () { return mb.messages.length; }, 0);
3136
- var n = Math.min(p.limit || 20, total);
3137
- if (n <= 0) return ok({ mailbox: mailboxName, total: total, messages: [] });
3138
-
3139
- // Batch the property reads: one Apple Event per property beats one per message
3140
- // by roughly 6x. slice() on the message collection keeps it to a range specifier.
3141
- var slice = mb.messages.slice(0, n);
3142
- var subjects = prop(function () { return slice.subject(); }, []);
3143
- var senders = prop(function () { return slice.sender(); }, []);
3144
- var dates = prop(function () { return slice.dateReceived(); }, []);
3145
- var reads = prop(function () { return slice.readStatus(); }, []);
3146
- var flags = prop(function () { return slice.flaggedStatus(); }, []);
3147
- var ids = prop(function () { return slice.id(); }, []);
3148
-
3149
- var out = [];
3150
- for (var i = 0; i < n; i++) {
3151
- out.push({
3152
- id: ids[i] === undefined ? null : ids[i],
3153
- accountUuid: p.accountUuid,
3154
- mailbox: mailboxName,
3155
- subject: subjects[i] === undefined ? null : subjects[i],
3156
- sender: senders[i] === undefined ? null : senders[i],
3157
- dateReceived: iso(dates[i]),
3158
- read: reads[i] === undefined ? null : reads[i],
3159
- flagged: flags[i] === undefined ? null : flags[i]
3160
- });
3161
- }
3162
- return ok({ mailbox: mailboxName, total: total, messages: out });
3163
- `);
3164
- /** Resolve a batch of message ids inside one mailbox. ~0.1s even on a 29k mailbox. */
3165
- const GET_MESSAGES = script(`
3166
- var acct = findAccount(M, p.accountUuid);
3167
- if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
3168
- var mb = resolveMailbox(acct, p.mailbox);
3169
- if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
3170
- var mailboxName = prop(function () { return mb.name(); }, p.mailbox);
3171
-
3172
- var out = [];
3173
- for (var i = 0; i < p.ids.length; i++) {
3174
- var id = p.ids[i];
3175
- try {
3176
- var m = mb.messages.byId(id);
3177
- var summary = messageSummary(m, p.accountUuid, mailboxName);
3178
- if (p.withContent) {
3179
- summary.content = prop(function () { return m.content(); }, null);
3180
- }
3181
- if (p.withSource) {
3182
- summary.source = prop(function () { return m.source(); }, null);
3183
- }
3184
- if (p.withHeaders) {
3185
- summary.allHeaders = prop(function () { return m.allHeaders(); }, null);
3186
- }
3187
- out.push(summary);
3188
- } catch (e) {
3189
- out.push({ id: id, found: false, error: String(e && e.message ? e.message : e) });
3190
- }
3191
- }
3192
- return ok(out);
3193
- `);
3194
- //#endregion
3195
3555
  //#region src/client/mailbox-map.ts
3196
3556
  var MailboxMap = class {
3197
3557
  #runner;
@@ -4760,7 +5120,7 @@ const registerComposeTools = (server, client) => {
4760
5120
  });
4761
5121
  }));
4762
5122
  server.registerTool("apple_mail_reply_to_message", {
4763
- 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.",
4764
5124
  inputSchema: {
4765
5125
  ref: messageRefArg,
4766
5126
  body: bodyArg,
@@ -5211,4 +5571,4 @@ const createServer = (opts) => {
5211
5571
  //#endregion
5212
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 };
5213
5573
 
5214
- //# sourceMappingURL=server-CKe5t7r_.js.map
5574
+ //# sourceMappingURL=server-CcHy5Pw4.js.map