@mgcrea/mcp-apple-mail 1.22.1 → 1.23.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: "153c3ea",
18
- gitCommitDate: "2026-09-16T14:44:21+02:00"
17
+ gitCommit: "254e371",
18
+ gitCommitDate: "2026-09-18T23:50:15+02:00"
19
19
  };
20
20
  //#endregion
21
21
  //#region src/client/errors.ts
@@ -179,6 +179,34 @@ const BODY_DEPTH = 8;
179
179
  const FOCUS_TIMEOUT_MS = 2e3;
180
180
  /** Between focus attempts. Each one is a round trip, so this is not a spin. */
181
181
  const FOCUS_POLL_MS = 100;
182
+ /**
183
+ * How many leading blocks to classify as quoted or not.
184
+ *
185
+ * `composerBody` only needs the FIRST quoted block — everything from it down is
186
+ * the original — and on a reply that is the attribution line, two or three
187
+ * blocks in. The bound is therefore generous rather than tight, and its job is
188
+ * the failure case: a body whose boundary is not inside it is reported as
189
+ * unknown rather than guessed at, because guessing "no quote" would offer the
190
+ * whole quoted original up for replacement.
191
+ */
192
+ const BLOCK_SCAN_MAX = 60;
193
+ /**
194
+ * How many times to ask for a block's quote level before giving up on it.
195
+ *
196
+ * A busy WebKit view answers "did not answer in time … retry" rather than
197
+ * refusing, and it says so straight after a paste — which is exactly when this
198
+ * is read. See `#quoteLevel`.
199
+ */
200
+ const QUOTE_READ_TRIES = 3;
201
+ const QUOTE_READ_PAUSE_MS = 120;
202
+ /**
203
+ * How many keystrokes go in one `apple_desktop_run`.
204
+ *
205
+ * The verb caps a run at 25 steps. Staying under it here means a burst is
206
+ * chunked rather than refused, which matters because the number of strokes is
207
+ * the number of lines in somebody's draft.
208
+ */
209
+ const KEY_BURST = 20;
182
210
  var MailAxLane = class MailAxLane {
183
211
  #channel;
184
212
  constructor(channel) {
@@ -284,6 +312,36 @@ var MailAxLane = class MailAxLane {
284
312
  await new Promise((resolve) => setTimeout(resolve, 200));
285
313
  }
286
314
  }
315
+ /**
316
+ * Every composer currently under this subject, in window order.
317
+ *
318
+ * `findComposer` takes the first match because it is looking for a window it
319
+ * just opened. Rewriting one that was already there is the opposite problem:
320
+ * the caller has to know whether the subject picks out ONE composer, because
321
+ * two under one title cannot be told apart — handles are minted per call —
322
+ * and replacing the body of the wrong one destroys what somebody wrote. So
323
+ * this returns the list and lets `revise.ts` refuse on its length.
324
+ *
325
+ * Does not poll. Nothing here opened a window, so there is nothing to wait
326
+ * for: the composer either is on screen or is not.
327
+ */
328
+ async findComposers(subject) {
329
+ const listed = await this.#call("list_windows", {
330
+ bundleId: MAIL_BUNDLE,
331
+ includeTitles: true
332
+ });
333
+ const found = [];
334
+ for (const win of listed.windows ?? []) {
335
+ if ((win.title ?? "") !== subject) continue;
336
+ const body = await this.#bodyOf(win.index);
337
+ if (body) found.push({
338
+ window: win.handle,
339
+ body,
340
+ index: win.index
341
+ });
342
+ }
343
+ return found;
344
+ }
287
345
  async #bodyOf(windowIndex) {
288
346
  return ((await this.#call("ui_tree", {
289
347
  bundleId: MAIL_BUNDLE,
@@ -381,6 +439,30 @@ var MailAxLane = class MailAxLane {
381
439
  * typed.
382
440
  */
383
441
  async paste(ref, focusTimeoutMs = FOCUS_TIMEOUT_MS) {
442
+ return this.keys(ref, [{
443
+ key: "v",
444
+ modifiers: ["command"]
445
+ }], focusTimeoutMs);
446
+ }
447
+ /**
448
+ * Focus the composer's body and send a burst of keystrokes to it.
449
+ *
450
+ * What `paste` was, generalised, because replacing a reply's text without
451
+ * touching its quote is a sequence rather than one key: the caret goes to the
452
+ * top of the document, the selection is walked down to the end of the
453
+ * sender's own text, and only then is anything pasted over it.
454
+ *
455
+ * Sent through `apple_desktop_run` so a burst is ONE round trip. That is not
456
+ * only speed: every stroke in a run is checked before the first one is posted,
457
+ * and the run stops at the first failure, so a selection cannot be left
458
+ * half-extended by a refusal partway through.
459
+ *
460
+ * Each stroke names the body's handle, so the desktop server brings Mail
461
+ * forward before posting and refuses rather than typing into whatever the
462
+ * person at the keyboard just switched to.
463
+ */
464
+ async keys(ref, strokes, focusTimeoutMs = FOCUS_TIMEOUT_MS) {
465
+ if (strokes.length === 0) return true;
384
466
  try {
385
467
  await this.#call("raise_window", { handle: ref.window });
386
468
  await this.activate();
@@ -390,17 +472,110 @@ var MailAxLane = class MailAxLane {
390
472
  if (Date.now() >= deadline) return false;
391
473
  await new Promise((resolve) => setTimeout(resolve, FOCUS_POLL_MS));
392
474
  }
393
- await this.#call("key", {
394
- key: "v",
395
- modifiers: ["command"],
396
- handle: ref.body
397
- });
475
+ for (let at = 0; at < strokes.length; at += KEY_BURST) {
476
+ const chunk = strokes.slice(at, at + KEY_BURST);
477
+ if (chunk.length === 1) {
478
+ const only = chunk[0];
479
+ await this.#call("key", {
480
+ ...only,
481
+ handle: ref.body
482
+ });
483
+ continue;
484
+ }
485
+ await this.#call("run", { steps: chunk.map((stroke) => ({
486
+ tool: "key",
487
+ ...stroke,
488
+ handle: ref.body
489
+ })) });
490
+ }
398
491
  return true;
399
492
  } catch {
400
493
  return false;
401
494
  }
402
495
  }
