teams-cli 0.2.2

A Microsoft Teams CLI and TUI designed equally for humans and agents
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
//! A dedicated Chromium profile. Verification precedes every page connection; closing
//! uses the verified browser's DevTools socket, never a signal to an arbitrary PID. Only
//! the verified browser is signalled, when it does not exit after closing its endpoint.
use super::{ConnectionMetadata, ProbeStatus, cdp::Cdp, connection::Action, session::Verifier};
use crate::{config::DesktopAccount, error::AppError};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::{
    ffi::OsString,
    fs::{File, OpenOptions},
    io::{Read, Seek, Write},
    os::unix::{ffi::OsStringExt, fs::OpenOptionsExt, process::CommandExt},
    path::{Path, PathBuf},
    process::{Command, Stdio},
    time::Duration,
};

pub struct BrowserSystem {
    pub core: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Identity {
    pid: u32,
    started: String,
    executable: PathBuf,
}

#[derive(Debug, Serialize, Deserialize)]
struct State {
    version: u8,
    port: u16,
    owner: Option<Identity>,
    visible: bool,
    #[serde(default)]
    core: bool,
    phase: String,
}

fn failed(message: &str) -> AppError {
    AppError::Desktop(message.into())
}

pub(super) fn data_directory() -> Result<PathBuf, AppError> {
    let base = match std::env::var_os("TEAMS_DESKTOP_BROWSER_DATA_DIR") {
        Some(path) => {
            let path = PathBuf::from(path);
            if !path.is_absolute() {
                return Err(failed(
                    "TEAMS_DESKTOP_BROWSER_DATA_DIR must be an absolute path",
                ));
            }
            path
        }
        None => dirs::data_local_dir()
            .ok_or_else(|| failed("could not locate the browser profile directory"))?
            .join("teams-cli/browser"),
    };
    Ok(base)
}

fn directory(port: u16) -> Result<PathBuf, AppError> {
    Ok(data_directory()?.join(port.to_string()))
}

/// Avoid assigning a new account a port with an older browser's saved sign-in.
pub fn has_saved_data(port: u16) -> Result<bool, AppError> {
    Ok(directory(port)?.try_exists()?)
}

fn profile(dir: &Path) -> PathBuf {
    dir.join("profile")
}

pub fn executable() -> Result<PathBuf, AppError> {
    if let Some(path) = std::env::var_os("TEAMS_DESKTOP_BROWSER") {
        let path = PathBuf::from(path);
        if !path.is_absolute() {
            return Err(failed(
                "TEAMS_DESKTOP_BROWSER must be an absolute path to the Chrome/Chromium/Edge executable (not a shell wrapper)",
            ));
        }
        return std::fs::canonicalize(path)
            .map_err(|_| failed("TEAMS_DESKTOP_BROWSER does not exist; fix or unset this override, then retry setup"));
    }
    let candidates = if cfg!(target_os = "macos") {
        vec![
            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
            "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
            "/Applications/Chromium.app/Contents/MacOS/Chromium",
        ]
    } else {
        vec![
            "/opt/google/chrome/chrome",
            "/opt/microsoft/msedge/msedge",
            "/opt/microsoft/msedge-beta/msedge",
            "/usr/lib/chromium/chromium",
            "/usr/lib64/chromium-browser/chromium-browser",
            "/usr/lib/chromium-browser/chromium-browser",
        ]
    };
    candidates.iter().find_map(|p| std::fs::canonicalize(p).ok())
        .ok_or_else(|| failed("install Chrome, Chromium or Edge, or set TEAMS_DESKTOP_BROWSER to its executable; WSL2 uses a Linux browser"))
}

pub fn prerequisites() -> Result<(), AppError> {
    prerequisites_for(false)
}

pub fn prerequisites_for(core: bool) -> Result<(), AppError> {
    if core {
        super::browser_install::installed().map_err(|error| failed(&format!("The lightweight browser is not ready: {error}. Run `teams desktop login --desktop-client browser-core` to set it up.")))?;
    } else {
        executable()?;
    }
    verification_prerequisites()
}

fn verification_prerequisites() -> Result<(), AppError> {
    #[cfg(target_os = "macos")]
    if !Path::new("/usr/sbin/lsof").is_file() {
        return Err(failed("lsof is required to verify the browser listener"));
    }
    #[cfg(target_os = "linux")]
    if !Path::new("/proc/net/tcp").is_file() {
        return Err(failed(
            "Linux /proc is required to verify the browser listener",
        ));
    }
    Ok(())
}

fn display_prerequisites() -> Result<(), AppError> {
    #[cfg(target_os = "linux")]
    if !["DISPLAY", "WAYLAND_DISPLAY"]
        .iter()
        .any(|key| std::env::var_os(key).is_some_and(|value| !value.is_empty()))
    {
        return Err(failed(
            "Browser sign-in needs a display. Enable WSLg on WSL2, or run from a Linux desktop session.",
        ));
    }
    Ok(())
}

/// Local prerequisites and (only if needed) public download metadata. No profile is created.
pub async fn preflight(core: bool) -> Result<bool, AppError> {
    display_prerequisites()?;
    verification_prerequisites()?;
    let base = data_directory()?;
    if base.try_exists()? {
        validate_directory(&base)?;
    }
    if core {
        super::browser_install::preflight().await
    } else {
        browser_version(&executable()?)?;
        Ok(false)
    }
}

fn session_executable(core: bool, visible: bool) -> Result<PathBuf, AppError> {
    if core {
        let (chrome, shell) = super::browser_install::installed()?;
        Ok(if visible { chrome } else { shell })
    } else {
        executable()
    }
}

pub(super) fn browser_version(path: &Path) -> Result<String, AppError> {
    browser_version_with_timeout(path, Duration::from_secs(5))
}

fn browser_version_with_timeout(path: &Path, timeout: Duration) -> Result<String, AppError> {
    // Files avoid pipe backpressure; a broken executable must not stall setup.
    let mut stdout = tempfile::tempfile()?;
    let mut stderr = tempfile::tempfile()?;
    let mut child = Command::new(path)
        .arg("--version")
        .stdin(Stdio::null())
        .stdout(stdout.try_clone()?)
        .stderr(stderr.try_clone()?)
        .spawn()?;
    let deadline = std::time::Instant::now() + timeout;
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break status,
            Ok(None) if std::time::Instant::now() < deadline => {
                std::thread::sleep(Duration::from_millis(20));
            }
            result => {
                let _ = child.kill();
                let _ = child.wait();
                return Err(match result {
                    Err(error) => error.into(),
                    _ => failed(
                        "Checking the browser version timed out. Check its executable or unset the browser overrides, then retry setup.",
                    ),
                });
            }
        }
    };
    if !status.success() {
        stderr.rewind()?;
        let mut detail = Vec::new();
        stderr.take(400).read_to_end(&mut detail)?;
        return Err(failed(&format!(
            "The browser could not start: {}. On Linux, install the Chrome system libraries named in this error and retry setup.",
            String::from_utf8_lossy(&detail).trim()
        )));
    }
    stdout.rewind()?;
    let mut version = Vec::new();
    stdout.take(4096).read_to_end(&mut version)?;
    String::from_utf8_lossy(&version)
        .split_whitespace()
        .find(|s| s.split('.').count() == 4 && s.bytes().all(|b| b.is_ascii_digit() || b == b'.'))
        .map(str::to_owned)
        .ok_or_else(|| failed("unrecognized browser version"))
}

