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
//! macOS account-backed Apple app integrations not covered by Calendar,
//! Contacts, Mail, or Messages.
//!
//! These capabilities are advertised by Internet Accounts on macOS. Apple
//! exposes them through a mix of public automation dictionaries and protected
//! on-disk stores. Each method returns an availability envelope instead of
//! treating TCC/Full-Disk-Access denial as an exceptional transport failure.

use crate::{Availability, IntegrationError};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct NoteAccount {
    pub id: String,
    pub name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct NoteSummary {
    pub id: String,
    pub name: String,
    pub folder: Option<String>,
    pub modified: Option<String>,
}

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

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct NotesListing {
    #[serde(flatten)]
    pub availability: Availability,
    pub notes: Vec<NoteSummary>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ReminderList {
    pub id: String,
    pub name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ReminderItem {
    pub id: String,
    pub name: String,
    pub list: Option<String>,
    pub due: Option<String>,
    pub completed: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ReminderListListing {
    #[serde(flatten)]
    pub availability: Availability,
    pub lists: Vec<ReminderList>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ReminderItemListing {
    #[serde(flatten)]
    pub availability: Availability,
    pub reminders: Vec<ReminderItem>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct PhotoAlbum {
    pub id: String,
    pub name: String,
    pub count: Option<u32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct PhotoAlbumListing {
    #[serde(flatten)]
    pub availability: Availability,
    pub albums: Vec<PhotoAlbum>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Bookmark {
    pub title: String,
    pub url: Option<String>,
    pub source: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct BookmarkListing {
    #[serde(flatten)]
    pub availability: Availability,
    pub bookmarks: Vec<Bookmark>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct FileLocation {
    pub id: String,
    pub name: String,
    pub path: String,
    pub exists: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct FileLocationListing {
    #[serde(flatten)]
    pub availability: Availability,
    pub locations: Vec<FileLocation>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct KeychainStatus {
    #[serde(flatten)]
    pub availability: Availability,
}

pub fn notes_accounts() -> Result<NotesAccountListing, IntegrationError> {
    backend::notes_accounts()
}

pub fn notes_find(query: &str, limit: usize) -> Result<NotesListing, IntegrationError> {
    backend::notes_find(query, limit)
}

pub fn reminders_lists() -> Result<ReminderListListing, IntegrationError> {
    backend::reminders_lists()
}

pub fn reminders_items(limit: usize) -> Result<ReminderItemListing, IntegrationError> {
    backend::reminders_items(limit)
}

pub fn photos_albums() -> Result<PhotoAlbumListing, IntegrationError> {
    backend::photos_albums()
}

pub fn bookmarks_list(limit: usize) -> Result<BookmarkListing, IntegrationError> {
    backend::bookmarks_list(limit)
}

pub fn files_locations() -> Result<FileLocationListing, IntegrationError> {
    backend::files_locations()
}

pub fn keychain_status() -> Result<KeychainStatus, IntegrationError> {
    backend::keychain_status()
}

#[cfg(target_os = "macos")]
mod backend {
    use super::*;
    use serde_json::Value;
    use std::path::PathBuf;
    use std::process::Command;

    const NOTES_JXA: &str = r#"
function app() { const a = Application("/System/Applications/Notes.app"); a.includeStandardAdditions = true; return a; }
function accountOut(a) {
  let id = ""; let name = "";
  try { id = String(a.id()); } catch (e) {}
  try { name = String(a.name()); } catch (e) {}
  return {id: id || name, name: name || id};
}
function noteOut(n) {
  let id = ""; let name = ""; let folder = null; let modified = null;
  try { id = String(n.id()); } catch (e) {}
  try { name = String(n.name()); } catch (e) {}
  try { folder = String(n.container().name()); } catch (e) {}
  try { modified = String(n.modificationDate()); } catch (e) {}
  return {id: id || name, name: name || id, folder: folder, modified: modified};
}
function run(argv) {
  const mode = argv[0] || "accounts";
  try {
    const Notes = app();
    if (mode === "accounts") {
      return JSON.stringify({available:true, backend:"notes_app", reason:null, accounts: Notes.accounts().map(accountOut)});
    }
    const query = String(argv[1] || "").toLowerCase();
    const limit = Number(argv[2] || "50");
    let out = [];
    Notes.accounts().forEach(a => {
      a.notes().forEach(n => {
        let hay = "";
        try { hay += " " + String(n.name()).toLowerCase(); } catch (e) {}
        try { hay += " " + String(n.plaintext()).toLowerCase(); } catch (e) {}
        if (!query || hay.indexOf(query) >= 0) out.push(noteOut(n));
      });
    });
    return JSON.stringify({available:true, backend:"notes_app", reason:null, notes: out.slice(0, limit)});
  } catch (e) {
    if (mode === "accounts") return JSON.stringify({available:false, backend:"notes_app", reason:String(e), accounts:[]});
    return JSON.stringify({available:false, backend:"notes_app", reason:String(e), notes:[]});
  }
}
"#;

    const REMINDERS_JXA: &str = r#"
function app() { const a = Application("/System/Applications/Reminders.app"); a.includeStandardAdditions = true; return a; }
function listOut(l) {
  let id = ""; let name = "";
  try { id = String(l.id()); } catch (e) {}
  try { name = String(l.name()); } catch (e) {}
  return {id: id || name, name: name || id};
}
function itemOut(r) {
  let id = ""; let name = ""; let list = null; let due = null; let completed = false;
  try { id = String(r.id()); } catch (e) {}
  try { name = String(r.name()); } catch (e) {}
  try { list = String(r.container().name()); } catch (e) {}
  try { due = String(r.dueDate()); } catch (e) {}
  try { completed = !!r.completed(); } catch (e) {}
  return {id: id || name, name: name || id, list: list, due: due, completed: completed};
}
function run(argv) {
  const mode = argv[0] || "lists";
  try {
    const Reminders = app();
    if (mode === "lists") {
      return JSON.stringify({available:true, backend:"reminders_app", reason:null, lists: Reminders.lists().map(listOut)});
    }
    const limit = Number(argv[1] || "50");
    let out = [];
    Reminders.lists().forEach(l => l.reminders().forEach(r => { if (!r.completed()) out.push(itemOut(r)); }));
    return JSON.stringify({available:true, backend:"reminders_app", reason:null, reminders: out.slice(0, limit)});
  } catch (e) {
    if (mode === "lists") return JSON.stringify({available:false, backend:"reminders_app", reason:String(e), lists:[]});
    return JSON.stringify({available:false, backend:"reminders_app", reason:String(e), reminders:[]});
  }
}
"#;

    const PHOTOS_JXA: &str = r#"
function run(argv) {
  try {
    const Photos = Application("/System/Applications/Photos.app");
    Photos.includeStandardAdditions = true;
    const albums = Photos.albums().map(a => {
      let id = ""; let name = ""; let count = null;
      try { id = String(a.id()); } catch (e) {}
      try { name = String(a.name()); } catch (e) {}
      try { count = a.mediaItems().length; } catch (e) {}
      return {id: id || name, name: name || id, count: count};
    });
    return JSON.stringify({available:true, backend:"photos_app", reason:null, albums: albums});
  } catch (e) {
    return JSON.stringify({available:false, backend:"photos_app", reason:String(e), albums:[]});
  }
}
"#;

    pub fn notes_accounts() -> Result<NotesAccountListing, IntegrationError> {
        Ok(
            run_jxa(NOTES_JXA, &["accounts"]).unwrap_or_else(|e| NotesAccountListing {
                availability: Availability::pending("notes_app", e.to_string()),
                accounts: vec![],
            }),
        )
    }

    pub fn notes_find(query: &str, limit: usize) -> Result<NotesListing, IntegrationError> {
        Ok(
            run_jxa(NOTES_JXA, &["find", query, &limit.to_string()]).unwrap_or_else(|e| {
                NotesListing {
                    availability: Availability::pending("notes_app", e.to_string()),
                    notes: vec![],
                }
            }),
        )
    }

    pub fn reminders_lists() -> Result<ReminderListListing, IntegrationError> {
        Ok(
            run_jxa(REMINDERS_JXA, &["lists"]).unwrap_or_else(|e| ReminderListListing {
                availability: Availability::pending("reminders_app", e.to_string()),
                lists: vec![],
            }),
        )
    }

    pub fn reminders_items(limit: usize) -> Result<ReminderItemListing, IntegrationError> {
        Ok(
            run_jxa(REMINDERS_JXA, &["items", &limit.to_string()]).unwrap_or_else(|e| {
                ReminderItemListing {
                    availability: Availability::pending("reminders_app", e.to_string()),
                    reminders: vec![],
                }
            }),
        )
    }

    pub fn photos_albums() -> Result<PhotoAlbumListing, IntegrationError> {
        Ok(
            run_jxa(PHOTOS_JXA, &[]).unwrap_or_else(|e| PhotoAlbumListing {
                availability: Availability::pending("photos_app", e.to_string()),
                albums: vec![],
            }),
        )
    }

    pub fn bookmarks_list(limit: usize) -> Result<BookmarkListing, IntegrationError> {
        let mut path = home();
        path.push("Library/Safari/Bookmarks.plist");
        let output = Command::new("/usr/bin/plutil")
            .args(["-convert", "json", "-o", "-"])
            .arg(path)
            .output()
            .map_err(|e| IntegrationError::Backend(format!("bookmarks plutil: {e}")))?;
        if !output.status.success() {
            return Ok(BookmarkListing {
                availability: Availability::pending(
                    "safari_bookmarks",
                    String::from_utf8_lossy(&output.stderr).trim().to_string(),
                ),
                bookmarks: vec![],
            });
        }
        let value: Value = serde_json::from_slice(&output.stdout)
            .map_err(|e| IntegrationError::Backend(format!("bookmarks json: {e}")))?;
        let mut bookmarks = Vec::new();
        collect_bookmarks(&value, &mut bookmarks, limit);
        Ok(BookmarkListing {
            availability: Availability::available("safari_bookmarks"),
            bookmarks,
        })
    }

    pub fn files_locations() -> Result<FileLocationListing, IntegrationError> {
        let mut locations = Vec::new();
        let mut add = |id: &str, name: &str, path: PathBuf| {
            locations.push(FileLocation {
                id: id.to_string(),
                name: name.to_string(),
                exists: path.exists(),
                path: path.to_string_lossy().to_string(),
            });
        };
        let home = home();
        add(
            "icloud_drive",
            "iCloud Drive",
            home.join("Library/Mobile Documents/com~apple~CloudDocs"),
        );
        add("desktop", "Desktop", home.join("Desktop"));
        add("documents", "Documents", home.join("Documents"));
        let available = locations.iter().any(|location| location.exists);
        Ok(FileLocationListing {
            availability: if available {
                Availability::available("macos_files")
            } else {
                Availability::pending("macos_files", "No standard macOS file locations found.")
            },
            locations,
        })
    }

    pub fn keychain_status() -> Result<KeychainStatus, IntegrationError> {
        let check = car_secrets::SecretStore::new().availability();
        Ok(KeychainStatus {
            availability: if check.available {
                Availability::available("keychain")
            } else {
                Availability::pending(
                    "keychain",
                    check
                        .reason
                        .unwrap_or_else(|| "macOS Keychain is unavailable.".to_string()),
                )
            },
        })
    }

    /// Thin wrapper over [`crate::jxa::run`]. This used to be its own copy of
    /// the spawn/write/wait dance, and it wrote the script through
    /// `child.stdin.as_mut()` — which never closes the pipe, so `osascript -`
    /// never saw EOF and never ran the script. Every call here burned its 5s
    /// watchdog and reported an Apple Events timeout, making `notes.*`,
    /// `reminders.*` and `photos.*` permanently unavailable no matter the TCC
    /// state (Parslee-ai/car#618).
    fn run_jxa<T: serde::de::DeserializeOwned>(
        script: &str,
        args: &[&str],
    ) -> Result<T, IntegrationError> {
        crate::jxa::run(script, args, crate::jxa::DEFAULT_TIMEOUT)
    }

    fn collect_bookmarks(value: &Value, out: &mut Vec<Bookmark>, limit: usize) {
        if out.len() >= limit {
            return;
        }
        if let Some(url) = value.get("URLString").and_then(Value::as_str) {
            let title = value
                .get("URIDictionary")
                .and_then(|v| v.get("title"))
                .and_then(Value::as_str)
                .or_else(|| value.get("Title").and_then(Value::as_str))
                .unwrap_or(url);
            out.push(Bookmark {
                title: title.to_string(),
                url: Some(url.to_string()),
                source: "safari".to_string(),
            });
        }
        if let Some(children) = value.get("Children").and_then(Value::as_array) {
            for child in children {
                collect_bookmarks(child, out, limit);
                if out.len() >= limit {
                    break;
                }
            }
        }
    }

    fn home() -> PathBuf {
        PathBuf::from(std::env::var_os("HOME").unwrap_or_default())
    }
}

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

    // Notes.app / Reminders.app are macOS-only, but the equivalents for the
    // signed-in Microsoft 365 account — OneNote and Microsoft To Do — are
    // reachable through the same Graph device-code OAuth that already backs
    // Contacts/Calendar/Mail off macOS (car#520). So these are a real backend
    // when `CAR_MSGRAPH_CLIENT_ID` is set, and a Graph-pointing pending stub
    // otherwise (not the generic "only modeled on macOS").
    fn graph_pending(surface: &str) -> Availability {
        Availability::pending(
            "msgraph",
            format!(
                "Set CAR_MSGRAPH_CLIENT_ID (Azure AD app) to enable the Microsoft \
                 Graph {surface} backend (car#520)."
            ),
        )
    }

    pub fn notes_accounts() -> Result<NotesAccountListing, IntegrationError> {
        if crate::msgraph::is_configured() {
            return Ok(match crate::msgraph::onenote_notebooks() {
                Ok(nbs) => NotesAccountListing {
                    availability: Availability::available("msgraph"),
                    accounts: nbs
                        .into_iter()
                        .map(|n| NoteAccount {
                            id: n.id,
                            name: n.name,
                        })
                        .collect(),
                },
                Err(e) => NotesAccountListing {
                    availability: Availability::pending("msgraph", e.to_string()),
                    accounts: vec![],
                },
            });
        }
        Ok(NotesAccountListing {
            availability: graph_pending("OneNote notes"),
            accounts: vec![],
        })
    }

    pub fn notes_find(query: &str, limit: usize) -> Result<NotesListing, IntegrationError> {
        if crate::msgraph::is_configured() {
            return Ok(match crate::msgraph::onenote_pages(query, limit.max(1)) {
                Ok(pages) => NotesListing {
                    availability: Availability::available("msgraph"),
                    notes: pages
                        .into_iter()
                        .map(|p| NoteSummary {
                            id: p.id,
                            name: p.title,
                            folder: p.notebook,
                            modified: p.modified,
                        })
                        .collect(),
                },
                Err(e) => NotesListing {
                    availability: Availability::pending("msgraph", e.to_string()),
                    notes: vec![],
                },
            });
        }
        Ok(NotesListing {
            availability: graph_pending("OneNote notes"),
            notes: vec![],
        })
    }

    pub fn reminders_lists() -> Result<ReminderListListing, IntegrationError> {
        if crate::msgraph::is_configured() {
            return Ok(match crate::msgraph::todo_lists() {
                Ok(lists) => ReminderListListing {
                    availability: Availability::available("msgraph"),
                    lists: lists
                        .into_iter()
                        .map(|l| ReminderList {
                            id: l.id,
                            name: l.name,
                        })
                        .collect(),
                },
                Err(e) => ReminderListListing {
                    availability: Availability::pending("msgraph", e.to_string()),
                    lists: vec![],
                },
            });
        }
        Ok(ReminderListListing {
            availability: graph_pending("To Do reminders"),
            lists: vec![],
        })
    }

    pub fn reminders_items(limit: usize) -> Result<ReminderItemListing, IntegrationError> {
        if crate::msgraph::is_configured() {
            return Ok(match crate::msgraph::todo_tasks(limit) {
                Ok(tasks) => ReminderItemListing {
                    availability: Availability::available("msgraph"),
                    reminders: tasks
                        .into_iter()
                        .map(|t| ReminderItem {
                            id: t.id,
                            name: t.title,
                            list: t.list,
                            due: t.due,
                            completed: t.completed,
                        })
                        .collect(),
                },
                Err(e) => ReminderItemListing {
                    availability: Availability::pending("msgraph", e.to_string()),
                    reminders: vec![],
                },
            });
        }
        Ok(ReminderItemListing {
            availability: graph_pending("To Do reminders"),
            reminders: vec![],
        })
    }

    pub fn photos_albums() -> Result<PhotoAlbumListing, IntegrationError> {
        Ok(PhotoAlbumListing {
            availability: pending("photos_app"),
            albums: vec![],
        })
    }

    /// Safari is macOS-only, but the Chromium family (Chrome/Edge/Brave) is the
    /// default browser off macOS and stores bookmarks as a stable JSON file per
    /// profile, so this is a real backend on Windows and Linux rather than a
    /// pending stub. Each installed browser's every profile is read and merged.
    ///
    /// Permission posture (deliberate, differs from the macOS Safari path): the
    /// macOS reader goes through `plutil` against a TCC-protected file, so it can
    /// be denied by Full Disk Access. A Chromium `Bookmarks` file sits in the
    /// user's own profile under `%LOCALAPPDATA%` / `~/.config` with no OS gate —
    /// this process already runs as the user, so reading their own browser
    /// bookmarks is not a privilege escalation. Like every other integration it
    /// is still reached only through the auth-token-gated localhost daemon.
    pub fn bookmarks_list(limit: usize) -> Result<BookmarkListing, IntegrationError> {
        let files = chromium_bookmark_files();
        if files.is_empty() {
            return Ok(BookmarkListing {
                availability: Availability::pending(
                    "chromium_bookmarks",
                    "No Chromium-based browser (Chrome, Edge, or Brave) bookmarks found.",
                ),
                bookmarks: vec![],
            });
        }
        // A browser is installed but may simply have no bookmarks yet — that is a
        // real `available: true` with an empty list, not a failure.
        let mut bookmarks = Vec::new();
        for (source, file) in &files {
            if bookmarks.len() >= limit {
                break;
            }
            if let Ok(text) = std::fs::read_to_string(file) {
                parse_chromium_bookmarks(&text, source, &mut bookmarks, limit);
            }
        }
        Ok(BookmarkListing {
            availability: Availability::available("chromium_bookmarks"),
            bookmarks,
        })
    }

    /// Every `<profile>/Bookmarks` file across every installed Chromium browser,
    /// paired with a source label (`"chrome"`, or `"edge:Profile 1"` for a
    /// non-default profile). Scans each browser's user-data dir for subdirectories
    /// that actually contain a `Bookmarks` file, so arbitrarily-named profiles and
    /// the `System Profile`/`Guest Profile` pseudo-dirs are handled without a
    /// hard-coded `Default`/`Profile N` list.
    fn chromium_bookmark_files() -> Vec<(String, std::path::PathBuf)> {
        use std::path::PathBuf;
        let mut roots: Vec<(&'static str, PathBuf)> = Vec::new();
        #[cfg(target_os = "windows")]
        {
            if let Some(local) = std::env::var_os("LOCALAPPDATA").map(PathBuf::from) {
                roots.push(("chrome", local.join(r"Google\Chrome\User Data")));
                roots.push(("edge", local.join(r"Microsoft\Edge\User Data")));
                roots.push((
                    "brave",
                    local.join(r"BraveSoftware\Brave-Browser\User Data"),
                ));
            }
        }
        #[cfg(not(target_os = "windows"))]
        {
            if let Some(config) = dirs::config_dir() {
                roots.push(("chrome", config.join("google-chrome")));
                roots.push(("chromium", config.join("chromium")));
                roots.push(("edge", config.join("microsoft-edge")));
                roots.push(("brave", config.join("BraveSoftware/Brave-Browser")));
            }
        }
        let mut files = Vec::new();
        for (browser, base) in roots {
            let Ok(entries) = std::fs::read_dir(&base) else {
                continue;
            };
            for entry in entries.flatten() {
                let profile_dir = entry.path();
                if !profile_dir.is_dir() {
                    continue;
                }
                let bookmarks = profile_dir.join("Bookmarks");
                if !bookmarks.exists() {
                    continue;
                }
                let profile = entry.file_name().to_string_lossy().into_owned();
                let source = if profile == "Default" {
                    browser.to_string()
                } else {
                    format!("{browser}:{profile}")
                };
                files.push((source, bookmarks));
            }
        }
        files
    }

    /// Parse one Chromium `Bookmarks` JSON document, appending every URL bookmark
    /// (bookmark bar, other, and synced roots, depth-first) up to `limit`.
    fn parse_chromium_bookmarks(json: &str, source: &str, out: &mut Vec<Bookmark>, limit: usize) {
        let Ok(value) = serde_json::from_str::<Value>(json) else {
            return;
        };
        let Some(roots) = value.get("roots") else {
            return;
        };
        for key in ["bookmark_bar", "other", "synced"] {
            if out.len() >= limit {
                break;
            }
            if let Some(node) = roots.get(key) {
                collect_chromium(node, source, out, limit);
            }
        }
    }

    /// Depth-first walk of a Chromium bookmark node: `type: "url"` nodes are
    /// collected, `type: "folder"` (and any node carrying `children`) are recursed.
    fn collect_chromium(node: &Value, source: &str, out: &mut Vec<Bookmark>, limit: usize) {
        if out.len() >= limit {
            return;
        }
        if node.get("type").and_then(Value::as_str) == Some("url") {
            if let Some(url) = node.get("url").and_then(Value::as_str) {
                let title = node
                    .get("name")
                    .and_then(Value::as_str)
                    .filter(|s| !s.is_empty())
                    .unwrap_or(url);
                out.push(Bookmark {
                    title: title.to_string(),
                    url: Some(url.to_string()),
                    source: source.to_string(),
                });
            }
            return;
        }
        if let Some(children) = node.get("children").and_then(Value::as_array) {
            for child in children {
                collect_chromium(child, source, out, limit);
                if out.len() >= limit {
                    break;
                }
            }
        }
    }

    /// Unlike Notes/Reminders/Photos/Safari — which are genuinely macOS-only apps
    /// — user file locations exist on every platform, so this is a real backend
    /// on Windows and Linux, not a pending stub. `dirs` resolves them through the
    /// Known Folder API on Windows (so a Documents/Downloads folder relocated to
    /// another drive is reported at its real path, not a guessed
    /// `%USERPROFILE%\Documents`) and XDG user-dirs on Linux.
    pub fn files_locations() -> Result<FileLocationListing, IntegrationError> {
        let mut locations = Vec::new();
        let mut add = |id: &str, name: &str, path: Option<std::path::PathBuf>| {
            if let Some(path) = path {
                locations.push(FileLocation {
                    id: id.to_string(),
                    name: name.to_string(),
                    exists: path.exists(),
                    path: path.to_string_lossy().to_string(),
                });
            }
        };
        add("desktop", "Desktop", dirs::desktop_dir());
        add("documents", "Documents", dirs::document_dir());
        add("downloads", "Downloads", dirs::download_dir());
        // OneDrive is the standard cloud drive on Windows and has no `dirs`
        // accessor. Prefer the env var Windows sets when a personal OneDrive is
        // configured, else fall back to the conventional `%USERPROFILE%\OneDrive`.
        #[cfg(target_os = "windows")]
        {
            let onedrive = std::env::var_os("OneDrive")
                .map(std::path::PathBuf::from)
                .or_else(|| dirs::home_dir().map(|h| h.join("OneDrive")));
            add("onedrive", "OneDrive", onedrive);
        }

        let backend = if cfg!(target_os = "windows") {
            "windows_files"
        } else {
            "xdg_files"
        };
        let available = locations.iter().any(|location| location.exists);
        Ok(FileLocationListing {
            availability: if available {
                Availability::available(backend)
            } else {
                Availability::pending(backend, "No standard user file locations found.")
            },
            locations,
        })
    }

    pub fn keychain_status() -> Result<KeychainStatus, IntegrationError> {
        let check = car_secrets::SecretStore::new().availability();
        Ok(KeychainStatus {
            availability: if check.available {
                Availability::available("keychain")
            } else {
                Availability::pending(
                    "keychain",
                    check
                        .reason
                        .unwrap_or_else(|| "OS keychain is unavailable.".to_string()),
                )
            },
        })
    }

    fn pending(backend: &'static str) -> Availability {
        Availability::pending(backend, "This Apple integration is only modeled on macOS.")
    }

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

        // A trimmed but structurally faithful Chromium `Bookmarks` document:
        // nested folders, the three standard roots, and an empty-name entry.
        const FIXTURE: &str = r#"{
          "roots": {
            "bookmark_bar": {
              "type": "folder",
              "children": [
                { "type": "url", "name": "Rust", "url": "https://www.rust-lang.org/" },
                { "type": "folder", "name": "Dev", "children": [
                  { "type": "url", "name": "GitHub", "url": "https://github.com/" }
                ]}
              ]
            },
            "other": {
              "type": "folder",
              "children": [
                { "type": "url", "name": "", "url": "https://example.com/" }
              ]
            },
            "synced": { "type": "folder", "children": [] }
          }
        }"#;

        #[test]
        fn parses_nested_bookmarks_across_roots() {
            let mut out = Vec::new();
            parse_chromium_bookmarks(FIXTURE, "chrome", &mut out, 100);
            let urls: Vec<&str> = out.iter().filter_map(|b| b.url.as_deref()).collect();
            assert_eq!(
                urls,
                [
                    "https://www.rust-lang.org/",
                    "https://github.com/",
                    "https://example.com/"
                ]
            );
            // An empty `name` falls back to the URL as the display title.
            let example = out
                .iter()
                .find(|b| b.url.as_deref() == Some("https://example.com/"))
                .unwrap();
            assert_eq!(example.title, "https://example.com/");
            assert!(out.iter().all(|b| b.source == "chrome"));
        }

        #[test]
        fn respects_the_limit() {
            let mut out = Vec::new();
            parse_chromium_bookmarks(FIXTURE, "edge", &mut out, 2);
            assert_eq!(out.len(), 2);
        }

        #[test]
        fn malformed_json_yields_nothing_and_does_not_panic() {
            let mut out = Vec::new();
            parse_chromium_bookmarks("}{ not json", "brave", &mut out, 10);
            assert!(out.is_empty());
        }
    }
}

#[cfg(all(test, not(target_os = "macos")))]
mod non_macos_tests {
    use super::*;

    // Unlike the other Apple-only surfaces, file locations are a real backend on
    // Windows/Linux — the CLI's `car files locations` must return the user's
    // folders, not the macOS-only empty stub it used to.
    #[test]
    fn files_locations_is_real_off_macos() {
        let listing = files_locations().expect("files_locations returns a listing");
        let expected_backend = if cfg!(target_os = "windows") {
            "windows_files"
        } else {
            "xdg_files"
        };
        assert_eq!(listing.availability.backend, expected_backend);

        // On Windows the Known Folder API always resolves Desktop/Documents/
        // Downloads (+OneDrive, which has no `dirs` accessor), so assert they're
        // present. On Linux `dirs` reads `~/.config/user-dirs.dirs`, which a
        // headless CI runner does not have — there `dirs::*` returns `None` and
        // `locations` is legitimately empty. So off Windows we only require the
        // envelope to be well-formed and not panic, not any specific entry.
        #[cfg(target_os = "windows")]
        {
            for id in ["desktop", "documents", "downloads", "onedrive"] {
                assert!(
                    listing.locations.iter().any(|l| l.id == id),
                    "expected a {id} location on Windows, got {:?}",
                    listing.locations
                );
            }
        }
    }

    // Bookmarks read the Chromium family off macOS. On a runner with no browser
    // installed this is a well-formed pending/empty envelope; with a browser it's
    // available. Either way the backend is `chromium_bookmarks` and it never
    // panics — the deterministic parsing is covered by `backend::bookmark_tests`.
    #[test]
    fn bookmarks_use_the_chromium_backend_off_macos() {
        let listing = bookmarks_list(10).expect("bookmarks_list returns a listing");
        assert_eq!(listing.availability.backend, "chromium_bookmarks");
        if listing.availability.available {
            assert!(
                listing.bookmarks.iter().all(|b| b.url.is_some()),
                "every collected bookmark should carry a URL"
            );
        } else {
            assert!(listing.bookmarks.is_empty());
        }
    }

    // Off macOS, notes/reminders route through Microsoft Graph (OneNote / To
    // Do) — the `msgraph` backend, pending when unconfigured, not the old "only
    // modeled on macOS" stub. Guarded on `is_configured()` so the test never
    // triggers a device-code login on a runner that happens to set the env.
    #[test]
    fn notes_reminders_use_graph_backend_off_macos() {
        if crate::msgraph::is_configured() {
            return;
        }
        let na = notes_accounts().unwrap();
        assert_eq!(na.availability.backend, "msgraph");
        assert!(!na.availability.available && na.accounts.is_empty());

        let nf = notes_find("x", 5).unwrap();
        assert_eq!(nf.availability.backend, "msgraph");
        assert!(nf.notes.is_empty());

        let rl = reminders_lists().unwrap();
        assert_eq!(rl.availability.backend, "msgraph");
        assert!(rl.lists.is_empty());

        let ri = reminders_items(5).unwrap();
        assert_eq!(ri.availability.backend, "msgraph");
        assert!(ri.reminders.is_empty());
    }
}