computer-use 0.2.0

Cross-platform desktop automation for agents: screenshots, mouse, keyboard, accessibility, CDP, and isolation.
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
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
//! Application policy: built-in deny list plus user and admin `policy.toml`.
//!
//! Resolution order is built-in deny, then admin policy, then user policy.
//! Deny wins. A user allow cannot override an admin deny or a built-in deny.
//! Admin `allow` entries do not grant access. A missing user file is
//! `default = "allow"` plus this built-in list. `pause_on_user_input` defaults
//! to false when the key is absent, so a missing file does not install an event tap.

use std::path::Path;

use crate::error::ComputerError;
use crate::target::AppSelector;

const SYSTEM_SETTINGS_BUNDLES: &[&str] = &["com.apple.systempreferences", "com.apple.Settings"];

/// Bundle ids that are always refused. Comparison is case-insensitive.
const DENIED_BUNDLE_IDS: &[&str] = &[
    "com.apple.Terminal",
    "com.googlecode.iterm2",
    "dev.warp.Warp-Stable",
    "org.alacritty",
    "net.kovidgoyal.kitty",
    "com.mitchellh.ghostty",
    "com.github.wez.wezterm",
    "co.zeit.hyper",
    "com.1password.1password",
    "com.agilebits.onepassword7",
    "com.bitwarden.desktop",
    "org.keepassxc.KeePassXC",
    "com.dashlane.Dashlane",
    "in.sinew.Enpass-Desktop",
    "com.lastpass.LastPass",
    "com.lastpass.lastpassmacdesktop",
    "com.apple.Passwords",
    "com.apple.keychainaccess",
    "Microsoft.WindowsTerminal",
    "app.crynta.terax",
];

/// Executable file names, matched case-insensitively after canonicalization.
const DENIED_EXE_NAMES: &[&str] = &[
    "Terminal",
    "iTerm2",
    "Warp",
    "Alacritty",
    "kitty",
    "ghostty",
    "wezterm",
    "wezterm-gui",
    "Hyper",
    "hyper",
    "powershell.exe",
    "cmd.exe",
    "wt.exe",
    "WindowsTerminal.exe",
    "gnome-terminal",
    "konsole",
    "xterm",
    "1Password",
    "1Password.exe",
    "Bitwarden",
    "Bitwarden.exe",
    "KeePassXC",
    "KeePassXC.exe",
    "KeePass.exe",
    "Dashlane",
    "Dashlane.exe",
    "Enpass",
    "Enpass.exe",
    "LastPass",
    "lastpass",
    "LastPass.exe",
    "Passwords",
    "Passwords.exe",
    "Keychain Access",
    "Terax",
];

/// `.app` bundle directory names, matched as a single path component.
const DENIED_APP_BUNDLES: &[&str] = &[
    "Terminal.app",
    "iTerm.app",
    "iTerm2.app",
    "Warp.app",
    "Alacritty.app",
    "kitty.app",
    "Ghostty.app",
    "WezTerm.app",
    "Hyper.app",
    "1Password.app",
    "1Password 7.app",
    "Bitwarden.app",
    "KeePassXC.app",
    "Dashlane.app",
    "Enpass.app",
    "LastPass.app",
    "Passwords.app",
    "Keychain Access.app",
    "Terax.app",
];

/// Display names refused before a bundle is resolved. `Terminal` is enough
/// to refuse `launch Terminal` without scanning the disk.
const DENIED_DISPLAY_NAMES: &[&str] = &[
    "Terminal",
    "iTerm",
    "iTerm2",
    "Warp",
    "Alacritty",
    "kitty",
    "Ghostty",
    "WezTerm",
    "Hyper",
    "1Password",
    "1Password 7",
    "Bitwarden",
    "KeePassXC",
    "Dashlane",
    "Enpass",
    "LastPass",
    "Passwords",
    "Keychain Access",
    "Windows Terminal",
    "Terax",
];

/// Why a built-in rule refused an app.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Denial {
    /// `bundle`, `path`, `name`, or `system-settings`.
    pub source: &'static str,
    /// Human-readable explanation. Does not include typed text or URLs.
    pub message: String,
}

/// Refuse `selector` before it is resolved, when the selector itself is enough.
pub fn selector_denial(selector: &AppSelector) -> Option<Denial> {
    match selector {
        AppSelector::Pid(_) => None,
        AppSelector::BundleId(bundle_id) => bundle_denial(bundle_id).map(|message| Denial {
            source: "bundle",
            message,
        }),
        AppSelector::Name(name) => {
            if denied_display_name(name) {
                Some(Denial {
                    source: "name",
                    message: format!("built-in deny list refuses {name}"),
                })
            } else {
                None
            }
        }
        AppSelector::Path(path) => path_denial(path).map(|message| Denial {
            source: "path",
            message,
        }),
    }
}

/// Refuse a resolved app. System Settings is refused only when the targeted
/// window title or accessibility identifier mentions Privacy or Security.
pub fn identity_denial(
    bundle_id: Option<&str>,
    exe_path: Option<&Path>,
    window_title: Option<&str>,
    ax_identifier: Option<&str>,
) -> Option<Denial> {
    if let Some(bundle_id) = bundle_id {
        if let Some(message) = bundle_denial(bundle_id) {
            return Some(Denial {
                source: "bundle",
                message,
            });
        }
        if is_system_settings(bundle_id) && privacy_or_security(window_title, ax_identifier) {
            return Some(Denial {
                source: "system-settings",
                message: "built-in deny list refuses System Settings while the targeted window title or identifier contains Privacy or Security".into(),
            });
        }
    }
    if let Some(path) = exe_path {
        if let Some(message) = path_denial(path) {
            return Some(Denial {
                source: "path",
                message,
            });
        }
    }
    None
}

/// Map a denial to [`ComputerError::PolicyDenied`].
pub fn deny_or_allow(denial: Option<Denial>) -> Result<(), ComputerError> {
    match denial {
        None => Ok(()),
        Some(denial) => Err(ComputerError::PolicyDenied(denial.message)),
    }
}

/// `loginwindow`, `WindowServer`, and this process cannot be quit.
pub fn quit_is_protected(
    pid: i32,
    current_pid: i32,
    bundle_id: Option<&str>,
    name: &str,
    path: Option<&str>,
) -> bool {
    if pid == current_pid {
        return true;
    }
    if bundle_id.is_some_and(|id| id.eq_ignore_ascii_case("com.apple.loginwindow")) {
        return true;
    }
    let name = name.trim();
    if name.eq_ignore_ascii_case("loginwindow") || name.eq_ignore_ascii_case("WindowServer") {
        return true;
    }
    path.is_some_and(|path| {
        Path::new(path)
            .file_name()
            .and_then(|file| file.to_str())
            .is_some_and(|file| {
                file.eq_ignore_ascii_case("loginwindow")
                    || file.eq_ignore_ascii_case("WindowServer")
            })
    })
}