403
496
  /**
497
+ * Read the composer's own text, stopping where the quoted original begins.
498
+ *
499
+ * Null when the boundary cannot be established, and that answer is the point.
500
+ * Two ways it happens: the body cannot be read at all, or no quoted block was
501
+ * found within `BLOCK_SCAN_MAX` of a body that has more blocks than that.
502
+ * Reporting the second as "no quote, all of it is yours" would hand the whole
503
+ * quoted message to a caller that is about to replace what it is given.
504
+ *
505
+ * The quote level is read per element rather than from the tree, because the
506
+ * tree's field set is chosen for addressing controls and does not carry it.
507
+ * Affordable only natively — 0.2 ms a read against System Events' 47 ms — and
508
+ * bounded anyway, since the loop stops at the first quoted block and on a
509
+ * reply that is two or three in.
510
+ */
511
+ /**
512
+ * One block's quote level, retried, because "busy" is not "no".
513
+ *
514
+ * MEASURED, macOS 27.0: on a composer quoting a long thread, a single
515
+ * `AXBlockQuoteLevel` read came back `Reading AXBlockQuoteLevel of 'e8320' did
516
+ * not answer in time. The app may be busy; retry.` — WebKit still digesting
517
+ * the paste that had just landed in it. One such timeout used to fail the
518
+ * whole read, which failed the verification, which refused a rewrite that had
519
+ * in fact gone in perfectly and left the composer unsaved.
520
+ *
521
+ * The app says to retry, so it retries. Null is kept for a read that never
522
+ * answers, because the caller must not mistake it for level zero.
523
+ */
524
+ async #quoteLevel(handle) {
525
+ for (let attempt = 0; attempt < QUOTE_READ_TRIES; attempt += 1) try {
526
+ const read = await this.#call("get_attribute", {
527
+ handle,
528
+ attribute: "AXBlockQuoteLevel"
529
+ });
530
+ return typeof read.value === "number" ? read.value : 0;
531
+ } catch {
532
+ if (attempt + 1 >= QUOTE_READ_TRIES) return null;
533
+ await new Promise((resolve) => setTimeout(resolve, QUOTE_READ_PAUSE_MS));
534
+ }
535
+ return null;
536
+ }
537
+ async composerBody(body) {
538
+ let tree;
539
+ try {
540
+ tree = await this.#call("expand", {
541
+ handle: body,
542
+ detail: "all",
543
+ maxDepth: BODY_DEPTH
544
+ });
545
+ } catch {
546
+ return null;
547
+ }
548
+ const elements = tree.elements ?? [];
549
+ const starts = elements.flatMap((el, at) => el.depth === 0 ? [at] : []);
550
+ let boundary = null;
551
+ for (let block = 0; block < starts.length && block < BLOCK_SCAN_MAX; block += 1) {
552
+ const handle = elements[starts[block]]?.handle;
553
+ if (!handle) continue;
554
+ const level = await this.#quoteLevel(handle);
555
+ if (level === null) return null;
556
+ if (level > 0) {
557
+ boundary = block;
558
+ break;
559
+ }
560
+ }
561
+ const truncated = tree.truncated !== void 0 || (tree.matched ?? 0) > elements.length;
562
+ if (boundary === null) {
563
+ if (truncated || starts.length > BLOCK_SCAN_MAX) return null;
564
+ boundary = starts.length;
565
+ }
566
+ const lines = [];
567
+ for (let block = 0; block < boundary; block += 1) {
568
+ const from = starts[block];
569
+ const to = starts[block + 1] ?? elements.length;
570
+ lines.push(elements.slice(from, to).map((el) => el.value).filter((v) => typeof v === "string").join(""));
571
+ }
572
+ return {
573
+ text: lines.join("\n"),
574
+ blocks: boundary,
575
+ quoted: boundary < starts.length
576
+ };
577
+ }
578
+ /**
404
579
  * Send the composer, or save it as a draft.
405
580
  *
406
581
  * A keyboard shortcut rather than the Send button, and that is a correctness
@@ -1940,7 +2115,29 @@ const LIST_RECENT = script(`
1940
2115
 
1941
2116
  // Batch the property reads: one Apple Event per property beats one per message
1942
2117
  // by roughly 6x. slice() on the message collection keeps it to a range specifier.
1943
- var slice = mb.messages.slice(0, n);
2118
+ /*
2119
+ * slice(from, to) on an Apple Events specifier is INCLUSIVE of "to".
2120
+ *
2121
+ * It is not JavaScript's slice. JXA turns it into a range specifier, so
2122
+ * slice(0, n) asks for n + 1 messages, and asking for one past the end raises
2123
+ * "Invalid index." -- which prop() swallows, leaving every batched read as []
2124
+ * and every field on every row NULL, including the id the ref is built from.
2125
+ *
2126
+ * MEASURED, macOS 27.0 (build 26A428), against a live Mail:
2127
+ *
2128
+ * Sent Items (303) slice(0, 2) -> 3 subjects
2129
+ * Sent Items (303) slice(0, 303) -> Invalid index.
2130
+ * Sent Items (303) slice(0, 302) -> 303 subjects
2131
+ * Drafts (1) slice(0, 1) -> Invalid index.
2132
+ * Drafts (1) slice(0, 0) -> 1 subject
2133
+ *
2134
+ * So the failure is not about drafts, which is where it was found. It is
2135
+ * every listing whose limit reaches the end of the mailbox: n === total, and
2136
+ * the read asks for one message that is not there. A mailbox holding fewer
2137
+ * messages than the default limit could never be listed at all -- it came
2138
+ * back as rows of nulls carrying unusable #null refs.
2139
+ */
2140
+ var slice = mb.messages.slice(0, n - 1);
1944
2141
  var subjects = prop(function () { return slice.subject(); }, []);
1945
2142
  var senders = prop(function () { return slice.sender(); }, []);
1946
2143
  var dates = prop(function () { return slice.dateReceived(); }, []);
@@ -2038,8 +2235,13 @@ const SENT_SINCE = script(`
2038
2235
  var n = Math.min(p.limit || 25, total);
2039
2236
  if (n <= 0) return ok({ checked: true, mailbox: mailbox, total: total, found: false, newest: null, messages: [] });
2040
2237
 
2041
- // One Apple Event per property rather than one per message, as LIST_RECENT.
2042
- var slice = box.messages.slice(0, n);
2238
+ // One Apple Event per property rather than one per message, as LIST_RECENT —
2239
+ // including its inclusive-range correction, and here it matters more than
2240
+ // anywhere else: this is the read that decides whether a reply was SENT. A
2241
+ // Sent mailbox holding fewer messages than the limit raised "Invalid index.",
2242
+ // every subject came back empty, and the answer was "it does NOT appear to
2243
+ // have been sent" for a mail that had gone — which invites sending it twice.
2244
+ var slice = box.messages.slice(0, n - 1);
2043
2245
  var subjects = prop(function () { return slice.subject(); }, []);
2044
2246
  var sent = prop(function () { return slice.dateSent(); }, []);
2045
2247
  var received = prop(function () { return slice.dateReceived(); }, []);
@@ -2396,49 +2598,15 @@ const SEND_MESSAGE = script(`
2396
2598
  note: "Draft window is open in Mail for review." });