fn validate_core(account: DesktopAccount) -> Result<(), AppError> {
    if account != DesktopAccount::Personal {
        return Err(failed(
            "browser-core currently requires --desktop-account personal",
        ));
    }
    if browser_version(&session_executable(true, true)?)?
        != browser_version(&session_executable(true, false)?)?
    {
        return Err(failed(
            "visible browser and headless shell must have exactly matching versions",
        ));
    }
    Ok(())
}

fn load(dir: &Path, port: u16) -> Result<Option<State>, AppError> {
    match std::fs::read(dir.join("connection.json")) {
        Ok(bytes) => {
            let state: State = serde_json::from_slice(&bytes)
                .map_err(|_| failed("invalid browser connection record; preserved for recovery"))?;
            if state.version != 1
                || state.port != port
                || !matches!(state.phase.as_str(), "starting" | "active" | "core_ready")
            {
                return Err(failed(
                    "invalid browser connection record; preserved for recovery",
                ));
            }
            Ok(Some(state))
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(error) => Err(error.into()),
    }
}

fn save(dir: &Path, state: &State) -> Result<(), AppError> {
    let mut file = tempfile::NamedTempFile::new_in(dir)?;
    file.write_all(&serde_json::to_vec(state).map_err(|_| failed("invalid browser state"))?)?;
    file.as_file().sync_all()?;
    file.persist(dir.join("connection.json"))
        .map_err(|e| e.error)?;
    Ok(())
}

fn arguments_match(args: &[OsString], profile: &Path, port: u16) -> bool {
    let mut expected = OsString::from("--user-data-dir=");
    expected.push(profile);
    let debug = OsString::from(format!("--remote-debugging-port={port}"));
    args.iter()
        .filter(|a| a.to_string_lossy().starts_with("--user-data-dir"))
        .count()
        == 1
        && args.contains(&expected)
        && args
            .iter()
            .filter(|a| a.to_string_lossy().starts_with("--remote-debugging-port"))
            .count()
            == 1
        && args.contains(&debug)
        && !args
            .iter()
            .any(|a| a == "--remote-debugging-pipe" || a.to_string_lossy().starts_with("--type="))
}

fn owned(state: &State, dir: &Path) -> bool {
    if validate_directory(dir).is_err() || validate_directory(&profile(dir)).is_err() {
        return false;
    }
    state.owner.as_ref().is_some_and(|owner| {
        system::process(owner.pid).is_ok_and(|(identity, args)| {
            identity == *owner && arguments_match(&args, &profile(dir), state.port)
        })
    })
}

impl Verifier for BrowserSystem {
    fn core_only(&self, port: u16) -> bool {
        self.core
            && directory(port)
                .and_then(|d| load(&d, port))
                .map_or(true, |state| state.is_none_or(|s| !s.visible))
    }

    async fn verify(&self, port: u16) -> Result<(ConnectionMetadata, Vec<Value>), AppError> {
        prerequisites_for(self.core)?;
        let mut metadata = ConnectionMetadata::empty(port);
        let sockets = system::listeners(port)?;
        if sockets.is_empty() {
            return Ok((metadata, vec![]));
        }
        metadata.loopback_only = Some(sockets.iter().all(|s| s.loopback));
        if metadata.loopback_only != Some(true) {
            metadata.status = ProbeStatus::UnsafeListenerRefused;
            return Ok((metadata, vec![]));
        }
        let dir = directory(port)?;
        let state = load(&dir, port)?;
        let trusted = state.as_ref().is_some_and(|s| {
            s.core == self.core
                && owned(s, &dir)
                && s.owner.as_ref().is_some_and(|o| {
                    session_executable(s.core, s.visible).is_ok_and(|e| e == o.executable)
                        && system::owns_sockets(o.pid, &sockets)
                })
                && owned(s, &dir)
        });
        metadata.teams_owned = Some(trusted);
        if !trusted {
            metadata.status = ProbeStatus::NonTeamsListenerRefused;
            return Ok((metadata, vec![]));
        }
        let targets = super::fill_metadata(&mut metadata).await;
        if state
            .as_ref()
            .is_some_and(|s| s.core && !s.visible && s.phase != "core_ready")
        {
            return Ok((metadata, vec![]));
        }
        Ok((metadata, targets))
    }
}

fn launch_args(
    dir: &Path,
    port: u16,
    account: DesktopAccount,
    visible: bool,
    core: bool,
) -> Vec<OsString> {
    let mut data = OsString::from("--user-data-dir=");
    data.push(profile(dir));
    let mut args = vec![
        data,
        format!("--remote-debugging-port={port}").into(),
        "--remote-debugging-address=127.0.0.1".into(),
        "--no-first-run".into(),
        "--no-default-browser-check".into(),
    ];
    if core && cfg!(target_os = "macos") {
        args.push("--use-mock-keychain".into());
    }
    #[cfg(target_os = "linux")]
    if visible && std::env::var_os("WAYLAND_DISPLAY").is_some() {
        args.push("--ozone-platform-hint=auto".into());
    }
    if !visible {
        args.push("--headless=new".into());
        if core {
            args.push("--disable-gpu".into());
            args.push("--js-flags=--lite-mode --optimize-for-size".into());
        }
    }
    let url = if account == DesktopAccount::Personal {
        "https://teams.live.com"
    } else {
        "https://teams.cloud.microsoft"
    };
    args.push(if core && !visible {
        "about:blank".into()
    } else {
        format!("--app={url}").into()
    });
    args
}

struct Guard(File);
impl Drop for Guard {
    fn drop(&mut self) {
        let _ = self.0.unlock();
    }
}

pub(super) fn prepare_directory(dir: &Path) -> Result<(), AppError> {
    use std::os::unix::fs::DirBuilderExt;
    std::fs::DirBuilder::new()
        .recursive(true)
        .mode(0o700)
        .create(dir)?;
    validate_directory(dir)
}

pub(super) fn validate_directory(dir: &Path) -> Result<(), AppError> {
    use std::os::unix::fs::MetadataExt;
    let metadata = std::fs::symlink_metadata(dir)?;
    let me = system::uid()?;
    if !metadata.is_dir() || metadata.uid() != me || metadata.mode() & 0o077 != 0 {
        return Err(failed(
            "the dedicated browser directory must be owned by you with permissions 0700",
        ));
    }
    Ok(())
}

/// Browser sessions persist independently of the CLI. Sign-in data survives disconnect.
// Separate orchestration from OS/browser operations so the visibility transition
// and failure behavior can be tested without a signed-in Microsoft account.
trait LoginSession {
    async fn connect(&mut self, visible: bool) -> Result<(), AppError>;
    async fn disconnect(&mut self) -> Result<(), AppError>;
    async fn wait_read(&mut self, timeout: Duration) -> Result<(), AppError>;
    /// Whether the headless browser keeps Teams signed in for `period`.
    async fn stays_signed_in(&mut self, period: Duration) -> Result<bool, AppError>;
}

/// Returns whether the browser was left visible.
async fn login_flow(session: &mut impl LoginSession) -> Result<bool, AppError> {
    session.connect(true).await?;
    session
        .wait_read(Duration::from_secs(300))
        .await
        .map_err(|error| {
            error.with_hint(
        "The visible browser and its profile were preserved; sign-in has not completed there yet.")
        })?;
    session.disconnect().await?;
    session.connect(false).await?;
    session
        .wait_read(Duration::from_secs(60))
        .await
        .map_err(|error| {
            error.with_hint(
        "The headless browser and saved profile were preserved; headless chat access is not ready.")
        })?;
    if session.stays_signed_in(Duration::from_secs(60)).await? {
        return Ok(false);
    }
    // Teams renews its sign-in shortly after loading. Organisations that sign in through
    // their own identity provider (such as AD FS with Windows sign-in) refuse that renewal
    // headless and send the page back to sign-in, so the visible browser stays open.
    session.disconnect().await?;
    session.connect(true).await?;
    session.wait_read(Duration::from_secs(300)).await.map_err(|error| error.with_hint(
        "Your organisation's sign-in needs the visible browser; sign-in has not completed there yet."))?;
    Ok(true)
}

async fn resume_flow(session: &mut impl LoginSession, visible: bool) -> Result<bool, AppError> {
    session.connect(visible).await?;
    session.wait_read(Duration::from_secs(60)).await?;
    Ok(visible)
}

async fn check_resumed_session(session: &mut impl LoginSession) -> Result<(), AppError> {
    if session.stays_signed_in(Duration::from_secs(60)).await? {
        Ok(())
    } else {
        Err(AppError::Auth("Teams needs its browser window to stay signed in. Reopen sign-in to continue; your saved session is preserved.".into()))
    }
}

/// Reuse an opted-in inbox's saved session without forcing a visible login or mode switch.
pub async fn resume(
    port: u16,
    account: DesktopAccount,
    core: bool,
    quiet: bool,
) -> Result<(bool, Option<super::ConnectionWatch>), AppError> {
    let status = manage(port, account, Action::Status, false, core).await?;
    let already_running = status["endpoint_available"] == true;
    let visible = status["management"]["visible"].as_bool().unwrap_or(false);
    let mut session = BrowserLogin {
        port,
        account,
        core,
        quiet,
        resume_only: true,
    };
    let result = resume_flow(&mut session, visible).await;
    if let Err(error) = result {
        // Only a fresh, verified sign-in redirect is classified as expired auth.
        // Ownership failures and unknown cache layouts must never trigger a login restart.
        let metadata = (BrowserSystem { core }).probe(port).await?;
        if metadata.signed_out() {
            return Err(AppError::Auth(
                "Your saved Teams session needs sign-in again.".into(),
            ));
        }
        return Err(error);
    }
    let visible = result?;
    let watch = if !visible && !already_running && account != DesktopAccount::Personal {
        let (sender, receiver) = std::sync::mpsc::channel();
        let task = tokio::spawn(async move {
            session.quiet = true;
            let result = check_resumed_session(&mut session).await;
            let _ = sender.send(result);
        });
        Some(super::ConnectionWatch { receiver, task })
    } else {
        None
    };
    Ok((visible, watch))
}

struct BrowserLogin {
    port: u16,
    account: DesktopAccount,
    core: bool,
    quiet: bool,
    resume_only: bool,
}

impl LoginSession for BrowserLogin {
    async fn connect(&mut self, visible: bool) -> Result<(), AppError> {
        // An existing session can be reused in its current mode. A mode change
        // closes only the verified managed browser and keeps its profile.
        let dir = directory(self.port)?;
        if let Some(state) = load(&dir, self.port)?
            && state.core == self.core
            && !owned(&state, &dir)
            && system::listeners(self.port)?.is_empty()
        {
            manage(self.port, self.account, Action::Recover, false, self.core).await?;
        }
        if let Some(state) = load(&dir, self.port)?
            && state.visible != visible
        {
            self.disconnect().await?;
        }
        manage(self.port, self.account, Action::Connect, visible, self.core).await?;
        Ok(())
    }

    async fn disconnect(&mut self) -> Result<(), AppError> {
        manage(
            self.port,
            self.account,
            Action::Disconnect,
            false,
            self.core,
        )
        .await?;
        Ok(())
    }

    async fn wait_read(&mut self, timeout: Duration) -> Result<(), AppError> {
        tokio::time::timeout(timeout, async {
            loop {
                // Fresh verification on every attempt, including during navigation.
                let mut session = super::session::Session::new(BrowserSystem { core: self.core });
                let mut request = super::read_request(self.port, None, 1, None)?;
                request["account_type"] = json!(self.account);
                let reply = session.read(&request).await?;
                if login_read_ready(&reply)? {
                    return Ok(());
                }
                if self.resume_only
                    && (BrowserSystem { core: self.core })
                        .probe(self.port)
                        .await?
                        .signed_out()
                {
                    return Err(AppError::Auth(
                        "Your saved Teams session needs sign-in again.".into(),
                    ));
                }
                tokio::time::sleep(Duration::from_secs(1)).await;
            }
        })
        .await
        .map_err(|_| failed("Timed out waiting for a readable Teams chat cache"))?
    }

    async fn stays_signed_in(&mut self, period: Duration) -> Result<bool, AppError> {
        // Personal accounts renew headless; their sign-in needs no extra wait.
        if self.account == DesktopAccount::Personal {
            return Ok(true);
        }
        if !self.quiet {
            eprintln!("Checking that Teams stays signed in without its window (up to a minute).");
        }
        if !watch_sign_in(&BrowserSystem { core: self.core }, self.port, period).await? {
            return Ok(false);
        }
        self.wait_read(Duration::from_secs(60)).await?;
        Ok(true)
    }
}

async fn watch_sign_in(
    system: &impl Verifier,
    port: u16,
    period: Duration,
) -> Result<bool, AppError> {
    let deadline = tokio::time::Instant::now() + period;
    while tokio::time::Instant::now() < deadline {
        let (metadata, _) = system.verify(port).await?;
        if !metadata.endpoint_available() {
            return Err(failed(&format!(
                "The dedicated browser became unavailable while checking sign-in. {}",
                metadata.detail()
            )));
        }
        if metadata.signed_out() {
            return Ok(false);
        }
        tokio::time::sleep(Duration::from_secs(2)).await;
    }
    Ok(true)
}

fn login_read_ready(reply: &Value) -> Result<bool, AppError> {
    if matches!(reply["error"].as_str(), Some("no_target" | "read_failed")) {
        return Ok(false);
    }
    // The cache is not yet available during sign-in and initial Teams loading.
    // Ownership/origin/account refusals still fail immediately.
    if reply["result"].get("exceptionDetails").is_some() {
        return Ok(false);
    }
    if let Some(raw) = reply["result"]["result"]["value"].as_str()
        && let Ok(value) = serde_json::from_str::<Value>(raw)
        && matches!(value["error"].as_str(), Some("layout" | "core_not_ready"))
    {
        return Ok(false);
    }
    super::read_page(reply).map(|_| true)
}

pub async fn login(port: u16, account: DesktopAccount, core: bool) -> Result<Value, AppError> {
    login_with_progress(port, account, core, false).await
}

pub async fn login_with_progress(
    port: u16,
    account: DesktopAccount,
    core: bool,
    quiet: bool,
) -> Result<Value, AppError> {
    login_with_recovery(port, account, core, quiet, true).await
}

pub(super) async fn login_with_recovery(
    port: u16,
    account: DesktopAccount,
    core: bool,
    quiet: bool,
    recovery: bool,
) -> Result<Value, AppError> {
    display_prerequisites()?;
    if core {
        super::browser_install::ensure_with_progress(quiet).await?;
    }
    prerequisites_for(core)?;
    let dir = directory(port)?;
    prepare_directory(&dir)?;
    let lock = OpenOptions::new()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .mode(0o600)
        .open(dir.join("login.lock"))?;
    lock.try_lock()
        .map_err(|_| failed("another browser login is running"))?;
    let _guard = Guard(lock);
    if !quiet {
        eprintln!(
            "Opening Teams sign-in. Complete sign-in in the window; it will hide automatically once your chats are ready."
        );
    }
    let visible = login_flow(&mut BrowserLogin {
        port,
        account,
        core,
        quiet,
        resume_only: false,
    })
    .await.map_err(|error| if recovery {
        error.with_hint(&format!("Retry sign-in: `teams desktop login --desktop-client {} --port {port}`. To close this dedicated browser: `teams desktop disconnect --desktop-client {} --port {port}`.", if core { "browser-core" } else { "browser" }, if core { "browser-core" } else { "browser" }))
    } else { error })?;
    if visible && !quiet {
        eprintln!(
            "Your organisation's sign-in does not allow Teams to stay signed in without its window, so the browser stays visible. Minimise it, but keep it open."
        );
    }
    let mut value = manage(port, account, Action::Status, false, core).await?;
    if value["endpoint_available"] != true {
        return Err(failed(
            "The dedicated browser closed or changed after sign-in; retry the sign-in command.",
        ));
    }
    value["session_verified"] = json!(true);
    Ok(value)
}

pub async fn manage(
    port: u16,
    account: DesktopAccount,
    action: Action,
    visible: bool,
    core: bool,
) -> Result<Value, AppError> {
    if core && matches!(action, Action::Connect) {
        super::browser_install::ensure().await?;
    }
    prerequisites_for(core)?;
    let dir = directory(port)?;
    prepare_directory(&dir)?;
    prepare_directory(&profile(&dir))?;
    let lock = OpenOptions::new()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .mode(0o600)
        .open(dir.join("connection.lock"))?;
    lock.try_lock()
        .map_err(|_| failed("another browser connection command is running"))?;
    let _guard = Guard(lock);
    let mut state = load(&dir, port)?;
    let system = BrowserSystem { core };
    let recover = format!(
        "teams desktop recover --desktop-client {} --port {port}",
        if core { "browser-core" } else { "browser" }
    );
    if state.as_ref().is_some_and(|s| s.core != core) {
        return Err(failed(
            "this port uses another browser mode; use its original --desktop-client to disconnect it first",
        ));
    }
    match action {
        Action::Status => {}
        Action::Connect => {
            if core {
                validate_core(account)?;
            }
            // A dead/reused owner with an empty port can be forgotten without
            // touching a process. Unrecorded startups and occupied ports still refuse.
            if state
                .as_ref()
                .is_some_and(|s| s.owner.is_some() && !owned(s, &dir))
                && system::listeners(port)?.is_empty()
            {
                std::fs::remove_file(dir.join("connection.json"))?;
                state = None;
            }
            if let Some(current) = state.as_ref() {
                if !owned(current, &dir) {
                    return Err(failed(&format!(
                        "the saved browser session is no longer owned; run `{recover}` before connecting"
                    )));
                }
                if current.visible != visible {
                    return Err(failed(
                        "disconnect the browser before changing between visible and headless mode",
                    ));
                }
            } else {
                let (metadata, _) = system.verify(port).await?;
                if metadata.status != ProbeStatus::NoListener {
                    return Err(failed(
                        "the browser debugging port is already in use; its listener was left untouched",
                    ));
                }
                let mut next = State {
                    version: 1,
                    port,
                    owner: None,
                    visible,
                    core,
                    phase: "starting".into(),
                };
                save(&dir, &next)?;
                let mut child = Command::new(session_executable(core, visible)?)
                    .args(launch_args(&dir, port, account, visible, core))
                    .stdin(Stdio::null())
                    .stdout(Stdio::null())
                    .stderr(Stdio::null())
                    .process_group(0)
                    .spawn()
                    .map_err(|error| {
                        failed(&format!(
                            "could not launch the Teams browser: {error}; run `{recover}`"
                        ))
                    })?;
                let pid = child.id();
                // Capture the process after exec, then reap it without tying its life to the CLI.
                let owner = system::process(pid).map(|(identity, _)| identity);
                std::thread::spawn(move || {
                    let _ = child.wait();
                });
                next.owner = Some(owner?);
                save(&dir, &next)?;
                state = Some(next);
            }
            let mut ready = false;
            for _ in 0..100 {
                let current = state.as_ref().expect("browser state");
                if !owned(current, &dir) {
                    break;
                }
                if system.probe(port).await?.endpoint_available() {
                    ready = true;
                    break;
                }
                tokio::time::sleep(Duration::from_millis(200)).await;
            }
            if !ready {
                return Err(failed(&format!(
                    "the browser did not open its debugging endpoint; its recovery record was preserved. Inspect it with `teams desktop status`, or run `{recover}`."
                )));
            }
            let current = state.as_mut().expect("browser state");
            if core && !visible && current.phase != "core_ready" {
                let targets = super::fill_metadata(&mut ConnectionMetadata::empty(port)).await;
                let pages: Vec<_> = targets.iter().filter(|t| t["type"] == "page").collect();
                let target = pages
                    .first()
                    .filter(|_| pages.len() == 1)
                    .and_then(|t| t["id"].as_str().filter(|id| super::valid_id(id)))
                    .ok_or_else(|| {
                        failed("core startup requires exactly one managed browser page")
                    })?;
                super::browser_core::start(port, target).await?;
                current.phase = "core_ready".into();
            } else if !core || visible {
                current.phase = "active".into();
            }
            save(&dir, current)?;
        }
        Action::Disconnect | Action::Recover => {
            if matches!(action, Action::Recover)
                && let Some(current) = state.as_mut()
                && current.owner.is_none()
            {
                let expected = session_executable(current.core, current.visible)?;
                let mut candidates = system::pids()?
                    .into_iter()
                    .filter_map(|pid| system::process(pid).ok())
                    .filter(|(identity, args)| {
                        identity.executable == expected
                            && arguments_match(args, &profile(&dir), port)
                    });
                if let Some((identity, _)) = candidates.next() {
                    if candidates.next().is_some() {
                        return Err(failed(
                            "multiple browser processes match the interrupted startup; they were left untouched",
                        ));
                    }
                    current.owner = Some(identity);
                    save(&dir, current)?;
                }
            }
            if let Some(current) = state.as_ref() {
                if owned(current, &dir) && system::listeners(port)?.is_empty() {
                    // It already released its endpoint, as after a close request it never
                    // finished, so DevTools cannot reach it any more.
                    stop(current, &dir).await?;
                } else if owned(current, &dir) {
                    let (metadata, _) = system.verify(port).await?;
                    if !metadata.endpoint_available() {
                        return Err(failed(&format!(
                            "browser ownership could not be verified; close the dedicated browser manually, then run `{recover}`"
                        )));
                    }
                    let (version, _) = super::read_metadata(port).await?;
                    let id = browser_id(&version, port)?;
                    if !owned(current, &dir) {
                        return Err(failed("the browser process changed; it was left untouched"));
                    }
                    Cdp::close_browser(port, &id).await?;
                    if !exited(current, &dir, Duration::from_secs(10)).await {
                        stop(current, &dir).await?;
                    }
                } else if current.owner.is_some() {
                    // A reused or changed PID is never contacted or signalled. Recover
                    // clears stale state only when there is no listener left on its port.
                    if !matches!(action, Action::Recover) || !system::listeners(port)?.is_empty() {
                        return Err(failed(
                            "the saved browser process changed; it was left untouched. Close the dedicated browser, then recover",
                        ));
                    }
                } else if std::fs::symlink_metadata(profile(&dir).join("SingletonLock")).is_ok()
                    || !system::listeners(port)?.is_empty()
                {
                    return Err(failed(
                        "browser startup was interrupted before ownership was saved; close the dedicated browser manually, then recover",
                    ));
                }
                std::fs::remove_file(dir.join("connection.json"))?;
                state = None;
            } else if !system::listeners(port)?.is_empty() {
                return Err(failed(
                    "this browser is not managed by teams-cli; it was left untouched",
                ));
            }
        }
    }
    let metadata = system.probe(port).await?;
    let live = state.as_ref().is_some_and(|s| owned(s, &dir));
    Ok(
        json!({"port":port,"endpoint_available":metadata.endpoint_available(),"session_verified":false,
        "connection":metadata,"browser_profile":profile(&dir),
        "management":{"managed":state.is_some(),"port":state.as_ref().map(|s|s.port),
        "phase":state.as_ref().map(|s|s.phase.as_str()).unwrap_or("idle"),
        "visible":state.as_ref().map(|s|s.visible),"core_only":core,"settings_pending":false,
        "needs_recovery":state.as_ref().is_some_and(|s|!matches!(s.phase.as_str(), "active" | "core_ready") || !live)}}),
    )
}

/// Whether the saved browser exits within `timeout`.
async fn exited(state: &State, dir: &Path, timeout: Duration) -> bool {
    let deadline = tokio::time::Instant::now() + timeout;
    while owned(state, dir) {
        if tokio::time::Instant::now() >= deadline {
            return false;
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
    true
}

/// Stops the saved browser when it was asked to close and did not: Chrome can hang on
/// exit after closing its endpoint. Only the process verified by PID, start time,
/// executable and profile arguments is signalled.
async fn stop(state: &State, dir: &Path) -> Result<(), AppError> {
    if let Some(owner) = state.owner.as_ref()
        && owned(state, dir)
    {
        // SAFETY: kill(2) has no memory effects; the PID was verified just above.
        unsafe { libc::kill(owner.pid as libc::pid_t, libc::SIGKILL) };
    }
    if exited(state, dir, Duration::from_secs(5)).await {
        return Ok(());
    }
    Err(failed(
        "the browser has not closed; its recovery record was preserved. Close the dedicated browser manually, then recover.",
    ))
}

impl BrowserSystem {
    async fn probe(&self, port: u16) -> Result<ConnectionMetadata, AppError> {
        Ok(self.verify(port).await?.0)
    }
}

fn browser_id(version: &Value, port: u16) -> Result<String, AppError> {
    let url = version["webSocketDebuggerUrl"]
        .as_str()
        .and_then(|s| url::Url::parse(s).ok())
        .ok_or_else(|| failed("the browser did not advertise a valid control socket"))?;
    let id = url.path().strip_prefix("/devtools/browser/").unwrap_or("");
    if url.scheme() != "ws"
        || !matches!(url.host_str(), Some("127.0.0.1" | "localhost" | "[::1]"))
        || url.port() != Some(port)
        || !url.username().is_empty()
        || url.password().is_some()
        || url.query().is_some()
        || url.fragment().is_some()
        || !(8..=64).contains(&id.len())
        || !id.bytes().all(|b| b.is_ascii_hexdigit() || b == b'-')
    {
        return Err(failed("the browser advertised an unsafe control socket"));
    }
    Ok(id.into())
}

#[cfg(target_os = "linux")]
mod system {
    use super::*;
    use std::{collections::HashSet, os::unix::fs::MetadataExt};
    #[derive(Debug)]
    pub struct Socket {
        pub loopback: bool,
        inode: u64,
        uid: u32,
    }

    pub fn parse_sockets(text: &str, port: u16, ipv6: bool) -> Result<Vec<Socket>, AppError> {
        let mut sockets = vec![];
        for row in text.lines().skip(1) {
            let fields: Vec<_> = row.split_whitespace().collect();
            if fields.len() < 10 {
                return Err(failed("invalid Linux socket metadata"));
            }
            let (address, number) = fields[1]
                .split_once(':')
                .ok_or_else(|| failed("invalid Linux socket address"))?;
            let number =
                u16::from_str_radix(number, 16).map_err(|_| failed("invalid Linux socket port"))?;
            if number != port || fields[3] != "0A" {
                continue;
            }
            sockets.push(Socket {
                loopback: address
                    == if ipv6 {
                        "00000000000000000000000001000000"
                    } else {
                        "0100007F"
                    },
                uid: fields[7]
                    .parse()
                    .map_err(|_| failed("invalid Linux socket owner"))?,
                inode: fields[9]
                    .parse()
                    .map_err(|_| failed("invalid Linux socket inode"))?,
            });
        }
        Ok(sockets)
    }
    pub fn listeners(port: u16) -> Result<Vec<Socket>, AppError> {
        let mut sockets = parse_sockets(&std::fs::read_to_string("/proc/net/tcp")?, port, false)?;
        match std::fs::read_to_string("/proc/net/tcp6") {
            Ok(text) => sockets.extend(parse_sockets(&text, port, true)?),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => return Err(e.into()),
        }
        Ok(sockets)
    }
    pub fn process(pid: u32) -> Result<(Identity, Vec<OsString>), AppError> {
        let dir = PathBuf::from(format!("/proc/{pid}"));
        let uid = std::fs::metadata("/proc/self")?.uid();
        if std::fs::metadata(&dir)?.uid() != uid {
            return Err(failed("browser belongs to another user"));
        }
        let before = std::fs::read_to_string(dir.join("stat"))?;
        let args = arguments(&std::fs::read(dir.join("cmdline"))?);
        let exe = std::fs::read_link(dir.join("exe"))?;
        let after = std::fs::read_to_string(dir.join("stat"))?;
        let started = start_time(&before)?;
        if start_time(&after)? != started {
            return Err(failed("browser process changed during verification"));
        }
        Ok((
            Identity {
                pid,
                started,
                executable: exe,
            },
            args,
        ))
    }
    /// Chrome rewrites its process title as its arguments joined by spaces, so /proc
    /// can report a single argument; split that title back at each option.
    pub fn arguments(cmdline: &[u8]) -> Vec<OsString> {
        let args: Vec<_> = cmdline
            .split(|b| *b == 0)
            .filter(|a| !a.is_empty())
            .collect();
        let parts = match args[..] {
            [title] => {
                let mut parts = vec![];
                let mut start = 0;
                for i in 0..title.len().saturating_sub(2) {
                    if &title[i..i + 3] == b" --" {
                        parts.push(&title[start..i]);
                        start = i + 1;
                    }
                }
                parts.push(&title[start..]);
                parts
            }
            _ => args,
        };
        parts
            .into_iter()
            .map(|a| OsString::from_vec(a.into()))
            .collect()
    }
    pub fn start_time(stat: &str) -> Result<String, AppError> {
        stat.rsplit_once(") ")
            .and_then(|(_, rest)| rest.split_whitespace().nth(19))
            .filter(|s| s.bytes().all(|b| b.is_ascii_digit()))
            .map(String::from)
            .ok_or_else(|| failed("invalid Linux process identity"))
    }
    pub fn uid() -> Result<u32, AppError> {
        Ok(std::fs::metadata("/proc/self")?.uid())
    }
    pub fn pids() -> Result<Vec<u32>, AppError> {
        Ok(std::fs::read_dir("/proc")?
            .filter_map(Result::ok)
            .filter_map(|e| e.file_name().to_str()?.parse().ok())
            .collect())
    }
    pub fn owns_sockets(pid: u32, sockets: &[Socket]) -> bool {
        let Ok(fds) = std::fs::read_dir(format!("/proc/{pid}/fd")) else {
            return false;
        };
        let inodes: HashSet<_> = fds
            .filter_map(Result::ok)
            .filter_map(|e| std::fs::read_link(e.path()).ok())
            .filter_map(|p| {
                p.to_str()?
                    .strip_prefix("socket:[")?
                    .strip_suffix(']')?
                    .parse::<u64>()
                    .ok()
            })
            .collect();
        let Ok(me) = std::fs::metadata("/proc/self") else {
            return false;
        };
        sockets
            .iter()
            .all(|s| s.uid == me.uid() && inodes.contains(&s.inode))
    }
}

#[cfg(target_os = "macos")]
mod system {
    use super::*;
    #[derive(Debug)]
    pub struct Socket {
        pub loopback: bool,
        pid: u32,
    }
    #[link(name = "proc")]
    unsafe extern "C" {
        fn proc_pidpath(pid: libc::c_int, buffer: *mut libc::c_void, size: u32) -> libc::c_int;
    }
    fn run(path: &str, args: &[&str]) -> Result<String, AppError> {
        let output = Command::new(path)
            .args(args)
            .stdin(Stdio::null())
            .output()?;
        if !output.status.success() {
            return Err(failed("macOS browser process inspection failed"));
        }
        String::from_utf8(output.stdout).map_err(|_| failed("invalid macOS process metadata"))
    }
    pub fn listeners(port: u16) -> Result<Vec<Socket>, AppError> {
        let output = Command::new("/usr/sbin/lsof")
            .args(["-nP", &format!("-iTCP:{port}"), "-sTCP:LISTEN", "-Fpn"])
            .stdin(Stdio::null())
            .output()?;
        if !output.status.success() && output.status.code() != Some(1) {
            return Err(failed("browser listener inspection failed"));
        }
        super::super::macos::parse_listeners(&String::from_utf8_lossy(&output.stdout)).map(|list| {
            list.into_iter()
                .map(|(pid, address)| Socket {
                    pid,
                    loopback: super::super::macos::loopback_address(&address, port),
                })
                .collect()
        })
    }
    pub fn process(pid: u32) -> Result<(Identity, Vec<OsString>), AppError> {
        let snapshot = run("/bin/ps", &["-p", &pid.to_string(), "-o", "uid=,lstart="])?;
        let (uid, stamp) = snapshot
            .trim()
            .split_once(char::is_whitespace)
            .ok_or_else(|| failed("invalid browser process metadata"))?;
        // These OS queries do not inspect browser credentials or page data.
        if uid.parse::<u32>().ok() != Some(unsafe { libc::geteuid() }) {
            return Err(failed("browser belongs to another user"));
        }
        let mut path = vec![0u8; 4096];
        let n = unsafe { proc_pidpath(pid as i32, path.as_mut_ptr().cast(), path.len() as u32) };
        if n <= 0 {
            return Err(failed("could not inspect the browser executable"));
        }
        let executable = PathBuf::from(OsString::from_vec(
            path.split(|b| *b == 0).next().unwrap_or_default().into(),
        ));
        let mut mib = [libc::CTL_KERN, libc::KERN_PROCARGS2, pid as i32];
        let mut bytes = vec![0u8; 1024 * 1024];
        let mut len = bytes.len();
        if unsafe {
            libc::sysctl(
                mib.as_mut_ptr(),
                3,
                bytes.as_mut_ptr().cast(),
                &mut len,
                std::ptr::null_mut(),
                0,
            )
        } != 0
        {
            return Err(failed("could not inspect the browser launch arguments"));
        }
        bytes.truncate(len);
        let args = parse_args(&bytes)?;
        if run("/bin/ps", &["-p", &pid.to_string(), "-o", "uid=,lstart="])? != snapshot {
            return Err(failed("browser process changed"));
        }
        Ok((
            Identity {
                pid,
                started: stamp.trim().into(),
                executable,
            },
            args,
        ))
    }
    pub fn parse_args(bytes: &[u8]) -> Result<Vec<OsString>, AppError> {
        let count = bytes
            .get(..4)
            .map(|b| i32::from_ne_bytes(b.try_into().expect("four bytes")))
            .filter(|n| *n > 0 && *n <= 4096)
            .ok_or_else(|| failed("invalid browser arguments"))? as usize;
        let end = bytes[4..]
            .iter()
            .position(|b| *b == 0)
            .ok_or_else(|| failed("invalid browser arguments"))?
            + 4;
        let args = bytes[end..]
            .split(|b| *b == 0)
            .skip_while(|a| a.is_empty())
            .take(count)
            .map(|a| OsString::from_vec(a.into()))
            .collect::<Vec<_>>();
        if args.len() != count {
            return Err(failed("invalid browser arguments"));
        }
        Ok(args)
    }
    pub fn uid() -> Result<u32, AppError> {
        Ok(unsafe { libc::geteuid() })
    }
    pub fn pids() -> Result<Vec<u32>, AppError> {
        Ok(run("/bin/ps", &["-axo", "pid="])?
            .lines()
            .filter_map(|line| line.trim().parse().ok())
            .collect())
    }
    pub fn owns_sockets(pid: u32, sockets: &[Socket]) -> bool {
        sockets.iter().all(|s| s.pid == pid)
    }
}

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

    #[derive(Default)]
    struct FakeLogin {
        events: Vec<&'static str>,
        fail_visible: bool,
        fail_headless: bool,
        fail_close: bool,
        signs_out_headless: bool,
    }
    impl LoginSession for FakeLogin {
        async fn connect(&mut self, visible: bool) -> Result<(), AppError> {
            self.events
                .push(if visible { "visible" } else { "headless" });
            Ok(())
        }
        async fn disconnect(&mut self) -> Result<(), AppError> {
            self.events.push("close");
            if self.fail_close {
                return Err(failed("ownership changed"));
            }
            Ok(())
        }
        async fn wait_read(&mut self, timeout: Duration) -> Result<(), AppError> {
            let visible = timeout.as_secs() == 300;
            self.events.push(if visible {
                "read-visible"
            } else {
                "read-headless"
            });
            if (visible && self.fail_visible) || (!visible && self.fail_headless) {
                return Err(failed("not signed in"));
            }
            Ok(())
        }
        async fn stays_signed_in(&mut self, _period: Duration) -> Result<bool, AppError> {
            self.events.push("watch-headless");
            Ok(!self.signs_out_headless)
        }
    }

    #[tokio::test]
    async fn resume_preserves_visible_sessions_and_skips_repeated_work_sign_in_checks() {
        for visible in [false, true] {
            let mut session = FakeLogin::default();
            assert_eq!(resume_flow(&mut session, visible).await.unwrap(), visible);
            assert_eq!(
                session.events,
                [
                    if visible { "visible" } else { "headless" },
                    "read-headless"
                ]
            );
        }
    }

    #[tokio::test]
    async fn cold_resume_opens_a_verified_inbox_without_blocking_on_the_background_watch() {
        let mut session = FakeLogin {
            signs_out_headless: true,
            ..Default::default()
        };
        assert!(!resume_flow(&mut session, false).await.unwrap());
        assert_eq!(session.events, ["headless", "read-headless"]);
        let mut refused = FakeLogin {
            fail_headless: true,
            ..Default::default()
        };
        assert!(resume_flow(&mut refused, false).await.is_err());
        assert_eq!(refused.events, ["headless", "read-headless"]);
    }

    #[tokio::test]
    async fn the_background_watch_reports_sign_in_loss_without_restarting_the_browser() {
        let mut session = FakeLogin {
            signs_out_headless: true,
            ..Default::default()
        };
        assert!(matches!(
            check_resumed_session(&mut session).await,
            Err(AppError::Auth(_))
        ));
        assert_eq!(session.events, ["watch-headless"]);
    }

    #[tokio::test]
    async fn login_verifies_reads_before_and_after_hiding() {
        let mut session = FakeLogin::default();
        assert!(!login_flow(&mut session).await.unwrap());
        assert_eq!(
            session.events,
            [
                "visible",
                "read-visible",
                "close",
                "headless",
                "read-headless",
                "watch-headless"
            ]
        );
    }

    #[tokio::test]
    async fn sign_in_that_needs_the_window_reopens_it_visible() {
        let mut session = FakeLogin {
            signs_out_headless: true,
            ..Default::default()
        };
        assert!(login_flow(&mut session).await.unwrap());
        assert_eq!(
            session.events,
            [
                "visible",
                "read-visible",
                "close",
                "headless",
                "read-headless",
                "watch-headless",
                "close",
                "visible",
                "read-visible"
            ]
        );
    }

    #[tokio::test]
    async fn sign_in_watch_refuses_a_closed_or_unsafe_browser() {
        use super::super::owner::tests::FakeSystem;
        for listeners in [vec![], vec![(30, false)]] {
            let system = FakeSystem {
                listeners,
                ..FakeSystem::teams()
            };
            let error = watch_sign_in(&system, 9224, Duration::from_secs(1))
                .await
                .unwrap_err();
            assert!(error.to_string().contains("became unavailable"));
        }
    }

    #[tokio::test]
    async fn failed_visible_login_keeps_window_open() {
        let mut session = FakeLogin {
            fail_visible: true,
            ..Default::default()
        };
        let error = login_flow(&mut session).await.unwrap_err();
        assert!(
            error
                .to_string()
                .contains("visible browser and its profile were preserved")
        );
        assert_eq!(session.events, ["visible", "read-visible"]);
    }

    #[tokio::test]
    async fn headless_sign_in_is_verified_before_success() {
        let mut session = FakeLogin {
            fail_headless: true,
            ..Default::default()
        };
        let error = login_flow(&mut session).await.unwrap_err();
        assert!(
            error
                .to_string()
                .contains("headless browser and saved profile were preserved")
        );
        assert_eq!(session.events.last(), Some(&"read-headless"));
    }

    #[tokio::test]
    async fn failed_verified_close_prevents_headless_restart() {
        let mut session = FakeLogin {
            fail_close: true,
            ..Default::default()
        };
        assert!(login_flow(&mut session).await.is_err());
        assert_eq!(session.events, ["visible", "read-visible", "close"]);
    }

    #[test]
    fn login_retries_loading_but_refuses_unsafe_or_ambiguous_sessions() {
        for code in ["no_target", "read_failed"] {
            assert!(!login_read_ready(&json!({"error":code})).unwrap());
        }
        assert!(!login_read_ready(&json!({"result":{"exceptionDetails":{}}})).unwrap());
        for code in ["account_ambiguous", "not_loopback", "metadata_probe_failed"] {
            assert!(login_read_ready(&json!({"error":code})).is_err());
        }
        assert!(
            login_read_ready(
                &json!({"result":{"result":{"value":"{\"items\":[],\"next\":null}"}}})
            )
            .unwrap()
        );
    }

    #[test]
    fn browser_directories_refuse_shared_permissions_and_symlinks() {
        use std::os::unix::fs::{PermissionsExt, symlink};
        let temp = tempfile::tempdir().unwrap();
        let private = temp.path().join("private");
        prepare_directory(&private).unwrap();
        validate_directory(&private).unwrap();
        let link = temp.path().join("link");
        symlink(&private, &link).unwrap();
        assert!(prepare_directory(&link).is_err());
        std::fs::set_permissions(&private, std::fs::Permissions::from_mode(0o755)).unwrap();
        assert!(validate_directory(&private).is_err());
    }

    #[test]
    fn core_launch_preserves_sign_in_and_skips_ui_startup() {
        let dir = Path::new("/tmp/core profile");
        let args = launch_args(dir, 9333, DesktopAccount::Personal, false, true);
        assert!(args.contains(&OsString::from("about:blank")));
        assert!(args.contains(&OsString::from(
            "--js-flags=--lite-mode --optimize-for-size"
        )));
        assert!(arguments_match(&args, &profile(dir), 9333));
        let visible = launch_args(dir, 9333, DesktopAccount::Personal, true, true);
        assert!(!visible.contains(&OsString::from("--headless=new")));
        if cfg!(target_os = "macos") {
            assert!(visible.contains(&OsString::from("--use-mock-keychain")));
        }
    }

    #[test]
    fn launch_is_isolated_and_headless_unless_signing_in() {
        let dir = Path::new("/tmp/teams profile");
        let headless = launch_args(dir, 9333, DesktopAccount::Personal, false, false);
        assert!(headless.contains(&OsString::from("--headless=new")));
        assert!(headless.contains(&OsString::from("--app=https://teams.live.com")));
        assert!(arguments_match(&headless, &profile(dir), 9333));
        assert!(!arguments_match(
            &headless,
            Path::new("/tmp/normal-browser"),
            9333
        ));
        assert!(!arguments_match(&headless, &profile(dir), 9222));
        let visible = launch_args(dir, 9333, DesktopAccount::WorkSchool, true, false);
        assert!(!visible.contains(&OsString::from("--headless=new")));
        assert!(visible.contains(&OsString::from("--app=https://teams.cloud.microsoft")));
        let mut conflicting = headless.clone();
        conflicting.push("--user-data-dir=/tmp/normal-browser".into());
        assert!(!arguments_match(&conflicting, &profile(dir), 9333));
        let mut renderer = headless;
        renderer.push("--type=renderer".into());
        assert!(!arguments_match(&renderer, &profile(dir), 9333));
    }

    #[test]
    fn a_hung_browser_version_check_times_out_and_reaps_its_process() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let browser = dir.path().join("browser");
        std::fs::write(
            &browser,
            "#!/bin/sh\nprintf '%s' \"$$\" > \"${0}.pid\"\nexec sleep 30\n",
        )
        .unwrap();
        std::fs::set_permissions(&browser, std::fs::Permissions::from_mode(0o700)).unwrap();
        let started = std::time::Instant::now();
        let error = browser_version_with_timeout(&browser, Duration::from_millis(100)).unwrap_err();
        assert!(error.to_string().contains("timed out"));
        assert!(started.elapsed() < Duration::from_secs(2));
        let pid: i32 = std::fs::read_to_string(dir.path().join("browser.pid"))
            .unwrap()
            .parse()
            .unwrap();
        assert_eq!(unsafe { libc::kill(pid, 0) }, -1);
        assert_eq!(
            std::io::Error::last_os_error().raw_os_error(),
            Some(libc::ESRCH)
        );
    }

    #[test]
    fn browser_control_socket_never_follows_an_advertised_remote_host() {
        let socket = |url: &str| json!({"webSocketDebuggerUrl":url});
        assert_eq!(
            browser_id(
                &socket("ws://localhost:9333/devtools/browser/abcdef12-3456"),
                9333
            )
            .unwrap(),
            "abcdef12-3456"
        );
        for url in [
            "ws://example.com:9333/devtools/browser/abcdef12",
            "ws://127.0.0.1:9222/devtools/browser/abcdef12",
            "ws://user@127.0.0.1:9333/devtools/browser/abcdef12",
            "ws://127.0.0.1:9333/devtools/page/abcdef12",
            "ws://127.0.0.1:9333/devtools/browser/../../x",
            "ws://127.0.0.1:9333/devtools/browser/abcdef12?secret=x",
        ] {
            assert!(browser_id(&socket(url), 9333).is_err(), "{url}");
        }
    }

    #[test]
    fn corrupt_or_wrong_port_state_is_preserved() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("connection.json");
        std::fs::write(&path, b"corrupt").unwrap();
        assert!(load(dir.path(), 9333).is_err());
        assert_eq!(std::fs::read(&path).unwrap(), b"corrupt");
        let state = State {
            version: 1,
            port: 9333,
            owner: None,
            visible: true,
            core: false,
            phase: "starting".into(),
        };
        save(dir.path(), &state).unwrap();
        assert!(load(dir.path(), 9222).is_err());
        assert!(load(dir.path(), 9333).unwrap().is_some());
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn linux_sockets_include_unsafe_and_foreign_listeners() {
        let table = "header\n 0: 0100007F:2475 00000000:0000 0A 0:0 0:0 0 1000 0 42\n 1: 00000000:2475 00000000:0000 0A 0:0 0:0 0 2000 0 43\n 2: 0100007F:2475 00000000:0000 01 0:0 0:0 0 1000 0 44\n";
        let sockets = system::parse_sockets(table, 9333, false).unwrap();
        assert_eq!(sockets.len(), 2);
        assert!(sockets[0].loopback);
        assert!(!sockets[1].loopback);
        assert!(system::parse_sockets("header\nbroken", 9333, false).is_err());
        let v6 = "header\n 0: 00000000000000000000000001000000:2475 0:0 0A 0:0 0:0 0 1000 0 42\n";
        assert!(system::parse_sockets(v6, 9333, true).unwrap()[0].loopback);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn linux_identity_and_live_socket_ownership_are_checked() {
        let pid = std::process::id();
        let (identity, _) = system::process(pid).unwrap();
        assert_eq!(identity.executable, std::env::current_exe().unwrap());
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let sockets = system::listeners(listener.local_addr().unwrap().port()).unwrap();
        assert!(!sockets.is_empty());
        assert!(system::owns_sockets(pid, &sockets));
        assert!(!system::owns_sockets(0, &sockets));
        assert!(system::start_time("broken stat").is_err());
        // Command names can contain ')' and spaces; field positions start after the last ') '.
        let stat = format!("1 (browser ) name) S {} 1234 0", "0 ".repeat(18));
        assert_eq!(system::start_time(&stat).unwrap(), "1234");
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn a_verified_browser_that_hangs_is_stopped() {
        let base = tempfile::tempdir().unwrap();
        let dir = base.path().join("9333");
        prepare_directory(&dir).unwrap();
        prepare_directory(&profile(&dir)).unwrap();
        let mut data = OsString::from("--user-data-dir=");
        data.push(profile(&dir));
        // The trailing command keeps the shell from replacing itself with `sleep`.
        let mut child = Command::new("/bin/sh")
            .args(["-c", "sleep 30; :", "browser"])
            .arg(data)
            .arg("--remote-debugging-port=9333")
            .spawn()
            .unwrap();
        let (owner, _) = system::process(child.id()).unwrap();
        let state = State {
            version: 1,
            port: 9333,
            owner: Some(owner),
            visible: false,
            core: false,
            phase: "active".into(),
        };
        assert!(owned(&state, &dir));
        let reaper = std::thread::spawn(move || child.wait());
        stop(&state, &dir).await.unwrap();
        assert!(!owned(&state, &dir));
        assert!(!reaper.join().unwrap().unwrap().success());
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn linux_arguments_survive_chrome_process_title_rewrite() {
        let profile = Path::new("/home/me/teams data/9333/profile");
        let launched = b"/opt/my chrome/chrome\0--user-data-dir=/home/me/teams data/9333/profile\0--remote-debugging-port=9333\0--app=https://teams.live.com\0";
        let mut title = launched.map(|b| if b == 0 { b' ' } else { b });
        *title.last_mut().unwrap() = 0;
        for cmdline in [launched.as_slice(), title.as_slice()] {
            let args = system::arguments(cmdline);
            assert_eq!(args[0], "/opt/my chrome/chrome");
            assert!(arguments_match(&args, profile, 9333));
            assert!(!arguments_match(&args, profile, 9222));
        }
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn macos_launch_arguments_keep_paths_with_spaces_and_exclude_environment() {
        let args = [
            b"Chrome".as_slice(),
            b"--user-data-dir=/tmp/teams profile",
            b"--remote-debugging-port=9333",
        ];
        let mut bytes = (args.len() as i32).to_ne_bytes().to_vec();
        bytes.extend_from_slice(b"/Applications/Google Chrome\0\0\0");
        for arg in args {
            bytes.extend_from_slice(arg);
            bytes.push(0);
        }
        bytes.extend_from_slice(b"SECRET=not-an-argument\0");
        let parsed = system::parse_args(&bytes).unwrap();
        assert_eq!(parsed.len(), 3);
        assert!(arguments_match(
            &parsed,
            Path::new("/tmp/teams profile"),
            9333
        ));
        assert!(system::parse_args(b"bad").is_err());
    }
}