fn bundle_denial(bundle_id: &str) -> Option<String> {
    DENIED_BUNDLE_IDS
        .iter()
        .find(|id| id.eq_ignore_ascii_case(bundle_id))
        .map(|id| format!("built-in deny list refuses {id}"))
}

fn path_denial(path: &Path) -> Option<String> {
    if let Some(file) = path.file_name().and_then(|file| file.to_str()) {
        if DENIED_EXE_NAMES
            .iter()
            .any(|name| name.eq_ignore_ascii_case(file))
        {
            return Some(format!(
                "built-in deny list refuses executable {}",
                path.display()
            ));
        }
    }
    for component in path.components() {
        let text = component.as_os_str().to_string_lossy();
        if DENIED_APP_BUNDLES
            .iter()
            .any(|name| text.eq_ignore_ascii_case(name))
        {
            return Some(format!(
                "built-in deny list refuses path {}",
                path.display()
            ));
        }
    }
    None
}

fn denied_display_name(name: &str) -> bool {
    DENIED_DISPLAY_NAMES
        .iter()
        .any(|denied| denied.eq_ignore_ascii_case(name.trim()))
}

fn is_system_settings(bundle_id: &str) -> bool {
    SYSTEM_SETTINGS_BUNDLES
        .iter()
        .any(|id| id.eq_ignore_ascii_case(bundle_id))
}

fn privacy_or_security(window_title: Option<&str>, ax_identifier: Option<&str>) -> bool {
    [window_title, ax_identifier]
        .into_iter()
        .flatten()
        .any(|text| {
            let lower = text.to_ascii_lowercase();
            lower.contains("privacy") || lower.contains("security")
        })
}

/// Marker stored in `kCGEventSourceUserData` (`CGEventField::EventSourceUserData`, value 42).
///
/// P7 posts synthetic events with this value. The listen-only tap ignores them.
/// Field 43 is `kCGEventSourceUserID` and is not the marker.
pub const SYNTHETIC_EVENT_USER_DATA: i64 = 0x00C0_5EC0_0DE1;

/// True when a tap event was posted by this process and must not pause.
pub fn event_is_synthetic(user_data: i64) -> bool {
    user_data == SYNTHETIC_EVENT_USER_DATA
}

const BROWSER_BUNDLES: &[&str] = &[
    "com.apple.Safari",
    "com.google.Chrome",
    "com.google.Chrome.canary",
    "org.chromium.Chromium",
    "com.microsoft.edgemac",
    "com.microsoft.Edge",
    "com.brave.Browser",
    "company.thebrowser.Browser",
    "org.mozilla.firefox",
];

const BROWSER_EXES: &[&str] = &[
    "Safari",
    "Google Chrome",
    "Chromium",
    "chrome",
    "chrome.exe",
    "chromium",
    "msedge",
    "msedge.exe",
    "Microsoft Edge",
    "brave",
    "Brave Browser",
    "Arc",
    "firefox",
    "firefox.exe",
];

/// How [`decide`] classifies an action.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PolicyAction {
    /// `policy_check`. The app verdict is separate.
    Inspect,
    /// Always allowed: wait, doctor, displays, list, pause, resume.
    Always,
    /// Read-only maintenance that does not name a denied app.
    Benign,
    /// Tree, screenshot, or get-state. A denied target is refused.
    Observe,
    /// Changes the desktop.
    Mutate,
    /// Quit, including force quit. Allowed apps still need confirmation.
    Quit,
    /// A key combination.
    Key {
        /// Combo text such as `cmd+q`.
        combo: String,
    },
    /// `clipboard_set` (P8). Classified here so that phase can call [`decide`].
    ClipboardSet,
}

/// Allow, refuse, or ask the confirm hook.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Decision {
    /// The action may run.
    Allow {
        /// `builtin`, `admin`, `user`, or `default`.
        source: &'static str,
    },
    /// The action must not run.
    Deny {
        /// `builtin`, `admin`, or `user`.
        source: &'static str,
        /// Human-readable explanation. Does not include typed text or URLs.
        message: String,
    },
    /// A sensitive action. Run the confirm hook, or return `confirm_required`.
    Confirm {
        /// Why confirmation is required.
        reason: String,
    },
}

/// Resolved target passed to [`decide`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Subject {
    /// Localized name.
    pub name: Option<String>,
    /// Bundle id.
    pub bundle_id: Option<String>,
    /// Executable path. [`decide`] canonicalizes it.
    pub path: Option<String>,
    /// Process id.
    pub pid: Option<i32>,
    /// Window id when one was targeted.
    pub window_id: Option<u32>,
    /// Targeted window title. Used for the System Settings privacy rule.
    pub window_title: Option<String>,
    /// Accessibility identifier of the targeted window.
    pub ax_identifier: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct Rule {
    effect: RuleEffect,
    bundle_id: Option<String>,
    path: Option<String>,
    name: Option<String>,
    source: &'static str,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RuleEffect {
    Allow,
    Deny,
}

/// Merged admin and user policy.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoadedPolicy {
    user_default_deny: bool,
    admin_default_deny: bool,
    rules: Vec<Rule>,
    blocked_urls: Vec<String>,
    user_confirm: Option<String>,
    admin_confirm: Option<String>,
    timeout_secs: u64,
    /// True only when a loaded file sets the key. A missing file stays false.
    pub pause_on_user_input: bool,
}

impl Default for LoadedPolicy {
    fn default() -> Self {
        Self {
            user_default_deny: false,
            admin_default_deny: false,
            rules: Vec::new(),
            blocked_urls: Vec::new(),
            user_confirm: None,
            admin_confirm: None,
            timeout_secs: 30,
            pause_on_user_input: false,
        }
    }
}

impl LoadedPolicy {
    /// Patterns from the user and admin files.
    pub fn blocked_urls(&self) -> &[String] {
        &self.blocked_urls
    }

    /// Timeout for the confirm hook. Capped at 120 seconds.
    pub fn timeout_secs(&self) -> u64 {
        self.timeout_secs.clamp(1, 120)
    }
}