2397
2599
  `, { allowLaunch: true });
2398
2600
  /**
2399
- * Replace the body of a saved draft, by recreating it.
2601
+ * Resolve the draft a ref names, and the Drafts mailbox it has to be in.
2400
2602
  *
2401
- * ## Why recreating, when "edit the draft" is the obvious thing
2402
- *
2403
- * Because Mail's dictionary does not offer it, and that is measured rather than
2404
- * assumed — see `docs/mail-compose.md`. A saved draft is a `message`, whose
2405
- * `content` is `access="r"`. There is no `open` command and no `edit` command in
2406
- * the entire suite, so nothing turns a saved draft back into the `outgoing
2407
- * message` whose content IS writable. The only class that ever held a reference
2408
- * from one to the other is `OLD message editor`, marked `hidden` and
2409
- * "DEPRECATED - DO NOT USE".
2410
- *
2411
- * So the body is replaced the only way the interface allows: compose a new
2412
- * message carrying the old one's recipients and the new text, and remove the
2413
- * old one.
2414
- *
2415
- * ## The order is the safety property
2416
- *
2417
- * The replacement is created AND CONFIRMED PRESENT before the original is
2418
- * deleted, never the other way round. A delete-then-create that fails halfway
2419
- * has destroyed something the user wrote and cannot get back — this server has
2420
- * no undo and Mail's Trash may not be in play, since `moveDeletedMessagesToTrash`
2421
- * is per-account. If the confirmation does not come back, the original is left
2422
- * exactly where it was and the caller is told there are now two.
2423
- *
2424
- * ## What it refuses
2425
- *
2426
- * Recreating cannot carry everything across, and the two things it drops are
2427
- * both invisible in the result:
2428
- *
2429
- * * **Threading.** `In-Reply-To` and `References` are set by Mail's own
2430
- * `reply` command, which needs the original message. A recreated reply
2431
- * draft looks perfect and starts a new thread.
2432
- * * **Attachments.** Adding one to an outgoing message IS possible:
2433
- * `content.attachments.push(Mail.Attachment({fileName: Path(f)}))`, measured
2434
- * on macOS 26.6. What is missing is a file to point at. The bytes live in the
2435
- * original's sidecar tree, and extracting them first is not done here.
2436
- *
2437
- * Both are refused rather than silently dropped. A draft that is correct in
2438
- * every visible respect except the part nobody checks is the exact failure the
2439
- * compose path already learned once.
2603
+ * Shared verbatim by `DRAFT_FACTS` and `UPDATE_DRAFT`, because the two are two
2604
+ * readings of one question and a copy of this that drifted would let one of them
2605
+ * rewrite something the other would have refused. It returns early on every way
2606
+ * it can fail, and otherwise leaves `acct`, `original`, `drafts`, `draftsName`
2607
+ * and the draft's own facts in scope for whatever follows.
2440
2608
  */
2441
- const UPDATE_DRAFT = script(`
2609
+ const RESOLVE_DRAFT = `
2442
2610
  var acct = findAccount(M, p.accountUuid);
2443
2611
  if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
2444
2612
  var mb = resolveMailbox(acct, p.mailbox);
@@ -2523,6 +2691,93 @@ const UPDATE_DRAFT = script(`
2523
2691
  var oldSubject = String(prop(function () { return original.subject(); }, ""));
2524
2692
  var sender = String(prop(function () { return original.sender(); }, ""));
2525
2693
 
2694
+ `;
2695
+ /**
2696
+ * Everything about a draft that decides HOW it can be rewritten, and nothing more.
2697
+ *
2698
+ * Read on its own, before a line of it is changed, because there are now two
2699
+ * ways to rewrite a draft and the choice between them is made outside any
2700
+ * script: editing the open composer in place (`revise.ts`) needs the subject to
2701
+ * find the window and the body's opening to prove the window is this draft,
2702
+ * while recreating it (`UPDATE_DRAFT` below) needs neither.
2703
+ *
2704
+ * Costs one Apple Event and is only spent when the accessibility lane exists to
2705
+ * use it — `client/mail.ts` goes straight to recreation otherwise, so a server
2706
+ * running outside Cupertino pays nothing for a path it cannot take.
2707
+ *
2708
+ * `contentHead` is capped rather than whole: it is an identity, not a body, and
2709
+ * a quoted newsletter runs to six figures of characters.
2710
+ */
2711
+ const DRAFT_FACTS = script(`
2712
+ ${RESOLVE_DRAFT}
2713
+
2714
+ var content = String(prop(function () { return original.content(); }, ""));
2715
+
2716
+ return ok({
2717
+ subject: oldSubject,
2718
+ isReply: isReply,
2719
+ attachments: attachments,
2720
+ recipientCount: to.length + cc.length + bcc.length,
2721
+ draftsMailbox: draftsName,
2722
+ contentHead: content.slice(0, 400)
2723
+ });
2724
+ `);
2725
+ /**
2726
+ * Replace the body of a saved draft, by recreating it.
2727
+ *
2728
+ * ## Why recreating, when "edit the draft" is the obvious thing
2729
+ *
2730
+ * Because Mail's dictionary does not offer it, and that is measured rather than
2731
+ * assumed — see `docs/mail-compose.md`. A saved draft is a `message`, whose
2732
+ * `content` is `access="r"`. There is no `open` command and no `edit` command in
2733
+ * the entire suite, so nothing turns a saved draft back into the `outgoing
2734
+ * message` whose content IS writable. The only class that ever held a reference
2735
+ * from one to the other is `OLD message editor`, marked `hidden` and
2736
+ * "DEPRECATED - DO NOT USE".
2737
+ *
2738
+ * So the body is replaced the only way the interface allows: compose a new
2739
+ * message carrying the old one's recipients and the new text, and remove the
2740
+ * old one.
2741
+ *
2742
+ * ## The order is the safety property
2743
+ *
2744
+ * The replacement is created AND CONFIRMED PRESENT before the original is
2745
+ * deleted, never the other way round. A delete-then-create that fails halfway
2746
+ * has destroyed something the user wrote and cannot get back — this server has
2747
+ * no undo and Mail's Trash may not be in play, since `moveDeletedMessagesToTrash`
2748
+ * is per-account. If the confirmation does not come back, the original is left
2749
+ * exactly where it was and the caller is told there are now two.
2750
+ *
2751
+ * ## What it refuses
2752
+ *
2753
+ * Recreating cannot carry everything across, and the two things it drops are
2754
+ * both invisible in the result:
2755
+ *
2756
+ * * **Threading.** `In-Reply-To` and `References` are set by Mail's own
2757
+ * `reply` command, which needs the original message. A recreated reply
2758
+ * draft looks perfect and starts a new thread.
2759
+ * * **Attachments.** Adding one to an outgoing message IS possible:
2760
+ * `content.attachments.push(Mail.Attachment({fileName: Path(f)}))`, measured
2761
+ * on macOS 26.6. What is missing is a file to point at. The bytes live in the
2762
+ * original's sidecar tree, and extracting them first is not done here.
2763
+ *
2764
+ * Both are refused rather than silently dropped. A draft that is correct in
2765
+ * every visible respect except the part nobody checks is the exact failure the
2766
+ * compose path already learned once.
2767
+ *
2768
+ * ## This is the FALLBACK, not the first choice
2769
+ *
2770
+ * Every refusal below is a cost of recreating, and none of them is a cost of
2771
+ * editing. When the draft's own composer is still open — which it is for the
2772
+ * whole of "draft a reply, now change this line", because nothing here ever
2773
+ * closes one — `revise.ts` rewrites the body in that window instead, and
2774
+ * threading, attachments and the quoted original all survive because nothing is
2775
+ * remade. `client/mail.ts` tries that first and arrives here only when there is
2776
+ * no window to edit.
2777
+ */
2778
+ const UPDATE_DRAFT = script(`
2779
+ ${RESOLVE_DRAFT}
2780
+
2526
2781
  // Everything the caller needs to decide what to do instead, reported on the
2527
2782
  // refusals as well as on success.
