car-integrations 0.53.0

OS-native account-bound integrations (Calendar, Contacts, Mail) for CAR
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
//! Mail capability — enumerate accounts and mailboxes, summarize inbox, read
//! message rows and bodies, send/draft.
//!
//! The read surface is deliberately three calls rather than one: discover
//! ([`list_mailboxes`]), read rows ([`list_messages`]), then fetch a body
//! ([`message_body`]). It used to be [`list_inbox`] alone, which could only
//! ever see INBOX and returned no message id — so an agent looking for a
//! flight confirmation that a mail rule had already filed into "Travel" got an
//! empty result and said "no upcoming travel". That answer is *silently*
//! wrong: it reads as "no results" rather than "cannot see there"
//! (Parslee-ai/car-releases#84). Anything added here should preserve that
//! distinction — return `available: false` with a reason rather than an empty
//! list whenever the backend could not look.
//!
//! Unlike Calendar + Contacts, Mail has no clean *local* OS-native read API
//! off macOS — a real, structural parity gap, not merely unwired plumbing:
//!
//! - **macOS** — the one platform with a zero-setup local backend: JXA against
//!   Mail.app (below).
//! - **Windows** — there is no populated local mail store to read. The People
//!   and Calendar apps aggregate the user's connected accounts into the WinRT
//!   Contacts/Appointments stores (which is exactly why `windows_contacts` /
//!   `windows_calendar` read locally, unpackaged), but *no* modern mail app
//!   plays the equivalent `Windows.ApplicationModel.Email.EmailStore`
//!   data-provider role — the old Mail app is deprecated and the new Outlook is
//!   cloud-only. Verified 2026-07-26 from an unpackaged exe on a box with real
//!   connected accounts (Contacts/Calendar returned data):
//!   `EmailManager::RequestStoreAsync` succeeds but `FindMailboxesAsync`
//!   returns **0 mailboxes** for both `AppMailboxesReadWrite` and
//!   `AllMailboxesLimitedReadWrite`. Whether that 0 is the restricted `email`
//!   capability silently denying enumeration for an unpackaged process or the
//!   absent data provider, the outcome for CAR's unpackaged `.exe` is the same:
//!   nothing to read, so a WinRT mail backend is not viable. COM/MAPI reaches
//!   only *classic* Outlook (not new Outlook), needs it installed + running,
//!   and trips the Outlook programmatic-access security model — not a clean
//!   parity backend either. So do not re-chase `EmailStore` or MAPI here.
//! - **Linux** — no local backend (Evolution Data Server would be the candidate).
//!
//! Off macOS the backend is therefore **Microsoft Graph** (M365 mail, when
//! `CAR_MSGRAPH_CLIENT_ID` is set) — the same account CAR already reaches for
//! Graph contacts/calendar. The genuinely cross-platform *local* answer is an
//! IMAP + SMTP client keyed off [`car-accounts`](car_accounts) with credentials
//! from [`car-secrets`](car_secrets); it is not yet wired and, needing
//! per-account credentials, is not the zero-setup parity Mail.app gives macOS.
//!
//! Side-effecting operations (send, draft, delete) should always be
//! approval-gated at the product layer — this crate exposes them but does
//! not enforce consent UX.

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use super::{Availability, IntegrationError};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MailAccount {
    pub id: String,
    pub address: String,
    pub display_name: Option<String>,
    pub provider_hint: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InboxSummary {
    pub account_id: String,
    pub unread: u32,
    pub total: u32,
    pub most_recent_subject: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccountListing {
    #[serde(flatten)]
    pub availability: Availability,
    pub accounts: Vec<MailAccount>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InboxListing {
    #[serde(flatten)]
    pub availability: Availability,
    pub summaries: Vec<InboxSummary>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SendRequest {
    pub account_id: String,
    pub to: Vec<String>,
    #[serde(default)]
    pub cc: Vec<String>,
    #[serde(default)]
    pub bcc: Vec<String>,
    pub subject: String,
    pub body: String,
    /// When `true`, just save the message as a draft — don't send.
    #[serde(default)]
    pub draft_only: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SendResult {
    #[serde(flatten)]
    pub availability: Availability,
    /// `true` if the message was actually sent or drafted.
    pub sent: bool,
    pub message_id: Option<String>,
}

/// A mailbox (folder) inside one mail account.
///
/// `full_name` is the **selector**: pass it back verbatim as
/// [`MessageQuery::mailbox`] to read that mailbox. On macOS it is the
/// slash-joined path from the account root (`"Travel"`, `"Travel/2026"`); on
/// Microsoft Graph it is the folder id. `name` is the leaf label for display.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Mailbox {
    pub account_id: String,
    pub name: String,
    pub full_name: String,
    pub unread: u32,
    pub total: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MailboxListing {
    #[serde(flatten)]
    pub availability: Availability,
    #[serde(default)]
    pub mailboxes: Vec<Mailbox>,
}

/// One message row. Header-weight by design — `body` is populated only when
/// the caller asked for it via [`MessageQuery::include_body`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageSummary {
    /// Opaque, backend-qualified id — feed it straight back to
    /// [`message_body`]. Callers should not parse it; [`decode_message_id`]
    /// is the only supported reader.
    pub id: String,
    pub account_id: String,
    /// The mailbox this row came from, as the backend **resolved** it — not
    /// the selector the caller typed. Same shape as [`Mailbox::full_name`], so
    /// a row asked for as `"travel"` comes back stamped `"Travel/2026"` and
    /// can be matched against [`list_mailboxes`] output.
    pub mailbox: String,
    pub subject: Option<String>,
    pub sender: Option<String>,
    #[serde(default)]
    pub recipients: Vec<String>,
    pub date_received: Option<DateTime<Utc>>,
    pub read: bool,
    /// Short excerpt. Graph returns `bodyPreview` for free; Mail.app has no
    /// cheap equivalent, so on macOS this is `None` unless `include_body` was
    /// set — in which case it is the head of the body.
    pub preview: Option<String>,
    pub body: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageListing {
    #[serde(flatten)]
    pub availability: Availability,
    pub messages: Vec<MessageSummary>,
}

/// Which messages to read.
///
/// Every field has a default, and the defaults reproduce the pre-existing
/// INBOX-only behaviour: `mailbox: None` means [`DEFAULT_MAILBOX`], so a
/// caller that sends `{}` reads exactly what it read before this query
/// existed.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageQuery {
    #[serde(default)]
    pub account_ids: Vec<String>,
    /// Mailbox selector — a [`Mailbox::full_name`], or a bare leaf name like
    /// `"Travel"`. `None` reads [`DEFAULT_MAILBOX`].
    #[serde(default)]
    pub mailbox: Option<String>,
    #[serde(default = "default_limit")]
    pub limit: usize,
    /// Drop messages received before this instant. Applied *before* `limit`,
    /// so a narrow window still yields the newest `limit` matches rather than
    /// whatever survives a pre-filtered slice.
    #[serde(default)]
    pub since: Option<DateTime<Utc>>,
    #[serde(default)]
    pub include_body: bool,
}

impl Default for MessageQuery {
    fn default() -> Self {
        Self {
            account_ids: Vec::new(),
            mailbox: None,
            limit: default_limit(),
            since: None,
            include_body: false,
        }
    }
}

fn default_limit() -> usize {
    50
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageBodyResult {
    #[serde(flatten)]
    pub availability: Availability,
    /// Echo of the requested id, so a caller fetching several bodies can
    /// correlate replies without tracking call order.
    pub id: String,
    /// `"text"` or `"html"`.
    pub content_type: String,
    pub body: Option<String>,
    /// `true` when the body was cut at [`MESSAGE_BODY_CAP`].
    pub truncated: bool,
}

/// The mailbox read when [`MessageQuery::mailbox`] is `None`.
pub const DEFAULT_MAILBOX: &str = "INBOX";

/// Ceiling on a returned message body, in characters. A body is an unbounded
/// blob that has to cross a pipe (JXA stdout), the FFI boundary, and a
/// JSON-RPC frame; cut it once, here, and say so via
/// [`MessageBodyResult::truncated`] rather than letting one 40 MB newsletter
/// decide the size of a response.
pub const MESSAGE_BODY_CAP: usize = 100_000;

const MAILAPP_ID_PREFIX: &str = "mailapp";
const MSGRAPH_ID_PREFIX: &str = "msgraph";

/// A decoded [`MessageSummary::id`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MessageRef {
    /// Mail.app. Its numeric message id is only addressable *inside* one
    /// mailbox of one account, so the account and mailbox have to travel with
    /// it — which is the whole reason the wire id is composite rather than the
    /// bare number.
    MailApp {
        account_id: String,
        mailbox: String,
        local_id: String,
    },
    /// Microsoft Graph, whose id is addressable on its own.
    Graph { id: String },
}

fn b64(s: &str) -> String {
    URL_SAFE_NO_PAD.encode(s.as_bytes())
}

fn unb64(s: &str) -> Option<String> {
    String::from_utf8(URL_SAFE_NO_PAD.decode(s.as_bytes()).ok()?).ok()
}

/// Build the Mail.app composite id. The two variable-length components are
/// base64url'd because account names and mailbox paths carry `:` and `/`
/// freely, and this string has to survive JXA `argv` and the JSON wire
/// without an escaping rule of its own.
pub fn encode_message_id(account_id: &str, mailbox: &str, local_id: &str) -> String {
    format!(
        "{MAILAPP_ID_PREFIX}:{}:{}:{local_id}",
        b64(account_id),
        b64(mailbox)
    )
}

/// Build the Graph id. Graph ids are already opaque and globally unique, so
/// they only get the backend tag.
pub fn encode_graph_message_id(graph_id: &str) -> String {
    format!("{MSGRAPH_ID_PREFIX}:{graph_id}")
}

/// Inverse of [`encode_message_id`] / [`encode_graph_message_id`].
pub fn decode_message_id(id: &str) -> Result<MessageRef, IntegrationError> {
    let bad = || IntegrationError::Backend(format!("not a CAR mail message id: {id}"));
    let (prefix, rest) = id.split_once(':').ok_or_else(bad)?;
    match prefix {
        MSGRAPH_ID_PREFIX => {
            if rest.is_empty() {
                return Err(bad());
            }
            Ok(MessageRef::Graph {
                id: rest.to_string(),
            })
        }
        MAILAPP_ID_PREFIX => {
            // Exactly three fields: neither base64url component can contain a
            // `:`, and the numeric tail never does either.
            let mut parts = rest.splitn(3, ':');
            let account_id = unb64(parts.next().ok_or_else(bad)?).ok_or_else(bad)?;
            let mailbox = unb64(parts.next().ok_or_else(bad)?).ok_or_else(bad)?;
            let local_id = parts.next().ok_or_else(bad)?.to_string();
            if local_id.is_empty() {
                return Err(bad());
            }
            Ok(MessageRef::MailApp {
                account_id,
                mailbox,
                local_id,
            })
        }
        _ => Err(bad()),
    }
}

pub fn list_accounts() -> Result<AccountListing, IntegrationError> {
    backend::list_accounts()
}

/// Short inbox summary per account. For accounts where the backend can't
/// reach the server, the summary is omitted.
pub fn list_inbox(account_ids: &[String]) -> Result<InboxListing, IntegrationError> {
    backend::list_inbox(account_ids)
}

/// Enumerate every mailbox of the requested accounts (all accounts when the
/// slice is empty), including nested ones.
///
/// This exists because [`list_inbox`] could only ever see INBOX, and any user
/// with server-side rules has their most useful mail *already filed out of
/// INBOX* by the time an agent looks — so an INBOX-only scan reports "no
/// results" where the honest answer is "cannot see there"
/// (Parslee-ai/car-releases#84).
pub fn list_mailboxes(account_ids: &[String]) -> Result<MailboxListing, IntegrationError> {
    backend::list_mailboxes(account_ids)
}

/// Read message rows from one mailbox per account, newest first.
///
/// "Newest first" is global, not per account: rows from every matched account
/// are merged into one date-ordered list before [`MessageQuery::limit`] is
/// applied, so `limit: 1` over two accounts returns the newer of the two
/// messages rather than whichever account Mail happened to list first.
///
/// Rows carry a stable [`MessageSummary::id`] that [`message_body`] accepts.
pub fn list_messages(query: MessageQuery) -> Result<MessageListing, IntegrationError> {
    backend::list_messages(query)
}

/// Fetch one message's body by the id from [`list_messages`].
pub fn message_body(message_id: &str) -> Result<MessageBodyResult, IntegrationError> {
    backend::message_body(message_id)
}

/// Send or draft a message through the active platform mail backend.
pub fn send(req: SendRequest) -> Result<SendResult, IntegrationError> {
    backend::send(req)
}

#[cfg(target_os = "macos")]
mod backend {
    use super::*;

    // `pub(super)` only so the tests below can run this exact script against a
    // stubbed `mailApp()`. Without that the whole mailbox walk, selector
    // resolution, and sort/since/limit pipeline is an untested JS string —
    // which is how the multi-account ordering bug got in.
    pub(super) const JXA: &str = r#"
function normalizeAccount(account) {
  let name = "";
  let id = "";
  let addresses = [];
  try { name = String(account.name()); } catch (e) {}
  try { id = String(account.id()); } catch (e) {}
  if (!id) id = name;
  try { addresses = account.emailAddresses().map(String); } catch (e) {}
  return {
    id: id,
    address: addresses[0] || name,
    display_name: name || null,
    provider_hint: null
  };
}

function accountMatches(account, requested) {
  if (requested.length === 0) return true;
  const normalized = normalizeAccount(account);
  return requested.indexOf(normalized.id) >= 0 || requested.indexOf(normalized.address) >= 0 || requested.indexOf(normalized.display_name || "") >= 0;
}

function mailApp() {
  const app = Application("/System/Applications/Mail.app");
  app.includeStandardAdditions = true;
  return app;
}

// A `byName` specifier is lazy — it resolves (or throws) only when a property
// is read off it, so "did I get a real mailbox" needs an actual touch.
function mailboxUsable(box) {
  try { box.name(); return true; } catch (e) { return false; }
}

// Depth-first walk of every mailbox under `container` (an account or a
// mailbox), yielding {name, full_name, box}. Counts are deliberately NOT read
// here: resolution doesn't need them, and reading them is what makes an
// enumeration expensive.
function walkMailboxes(container, prefix, out, depth) {
  let boxes = [];
  try { boxes = container.mailboxes(); } catch (e) { return; }
  for (let i = 0; i < boxes.length; i++) {
    const box = boxes[i];
    let name = "";
    try { name = String(box.name()); } catch (e) { continue; }
    const full = prefix ? prefix + "/" + name : name;
    out.push({name: name, full_name: full, box: box});
    if (depth < 8) walkMailboxes(box, full, out, depth + 1);
  }
}

// Resolve a mailbox selector: the fast `byName` path first (which is what
// INBOX always hits), then a full-path match, then a leaf-name match. The last
// two are case-insensitive because mailbox names are localized and users type
// "travel".
//
// Returns `{box, full_name}`, not the bare box: the RESOLVED path has to
// travel with the mailbox so a row can report where it actually came from
// instead of echoing whatever selector the caller typed. A caller that asked
// for "travel" and got rows stamped "travel" cannot match them against
// `mail.mailboxes` output; stamped "Travel/2026" it can.
function resolveMailbox(account, wanted) {
  const target = String(wanted || "INBOX");
  let direct = null;
  try { direct = account.mailboxes.byName(target); } catch (e) {}
  if (direct && mailboxUsable(direct)) {
    // `byName` only ever reaches a top-level mailbox, so its own name IS the
    // full path — read it back so the casing is Mail's, not the caller's.
    let name = target;
    try { name = String(direct.name()); } catch (e) {}
    return {box: direct, full_name: name};
  }
  const all = [];
  walkMailboxes(account, "", all, 0);
  const lower = target.toLowerCase();
  for (let i = 0; i < all.length; i++) {
    if (all[i].full_name.toLowerCase() === lower) return {box: all[i].box, full_name: all[i].full_name};
  }
  for (let i = 0; i < all.length; i++) {
    if (all[i].name.toLowerCase() === lower) return {box: all[i].box, full_name: all[i].full_name};
  }
  return null;
}

// Newest first. `date_received` is an ISO-8601 `Z` string, so a plain string
// compare IS the chronological compare; rows with no date sort to the end
// rather than to the front.
function byDateDesc(a, b) {
  const x = String(a.date_received || "");
  const y = String(b.date_received || "");
  if (x === y) return 0;
  return x < y ? 1 : -1;
}

// "No account matched what you asked for" must not read as "you have no mail".
function unmatchedAccounts(requested) {
  return "no mail account matched " + requested.join(", ") + " — list them with mail.accounts";
}

function truncateBody(text, cap) {
  const s = String(text);
  if (cap > 0 && s.length > cap) return {body: s.slice(0, cap), truncated: true};
  return {body: s, truncated: false};
}

function run(argv) {
  const mode = argv[0] || "accounts";
  let Mail;
  try {
    Mail = mailApp();
  } catch (e) {
    return JSON.stringify({available:false, backend:"mail_app", reason:String(e), accounts:[], summaries:[], mailboxes:[], messages:[], content_type:"text", body:null, truncated:false, sent:false, message_id:null});
  }

  if (mode === "accounts") {
    try {
      return JSON.stringify({available:true, backend:"mail_app", reason:null, accounts: Mail.accounts().map(normalizeAccount)});
    } catch (e) {
      return JSON.stringify({available:false, backend:"mail_app", reason:String(e), accounts:[]});
    }
  }

  if (mode === "inbox") {
    const requested = argv.slice(1);
    const summaries = [];
    try {
      Mail.accounts().forEach(account => {
        if (!accountMatches(account, requested)) return;
        const normalized = normalizeAccount(account);
        let unread = 0;
        let total = 0;
        let subject = null;
        try {
          const inbox = account.mailboxes.byName("INBOX");
          const messages = inbox.messages();
          total = messages.length;
          for (let i = 0; i < messages.length; i++) {
            const message = messages[i];
            try { if (message.readStatus() === false) unread += 1; } catch (e) {}
            if (subject === null) {
              try { subject = String(message.subject()); } catch (e) {}
            }
          }
        } catch (e) {}
        summaries.push({account_id: normalized.id, unread: unread, total: total, most_recent_subject: subject});
      });
      return JSON.stringify({available:true, backend:"mail_app", reason:null, summaries:summaries});
    } catch (e) {
      return JSON.stringify({available:false, backend:"mail_app", reason:String(e), summaries:[]});
    }
  }

  if (mode === "mailboxes") {
    const requested = argv.slice(1);
    const mailboxes = [];
    let matchedAccounts = 0;
    try {
      Mail.accounts().forEach(account => {
        if (!accountMatches(account, requested)) return;
        matchedAccounts += 1;
        const normalized = normalizeAccount(account);
        const all = [];
        walkMailboxes(account, "", all, 0);
        for (let i = 0; i < all.length; i++) {
          let unread = 0;
          let total = 0;
          try { unread = Number(all[i].box.unreadCount()); } catch (e) {}
          // `.length` on the element specifier is a `count` Apple Event — one
          // round trip. Calling `messages()` first would materialize every
          // specifier in the mailbox just to count them.
          try { total = Number(all[i].box.messages.length); } catch (e) {}
          mailboxes.push({
            account_id: normalized.id,
            name: all[i].name,
            full_name: all[i].full_name,
            unread: isFinite(unread) ? unread : 0,
            total: isFinite(total) ? total : 0
          });
        }
      });
      // An `account_ids` filter that matched nothing is a caller error, not an
      // account with no folders — say so instead of returning an empty list.
      if (matchedAccounts === 0 && requested.length > 0) {
        return JSON.stringify({available:false, backend:"mail_app", reason:unmatchedAccounts(requested), mailboxes:[]});
      }
      return JSON.stringify({available:true, backend:"mail_app", reason:null, mailboxes:mailboxes});
    } catch (e) {
      return JSON.stringify({available:false, backend:"mail_app", reason:String(e), mailboxes:[]});
    }
  }

  if (mode === "messages") {
    try {
      const q = JSON.parse(argv[1] || "{}");
      const requested = q.account_ids || [];
      const wanted = q.mailbox || "INBOX";
      const limit = q.limit > 0 ? q.limit : 50;
      const since = q.since ? String(q.since) : null;
      const includeBody = q.include_body === true;
      const bodyCap = q.body_cap > 0 ? q.body_cap : 100000;
      // Every matched account contributes into ONE candidate array, which is
      // sorted and sliced ONCE at the end. Sorting and slicing per account and
      // concatenating makes the answer depend on account order: with an iCloud
      // and an Exchange account both holding a "Travel" mailbox, `limit: 1`
      // returns iCloud's newest message even when Exchange holds a newer one,
      // and `limit: 10` returns rows that are not in date order at all. That is
      // the same silent miss this surface exists to end, one level down
      // (Parslee-ai/car-releases#84) — and "newest first" is a documented
      // contract, not a best effort.
      const candidates = [];
      let matchedAccounts = 0;
      let resolvedMailbox = false;
      Mail.accounts().forEach(account => {
        if (!accountMatches(account, requested)) return;
        matchedAccounts += 1;
        const normalized = normalizeAccount(account);
        const hit = resolveMailbox(account, wanted);
        if (!hit) return;
        resolvedMailbox = true;
        const msgs = hit.box.messages;

        // Bulk array property gets: five Apple Events for the WHOLE mailbox,
        // whatever its size. The pre-existing inbox walk above reads each
        // property off each message individually, which is one Apple Event per
        // message per field — that is why a full mailbox scan flirts with the
        // 15s host timeout, and it is the thing not to repeat here.
        let ids = null, subjects = null, senders = null, dates = null, reads = null;
        try { ids = msgs.id(); } catch (e) {}
        try { subjects = msgs.subject(); } catch (e) {}
        try { senders = msgs.sender(); } catch (e) {}
        try { dates = msgs.dateReceived(); } catch (e) {}
        try { reads = msgs.readStatus(); } catch (e) {}

        const items = [];
        if (ids !== null) {
          for (let i = 0; i < ids.length; i++) {
            let iso = null;
            try { if (dates && dates[i]) iso = new Date(dates[i]).toISOString(); } catch (e) {}
            items.push({
              msgs: msgs,
              account_id: normalized.id,
              mailbox: hit.full_name,
              index: i,
              local_id: String(ids[i]),
              subject: subjects && subjects[i] != null ? String(subjects[i]) : null,
              sender: senders && senders[i] != null ? String(senders[i]) : null,
              date_received: iso,
              read: reads ? reads[i] === true : false
            });
          }
        } else {
          // Fallback when a bulk get throws (some IMAP accounts refuse them):
          // per-message reads, but bounded — never a whole-mailbox loop.
          let count = 0;
          try { count = Number(msgs.length); } catch (e) {}
          const scan = Math.min(count, limit * 4);
          for (let i = 0; i < scan; i++) {
            try {
              const m = msgs[i];
              let iso = null;
              try { iso = new Date(m.dateReceived()).toISOString(); } catch (e) {}
              items.push({
                msgs: msgs,
                account_id: normalized.id,
                mailbox: hit.full_name,
                index: i,
                local_id: String(m.id()),
                subject: (function(){ try { return String(m.subject()); } catch (e) { return null; } })(),
                sender: (function(){ try { return String(m.sender()); } catch (e) { return null; } })(),
                date_received: iso,
                read: (function(){ try { return m.readStatus() === true; } catch (e) { return false; } })()
              });
            } catch (e) {}
          }
        }

        // Per-account: newest first, then `since`, then at most `limit`
        // forwarded to the combined pool. Filtering before the slice is what
        // makes a narrow `since` window return real matches instead of
        // whatever happened to land in the first `limit` rows. Capping at
        // `limit` here is lossless for the global answer — `since` keeps a
        // PREFIX of a newest-first list, so an account can never own a
        // globally-selected row from beyond its own newest `limit` — and it
        // keeps one 200k-message mailbox from dominating the combined sort.
        items.sort(byDateDesc);
        let taken = 0;
        for (let i = 0; i < items.length && taken < limit; i++) {
          if (since && (!items[i].date_received || items[i].date_received < since)) continue;
          candidates.push(items[i]);
          taken += 1;
        }
      });
      // "No account matched what you asked for" and "that mailbox does not
      // exist here" must NOT look like "that mailbox is empty" — the
      // silent-empty answer is the whole failure this surface exists to end
      // (Parslee-ai/car-releases#84).
      if (matchedAccounts === 0 && requested.length > 0) {
        return JSON.stringify({available:false, backend:"mail_app", reason:unmatchedAccounts(requested), messages:[]});
      }
      if (matchedAccounts > 0 && !resolvedMailbox) {
        return JSON.stringify({available:false, backend:"mail_app", reason:"no mailbox named "+wanted+" in the selected account(s) — list them with mail.mailboxes", messages:[]});
      }
      // The ONE global sort. Only the rows that survive it pay for the per-row
      // Apple Events below, so a multi-account read costs no more round trips
      // than a single-account one did.
      candidates.sort(byDateDesc);
      const rows = [];
      for (let i = 0; i < candidates.length && rows.length < limit; i++) {
        const item = candidates[i];
        const row = {
          account_id: item.account_id,
          mailbox: item.mailbox,
          local_id: item.local_id,
          subject: item.subject,
          sender: item.sender,
          recipients: [],
          date_received: item.date_received,
          read: item.read,
          preview: null,
          body: null
        };
        // Per-row reads, bounded by `limit` rather than by mailbox size.
        try { row.recipients = item.msgs[item.index].toRecipients.address().map(String); } catch (e) {}
        if (includeBody) {
          try {
            const cut = truncateBody(item.msgs[item.index].content(), bodyCap);
            row.body = cut.body;
            row.preview = cut.body.slice(0, 200);
          } catch (e) {}
        }
        rows.push(row);
      }
      return JSON.stringify({available:true, backend:"mail_app", reason:null, messages:rows});
    } catch (e) {
      return JSON.stringify({available:false, backend:"mail_app", reason:String(e), messages:[]});
    }
  }

  if (mode === "body") {
    const accountId = String(argv[1] || "");
    const wanted = String(argv[2] || "INBOX");
    const localId = String(argv[3] || "");
    const bodyCap = Number(argv[4] || 100000);
    try {
      let found = null;
      const accounts = Mail.accounts();
      for (let a = 0; a < accounts.length && !found; a++) {
        if (!accountMatches(accounts[a], [accountId])) continue;
        const hit = resolveMailbox(accounts[a], wanted);
        if (!hit) continue;
        const box = hit.box;
        const numeric = parseInt(localId, 10);
        if (isFinite(numeric)) {
          try {
            const hits = box.messages.whose({id: numeric})();
            if (hits.length > 0) found = hits[0];
          } catch (e) {}
        }
        if (!found) {
          // `whose` is unsupported on some account types; fall back to one
          // bulk id fetch plus an index lookup, not a per-message probe.
          try {
            const ids = box.messages.id();
            for (let i = 0; i < ids.length; i++) {
              if (String(ids[i]) === localId) { found = box.messages[i]; break; }
            }
          } catch (e) {}
        }
      }
      if (!found) {
        return JSON.stringify({available:false, backend:"mail_app", reason:"message "+localId+" not found in mailbox "+wanted, content_type:"text", body:null, truncated:false});
      }
      let raw = null;
      try { raw = found.content(); } catch (e) {
        return JSON.stringify({available:false, backend:"mail_app", reason:String(e), content_type:"text", body:null, truncated:false});
      }
      const cut = truncateBody(raw === null ? "" : raw, bodyCap);
      return JSON.stringify({available:true, backend:"mail_app", reason:null, content_type:"text", body:cut.body, truncated:cut.truncated});
    } catch (e) {
      return JSON.stringify({available:false, backend:"mail_app", reason:String(e), content_type:"text", body:null, truncated:false});
    }
  }

  if (mode === "send") {
    try {
      const req = JSON.parse(argv[1] || "{}");
      const msg = Mail.OutgoingMessage({
        subject: req.subject || "",
        content: req.body || "",
        visible: false
      });
      Mail.outgoingMessages.push(msg);
      (req.to || []).forEach(address => msg.toRecipients.push(Mail.Recipient({address: String(address)})));
      (req.cc || []).forEach(address => msg.ccRecipients.push(Mail.Recipient({address: String(address)})));
      (req.bcc || []).forEach(address => msg.bccRecipients.push(Mail.Recipient({address: String(address)})));
      if (req.account_id) {
        const accounts = Mail.accounts();
        let matched = null;
        for (let i = 0; i < accounts.length; i++) {
          const normalized = normalizeAccount(accounts[i]);
          if (normalized.id === req.account_id || normalized.address === req.account_id || normalized.display_name === req.account_id) {
            matched = normalized;
            break;
          }
        }
        // A specified-but-unresolvable account must NOT silently fall
        // through to Mail's default outgoing account (car-releases#47).
        if (!matched) {
          return JSON.stringify({available:true, backend:"mail_app", reason:"sender_override_failed: requested account "+String(req.account_id)+" not found", sent:false, message_id:null});
        }
        // The JXA `sender` setter throws under some Mail/account-type
        // combos (EWS vs IMAP) and can also no-op without throwing.
        // Set it, then read it back and confirm the address actually
        // took — never assume success.
        let setError = null;
        try { msg.sender(matched.address); } catch (e) { setError = String(e); }
        let effective = null;
        try { effective = String(msg.sender()); } catch (e) {}
        const wanted = String(matched.address || "").toLowerCase();
        const took = wanted.length > 0 && effective !== null &&
                     String(effective).toLowerCase().indexOf(wanted) !== -1;
        if (!took) {
          return JSON.stringify({available:true, backend:"mail_app", reason:"sender_override_failed: requested "+matched.address+", effective "+String(effective)+(setError ? " (setter error: "+setError+")" : ""), sent:false, message_id:null});
        }
      }
      if (req.draft_only) {
        msg.save();
      } else {
        msg.send();
      }
      let messageId = null;
      try { messageId = String(msg.id()); } catch (e) {}
      return JSON.stringify({available:true, backend:"mail_app", reason:null, sent:true, message_id:messageId});
    } catch (e) {
      return JSON.stringify({available:false, backend:"mail_app", reason:String(e), sent:false, message_id:null});
    }
  }

  return JSON.stringify({available:false, backend:"mail_app", reason:"unknown mail mode", accounts:[], summaries:[], mailboxes:[], messages:[], content_type:"text", body:null, truncated:false, sent:false, message_id:null});
}
"#;

    pub fn list_accounts() -> Result<AccountListing, IntegrationError> {
        let mail_listing: AccountListing = run_jxa(&["accounts"])?;
        if mail_listing.availability.available || !mail_listing.accounts.is_empty() {
            return Ok(mail_listing);
        }

        let accounts = car_accounts::list()
            .map_err(|e| IntegrationError::Backend(format!("accounts fallback: {e}")))?
            .accounts
            .into_iter()
            .filter(|account| account.capabilities.iter().any(|cap| cap == "mail"))
            .map(|account| MailAccount {
                id: account.id,
                address: account.identifier.unwrap_or(account.label.clone()),
                display_name: Some(account.label),
                provider_hint: Some(account.provider),
            })
            .collect();

        Ok(AccountListing {
            availability: Availability::available("internet_accounts"),
            accounts,
        })
    }

    pub fn list_inbox(account_ids: &[String]) -> Result<InboxListing, IntegrationError> {
        let mut args = vec!["inbox"];
        args.extend(account_ids.iter().map(String::as_str));
        run_jxa(&args)
    }

    pub fn send(req: SendRequest) -> Result<SendResult, IntegrationError> {
        let req_json = serde_json::to_string(&req)
            .map_err(|e| IntegrationError::Backend(format!("mail request json: {e}")))?;
        run_jxa(&["send", req_json.as_str()])
    }

    pub fn list_mailboxes(account_ids: &[String]) -> Result<MailboxListing, IntegrationError> {
        let mut args = vec!["mailboxes"];
        args.extend(account_ids.iter().map(String::as_str));
        run_jxa(&args)
    }

    /// A row as JXA emits it: everything but the composite id, which JXA
    /// cannot build (no base64 in the JXA global scope) and which is Rust's
    /// job anyway — one encoder, one decoder, both unit-tested.
    #[derive(Deserialize)]
    struct RawMessage {
        #[serde(default)]
        account_id: String,
        #[serde(default)]
        mailbox: String,
        #[serde(default)]
        local_id: String,
        subject: Option<String>,
        sender: Option<String>,
        #[serde(default)]
        recipients: Vec<String>,
        date_received: Option<DateTime<Utc>>,
        #[serde(default)]
        read: bool,
        preview: Option<String>,
        body: Option<String>,
    }

    #[derive(Deserialize)]
    struct RawMessageListing {
        #[serde(flatten)]
        availability: Availability,
        #[serde(default)]
        messages: Vec<RawMessage>,
    }

    #[derive(Deserialize)]
    struct RawBodyResult {
        #[serde(flatten)]
        availability: Availability,
        #[serde(default)]
        content_type: String,
        body: Option<String>,
        #[serde(default)]
        truncated: bool,
    }

    pub fn list_messages(query: MessageQuery) -> Result<MessageListing, IntegrationError> {
        let mailbox = query
            .mailbox
            .clone()
            .unwrap_or_else(|| DEFAULT_MAILBOX.to_string());
        let payload = serde_json::json!({
            "account_ids": query.account_ids,
            "mailbox": mailbox,
            "limit": query.limit.clamp(1, 500),
            // JXA compares `since` against `Date.toISOString()` as a STRING,
            // so both sides must be the same shape. `to_rfc3339()` renders the
            // offset as `+00:00`, which sorts before `.` and would make the
            // comparison depend on formatting rather than on time — emit the
            // millisecond-precision `Z` form `toISOString()` produces.
            "since": query.since.map(|t| t.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string()),
            "include_body": query.include_body,
            "body_cap": MESSAGE_BODY_CAP,
        })
        .to_string();
        let raw: RawMessageListing = run_jxa(&["messages", payload.as_str()])?;
        Ok(MessageListing {
            availability: raw.availability,
            messages: raw
                .messages
                .into_iter()
                .map(|m| MessageSummary {
                    id: encode_message_id(&m.account_id, &m.mailbox, &m.local_id),
                    account_id: m.account_id,
                    mailbox: m.mailbox,
                    subject: m.subject,
                    sender: m.sender,
                    recipients: m.recipients,
                    date_received: m.date_received,
                    read: m.read,
                    preview: m.preview,
                    body: m.body,
                })
                .collect(),
        })
    }

    pub fn message_body(message_id: &str) -> Result<MessageBodyResult, IntegrationError> {
        let (account_id, mailbox, local_id) = match decode_message_id(message_id)? {
            MessageRef::MailApp {
                account_id,
                mailbox,
                local_id,
            } => (account_id, mailbox, local_id),
            MessageRef::Graph { .. } => {
                return Err(IntegrationError::Backend(format!(
                    "message id {message_id} belongs to the Microsoft Graph backend, \
                     not to Mail.app"
                )))
            }
        };
        let cap = MESSAGE_BODY_CAP.to_string();
        let raw: RawBodyResult = run_jxa(&[
            "body",
            account_id.as_str(),
            mailbox.as_str(),
            local_id.as_str(),
            cap.as_str(),
        ])?;
        Ok(MessageBodyResult {
            availability: raw.availability,
            id: message_id.to_string(),
            content_type: if raw.content_type.is_empty() {
                "text".to_string()
            } else {
                raw.content_type
            },
            body: raw.body,
            truncated: raw.truncated,
        })
    }

    /// Thin wrapper over [`crate::jxa::run`]. This used to be its own copy of
    /// the spawn/write/wait dance with a plain blocking `wait_with_output()`,
    /// so when Mail did not answer an Apple Event the call sat on Apple's ~120s
    /// default: `mail.accounts` took a measured 121.0s to return — and then
    /// reported `available: true` with an empty account list, a "success" that
    /// cost two minutes (Parslee-ai/car#618).
    fn run_jxa<T: serde::de::DeserializeOwned>(args: &[&str]) -> Result<T, IntegrationError> {
        crate::jxa::run(JXA, args, crate::jxa::DEFAULT_TIMEOUT)
    }
}

#[cfg(not(target_os = "macos"))]
mod backend {
    use super::*;

    pub fn list_accounts() -> Result<AccountListing, IntegrationError> {
        if crate::msgraph::is_configured() {
            return Ok(AccountListing {
                availability: Availability::available("msgraph"),
                accounts: vec![MailAccount {
                    id: "msgraph".into(),
                    address: String::new(),
                    display_name: Some("Microsoft 365".into()),
                    provider_hint: Some("microsoft".into()),
                }],
            });
        }
        Ok(AccountListing {
            availability: current_backend_pending(),
            accounts: vec![],
        })
    }

    pub fn list_inbox(_account_ids: &[String]) -> Result<InboxListing, IntegrationError> {
        // Microsoft Graph backend (car#520) when configured; else pending.
        if crate::msgraph::is_configured() {
            return Ok(match crate::msgraph::inbox_summary("msgraph") {
                Ok(summary) => InboxListing {
                    availability: Availability::available("msgraph"),
                    summaries: vec![summary],
                },
                Err(e) => InboxListing {
                    availability: Availability::pending("msgraph", e.to_string()),
                    summaries: vec![],
                },
            });
        }
        Ok(InboxListing {
            availability: current_backend_pending(),
            summaries: vec![],
        })
    }

    pub fn send(req: SendRequest) -> Result<SendResult, IntegrationError> {
        // Microsoft Graph send/draft (car#531) when configured; else pending.
        if crate::msgraph::is_configured() {
            return Ok(match crate::msgraph::send_mail(&req) {
                Ok(message_id) => SendResult {
                    availability: Availability::available("msgraph"),
                    sent: true,
                    message_id,
                },
                Err(e) => SendResult {
                    availability: Availability::pending("msgraph", e.to_string()),
                    sent: false,
                    message_id: None,
                },
            });
        }
        Ok(SendResult {
            availability: current_backend_pending(),
            sent: false,
            message_id: None,
        })
    }

    pub fn list_mailboxes(_account_ids: &[String]) -> Result<MailboxListing, IntegrationError> {
        if crate::msgraph::is_configured() {
            return Ok(match crate::msgraph::mail_folders("msgraph") {
                Ok(mailboxes) => MailboxListing {
                    availability: Availability::available("msgraph"),
                    mailboxes,
                },
                Err(e) => MailboxListing {
                    availability: Availability::pending("msgraph", e.to_string()),
                    mailboxes: vec![],
                },
            });
        }
        Ok(MailboxListing {
            availability: current_backend_pending(),
            mailboxes: vec![],
        })
    }

    pub fn list_messages(query: MessageQuery) -> Result<MessageListing, IntegrationError> {
        if crate::msgraph::is_configured() {
            return Ok(match crate::msgraph::messages("msgraph", &query) {
                Ok(messages) => MessageListing {
                    availability: Availability::available("msgraph"),
                    messages,
                },
                Err(e) => MessageListing {
                    availability: Availability::pending("msgraph", e.to_string()),
                    messages: vec![],
                },
            });
        }
        Ok(MessageListing {
            availability: current_backend_pending(),
            messages: vec![],
        })
    }

    pub fn message_body(message_id: &str) -> Result<MessageBodyResult, IntegrationError> {
        let graph_id = match decode_message_id(message_id)? {
            MessageRef::Graph { id } => id,
            MessageRef::MailApp { .. } => {
                return Err(IntegrationError::Backend(format!(
                    "message id {message_id} belongs to the macOS Mail.app backend, \
                     which is not available on this platform"
                )))
            }
        };
        if crate::msgraph::is_configured() {
            return Ok(match crate::msgraph::message_body(&graph_id) {
                Ok(mut r) => {
                    r.id = message_id.to_string();
                    r
                }
                Err(e) => MessageBodyResult {
                    availability: Availability::pending("msgraph", e.to_string()),
                    id: message_id.to_string(),
                    content_type: "text".into(),
                    body: None,
                    truncated: false,
                },
            });
        }
        Ok(MessageBodyResult {
            availability: current_backend_pending(),
            id: message_id.to_string(),
            content_type: "text".into(),
            body: None,
            truncated: false,
        })
    }

    fn current_backend_pending() -> Availability {
        Availability::pending(
            "imap_smtp",
            "Set CAR_MSGRAPH_CLIENT_ID (Azure AD app) to enable the Microsoft \
             Graph mail backend (car#520/#531 — inbox + send/draft; \
             car-releases#84 — mailboxes, message rows, bodies); a local \
             IMAP/SMTP backend is not yet wired.",
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // The composite id is the one piece of this feature that has to survive
    // two hostile hops — JXA `argv` and the JSON wire — so it is checked
    // against the characters that actually break naive delimiters.
    #[test]
    fn message_id_round_trips_through_awkward_names() {
        for (account, mailbox, local) in [
            ("iCloud", "INBOX", "12345"),
            ("Exchange: work", "Travel/2026 — flights", "7"),
            ("a:b:c", "x:y:z", "0"),
            ("", "", "1"),
            ("Ünïcode ✈", "Ordner/Reisen", "99999999"),
        ] {
            let encoded = encode_message_id(account, mailbox, local);
            assert!(
                !encoded[MAILAPP_ID_PREFIX.len() + 1..].contains(' '),
                "encoded id must be argv-safe: {encoded}"
            );
            assert_eq!(
                decode_message_id(&encoded).unwrap(),
                MessageRef::MailApp {
                    account_id: account.to_string(),
                    mailbox: mailbox.to_string(),
                    local_id: local.to_string(),
                }
            );
        }
    }

    #[test]
    fn graph_message_id_round_trips() {
        // Graph ids carry `=`, `-` and `_`; none of them may be mangled.
        let raw = "AAMkAGI2T=Gt-Zg_AAA";
        assert_eq!(
            decode_message_id(&encode_graph_message_id(raw)).unwrap(),
            MessageRef::Graph {
                id: raw.to_string()
            }
        );
    }

    #[test]
    fn decode_rejects_ids_it_did_not_mint() {
        for bad in [
            "",
            "12345",
            "mailapp",
            "mailapp:only-two:parts",
            "mailapp:aQ:aQ:",
            "mailapp:!!!:aQ:1",
            "msgraph:",
            "imap:aQ:aQ:1",
        ] {
            assert!(
                decode_message_id(bad).is_err(),
                "expected {bad:?} to be rejected"
            );
        }
    }

    // `{}` has to keep meaning "the INBOX, newest 50" — that is the promise
    // that every pre-existing caller of the mail read surface relies on.
    #[test]
    fn message_query_defaults_to_inbox_and_fifty() {
        let q: MessageQuery = serde_json::from_str("{}").unwrap();
        assert!(q.mailbox.is_none());
        assert_eq!(q.limit, 50);
        assert!(q.account_ids.is_empty());
        assert!(q.since.is_none());
        assert!(!q.include_body);
        assert_eq!(
            q.mailbox.unwrap_or_else(|| DEFAULT_MAILBOX.to_string()),
            "INBOX"
        );
    }

    #[test]
    fn message_query_parses_a_full_payload() {
        let q: MessageQuery = serde_json::from_str(
            r#"{"account_ids":["work"],"mailbox":"Travel","limit":5,
                "since":"2026-01-01T00:00:00Z","include_body":true}"#,
        )
        .unwrap();
        assert_eq!(q.account_ids, vec!["work".to_string()]);
        assert_eq!(q.mailbox.as_deref(), Some("Travel"));
        assert_eq!(q.limit, 5);
        assert_eq!(q.since.unwrap().to_rfc3339(), "2026-01-01T00:00:00+00:00");
        assert!(q.include_body);
    }

    // --- the JXA itself, against a stubbed Mail.app ------------------------
    //
    // Everything that actually closes Parslee-ai/car-releases#84 on macOS —
    // the mailbox walk, selector resolution, the sort/since/limit pipeline —
    // lives in a JS string that no other test reaches. That is how the
    // multi-account ordering bug got in: each account was sorted and sliced
    // inside `Mail.accounts().forEach`, so the concatenation was neither
    // globally newest-first nor limit-fair.
    //
    // The script IS testable without Mail.app. Appending a `mailApp = ...`
    // assignment after the script body overrides the hoisted declaration, so
    // `run` drives the real logic over a fake object graph — no Apple Events,
    // no TCC prompt, nothing that depends on the machine's mail setup.
    #[cfg(target_os = "macos")]
    mod jxa {
        use super::*;

        /// Two accounts that both hold a `Travel` mailbox, with the newest
        /// message overall in the SECOND one — the reporter's configuration
        /// (iCloud + Exchange, rules filing mail out of INBOX). Account one
        /// also nests `Travel/2026`, to pin path- and leaf-resolution.
        const MOCK: &str = r#"
function mkMessages(rows) {
  const api = function (i) { return api[i]; };
  rows.forEach(function (r, i) {
    api[i] = {
      id: function () { return r.id; },
      subject: function () { return r.subject; },
      sender: function () { return r.sender; },
      dateReceived: function () { return r.date; },
      readStatus: function () { return r.read === true; },
      content: function () { return "body of " + r.id; },
      toRecipients: { address: function () { return ["me@example.com"]; } }
    };
  });
  api.length = rows.length;
  api.id = function () { return rows.map(function (r) { return r.id; }); };
  api.subject = function () { return rows.map(function (r) { return r.subject; }); };
  api.sender = function () { return rows.map(function (r) { return r.sender; }); };
  api.dateReceived = function () { return rows.map(function (r) { return r.date; }); };
  api.readStatus = function () { return rows.map(function (r) { return r.read === true; }); };
  api.whose = function () { return function () { return []; }; };
  return api;
}
function mkBox(name, rows, children) {
  const kids = children || [];
  return {
    name: function () { return name; },
    unreadCount: function () { return 0; },
    messages: mkMessages(rows),
    mailboxes: function () { return kids; }
  };
}
function mkAccount(id, address, boxes) {
  const list = function () { return boxes; };
  list.byName = function (n) {
    for (let i = 0; i < boxes.length; i++) if (boxes[i].name() === n) return boxes[i];
    throw new Error("no mailbox " + n);
  };
  return {
    id: function () { return id; },
    name: function () { return address; },
    emailAddresses: function () { return [address]; },
    mailboxes: list
  };
}
const ACC1 = mkAccount("ACC-1", "one@example.com", [
  mkBox("INBOX", [{id: 11, subject: "inbox one", sender: "a@x", date: "2026-03-03T00:00:00Z"}]),
  mkBox("Travel", [
    {id: 101, subject: "acc1 aug", sender: "air@x", date: "2026-08-01T00:00:00Z"},
    {id: 102, subject: "acc1 jan", sender: "air@x", date: "2026-01-01T00:00:00Z"}
  ], [
    mkBox("2026", [{id: 103, subject: "nested", sender: "air@x", date: "2026-05-05T00:00:00Z"}])
  ])
]);
const ACC2 = mkAccount("ACC-2", "two@example.com", [
  mkBox("INBOX", [{id: 21, subject: "inbox two", sender: "b@x", date: "2026-04-04T00:00:00Z"}]),
  mkBox("Travel", [{id: 201, subject: "acc2 newest", sender: "air@x", date: "2026-08-20T00:00:00Z"}])
]);
const MOCK_APP = {accounts: function () { return [ACC1, ACC2]; }, includeStandardAdditions: false};
mailApp = function () { return MOCK_APP; };
"#;

        fn run(args: &[&str]) -> serde_json::Value {
            let script = format!("{}\n{MOCK}", super::super::backend::JXA);
            let out = crate::jxa::run_raw(&script, args, crate::jxa::DEFAULT_TIMEOUT)
                .expect("osascript should run the stubbed script");
            serde_json::from_slice(&out).expect("stubbed script should emit JSON")
        }

        fn messages(query: serde_json::Value) -> serde_json::Value {
            run(&["messages", &query.to_string()])
        }

        fn dates(v: &serde_json::Value) -> Vec<String> {
            v["messages"]
                .as_array()
                .unwrap()
                .iter()
                .map(|m| m["date_received"].as_str().unwrap_or("").to_string())
                .collect()
        }

        // THE regression. Sorting and slicing per account and concatenating
        // returns ACC-1's 2026-08-01 message here and drops ACC-2's
        // 2026-08-20 one, which is the newest overall — an agent asking for
        // the newest travel mail confidently misses the newest flight
        // confirmation, and it reads as "no results", not "cannot see there".
        #[test]
        fn newest_first_is_global_across_accounts_not_per_account() {
            let one = messages(serde_json::json!({"mailbox": "Travel", "limit": 1}));
            assert_eq!(dates(&one), vec!["2026-08-20T00:00:00.000Z"]);
            assert_eq!(one["messages"][0]["account_id"], "ACC-2");

            // And the full listing is in date order, not account order.
            let all = messages(serde_json::json!({"mailbox": "Travel", "limit": 10}));
            assert_eq!(
                dates(&all),
                vec![
                    "2026-08-20T00:00:00.000Z",
                    "2026-08-01T00:00:00.000Z",
                    "2026-01-01T00:00:00.000Z",
                ]
            );
        }

        #[test]
        fn limit_is_shared_across_accounts() {
            let two = messages(serde_json::json!({"mailbox": "Travel", "limit": 2}));
            assert_eq!(two["messages"].as_array().unwrap().len(), 2);
            assert_eq!(
                dates(&two),
                vec!["2026-08-20T00:00:00.000Z", "2026-08-01T00:00:00.000Z"]
            );
        }

        // The whole point of the issue: mail filed out of INBOX by a rule.
        #[test]
        fn nested_mailboxes_resolve_by_path_by_leaf_and_case_insensitively() {
            for selector in ["Travel/2026", "travel/2026", "2026"] {
                let v = messages(serde_json::json!({"mailbox": selector}));
                assert_eq!(
                    v["messages"][0]["subject"], "nested",
                    "selector {selector:?} should reach the nested mailbox"
                );
                // Rows are stamped with the RESOLVED path, not the selector
                // the caller typed, so they match `mail.mailboxes` output.
                assert_eq!(v["messages"][0]["mailbox"], "Travel/2026");
            }
            let cased = messages(serde_json::json!({"mailbox": "travel", "limit": 1}));
            assert_eq!(cased["messages"][0]["mailbox"], "Travel");
        }

        // `since` compares instants, not formats, and is inclusive at the
        // instant itself — fixed by hand in efa541ea and unprotected until now.
        #[test]
        fn since_is_inclusive_at_the_instant_and_exclusive_one_ms_later() {
            let at = messages(serde_json::json!({
                "mailbox": "Travel", "account_ids": ["ACC-1"],
                "since": "2026-08-01T00:00:00.000Z"
            }));
            assert_eq!(dates(&at), vec!["2026-08-01T00:00:00.000Z"]);

            let past = messages(serde_json::json!({
                "mailbox": "Travel", "account_ids": ["ACC-1"],
                "since": "2026-08-01T00:00:00.001Z"
            }));
            assert!(past["messages"].as_array().unwrap().is_empty());
        }

        // `since` is applied BEFORE the limit, so a narrow window still yields
        // real matches instead of whatever survived a pre-filtered slice.
        #[test]
        fn since_filters_before_the_limit() {
            let v = messages(serde_json::json!({
                "mailbox": "Travel", "limit": 1, "since": "2026-02-01T00:00:00.000Z"
            }));
            assert_eq!(dates(&v), vec!["2026-08-20T00:00:00.000Z"]);
        }

        // "Cannot see there" must never render as "there is nothing there".
        #[test]
        fn unreachable_targets_report_a_reason_rather_than_an_empty_list() {
            let no_box = messages(serde_json::json!({"mailbox": "Nope"}));
            assert_eq!(no_box["available"], false);
            assert!(no_box["reason"]
                .as_str()
                .unwrap()
                .contains("mail.mailboxes"));

            let no_account =
                messages(serde_json::json!({"mailbox": "Travel", "account_ids": ["ACC-NOPE"]}));
            assert_eq!(no_account["available"], false);
            assert!(no_account["reason"].as_str().unwrap().contains("ACC-NOPE"));

            let no_account_boxes = run(&["mailboxes", "ACC-NOPE"]);
            assert_eq!(no_account_boxes["available"], false);
            assert!(no_account_boxes["reason"]
                .as_str()
                .unwrap()
                .contains("mail.accounts"));
        }

        #[test]
        fn mailbox_enumeration_includes_nested_mailboxes() {
            let v = run(&["mailboxes"]);
            let names: Vec<&str> = v["mailboxes"]
                .as_array()
                .unwrap()
                .iter()
                .map(|m| m["full_name"].as_str().unwrap())
                .collect();
            assert!(names.contains(&"Travel"), "{names:?}");
            assert!(names.contains(&"Travel/2026"), "{names:?}");
        }

        // `{}` still means "the INBOX, newest 50" for every pre-existing caller.
        #[test]
        fn an_empty_query_still_reads_the_inbox() {
            let v = messages(serde_json::json!({}));
            let subjects: Vec<&str> = v["messages"]
                .as_array()
                .unwrap()
                .iter()
                .map(|m| m["subject"].as_str().unwrap())
                .collect();
            assert_eq!(subjects, vec!["inbox two", "inbox one"]);
        }

        // The composite id has to survive the round trip back to a body fetch.
        #[test]
        fn row_ids_decode_to_the_account_and_resolved_mailbox() {
            let v = messages(serde_json::json!({"mailbox": "2026"}));
            let account = v["messages"][0]["account_id"].as_str().unwrap();
            let mailbox = v["messages"][0]["mailbox"].as_str().unwrap();
            let local = v["messages"][0]["local_id"].as_str().unwrap();
            let id = encode_message_id(account, mailbox, local);
            assert_eq!(
                decode_message_id(&id).unwrap(),
                MessageRef::MailApp {
                    account_id: "ACC-1".into(),
                    mailbox: "Travel/2026".into(),
                    local_id: "103".into(),
                }
            );
            let body = run(&["body", "ACC-1", "Travel/2026", "103", "100000"]);
            assert_eq!(body["available"], true);
            assert_eq!(body["body"], "body of 103");
        }
    }

    #[test]
    fn listings_carry_the_availability_envelope_inline() {
        let listing = MailboxListing {
            availability: Availability::available("mail_app"),
            mailboxes: vec![Mailbox {
                account_id: "iCloud".into(),
                name: "Travel".into(),
                full_name: "Travel".into(),
                unread: 2,
                total: 17,
            }],
        };
        let v = serde_json::to_value(&listing).unwrap();
        assert_eq!(v["available"], serde_json::json!(true));
        assert_eq!(v["backend"], serde_json::json!("mail_app"));
        assert_eq!(v["mailboxes"][0]["full_name"], serde_json::json!("Travel"));
    }
}