/// Built-in deny, then admin, then user. Deny wins over allow.
pub fn decide(policy: &LoadedPolicy, target: &Subject, action: &PolicyAction) -> Decision {
    if matches!(
        action,
        PolicyAction::Always | PolicyAction::Benign | PolicyAction::Inspect
    ) {
        return Decision::Allow { source: "default" };
    }
    let verdict = app_verdict(policy, target);
    if let Decision::Deny { .. } = &verdict {
        return verdict;
    }
    if unscoped_target(target)
        && matches!(
            action,
            PolicyAction::Mutate
                | PolicyAction::Quit
                | PolicyAction::Key { .. }
                | PolicyAction::ClipboardSet
        )
        && (policy.admin_default_deny || policy.user_default_deny)
    {
        let source = if policy.admin_default_deny {
            "admin"
        } else {
            "user"
        };
        return Decision::Deny {
            source,
            message: format!("{source} policy default is deny and no app was named"),
        };
    }
    if matches!(action, PolicyAction::Quit) && quit_protected(target) {
        return Decision::Deny {
            source: "builtin",
            message: "refusing to quit loginwindow, WindowServer, or this process".into(),
        };
    }
    if let Some(reason) = confirm_reason(action) {
        return Decision::Confirm { reason };
    }
    verdict
}

/// Allow or deny for `policy check`. Never returns [`Decision::Confirm`].
pub fn app_verdict(policy: &LoadedPolicy, target: &Subject) -> Decision {
    let canonical = target
        .path
        .as_deref()
        .map(|path| crate::target::canonical_exe_path(Path::new(path)));
    if let Some(denial) = identity_denial(
        target.bundle_id.as_deref(),
        canonical.as_deref(),
        target.window_title.as_deref(),
        target.ax_identifier.as_deref(),
    ) {
        return Decision::Deny {
            source: "builtin",
            message: denial.message,
        };
    }
    if target.bundle_id.is_none() && canonical.is_none() {
        if let Some(name) = target.name.as_deref() {
            if denied_display_name(name) {
                return Decision::Deny {
                    source: "builtin",
                    message: format!("built-in deny list refuses {name}"),
                };
            }
        }
    }
    let subject_path = canonical.unwrap_or_default();
    if policy.rules.iter().any(|rule| {
        rule.source == "admin"
            && rule.effect == RuleEffect::Deny
            && deny_matches(rule, target, &subject_path)
    }) {
        return Decision::Deny {
            source: "admin",
            message: "admin policy denies this app".into(),
        };
    }
    if policy.rules.iter().any(|rule| {
        rule.source == "user"
            && rule.effect == RuleEffect::Deny
            && deny_matches(rule, target, &subject_path)
    }) {
        return Decision::Deny {
            source: "user",
            message: "user policy denies this app".into(),
        };
    }
    if let Some(message) = allow_path_mismatch(policy, target, &subject_path) {
        return Decision::Deny {
            source: "user",
            message,
        };
    }
    // An empty subject is the desktop or an action that named no app.
    // Default deny applies to a named app. Unscoped mutating actions are
    // refused in `decide`. A user allow never overrides an admin default deny.
    let named = !unscoped_target(target);
    if policy.admin_default_deny && named {
        return Decision::Deny {
            source: "admin",
            message: "admin policy default is deny".into(),
        };
    }
    if user_allow_matches(policy, target, &subject_path) {
        return Decision::Allow { source: "user" };
    }
    if policy.user_default_deny && named {
        return Decision::Deny {
            source: "user",
            message: "user policy default is deny".into(),
        };
    }
    Decision::Allow { source: "default" }
}

fn unscoped_target(target: &Subject) -> bool {
    target.name.is_none()
        && target.bundle_id.is_none()
        && target.path.is_none()
        && target.pid.is_none()
}

fn quit_protected(target: &Subject) -> bool {
    let Some(pid) = target.pid else {
        return false;
    };
    quit_is_protected(
        pid,
        std::process::id() as i32,
        target.bundle_id.as_deref(),
        target.name.as_deref().unwrap_or(""),
        target.path.as_deref(),
    )
}

fn confirm_reason(action: &PolicyAction) -> Option<String> {
    match action {
        PolicyAction::Quit => Some("quit".into()),
        PolicyAction::ClipboardSet => Some("clipboard_set".into()),
        PolicyAction::Key { combo } if key_needs_confirm(combo) => {
            Some(format!("key combination {combo}"))
        }
        _ => None,
    }
}

fn deny_matches(rule: &Rule, target: &Subject, canonical: &Path) -> bool {
    if let Some(bundle) = &rule.bundle_id {
        if target
            .bundle_id
            .as_ref()
            .is_some_and(|id| id.eq_ignore_ascii_case(bundle))
        {
            return true;
        }
    }
    if let Some(path) = &rule.path {
        if path_matches(canonical, path) {
            return true;
        }
    }
    if let Some(name) = &rule.name {
        if target
            .name
            .as_ref()
            .is_some_and(|value| value.eq_ignore_ascii_case(name))
        {
            return true;
        }
    }
    false
}

fn user_allow_matches(policy: &LoadedPolicy, target: &Subject, canonical: &Path) -> bool {
    policy.rules.iter().any(|rule| {
        rule.source == "user"
            && rule.effect == RuleEffect::Allow
            && allow_matches(rule, target, canonical)
    })
}

fn allow_matches(rule: &Rule, target: &Subject, canonical: &Path) -> bool {
    let mut saw = false;
    if let Some(bundle) = &rule.bundle_id {
        saw = true;
        if !target
            .bundle_id
            .as_ref()
            .is_some_and(|id| id.eq_ignore_ascii_case(bundle))
        {
            return false;
        }
    }
    if let Some(path) = &rule.path {
        saw = true;
        if !path_matches(canonical, path) {
            return false;
        }
    }
    if let Some(name) = &rule.name {
        saw = true;
        if !target
            .name
            .as_ref()
            .is_some_and(|value| value.eq_ignore_ascii_case(name))
        {
            return false;
        }
    }
    saw
}