2528
2783
  var facts = {
@@ -2534,19 +2789,21 @@ const UPDATE_DRAFT = script(`
2534
2789
 
2535
2790
  if (isReply) {
2536
2791
  return ok({
2537
- replaced: false, degraded: true, capability: "threading", draft: facts,
2792
+ replaced: false, method: "recreate", degraded: true, capability: "threading", draft: facts,
2538
2793
  reason:
2539
2794
  "This draft is a reply or a forward: its headers carry In-Reply-To or References, and " +
2540
2795
  "those are written by Mail's own reply command, which needs the original message. " +
2541
2796
  "Recreating it would produce a draft that looks right and starts a NEW thread.",
2542
2797
  hint:
2543
- "Edit the body in Mail directly, or delete this draft and start again with " +
2544
- "apple_mail_reply_to_message, which threads correctly."
2798
+ "This draft's composer window is NOT open in Mail — if it were, the body would have been " +
2799
+ "edited in place and this refusal would not have happened. Either reopen the draft in " +
2800
+ "Mail and edit it there, or delete it and start again with apple_mail_reply_to_message, " +
2801
+ "which threads correctly and leaves the composer open for further revisions."
2545
2802
  });
2546
2803
  }
2547
2804
  if (attachments > 0) {
2548
2805
  return ok({
2549
- replaced: false, degraded: true, capability: "attachments", draft: facts,
2806
+ replaced: false, method: "recreate", degraded: true, capability: "attachments", draft: facts,
2550
2807
  reason:
2551
2808
  "This draft carries " + attachments + " attachment(s). Recreating it would silently drop " +
2552
2809
  "them: their bytes live inside the original message, not as files this can point at, and " +
@@ -2558,7 +2815,7 @@ const UPDATE_DRAFT = script(`
2558
2815
  var subject = p.subject === null || p.subject === undefined ? oldSubject : String(p.subject);
2559
2816
  if (!subject) {
2560
2817
  return ok({
2561
- replaced: false, degraded: true, capability: "confirmation", draft: facts,
2818
+ replaced: false, method: "recreate", degraded: true, capability: "confirmation", draft: facts,
2562
2819
  reason:
2563
2820
  "This draft has no subject, and the subject is the only handle this server has for " +
2564
2821
  "finding the replacement again after Mail saves it. Without that confirmation the " +
@@ -2605,7 +2862,7 @@ const UPDATE_DRAFT = script(`
2605
2862
 
2606
2863
  if (newId === null) {
2607
2864
  return ok({
2608
- replaced: false, degraded: true, capability: "confirmation", draft: facts, saved: saved,
2865
+ replaced: false, method: "recreate", degraded: true, capability: "confirmation", draft: facts, saved: saved,
2609
2866
  reason:
2610
2867
  "The replacement was composed but never appeared in " + draftsName + " within four " +
2611
2868
  "seconds, so it could not be confirmed. THE ORIGINAL DRAFT WAS NOT DELETED — there are " +
@@ -2648,6 +2905,7 @@ const UPDATE_DRAFT = script(`
2648
2905
 
2649
2906
  return ok({
2650
2907
  replaced: true,
2908
+ method: "recreate",
2651
2909
  newId: settledId,
2652
2910
  confirmedId: newId,
2653
2911
  draftsMailbox: draftsName,
@@ -3012,6 +3270,29 @@ const SEND_TIMEOUT_MS = 5e3;
3012
3270
  */
3013
3271
  const VERIFY_CHARS = 400;
3014
3272
  /**
3273
+ * How long to keep re-reading the body for text that was just pasted.
3274
+ *
3275
+ * **A paste is not on screen when the keystroke returns.** `apple_desktop_key`
3276
+ * answers once the event is POSTED; WebKit then has to take it, edit the
3277
+ * document and republish an accessibility tree. Reading once, immediately, races
3278
+ * that — and loses on exactly the mail where it hurts, because the re-layout is
3279
+ * paid for the whole document and a reply carries the original inside it.
3280
+ *
3281
+ * MEASURED, macOS 27.0 (build 26A428): a two-line reply pasted into a composer
3282
+ * quoting a 322-element newsletter came back `bodyVerified: false` with "SOMETHING
3283
+ * DID land in it that could not be read back" — and the tree, read again a
3284
+ * moment later, held both lines exactly as sent. A correct reply reported as a
3285
+ * failure, which then tells its reader not to retry.
3286
+ *
3287
+ * So the read is polled, like the focus above it and for the same reason
3288
+ * `docs/desktop.md` gives: readable is not ready, and no fixed settle time is
3289
+ * right. Costs nothing on the common path — the first read still usually
3290
+ * answers — and the bound only has to be longer than a slow re-layout.
3291
+ */
3292
+ const RENDER_TIMEOUT_MS$1 = 3e3;
3293
+ /** Between read-backs. Each is a round trip over a subtree, so not a spin. */
3294
+ const RENDER_POLL_MS$1 = 150;
3295
+ /**
3015
3296
  * How far back to accept a message in Sent as this call's.
3016
3297
  *
3017
3298
  * Generous on purpose. `dateSent` and the moment the row appears are not the
@@ -3025,16 +3306,44 @@ const compare = (before, after) => {
3025
3306
  if (before === null || after === null) return "unknown";
3026
3307
  return after === before ? "no" : "yes";
3027
3308
  };
3309
+ /**
3310
+ * `pbcopy` and `pbpaste` speak the locale's encoding, NOT UTF-8.
3311
+ *
3312
+ * With no `LANG` or `LC_CTYPE` in the environment they fall back to MacRoman,
3313
+ * and this server is spawned by the app with a minimal environment that has
3314
+ * neither. Every byte outside ASCII is then wrong in both directions:
3315
+ *
3316
+ * echo 'em dash — here' | pbcopy (no locale) -> pasted as 'em dash ‚Äî here'
3317
+ * echo 'em dash — here' | pbcopy (LC_CTYPE) -> pasted as 'em dash — here'
3318
+ *
3319
+ * MEASURED, macOS 27.0, and found in a live composer: a body pasted through this
3320
+ * path arrived with `—` turned into `‚Äî` — the UTF-8 bytes of the dash read back
3321
+ * as MacRoman. It is not a display artefact; that is what went into the draft,
3322
+ * and it would have gone into the mail. For anyone writing French or German it
3323
+ * mangles every accent, and the reader's own quotation marks with them.
3324
+ *
3325
+ * The read matters just as much, and is worse in kind. This clipboard is
3326
+ * BORROWED — read, overwritten, and put back — so a `pbpaste` that mis-decodes
3327
+ * hands back a corrupted copy of whatever the person had copied. Replying to a
3328
+ * mail should not quietly rewrite their clipboard.
3329
+ *
3330
+ * `LC_CTYPE=UTF-8` is the narrowest fix: it names the character encoding and
3331
+ * nothing else, so no message, date or sort order changes with it.
3332
+ */
3333
+ const clipboardEnv = {
3334
+ ...process.env,
3335
+ LC_CTYPE: "UTF-8"
3336
+ };
3028
3337
  const systemClipboard = {
3029
3338
  async read() {
3030
3339
  try {
3031
- return (await run("/usr/bin/pbpaste", [])).stdout;
3340
+ return (await run("/usr/bin/pbpaste", [], { env: clipboardEnv })).stdout;
3032
3341
  } catch {
3033
3342
  return null;
3034
3343
  }
3035
3344
  },
3036
3345
  async write(text) {
3037
- const child = execFile("/usr/bin/pbcopy", []);
3346
+ const child = execFile("/usr/bin/pbcopy", [], { env: clipboardEnv });
3038
3347
  child.stdin?.end(text);
3039
3348
  await new Promise((resolve, reject) => {
3040
3349
  child.on("close", resolve);
@@ -3050,9 +3359,8 @@ const systemClipboard = {
3050
3359
  * or a file promise still comes back as text, because there is no way to carry
3051
3360
  * an arbitrary item across without knowing its type.
3052
3361
  */
3053
- const withClipboard = async (clipboard, text, body) => {
3362
+ const borrowClipboard = async (clipboard, body) => {
3054
3363
  const saved = await clipboard.read();
3055
- await clipboard.write(text);
3056
3364
  try {
3057
3365
  return await body();
3058
3366
  } finally {
@@ -3061,18 +3369,34 @@ const withClipboard = async (clipboard, text, body) => {
3061
3369
  } catch {}
3062
3370
  }
3063
3371
  };
3064
- const paste = async (lane, clipboard, ref, text, focusTimeoutMs) => {
3372
+ const withClipboard = (clipboard, text, body) => borrowClipboard(clipboard, async () => {
3373
+ await clipboard.write(text);
3374
+ return body();
3375
+ });
3376
+ /**
3377
+ * Wait for text to appear in the body, rather than reading for it once.
3378
+ *
3379
+ * Returns as soon as it matches, so the poll costs nothing when the tree is
3380
+ * already current. See `RENDER_TIMEOUT_MS` for the measurement that put it here.
3381
+ */
3382
+ const awaitBody = async (lane, body, expected, timeoutMs = RENDER_TIMEOUT_MS$1) => {
3383
+ const deadline = Date.now() + timeoutMs;
3384
+ for (;;) {
3385
+ const after = await lane.bodyText(body);
3386
+ if (after !== null && containsText(after, expected)) return true;
3387
+ if (Date.now() >= deadline) return false;
3388
+ await new Promise((resolve) => setTimeout(resolve, RENDER_POLL_MS$1));
3389
+ }
3390
+ };
3391
+ const paste = async (lane, clipboard, ref, text, focusTimeoutMs, renderTimeoutMs) => {
3065
3392
  const expected = text.length > VERIFY_CHARS ? text.slice(0, VERIFY_CHARS) : text;
3066
3393
  const sizeBefore = await lane.bodySize(ref.body);
3067
3394
  return withClipboard(clipboard, text, async () => {
3068
3395
  for (let attempt = 0; attempt < 2; attempt += 1) {
3069
- if (await lane.paste(ref, focusTimeoutMs)) {
3070
- const after = await lane.bodyText(ref.body);
3071
- if (after !== null && containsText(after, expected)) return {
3072
- verified: true,
3073
- landed: "yes"
3074
- };
3075
- }
3396
+ if (await lane.paste(ref, focusTimeoutMs) && await awaitBody(lane, ref.body, expected, renderTimeoutMs)) return {
3397
+ verified: true,
3398
+ landed: "yes"
3399
+ };
3076
3400
  if (compare(sizeBefore, await lane.bodySize(ref.body)) !== "no") break;
3077
3401
  }
3078
3402
  return {
@@ -3195,7 +3519,7 @@ const replyOrForwardNatively = async (lane, runner, params, opts = {}) => {
3195
3519
  let bodyVerified = null;
3196
3520
  let verifiedChars = 0;
3197
3521
  if (params.body) {
3198
- const result = await paste(lane, clipboard, ref, params.body, opts.focusTimeoutMs);
3522
+ const result = await paste(lane, clipboard, ref, params.body, opts.focusTimeoutMs, opts.renderTimeoutMs);
3199
3523
  bodyVerified = result.verified;
3200
3524
  verifiedChars = result.verified ? Math.min(params.body.length, VERIFY_CHARS) : 0;
3201
3525
  if (!result.verified) {
@@ -3708,6 +4032,283 @@ const groupRefsByMailbox = (refs) => {
3708
4032
  return groups;
3709
4033
  };
3710
4034
  //#endregion
4035
+ //#region src/client/revise.ts
4036
+ /**
4037
+ * Rewrite a draft by editing its open composer, instead of recreating it.
4038
+ *
4039
+ * ## Why this exists
4040
+ *
4041
+ * `UPDATE_DRAFT` replaces a draft by composing a new one and deleting the old,
4042
+ * because Mail's scripting interface offers no way to edit a saved draft —
4043
+ * `docs/mail-compose.md` carries the dictionary evidence. Recreation cannot
4044
+ * carry threading or attachments across, so it REFUSES a reply draft rather
4045
+ * than silently starting a new thread.
4046
+ *
4047
+ * Which refuses the most common request there is. "Draft a reply, now change
4048
+ * this line" ended at a tool that would not do it and a person deleting the
4049
+ * draft by hand.
4050
+ *
4051
+ * Nothing about that limit was ever about editing. It is about RECREATION: a
4052
+ * composer's body can be rewritten in place, the save lands on the same draft,
4053
+ * and threading, attachments and the quoted original are all still there
4054
+ * afterwards because nothing was ever remade. What was missing was a way in —
4055
+ * and in the case that matters there already is one, because the composer the
4056
+ * reply was written in is still on screen. Nothing here ever closes one.
4057
+ *
4058
+ * ## The safety property
4059
+ *
4060
+ * `UPDATE_DRAFT`'s is an order: confirm the replacement before deleting the
4061
+ * original. This path deletes nothing, so its hazard is a different one —
4062
+ * replacing text that is not the text we meant to replace — and its guard is
4063
+ * that **every step that could destroy something is verified before it is
4064
+ * taken**, never after:
4065
+ *
4066
+ * * The window is matched to the draft by CONTENT, not only by subject. Two
4067
+ * replies in one thread carry the same title.
4068
+ * * The selection is read back by copying it, and must equal the composer's
4069
+ * own text exactly. Selecting and copying change nothing, so a selection
4070
+ * that cannot be made to match is abandoned with the draft untouched.
4071
+ * * The quoted original is located by `AXBlockQuoteLevel` and never selected.
4072
+ * A body whose quote boundary cannot be established is refused.
4073
+ * * The paste is read back before the save, and a body that does not match is
4074
+ * NOT saved — leaving the draft as it was and the window open to look at.
4075
+ *
4076
+ * MEASURED, macOS 27.0 (build 26A428), on a reply composer quoting a newsletter
4077
+ * of 322 elements: the selection copied back as exactly the two lines above the
4078
+ * quote, the paste replaced them with three, the attribution line and the whole
4079
+ * quoted body survived, and command-S left ONE draft whose `In-Reply-To` and
4080
+ * `References` were unchanged.
4081
+ */
4082
+ /**
4083
+ * How much of the draft's stored text has to match the window's.
4084
+ *
4085
+ * The question is only ever "is this window this draft", and the opening of a
4086
+ * body answers it — two drafts that agree for 120 characters and diverge later
4087
+ * are not something a subject match plus this can tell apart, but they are also
4088
+ * not what goes wrong. What goes wrong is a leftover composer from another
4089
+ * thread, and it disagrees immediately.
4090
+ */
4091
+ const IDENTITY_CHARS = 120;
4092
+ /**
4093
+ * How far the selection may be walked past the block count.
4094
+ *
4095
+ * `blocks` counts paragraphs and the selection moves by rendered lines, so a
4096
+ * body that wraps needs extra presses — one per wrapped line. The bound is
4097
+ * generous because overshooting is not the risk (the copy-back catches it); the
4098
+ * risk is looping on a composer that stopped responding.
4099
+ */
4100
+ const MAX_EXTRA_LINES = 200;
4101
+ /**
4102
+ * How long to wait for a pasted body to reach the accessibility tree.
4103
+ *
4104
+ * Longer than the equivalent in `compose.ts`, and for a measured reason: this
4105
+ * read is not one call but a walk plus a quote-level read per leading block, and
4106
+ * it runs against a WebKit view that has just been handed a paste. On a composer
4107
+ * quoting a long thread the attribute reads themselves started timing out, and
4108
+ * four seconds was not enough for the view to settle and answer.
4109
+ */
4110
+ const RENDER_TIMEOUT_MS = 12e3;
4111
+ const RENDER_POLL_MS = 250;
4112
+ /**
4113
+ * How long to wait for a copy to reach the pasteboard.
4114
+ *
4115
+ * **MEASURED, and it cost a live run.** `apple_desktop_key` answers when the
4116
+ * keystroke is POSTED. Reading the pasteboard on the next line raced Mail's
4117
+ * handling of command-C and read back the sentinel, so a selection that was in
4118
+ * fact made and correct came back as "the selection could not be read" and the
4119
+ * rewrite refused. The hand probe that established this whole sequence had a
4120
+ * 300 ms wait between the two and never saw it.
4121
+ *
4122
+ * The same shape as the focus poll and the render poll: readable is not ready,
4123
+ * so it is polled rather than waited for, and a copy that arrives immediately
4124
+ * costs one read.
4125
+ */
4126
+ const COPY_TIMEOUT_MS = 1500;
4127
+ const COPY_POLL_MS = 50;
4128
+ /** A refusal, shaped like `UPDATE_DRAFT`'s so a caller reads one thing. */
4129
+ const refuse = (capability, facts, reason, hint, extra = {}) => ({
4130
+ replaced: false,
4131
+ degraded: true,
4132
+ method: "inPlace",
4133
+ capability,
4134
+ draft: {
4135
+ subject: facts.subject,
4136
+ isReply: facts.isReply,
4137
+ attachments: facts.attachments,
4138
+ recipientCount: facts.recipientCount
4139
+ },
4140
+ reason,
4141
+ hint,
4142
+ ...extra
4143
+ });
4144
+ /**
4145
+ * Is this window showing this draft?
4146
+ *
4147
+ * Compared on the opening of both, squashed, because the two readings come from
4148
+ * different places — one is Mail's plain-text rendering of the stored message,
4149
+ * the other is what an accessibility client sees a WebKit view display — and
4150
+ * they agree on the words while disagreeing about every line break.
4151
+ */
4152
+ const sameDraft = (stored, shown) => {
4153
+ const a = squash(stored);
4154
+ const b = squash(shown);
4155
+ if (a.length === 0 || b.length === 0) return a.length === b.length;
4156
+ const chars = Math.min(a.length, b.length, IDENTITY_CHARS);
4157
+ return a.slice(0, chars) === b.slice(0, chars);
4158
+ };
4159
+ /**
4160
+ * Select exactly the composer's own text, and prove it.
4161
+ *
4162
+ * The caret goes to the top of the document, the selection is extended down one
4163
+ * rendered line at a time and out to each line's end, and after every extension
4164
+ * it is COPIED and compared. Only an exact match ends the loop.
4165
+ *
4166
+ * Copying is how the selection is read at all: `AXSelectedText` and
4167
+ * `AXSelectedTextRange` both read null on Mail's composer web area, and
4168
+ * `AXSelectedTextMarkerRange` comes back as an opaque `<__NSCFType>` — measured
4169
+ * on macOS 27.0. The pasteboard is the only place the selection is legible.
4170
+ *
4171
+ * A sentinel goes on the clipboard before each copy, because **command-C over
4172
+ * an empty selection leaves the pasteboard alone**: without it, a copy that
4173
+ * never happened reads back as whatever the previous one put there, and the
4174
+ * comparison would be against our own stale answer.
4175
+ */
4176
+ const selectOwnText = async (lane, clipboard, ref, shown, focusTimeoutMs) => {
4177
+ const strokes = [{
4178
+ key: "up",
4179
+ modifiers: ["command"]
4180
+ }];
4181
+ for (let line = 1; line < shown.blocks; line += 1) strokes.push({
4182
+ key: "down",
4183
+ modifiers: ["shift"]
4184
+ });
4185
+ strokes.push({
4186
+ key: "right",
4187
+ modifiers: ["shift", "command"]
4188
+ });
4189
+ if (!await lane.keys(ref, strokes, focusTimeoutMs)) return "unfocused";
4190
+ const wanted = squash(shown.text);
4191
+ for (let extra = 0; extra <= MAX_EXTRA_LINES; extra += 1) {
4192
+ const sentinel = `cupertino-selection-${Date.now()}-${extra}`;
4193
+ await clipboard.write(sentinel);
4194
+ if (!await lane.keys(ref, [{
4195
+ key: "c",
4196
+ modifiers: ["command"]
4197
+ }], focusTimeoutMs)) return "unfocused";
4198
+ const copied = await awaitCopy(clipboard, sentinel);
4199
+ if (copied === null) return "blind";
4200
+ const got = squash(copied);
4201
+ if (got === wanted) return "selected";
4202
+ if (!wanted.startsWith(got)) return "overshot";
4203
+ if (!await lane.keys(ref, [{
4204
+ key: "down",
4205
+ modifiers: ["shift"]
4206
+ }, {
4207
+ key: "right",
4208
+ modifiers: ["shift", "command"]
4209
+ }], focusTimeoutMs)) return "unfocused";
4210
+ }
4211
+ return "overshot";
4212
+ };
4213
+ /**
4214
+ * Wait for the pasteboard to hold something other than the sentinel.
4215
+ *
4216
+ * Null means the copy never arrived — which is what an EMPTY selection looks
4217
+ * like, since command-C over one leaves the pasteboard alone, and is the answer
4218
+ * that stops the rewrite. Anything else is the selection, whatever it says.
4219
+ */
4220
+ const awaitCopy = async (clipboard, sentinel) => {
4221
+ const deadline = Date.now() + COPY_TIMEOUT_MS;
4222
+ for (;;) {
4223
+ const copied = await clipboard.read();
4224
+ if (copied !== null && copied !== sentinel) return copied;
4225
+ if (Date.now() >= deadline) return null;
4226
+ await new Promise((resolve) => setTimeout(resolve, COPY_POLL_MS));
4227
+ }
4228
+ };
4229
+ /** Wait for the composer's own text to read back as what was just pasted. */
4230
+ const awaitOwnText = async (lane, ref, expected, timeoutMs) => {
4231
+ const wanted = squash(expected);
4232
+ const deadline = Date.now() + timeoutMs;
4233
+ for (;;) {
4234
+ const shown = await lane.composerBody(ref.body);
4235
+ if (shown && squash(shown.text) === wanted) return shown;
4236
+ if (Date.now() >= deadline) return null;
4237
+ await new Promise((resolve) => setTimeout(resolve, RENDER_POLL_MS));
4238
+ }
4239
+ };
4240
+ /**
4241
+ * Replace a draft's body in its open composer.
4242
+ *
4243
+ * Null — and only null — means there is no composer to edit, which is the
4244
+ * caller's signal to fall back to recreating the draft. Every other outcome,
4245
+ * including every refusal, is a result the caller returns as it stands.
4246
+ */
4247
+ const reviseDraftInPlace = async (lane, facts, opts) => {
4248
+ const clipboard = opts.clipboard ?? systemClipboard;
4249
+ const renderTimeoutMs = opts.renderTimeoutMs ?? RENDER_TIMEOUT_MS;
4250
+ const watch = lane.watch();
4251
+ if (!(await lane.reach()).ok) return null;
4252
+ const composers = await lane.findComposers(facts.subject);
4253
+ if (composers.length === 0) return null;
4254
+ if (composers.length > 1) return refuse("composer", facts, `${composers.length} composer windows in Mail are titled "${facts.subject}", and nothing here can tell which of them holds this draft — window handles are minted per call. Replacing the body of the wrong one would destroy what is in it, so nothing was touched.`, "Close or finish all but one of those windows in Mail, then try again.");
4255
+ const ref = composers[0];
4256
+ const shown = await lane.composerBody(ref.body);
4257
+ if (!shown) return refuse("composer", facts, `The composer for "${facts.subject}" is open but where its quoted original begins could not be established, so there is no way to tell the draft's own text from the message it quotes. Nothing was changed.`, "Edit the body in Mail directly.");
4258
+ if (!sameDraft(facts.contentHead, shown.text)) return refuse("identity", facts, `A composer titled "${facts.subject}" is open, but what it holds is not what this draft holds — most likely a different message under the same subject, such as another reply in the thread. Rewriting it would destroy text belonging to something else, so nothing was touched.`, "Check which windows are open in Mail, or edit the draft there directly.", {
4259
+ composerText: shown.text.slice(0, 200),
4260
+ draftText: facts.contentHead.slice(0, 200)
4261
+ });
4262
+ const outcome = await borrowClipboard(clipboard, async () => {
4263
+ const selection = shown.blocks === 0 ? await lane.keys(ref, [{
4264
+ key: "up",
4265
+ modifiers: ["command"]
4266
+ }], opts.focusTimeoutMs).then((ok) => ok ? "selected" : "unfocused") : await selectOwnText(lane, clipboard, ref, shown, opts.focusTimeoutMs);
4267
+ if (selection !== "selected") return {
4268
+ selection,
4269
+ shown: null
4270
+ };
4271
+ await clipboard.write(opts.body);
4272
+ if (!await lane.keys(ref, [{
4273
+ key: "v",
4274
+ modifiers: ["command"]
4275
+ }], opts.focusTimeoutMs)) return {
4276
+ selection: "unfocused",
4277
+ shown: null
4278
+ };
4279
+ return {
4280
+ selection,
4281
+ shown: await awaitOwnText(lane, ref, opts.body, renderTimeoutMs)
4282
+ };
4283
+ });
4284
+ if (outcome.selection === "unfocused") return refuse("composer", facts, `The composer for "${facts.subject}" would not take the keyboard, so nothing was typed into it and the draft is unchanged. Someone is probably using the Mac: a keystroke is refused rather than posted into whichever window they moved to.` + interferenceNote(await watch.check()), "Try again once the Mac is free, or edit the draft in Mail.");
4285
+ if (outcome.selection === "blind") return refuse("selection", facts, "The draft's own text could not be selected in its composer: copying the selection back returned nothing, so there is no way to know what a paste would replace. Nothing was changed — selecting and copying do not alter a draft.", "Edit the body in Mail directly.");
4286
+ if (outcome.selection === "overshot") return refuse("selection", facts, "The draft's own text could not be selected exactly: the selection read back does not match what the composer shows above its quoted original, so a paste could not be guaranteed to leave the quote alone. Nothing was changed — selecting and copying do not alter a draft.", "Edit the body in Mail directly, or delete this draft and write it again.");
4287
+ if (!outcome.shown) return refuse("confirmation", facts, `The new body was pasted into the composer for "${facts.subject}" but did not read back as what was sent within ${renderTimeoutMs / 1e3}s, so IT WAS NOT SAVED. The draft still holds its old text; the composer window on screen holds something this could not verify.` + interferenceNote(await watch.check()), "Look at the composer in Mail and either fix it there or close it without saving.");
4288
+ if (shown.quoted && !outcome.shown.quoted) return refuse("confirmation", facts, `The new body went into the composer for "${facts.subject}", but the quoted original that was below it is GONE from the window — so the replacement reached further than the draft's own text. IT WAS NOT SAVED: the draft on disk still holds its old text, quote and all.`, "Close the composer in Mail WITHOUT saving, or undo inside it with command-Z. The draft itself is untouched.");
4289
+ const saved = await lane.finish(false, ref);
4290
+ const disturbed = interferenceNote(await watch.check());
4291
+ const survivors = [
4292
+ ...facts.isReply ? ["its threading"] : [],
4293
+ ...outcome.shown.quoted ? ["the original it quotes"] : [],
4294
+ ...facts.attachments > 0 ? [`its ${facts.attachments} attachment(s)`] : []
4295
+ ];
4296
+ const kept = survivors.length === 0 ? "it is" : `${survivors.slice(0, -1).join(", ")}${survivors.length > 1 ? " and " : ""}${survivors.at(-1)} ${survivors.length > 1 ? "are" : "is"}`;
4297
+ return {
4298
+ replaced: true,
4299
+ method: "inPlace",
4300
+ subject: facts.subject,
4301
+ bodyLength: opts.body.length,
4302
+ threadingKept: facts.isReply,
4303
+ quoteKept: outcome.shown.quoted,
4304
+ attachmentsKept: facts.attachments,
4305
+ recipientCount: facts.recipientCount,
4306
+ draftsMailbox: facts.draftsMailbox,
4307
+ saved: saved === "pressed",
4308
+ note: saved === "pressed" ? `The draft was edited in its own composer window — nothing was recreated, so ${kept} untouched, and no second draft was made. The window is still open in Mail for review. Mail may renumber a saved draft's row within seconds, so re-find it by subject rather than reusing the ref across turns.` + disturbed : saved === "refused" ? "The new body is in the composer and verified, but Mail would not come forward, so command-S was not pressed and the draft on disk still holds the OLD text. The window is open with the new text in it. Press save in Mail, or try again once the Mac is free." + disturbed : "The new body was pasted and verified, and then the composer window went — nothing here closes one, so someone using the Mac closed or sent it. Look in Mail before doing anything else." + disturbed
4309
+ };
4310
+ };
4311
+ //#endregion
3711
4312
  //#region src/client/mail.ts
3712
4313
  /** The FDA sentence, kept verbatim for the case where FDA really is the problem. */
3713
4314
  const FDA_HINT = "The message file could not be read. Grant Full Disk Access to the app running this server and restart it.";
@@ -3725,6 +4326,8 @@ var AppleMailClient = class {
3725
4326
  * which one is live.
3726
4327
  */
3727
4328
  #ax;
4329
+ /** Undefined means the system pasteboard — see `AppleMailClientOptions`. */
4330
+ #clipboard;
3728
4331
  #located = null;
3729
4332
  #index = null;
3730
4333
  #indexError = null;
@@ -3744,6 +4347,7 @@ var AppleMailClient = class {
3744
4347
  ttlMs: opts.config.mailboxCacheTtlMs
3745
4348
  });
3746
4349
  this.#ax = opts.ax !== void 0 ? opts.ax : MailAxLane.open();
4350
+ this.#clipboard = opts.clipboard;
3747
4351
  }
3748
4352
  /** Which composer lane is live, for `diagnostics` to report. */
3749
4353
  get composerLane() {
@@ -4520,13 +5124,31 @@ var AppleMailClient = class {
4520
5124
  return result;
4521
5125
  }
4522
5126
  /**
4523
- * Replace a saved draft's body by recreating it.
5127
+ * Replace a saved draft's body, editing it where that is possible and
5128
+ * recreating it where it is not.
5129
+ *
5130
+ * ## Two lanes, and the order between them is the whole point
5131
+ *
5132
+ * **Editing the open composer comes first.** A draft whose composer is still
5133
+ * on screen — which is every draft this server has just written, because
5134
+ * nothing here closes one — can have its body replaced in that window, and
5135
+ * the save lands on the same draft. Threading, attachments and the quoted
5136
+ * original survive because nothing is remade. See `revise.ts`.
5137
+ *
5138
+ * **Recreating is the fallback.** It composes a replacement and deletes the
5139
+ * original, which is the only thing Mail's scripting interface allows, and it
5140
+ * is why `UPDATE_DRAFT` refuses a reply or a draft carrying attachments.
5141
+ * Those refusals are costs of recreating, not of editing, so they must never
5142
+ * be reached while a window that could simply be edited is open.
4524
5143
  *
4525
- * The refusals live in the script, next to the properties they are read from,
4526
- * and come back as ordinary results carrying `replaced: false` rather than as
4527
- * thrown errors — a caller that cannot rewrite this draft still wants to know
4528
- * WHY, and what to do instead, and both travel better as data than as a
4529
- * message string.
5144
+ * The preflight that decides is only paid when there is a lane to decide for:
5145
+ * with no accessibility lane — a package installed from npm and run by hand —
5146
+ * this goes straight to recreation and costs exactly what it always did.
5147
+ *
5148
+ * The refusals on both lanes come back as ordinary results carrying
5149
+ * `replaced: false` rather than as thrown errors: a caller that cannot rewrite
5150
+ * this draft still wants to know WHY and what to do instead, and both travel
5151
+ * better as data than as a message string.
4530
5152
  *
4531
5153
  * What is enforced here instead is the shape of the request, before Mail is
4532
5154
  * touched at all: an empty body would silently blank a draft the user wrote,
@@ -4535,10 +5157,23 @@ var AppleMailClient = class {
4535
5157
  async updateDraft(ref, opts) {
4536
5158
  if (!opts.body.trim()) throw new PreconditionError("A replacement body cannot be empty. Blanking a draft and reporting success is indistinguishable from having written it, so it is refused here rather than done. Delete the draft with apple_mail_delete_messages if that is what you meant.");
4537
5159
  const decoded = decodeRef(ref);
4538
- return withBusyRetry(() => this.runner.run(UPDATE_DRAFT, {
5160
+ const target = {
4539
5161
  accountUuid: decoded.accountUuid,
4540
5162
  mailbox: decoded.mailbox,
4541
- id: decoded.id,
5163
+ id: decoded.id
5164
+ };
5165
+ if (this.#ax) {
5166
+ const facts = await withBusyRetry(() => this.runner.run(DRAFT_FACTS, target));
5167
+ if (opts.subject === void 0 || opts.subject === facts.subject) {
5168
+ const edited = await reviseDraftInPlace(this.#ax, facts, {
5169
+ body: opts.body,
5170
+ clipboard: this.#clipboard
5171
+ });
5172
+ if (edited) return edited;
5173
+ }
5174
+ }
5175
+ return withBusyRetry(() => this.runner.run(UPDATE_DRAFT, {
5176
+ ...target,
4542
5177
  body: opts.body,
4543
5178
  subject: opts.subject ?? null
4544
5179
  }));
@@ -4571,7 +5206,7 @@ var AppleMailClient = class {
4571
5206
  replyToAll: opts.replyToAll ?? false,
4572
5207
  sendNow: opts.sendNow
4573
5208
  };
4574
- if (this.#ax) return replyOrForwardNatively(this.#ax, this.runner, params);
5209
+ if (this.#ax) return replyOrForwardNatively(this.#ax, this.runner, params, this.#clipboard ? { clipboard: this.#clipboard } : {});
4575
5210
  return this.runner.run(REPLY_OR_FORWARD, params);
4576
5211
  }
4577
5212
  #withRef(m) {
@@ -5195,11 +5830,11 @@ const registerComposeTools = (server, client) => {
5195
5830
  });
5196
5831
  }));
5197
5832
  server.registerTool("apple_mail_update_draft", {
5198
- description: "Replace the body of an unsent draft. Mail has no way to edit a saved draft — its `content` is read-only and there is no open or edit command — so this RECREATES it: a new draft with the same recipients and a new body, and the old one deleted once the replacement is confirmed present. The ref you passed in is DEAD afterwards and the result carries the new one. It REFUSES rather than doing damage, and returns `replaced: false` with a reason when it does: on a reply or forward draft, because In-Reply-To is set by Mail's reply command and a recreated one would silently start a new thread; on a draft carrying attachments, because their bytes are not available as files to re-attach; and on anything not in the Drafts mailbox, because deleting a sent or received message and writing a lookalike is not editing. In every refusal the original is untouched. If the replacement cannot be confirmed the original is KEPT and you are told there are now two — never assume a clean swap without reading `replaced`.",
5833
+ description: "Replace the body of an unsent draft — including a REPLY draft you have just written and been asked to revise, which is the usual reason to reach for this. It takes one of two routes and the result says which in `method`. `inPlace`: the draft's own composer window is still open in Mail, so the body is edited in that window. Nothing is recreated, so threading, attachments and the quoted original all survive, no second draft appears, and your ref stays valid — though Mail may renumber a saved draft within seconds, so re-find it by subject rather than reusing a ref across turns. `recreate`: no composer is open, so a new draft is composed with the same recipients and the old one deleted once the replacement is confirmed present; the ref you passed in is DEAD afterwards and the result carries the new one. It REFUSES rather than doing damage, and returns `replaced: false` with a reason when it does. Editing in place refuses when two composers share the subject, when the open window turns out to hold a different message, or when the draft's own text cannot be selected exactly — it will not risk swallowing the quoted original. Recreating refuses on a reply or forward draft, because In-Reply-To is set by Mail's reply command and a recreated one would silently start a new thread; on a draft carrying attachments, because their bytes are not available as files to re-attach; and on anything not in the Drafts mailbox, because deleting a sent or received message and writing a lookalike is not editing. In every refusal the original is untouched. If a recreated replacement cannot be confirmed the original is KEPT and you are told there are now two — never assume a clean swap without reading `replaced`. Editing in place brings Mail to the front for a moment and borrows the clipboard, both of which are put back.",
5199
5834
  inputSchema: {
5200
5835
  ref: messageRefArg,
5201
5836
  body: z.string().min(1).describe("The complete new body. This REPLACES the draft's text rather than appending to it, so include everything that should remain — read the draft first with apple_mail_get_message if you are editing rather than rewriting."),
5202
- subject: z.string().optional().describe("A new subject. Defaults to the draft's existing one. A draft with no subject at all is refused unless you pass one, because the subject is how the replacement is found again before the original is deleted."),
5837
+ subject: z.string().optional().describe("A new subject. Defaults to the draft's existing one — OMIT IT unless the subject really is changing, because changing it forces the recreate route (a composer's subject field cannot be retyped from here), which in turn refuses a reply. On that route a draft with no subject at all is refused unless you pass one, because the subject is how the replacement is found again before the original is deleted."),
5203
5838
  confirm: confirmArg
5204
5839
  },
5205
5840
  annotations: {
@@ -5600,4 +6235,4 @@ const createServer = (opts) => {
5600
6235
  //#endregion
5601
6236
  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 };
5602
6237
 
5603
- //# sourceMappingURL=server-DsaFsRg0.js.map
6238
+ //# sourceMappingURL=server-pL69NC1O.js.map