fn allow_path_mismatch(
    policy: &LoadedPolicy,
    target: &Subject,
    canonical: &Path,
) -> Option<String> {
    let bundle = target.bundle_id.as_deref()?;
    let constrained: Vec<&Rule> = policy
        .rules
        .iter()
        .filter(|rule| {
            rule.effect == RuleEffect::Allow
                && rule.source == "user"
                && rule.path.is_some()
                && rule
                    .bundle_id
                    .as_ref()
                    .is_some_and(|id| id.eq_ignore_ascii_case(bundle))
        })
        .collect();
    if constrained.is_empty() {
        return None;
    }
    if constrained
        .iter()
        .any(|rule| path_matches(canonical, rule.path.as_deref().unwrap_or("")))
    {
        return None;
    }
    if policy.rules.iter().any(|rule| {
        rule.source == "user"
            && rule.effect == RuleEffect::Allow
            && rule.path.is_none()
            && rule
                .bundle_id
                .as_ref()
                .is_some_and(|id| id.eq_ignore_ascii_case(bundle))
    }) {
        return None;
    }
    Some("allow.path does not match the canonical executable path".into())
}

fn path_matches(canonical: &Path, rule_path: &str) -> bool {
    if canonical.as_os_str().is_empty() || rule_path.is_empty() {
        return false;
    }
    let rule = Path::new(rule_path);
    if canonical == rule {
        return true;
    }
    let subject = normalize_path(canonical);
    let allow = normalize_path(rule);
    if subject.eq_ignore_ascii_case(&allow) {
        return true;
    }
    let with_sep = if allow.ends_with('/') {
        allow.clone()
    } else {
        format!("{allow}/")
    };
    subject
        .to_ascii_lowercase()
        .starts_with(&with_sep.to_ascii_lowercase())
}

fn normalize_path(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

/// Load the user file at `explicit` (or the default path) and merge the admin file.
pub fn load_policy(explicit: Option<&Path>) -> Result<LoadedPolicy, ComputerError> {
    let user = user_policy_file(explicit)?;
    let admin = admin_policy_file();
    load_paths(user.as_deref(), admin.as_deref())
}

/// Load two already chosen files. `None` means that file is absent.
pub fn load_paths(
    user: Option<&Path>,
    admin: Option<&Path>,
) -> Result<LoadedPolicy, ComputerError> {
    let mut policy = LoadedPolicy::default();
    if let Some(path) = admin {
        merge_file(&mut policy, path, PolicyOrigin::Admin)?;
    }
    if let Some(path) = user {
        merge_file(&mut policy, path, PolicyOrigin::User)?;
    }
    policy.timeout_secs = policy.timeout_secs.min(120);
    Ok(policy)
}

#[derive(Clone, Copy)]
enum PolicyOrigin {
    User,
    Admin,
}

fn user_policy_file(explicit: Option<&Path>) -> Result<Option<std::path::PathBuf>, ComputerError> {
    if let Some(path) = explicit {
        if !path.is_file() {
            return Err(ComputerError::InvalidArguments(format!(
                "policy file not found: {}",
                path.display()
            )));
        }
        return Ok(Some(path.to_path_buf()));
    }
    let Some(base) = user_config_base() else {
        return Ok(None);
    };
    let path = base.join("computer-use").join("policy.toml");
    if path.is_file() {
        Ok(Some(path))
    } else {
        Ok(None)
    }
}

fn user_config_base() -> Option<std::path::PathBuf> {
    // Explicit `--policy` paths still load. Ambient config must not, in tests.
    ambient_user_config_base()
}

#[cfg(test)]
fn ambient_user_config_base() -> Option<std::path::PathBuf> {
    None
}

#[cfg(not(test))]
fn ambient_user_config_base() -> Option<std::path::PathBuf> {
    if let Some(xdg) = std::env::var_os("XDG_CONFIG_HOME") {
        if !xdg.is_empty() {
            return Some(std::path::PathBuf::from(xdg));
        }
    }
    dirs::home_dir().map(|home| home.join(".config"))
}

fn admin_policy_file() -> Option<std::path::PathBuf> {
    ambient_admin_policy_file()
}

#[cfg(test)]
fn ambient_admin_policy_file() -> Option<std::path::PathBuf> {
    None
}

#[cfg(not(test))]
fn ambient_admin_policy_file() -> Option<std::path::PathBuf> {
    if let Some(overridden) = std::env::var_os("COMPUTER_USE_ADMIN_POLICY") {
        let path = std::path::PathBuf::from(overridden);
        return path.is_file().then_some(path);
    }
    let path = default_admin_path();
    path.is_file().then_some(path)
}

#[cfg(all(not(test), windows))]
fn default_admin_path() -> std::path::PathBuf {
    let base = std::env::var_os("ProgramData")
        .map(std::path::PathBuf::from)
        .unwrap_or_else(|| std::path::PathBuf::from(r"C:\ProgramData"));
    base.join("computer-use").join("policy.toml")
}

#[cfg(all(not(test), not(windows)))]
fn default_admin_path() -> std::path::PathBuf {
    std::path::PathBuf::from("/etc/computer-use/policy.toml")
}

fn merge_file(
    policy: &mut LoadedPolicy,
    path: &Path,
    origin: PolicyOrigin,
) -> Result<(), ComputerError> {
    let text = std::fs::read_to_string(path).map_err(|error| policy_io(origin, path, error))?;
    if text.trim().is_empty() {
        return Ok(());
    }
    let parsed: PolicyFile =
        toml::from_str(&text).map_err(|error| parse_error(origin, path, &text, &error))?;
    if parsed.version.unwrap_or(0) != 1 {
        return Err(origin_error(
            origin,
            path,
            format!(
                "line {}: policy version must be 1",
                line_of_key(&text, "version")
            ),
        ));
    }
    let default_deny = match parsed.default.as_deref() {
        None => false,
        Some("allow") => false,
        Some("deny") => true,
        Some(other) => {
            return Err(origin_error(
                origin,
                path,
                format!(
                    "line {}: default must be allow or deny (got {other})",
                    line_of_key(&text, "default")
                ),
            ))
        }
    };
    if parsed.pause_on_user_input.unwrap_or(false) {
        policy.pause_on_user_input = true;
    }
    let source = match origin {
        PolicyOrigin::User => {
            policy.user_default_deny = default_deny;
            if let Some(confirm) = parsed.confirm.as_ref() {
                if let Some(command) = confirm
                    .command
                    .clone()
                    .filter(|text| !text.trim().is_empty())
                {
                    policy.user_confirm = Some(command);
                }
                if let Some(timeout) = confirm.timeout_secs {
                    policy.timeout_secs = timeout.clamp(1, 120);
                }
            }
            "user"
        }
        PolicyOrigin::Admin => {
            policy.admin_default_deny = default_deny;
            if let Some(confirm) = parsed.confirm.as_ref() {
                if let Some(command) = confirm
                    .command
                    .clone()
                    .filter(|text| !text.trim().is_empty())
                {
                    policy.admin_confirm = Some(command);
                }
                if policy.user_confirm.is_none() {
                    if let Some(timeout) = confirm.timeout_secs {
                        policy.timeout_secs = timeout.clamp(1, 120);
                    }
                }
            }
            "admin"
        }
    };
    for entry in parsed.deny {
        policy.rules.push(
            rule_from(entry, RuleEffect::Deny, source)
                .map_err(|detail| origin_error(origin, path, detail))?,
        );
    }
    if matches!(origin, PolicyOrigin::User) {
        for entry in parsed.allow {
            policy.rules.push(
                rule_from(entry, RuleEffect::Allow, source)
                    .map_err(|detail| origin_error(origin, path, detail))?,
            );
        }
    }
    if let Some(browser) = parsed.browser {
        policy.blocked_urls.extend(browser.blocked_urls);
    }
    Ok(())
}

fn rule_from(entry: PolicyEntry, effect: RuleEffect, source: &'static str) -> Result<Rule, String> {
    if entry.bundle_id.is_none() && entry.path.is_none() && entry.name.is_none() {
        return Err("policy allow and deny entries need bundle_id, path, or name".into());
    }
    let path = entry.path.map(|path| {
        crate::target::canonical_exe_path(Path::new(&path))
            .to_string_lossy()
            .into_owned()
    });
    Ok(Rule {
        effect,
        bundle_id: entry.bundle_id,
        path,
        name: entry.name,
        source,
    })
}

fn policy_io(origin: PolicyOrigin, path: &Path, error: std::io::Error) -> ComputerError {
    origin_error(origin, path, error.to_string())
}

fn line_of_key(text: &str, key: &str) -> usize {
    text.lines()
        .position(|line| {
            let trimmed = line.trim_start();
            trimmed.starts_with(key) && trimmed[key.len()..].trim_start().starts_with('=')
        })
        .map(|index| index + 1)
        .unwrap_or(1)
}

fn parse_error(
    origin: PolicyOrigin,
    path: &Path,
    text: &str,
    error: &toml::de::Error,
) -> ComputerError {
    let line = error
        .span()
        .map(|span| {
            text[..span.start.min(text.len())]
                .chars()
                .filter(|ch| *ch == '\n')
                .count()
                + 1
        })
        .or_else(|| line_from_display(&error.to_string()))
        .unwrap_or(1);
    origin_error(origin, path, format!("line {line}: {error}"))
}

fn line_from_display(text: &str) -> Option<usize> {
    let marker = "at line ";
    let start = text.find(marker)? + marker.len();
    text[start..]
        .split(|ch: char| !ch.is_ascii_digit())
        .next()?
        .parse()
        .ok()
}

fn origin_error(origin: PolicyOrigin, path: &Path, detail: String) -> ComputerError {
    match origin {
        PolicyOrigin::User => {
            ComputerError::InvalidArguments(format!("{}: {detail}", path.display()))
        }
        PolicyOrigin::Admin => ComputerError::PolicyDenied(format!("{}: {detail}", path.display())),
    }
}

#[derive(Debug, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct PolicyFile {
    #[serde(default)]
    version: Option<u32>,
    #[serde(default)]
    default: Option<String>,
    #[serde(default)]
    pause_on_user_input: Option<bool>,
    #[serde(default)]
    allow: Vec<PolicyEntry>,
    #[serde(default)]
    deny: Vec<PolicyEntry>,
    #[serde(default)]
    confirm: Option<ConfirmSection>,
    #[serde(default)]
    browser: Option<BrowserSection>,
}

#[derive(Debug, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct PolicyEntry {
    #[serde(default)]
    bundle_id: Option<String>,
    #[serde(default)]
    path: Option<String>,
    #[serde(default)]
    name: Option<String>,
}

#[derive(Debug, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct ConfirmSection {
    #[serde(default)]
    command: Option<String>,
    #[serde(default)]
    timeout_secs: Option<u64>,
}

#[derive(Debug, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct BrowserSection {
    #[serde(default)]
    blocked_urls: Vec<String>,
}

/// Program from the flag, then `COMPUTER_USE_CONFIRM_CMD`, then user policy, then admin.
///
/// Unit tests do not read the environment variable. The CLI process does.
pub fn confirm_program(policy: &LoadedPolicy, flag: Option<&str>) -> Option<String> {
    if let Some(flag) = flag.map(str::trim).filter(|text| !text.is_empty()) {
        return Some(flag.to_string());
    }
    #[cfg(not(test))]
    if let Ok(env) = std::env::var("COMPUTER_USE_CONFIRM_CMD") {
        if !env.trim().is_empty() {
            return Some(env);
        }
    }
    policy
        .user_confirm
        .clone()
        .or_else(|| policy.admin_confirm.clone())
}

/// JSON object written to the confirm hook's stdin.
#[derive(Debug, serde::Serialize)]
pub struct ConfirmDocument<'a> {
    /// Action name.
    pub action: &'a str,
    /// Target bundle id.
    pub bundle_id: Option<&'a str>,
    /// Target executable path.
    pub path: Option<&'a str>,
    /// Target pid.
    pub pid: Option<i32>,
    /// Target window id.
    pub window_id: Option<u32>,
    /// Element index.
    pub element: Option<u32>,
    /// Why this action is sensitive.
    pub reason: &'a str,
}

/// Spawn the hook. Exit 0 proceeds. Any other result is `confirm_denied`.
///
/// No configured command is `confirm_required` and the action does not run.
pub fn run_confirm(
    command: Option<&str>,
    timeout_secs: u64,
    document: &ConfirmDocument<'_>,
) -> Result<(), ComputerError> {
    let Some(command) = command.map(str::trim).filter(|text| !text.is_empty()) else {
        return Err(ComputerError::ConfirmRequired(format!(
            "{} requires a confirm hook ({})",
            document.action, document.reason
        )));
    };
    let (program, args) = split_command(command)?;
    let payload = serde_json::json!({
        "action": document.action,
        "app": {
            "bundle_id": document.bundle_id,
            "path": document.path,
        },
        "pid": document.pid,
        "window_id": document.window_id,
        "element": document.element,
        "reason": document.reason,
    });
    let bytes = serde_json::to_vec(&payload).map_err(|error| {
        ComputerError::ExecutionFailed(format!("confirm document encode failed: {error}"))
    })?;
    let timeout = std::time::Duration::from_secs(timeout_secs.clamp(1, 120));
    let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
    match crate::backend::run_with_stdin(&program, &arg_refs, &bytes, timeout) {
        Ok(output) if output.status.success() => Ok(()),
        Ok(output) => Err(ComputerError::ConfirmDenied(format!(
            "confirm hook exited {}",
            output
                .status
                .code()
                .map(|code| code.to_string())
                .unwrap_or_else(|| "without a status".into())
        ))),
        Err(error) => Err(ComputerError::ConfirmDenied(error)),
    }
}

/// Split a command into a program and arguments. Quotes may use `"` or `'`.
pub fn split_command(input: &str) -> Result<(String, Vec<String>), ComputerError> {
    let mut tokens = Vec::new();
    let mut current = String::new();
    let mut quote: Option<char> = None;
    let mut any = false;
    for ch in input.chars() {
        match quote {
            Some(mark) if ch == mark => quote = None,
            Some(_) => current.push(ch),
            None if ch == '"' || ch == '\'' => quote = Some(ch),
            None if ch.is_whitespace() => {
                if any {
                    tokens.push(std::mem::take(&mut current));
                    any = false;
                }
            }
            None => {
                current.push(ch);
                any = true;
            }
        }
    }
    if quote.is_some() {
        return Err(ComputerError::InvalidArguments(
            "confirm command has an unmatched quote".into(),
        ));
    }
    if any {
        tokens.push(current);
    }
    let mut tokens = tokens.into_iter();
    let program = tokens
        .next()
        .ok_or_else(|| ComputerError::InvalidArguments("confirm command is empty".into()))?;
    Ok((program, tokens.collect()))
}

/// Click or `AXPress` titles that need confirmation.
pub fn sensitive_title(title: &str) -> bool {
    title
        .split(|ch: char| !ch.is_ascii_alphanumeric())
        .any(|word| {
            matches!(
                word.to_ascii_lowercase().as_str(),
                "delete" | "erase" | "pay" | "purchase" | "send" | "submit"
            )
        })
}

/// `cmd+q` and `alt+f4`.
pub fn key_needs_confirm(keys: &str) -> bool {
    let Ok(combos) = crate::keys::parse_key_sequence(keys) else {
        return false;
    };
    combos.iter().any(|combo| {
        let command =
            combo.modifiers.len() == 1 && combo.modifiers[0] == crate::types::Modifier::Command;
        let alt = combo.modifiers.len() == 1 && combo.modifiers[0] == crate::types::Modifier::Alt;
        (command && combo.key.eq_ignore_ascii_case("q"))
            || (alt && combo.key.eq_ignore_ascii_case("f4"))
    })
}

/// Safari, Chrome, Chromium, Edge, Brave, Arc, and Firefox.
pub fn is_browser(bundle_id: Option<&str>, path: Option<&Path>, name: Option<&str>) -> bool {
    if bundle_id.is_some_and(|id| {
        BROWSER_BUNDLES
            .iter()
            .any(|browser| browser.eq_ignore_ascii_case(id))
    }) {
        return true;
    }
    if let Some(path) = path {
        if let Some(file) = path.file_name().and_then(|file| file.to_str()) {
            if BROWSER_EXES
                .iter()
                .any(|exe| exe.eq_ignore_ascii_case(file))
            {
                return true;
            }
        }
    }
    name.is_some_and(|name| {
        BROWSER_EXES
            .iter()
            .any(|exe| exe.eq_ignore_ascii_case(name.trim()))
            || name.eq_ignore_ascii_case("Google Chrome")
            || name.eq_ignore_ascii_case("Safari")
            || name.eq_ignore_ascii_case("Firefox")
            || name.eq_ignore_ascii_case("Microsoft Edge")
            || name.eq_ignore_ascii_case("Brave Browser")
            || name.eq_ignore_ascii_case("Arc")
    })
}

/// First `http://`, `https://`, or `file://` token in `text`.
pub fn url_in_text(text: &str) -> Option<&str> {
    for token in text.split_whitespace() {
        let token =
            token.trim_matches(|ch: char| matches!(ch, '"' | '\'' | '<' | '>' | '(' | ')' | ','));
        if token.starts_with("https://")
            || token.starts_with("http://")
            || token.starts_with("file://")
        {
            return Some(token);
        }
    }
    None
}

/// Pattern that matches `url`, if any. `*` matches any span, including empty.
///
/// A pattern that ends in `/*` also matches the same URL with no trailing slash.
/// P10 calls this before CDP navigation.
pub fn url_blocked<'a>(url: &str, patterns: &'a [String]) -> Option<&'a str> {
    patterns.iter().find_map(|pattern| {
        if glob_match(pattern, url) || slash_star_origin(pattern, url) {
            Some(pattern.as_str())
        } else {
            None
        }
    })
}

fn slash_star_origin(pattern: &str, url: &str) -> bool {
    let Some(origin) = pattern.strip_suffix("/*") else {
        return false;
    };
    url == origin || url.starts_with(&format!("{origin}?"))
}

fn glob_match(pattern: &str, text: &str) -> bool {
    let parts: Vec<&str> = pattern.split('*').collect();
    if parts.len() == 1 {
        return pattern == text;
    }
    if !text.starts_with(parts[0]) {
        return false;
    }
    let mut rest = &text[parts[0].len()..];
    for (index, part) in parts.iter().enumerate().skip(1) {
        if part.is_empty() {
            if index + 1 == parts.len() {
                return true;
            }
            continue;
        }
        if index + 1 == parts.len() {
            return rest.ends_with(part);
        }
        match rest.find(part) {
            Some(pos) => rest = &rest[pos + part.len()..],
            None => return false,
        }
    }
    true
}

std::thread_local! {
    static TEST_PAUSED: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
}

/// Clears a test pause override when dropped.
pub struct PauseOverride {
    previous: Option<bool>,
}

impl Drop for PauseOverride {
    fn drop(&mut self) {
        let previous = self.previous.take();
        TEST_PAUSED.with(|slot| slot.set(previous));
    }
}

/// Force [`is_paused`] on this thread until the guard drops.
///
/// This does not create an event tap and does not set the process-wide flag.
pub fn override_paused(paused: bool) -> PauseOverride {
    let previous = TEST_PAUSED.with(|slot| slot.replace(Some(paused)));
    PauseOverride { previous }
}

/// Whether mutating actions must return `paused`.
///
/// The pause file is the cross-process source of truth. The atomic flag covers
/// this process when the file could not be written. Tests consult the
/// thread-local override first, then the file, and never the real home directory.
pub fn is_paused() -> bool {
    #[cfg(test)]
    if let Some(paused) = TEST_PAUSED.with(|slot| slot.get()) {
        return paused;
    }
    if pause_file_present() {
        return true;
    }
    paused_without_file()
}

#[cfg(test)]
fn paused_without_file() -> bool {
    false
}

#[cfg(not(test))]
fn paused_without_file() -> bool {
    if FILE_IO_OK.load(std::sync::atomic::Ordering::Acquire) {
        PAUSED.store(false, std::sync::atomic::Ordering::Release);
        false
    } else {
        PAUSED.load(std::sync::atomic::Ordering::Acquire)
    }
}

#[cfg(not(test))]
static PAUSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static FILE_IO_OK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);

/// Set or clear the pause flag and the `paused` file next to the audit log.
pub fn set_paused(paused: bool) -> Result<(), ComputerError> {
    #[cfg(not(test))]
    PAUSED.store(paused, std::sync::atomic::Ordering::Release);
    match write_pause_file(paused) {
        Ok(()) => {
            FILE_IO_OK.store(true, std::sync::atomic::Ordering::Release);
            Ok(())
        }
        Err(error) => {
            FILE_IO_OK.store(false, std::sync::atomic::Ordering::Release);
            Err(error)
        }
    }
}

fn pause_file_present() -> bool {
    crate::audit::state_dir()
        .map(|dir| dir.join("paused").is_file())
        .unwrap_or(false)
}

fn write_pause_file(paused: bool) -> Result<(), ComputerError> {
    let Some(dir) = crate::audit::state_dir() else {
        return Ok(());
    };
    std::fs::create_dir_all(&dir).map_err(ComputerError::Io)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
    }
    let path = dir.join("paused");
    if paused {
        let mut options = std::fs::OpenOptions::new();
        options.write(true).create(true).truncate(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            options.mode(0o600);
            #[cfg(target_os = "linux")]
            options.custom_flags(0x20000);
            #[cfg(target_os = "macos")]
            options.custom_flags(0x0100);
        }
        options.open(&path).map_err(ComputerError::Io)?;
        Ok(())
    } else if path.exists() {
        std::fs::remove_file(&path).map_err(ComputerError::Io)
    } else {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(unix)]
    use std::fs;
    use std::path::PathBuf;

    #[test]
    fn terminal_bundle_id_and_fixture_path_are_denied() {
        let by_id = identity_denial(Some("com.apple.Terminal"), None, None, None).unwrap();
        assert_eq!(by_id.source, "bundle");
        assert!(by_id.message.contains("com.apple.Terminal"));

        let path = Path::new("/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal");
        let by_path = identity_denial(None, Some(path), None, None).unwrap();
        assert_eq!(by_path.source, "path");
        assert!(by_path.message.contains("Terminal.app"));

        let selector = AppSelector::BundleId("com.apple.Terminal".into());
        assert!(selector_denial(&selector).is_some());
        let named = AppSelector::Name(r#"Foo "Bar""#.into());
        assert!(selector_denial(&named).is_none());

        assert!(identity_denial(Some("app.crynta.terax"), None, None, None).is_some());
        assert!(selector_denial(&AppSelector::Name("Terax".into())).is_some());
        let terax = Path::new("/Applications/Terax.app/Contents/MacOS/Terax");
        assert!(identity_denial(None, Some(terax), None, None).is_some());
    }

    #[test]
    fn every_listed_bundle_and_exe_is_denied_and_notes_is_not() {
        for bundle_id in DENIED_BUNDLE_IDS {
            assert!(
                identity_denial(Some(bundle_id), None, None, None).is_some(),
                "{bundle_id}"
            );
        }
        for exe in DENIED_EXE_NAMES {
            let path = PathBuf::from("/usr/bin").join(exe);
            assert!(
                identity_denial(None, Some(&path), None, None).is_some(),
                "{exe}"
            );
        }
        assert!(identity_denial(
            Some("com.apple.Notes"),
            Some(Path::new(
                "/System/Applications/Notes.app/Contents/MacOS/Notes"
            )),
            None,
            None
        )
        .is_none());
        assert!(identity_denial(
            None,
            Some(Path::new("/usr/local/bin/TerminalHelper")),
            None,
            None
        )
        .is_none());
    }

    #[test]
    fn system_settings_privacy_window_is_denied_and_other_windows_are_not() {
        assert!(identity_denial(
            Some("com.apple.systempreferences"),
            Some(Path::new(
                "/System/Applications/System Settings.app/Contents/MacOS/System Settings"
            )),
            Some("Privacy & Security"),
            None,
        )
        .is_some());
        assert!(identity_denial(
            Some("com.apple.systempreferences"),
            None,
            Some("Displays"),
            Some("AXIdentifier"),
        )
        .is_none());
        assert!(identity_denial(Some("com.apple.systempreferences"), None, None, None).is_none());
        assert!(identity_denial(
            Some("com.apple.Settings"),
            None,
            Some("Privacy & Security"),
            None,
        )
        .is_some());
        assert!(
            identity_denial(Some("com.apple.Settings"), None, Some("Displays"), None).is_none()
        );
        assert!(identity_denial(
            Some("com.apple.systempreferences"),
            None,
            None,
            Some("Privacy_Security"),
        )
        .is_some());
    }

    #[test]
    fn powershell_cmd_and_wt_paths_are_denied() {
        for exe in ["powershell.exe", "cmd.exe", "wt.exe", "gnome-terminal"] {
            let path = PathBuf::from(r"C:\Windows\System32").join(exe);
            assert!(path_denial(&path).is_some(), "{exe}");
        }
    }

    #[test]
    fn quit_protects_loginwindow_windowserver_and_self() {
        assert!(quit_is_protected(9, 9, None, "computer-use", None));
        assert!(quit_is_protected(
            2,
            9,
            Some("com.apple.loginwindow"),
            "loginwindow",
            None
        ));
        assert!(quit_is_protected(3, 9, None, "WindowServer", None));
        assert!(!quit_is_protected(
            10,
            9,
            Some("com.apple.Notes"),
            "Notes",
            Some("/System/Applications/Notes.app/Contents/MacOS/Notes")
        ));
    }

    #[cfg(unix)]
    #[test]
    fn symlink_to_a_terminal_executable_is_denied() {
        let dir = std::env::temp_dir().join(format!(
            "computer-use-policy-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|duration| duration.as_nanos())
                .unwrap_or(0)
        ));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let real = dir.join("Terminal");
        fs::write(&real, b"fixture").unwrap();
        let link = dir.join("alias");
        std::os::unix::fs::symlink(&real, &link).unwrap();
        let canonical = fs::canonicalize(&link).unwrap();
        assert_eq!(
            canonical.file_name().and_then(|name| name.to_str()),
            Some("Terminal")
        );
        assert!(identity_denial(None, Some(&canonical), None, None).is_some());
        let user = dir.join("user.toml");
        std::fs::write(&user, "version = 1\n[[allow]]\npath = \"alias\"\n").unwrap();
        // The allow path is relative to the process, so point it at the symlink itself.
        let user_text = format!("version = 1\n[[allow]]\npath = \"{}\"\n", link.display());
        std::fs::write(&user, user_text).unwrap();
        let policy = load_paths(Some(&user), None).unwrap();
        let decision = decide(
            &policy,
            &Subject {
                path: Some(link.display().to_string()),
                ..Subject::default()
            },
            &PolicyAction::Mutate,
        );
        assert!(
            matches!(
                decision,
                Decision::Deny {
                    source: "builtin",
                    ..
                }
            ),
            "{decision:?}"
        );
        let _ = fs::remove_dir_all(&dir);
    }

    fn temp_dir(label: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "computer-use-{label}-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|duration| duration.as_nanos())
                .unwrap_or(0)
        ));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn subject_bundle(bundle: &str) -> Subject {
        Subject {
            bundle_id: Some(bundle.into()),
            ..Subject::default()
        }
    }

    #[test]
    fn default_deny_allows_only_listed_apps() {
        let dir = temp_dir("default-deny");
        let user = dir.join("user.toml");
        std::fs::write(
            &user,
            "version = 1\ndefault = \"deny\"\n\n[[allow]]\nbundle_id = \"com.apple.Notes\"\n",
        )
        .unwrap();
        let policy = load_paths(Some(&user), None).unwrap();
        assert!(matches!(
            app_verdict(&policy, &subject_bundle("com.apple.Notes")),
            Decision::Allow { source: "user" }
        ));
        assert!(matches!(
            app_verdict(&policy, &subject_bundle("com.apple.Finder")),
            Decision::Deny { source: "user", .. }
        ));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn admin_deny_beats_user_allow_and_builtin_beats_user_allow() {
        let dir = temp_dir("merge");
        let admin = dir.join("admin.toml");
        let user = dir.join("user.toml");
        std::fs::write(
            &admin,
            "version = 1\n[[deny]]\nbundle_id = \"com.apple.Notes\"\n",
        )
        .unwrap();
        std::fs::write(
            &user,
            "version = 1\n[[allow]]\nbundle_id = \"com.apple.Notes\"\n[[allow]]\nbundle_id = \"com.apple.Terminal\"\n",
        )
        .unwrap();
        let policy = load_paths(Some(&user), Some(&admin)).unwrap();
        assert!(matches!(
            app_verdict(&policy, &subject_bundle("com.apple.Notes")),
            Decision::Deny {
                source: "admin",
                ..
            }
        ));
        assert!(matches!(
            app_verdict(&policy, &subject_bundle("com.apple.Terminal")),
            Decision::Deny {
                source: "builtin",
                ..
            }
        ));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn glob_blocks_accounts_host_and_allows_example() {
        let patterns = vec!["https://accounts.example.com/*".to_string()];
        assert_eq!(
            url_blocked("https://accounts.example.com/login", &patterns),
            Some("https://accounts.example.com/*")
        );
        assert!(url_blocked("https://accounts.example.com/", &patterns).is_some());
        assert!(url_blocked("https://accounts.example.com", &patterns).is_some());
        assert!(url_blocked("https://example.com/", &patterns).is_none());
        assert!(url_blocked("https://example.com/accounts.example.com/", &patterns).is_none());
    }

    #[test]
    fn user_parse_error_names_the_line_and_admin_fails_closed() {
        let dir = temp_dir("parse");
        let user = dir.join("user.toml");
        std::fs::write(&user, "version = 1\n\ndefault = \"sometimes\"\n").unwrap();
        let error = load_paths(Some(&user), None).unwrap_err();
        assert_eq!(error.code(), "invalid_arguments");
        assert!(error.to_string().contains("line "), "{error}");
        let admin = dir.join("admin.toml");
        std::fs::write(&admin, "version = 1\nnope = true\n").unwrap();
        let error = load_paths(None, Some(&admin)).unwrap_err();
        assert_eq!(error.code(), "policy_denied");
        assert!(
            error.to_string().contains(&admin.display().to_string()),
            "{error}"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn confirm_hook_exit_codes() {
        let dir = temp_dir("confirm");
        let document = ConfirmDocument {
            action: "quit",
            bundle_id: Some("com.apple.Notes"),
            path: None,
            pid: Some(10),
            window_id: None,
            element: None,
            reason: "quit",
        };
        #[cfg(unix)]
        let (allow, deny) = {
            let allow = dir.join("allow.sh");
            let deny = dir.join("deny.sh");
            std::fs::write(&allow, "#!/bin/sh\ncat >/dev/null\nexit 0\n").unwrap();
            std::fs::write(&deny, "#!/bin/sh\ncat >/dev/null\nexit 1\n").unwrap();
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                std::fs::set_permissions(&allow, std::fs::Permissions::from_mode(0o700)).unwrap();
                std::fs::set_permissions(&deny, std::fs::Permissions::from_mode(0o700)).unwrap();
            }
            (allow.display().to_string(), deny.display().to_string())
        };
        #[cfg(windows)]
        let (allow, deny) = ("cmd /C exit 0".to_string(), "cmd /C exit 1".to_string());
        assert!(run_confirm(Some(&allow), 30, &document).is_ok());
        let denied = run_confirm(Some(&deny), 30, &document).unwrap_err();
        assert_eq!(denied.code(), "confirm_denied");
        let missing = run_confirm(None, 30, &document).unwrap_err();
        assert_eq!(missing.code(), "confirm_required");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn sensitive_titles_and_quit_shortcuts() {
        assert!(sensitive_title("Delete Note"));
        assert!(sensitive_title("SEND"));
        assert!(!sensitive_title("Save"));
        assert!(key_needs_confirm("cmd+q"));
        assert!(key_needs_confirm("alt+f4"));
        assert!(!key_needs_confirm("cmd+s"));
        assert!(!key_needs_confirm("meta+q"));
        assert!(!event_is_synthetic(1));
        assert!(event_is_synthetic(SYNTHETIC_EVENT_USER_DATA));
    }
}