teams-cli 0.1.13

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
//! Existing-endpoint diagnostics, chat reading through the Teams client's own cache, and
//! sending plain-text chat messages through the Teams window's own client. The WSL TUI
//! can restart Teams with explicit confirmation; evaluates only the fixed scripts in `desktop.js` and `desktop_send.js`.
//!
//! On Windows the CLI verifies the endpoint and reads in-process. Under WSL it drives the
//! Windows build of itself as a long-lived helper (`teams.exe desktop-helper`).
#[cfg(any(target_os = "macos", windows, test))]
mod cdp;
pub mod connection;
pub mod helper;
#[cfg(not(windows))]
pub mod install;
#[cfg(any(target_os = "macos", test))]
mod macos;
#[cfg(any(windows, test))]
mod owner;
#[cfg(any(target_os = "macos", windows, test))]
pub mod session;
#[cfg(windows)]
pub mod windows;

use crate::config::DesktopAccount;
use crate::{error::AppError, graph::Page};
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
#[cfg(any(target_os = "macos", windows, test))]
use std::time::Duration;
#[cfg(any(target_os = "macos", windows, test))]
const MAX_METADATA: usize = 1024 * 1024;
const MAX_READ: usize = 8 * 1024 * 1024;
/// Teams' own limit for one chat message.
pub const MAX_BODY: usize = 28_000;

pub fn messaging_unsupported() -> AppError {
    AppError::Unsupported("the experimental desktop backend reads chats and chat messages and sends plain-text chat messages only (macOS/Windows/WSL); teams, channels and identity need a Graph profile".into())
}

fn account_selection_error() -> AppError {
    AppError::Desktop("Multiple Teams accounts are available; use `init --backend desktop --desktop-account personal` or `--desktop-account work-school` to select a surface. Multiple cached accounts within that surface are still unsupported".into())
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ProbeStatus {
    NoListener,
    UnsafeListenerRefused,
    NonTeamsListenerRefused,
    MetadataProbeFailed,
    MetadataOk,
}

impl ProbeStatus {
    pub fn detail(self) -> &'static str {
        match self {
            Self::NoListener => {
                "No endpoint on this port: Teams is not running with its debugging port open. `teams desktop connect` opens it by restarting Teams after confirmation (it ends any call in progress)."
            }
            Self::UnsafeListenerRefused => "Refused a listener bound beyond loopback.",
            Self::NonTeamsListenerRefused => {
                "Refused a listener not owned by this user's installed Teams application."
            }
            Self::MetadataProbeFailed => {
                "Desktop metadata could not be verified; no session access was attempted."
            }
            Self::MetadataOk => {
                "Teams connection metadata is available. Sign-in and chat access remain unverified."
            }
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct BrowserVersion {
    pub browser: String,
    pub protocol: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TargetMetadata {
    #[serde(rename = "type")]
    pub kind: String,
    pub url_scheme: String,
    pub url_origin: String,
    pub teams_origin: bool,
    pub websocket_advertised: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ConnectionMetadata {
    pub port: u16,
    pub status: ProbeStatus,
    pub loopback_only: Option<bool>,
    pub teams_owned: Option<bool>,
    pub version: Option<BrowserVersion>,
    pub browser_websocket_advertised: bool,
    pub targets: Vec<TargetMetadata>,
}

impl ConnectionMetadata {
    #[cfg(any(target_os = "macos", windows, test))]
    fn empty(port: u16) -> Self {
        Self {
            port,
            status: ProbeStatus::NoListener,
            loopback_only: None,
            teams_owned: None,
            version: None,
            browser_websocket_advertised: false,
            targets: vec![],
        }
    }
    pub fn endpoint_available(&self) -> bool {
        self.status == ProbeStatus::MetadataOk
            && self.loopback_only == Some(true)
            && self.teams_owned == Some(true)
    }
}

pub struct DesktopClient {
    port: u16,
    account: DesktopAccount,
    /// The verified page connection, reused across reads.
    #[cfg(windows)]
    session: tokio::sync::Mutex<session::Session<windows::WindowsSystem>>,
    #[cfg(target_os = "macos")]
    session: tokio::sync::Mutex<session::Session<macos::MacSystem>>,
    /// The Windows helper under WSL, started on first use.
    #[cfg(not(any(windows, target_os = "macos")))]
    helper: tokio::sync::Mutex<helper::HelperClient>,
}

impl std::fmt::Debug for DesktopClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DesktopClient")
            .field("port", &self.port)
            .field("account", &self.account)
            .finish_non_exhaustive()
    }
}

impl DesktopClient {
    pub fn new(port: u16) -> Result<Self, AppError> {
        Self::with_account(port, DesktopAccount::Auto)
    }

    pub fn with_account(port: u16, account: DesktopAccount) -> Result<Self, AppError> {
        if port < 1024 {
            return Err(AppError::InvalidInput(
                "desktop port must be between 1024 and 65535".into(),
            ));
        }
        Ok(Self {
            port,
            account,
            #[cfg(windows)]
            session: tokio::sync::Mutex::new(session::Session::new(windows::WindowsSystem)),
            #[cfg(target_os = "macos")]
            session: tokio::sync::Mutex::new(session::Session::new(macos::MacSystem)),
            #[cfg(not(any(windows, target_os = "macos")))]
            helper: Default::default(),
        })
    }

    /// Only offered by the TUI after a verified no-listener probe on WSL.
    pub async fn needs_debugging_restart(&self) -> bool {
        platform().ok() == Some("wsl_windows_helper")
            && self
                .probe()
                .await
                .is_ok_and(|probe| probe.status == ProbeStatus::NoListener)
    }

    /// Called only after the person confirms the restart in the TUI.
    pub async fn restart_with_debugging(&self) -> Result<(), AppError> {
        if !self.needs_debugging_restart().await {
            return Err(AppError::Desktop(
                "Connection changed; press r to retry before restarting Teams".into(),
            ));
        }
        connection::manage(self, connection::Action::Connect)
            .await
            .map(|_| ())
    }

    pub async fn probe(&self) -> Result<ConnectionMetadata, AppError> {
        platform()?;
        #[cfg(any(windows, target_os = "macos"))]
        return self.session.lock().await.probe(self.port).await;
        #[cfg(not(any(windows, target_os = "macos")))]
        {
            let metadata = self
                .helper
                .lock()
                .await
                .call(json!({"op": "probe", "port": self.port}))
                .await?;
            serde_json::from_value(metadata)
                .map_err(|_| AppError::Desktop("Windows helper returned invalid metadata".into()))
        }
    }

    pub async fn chats(&self, limit: u16, cursor: Option<&str>) -> Result<Page, AppError> {
        self.read(None, limit, cursor).await
    }

    pub async fn messages(
        &self,
        chat: &str,
        limit: u16,
        cursor: Option<&str>,
    ) -> Result<Page, AppError> {
        self.read(Some(chat), limit, cursor).await
    }

    async fn read(
        &self,
        chat: Option<&str>,
        limit: u16,
        cursor: Option<&str>,
    ) -> Result<Page, AppError> {
        let mut request = read_request(self.port, chat, limit, cursor)?;
        request["account_type"] = json!(self.account);
        platform()?;
        #[cfg(any(windows, target_os = "macos"))]
        let reply = self.session.lock().await.read(&request).await?;
        #[cfg(not(any(windows, target_os = "macos")))]
        let reply = self
            .helper
            .lock()
            .await
            .call(json!({"op": "read", "request": request}))
            .await?;
        read_page(&reply)
    }

    /// Sends one plain-text chat message as the signed-in Teams user. Never retried: a lost
    /// answer is reported as unconfirmed, because Teams may already have the message.
    pub async fn send(&self, chat: &str, body: &str) -> Result<Value, AppError> {
        self.send_with_id(chat, body, &crate::delivery::client_message_id())
            .await
    }

    /// Uses one preallocated correlation ID. This is not an idempotency/retry key.
    pub async fn send_with_id(&self, chat: &str, body: &str, id: &str) -> Result<Value, AppError> {
        let mut request = send_request(self.port, chat, body)?;
        if !crate::delivery::valid_client_message_id(id) {
            return Err(AppError::InvalidInput("invalid client message ID".into()));
        }
        request["client_message_id"] = json!(id);
        request["account_type"] = json!(self.account);
        platform()?;
        #[cfg(any(windows, target_os = "macos"))]
        let reply = self.session.lock().await.send(&request).await?;
        #[cfg(not(any(windows, target_os = "macos")))]
        let reply = self
            .helper
            .lock()
            .await
            .call_once(json!({"op": "send", "request": request}))
            .await?;
        sent_message(&reply, chat).map_err(|error| match error {
            AppError::Unconfirmed(message) => AppError::UnconfirmedSend {
                message,
                chat_id: chat.into(),
                client_message_id: id.into(),
            },
            other => other,
        })
    }

    /// Checks only the newest 50 cached messages; absence is not proof of failure.
    pub async fn delivery(&self, chat: &str, id: &str) -> Result<Value, AppError> {
        check_chat(chat)?;
        if !crate::delivery::valid_client_message_id(id) {
            return Err(AppError::InvalidInput(
                "client message ID must contain 18 digits".into(),
            ));
        }
        let page = self.messages(chat, 50, None).await?;
        Ok(crate::delivery::reconcile(chat, id, &page.items))
    }

    /// Whether the Teams window that sends messages is reachable; sends nothing.
    pub async fn send_check(&self) -> Result<(), AppError> {
        platform()?;
        #[cfg(any(windows, target_os = "macos"))]
        let reply = self
            .session
            .lock()
            .await
            .send_check(self.port, self.account)
            .await?;
        #[cfg(not(any(windows, target_os = "macos")))]
        let reply = self
            .helper
            .lock()
            .await
            .call(json!({"op": "send_check", "port": self.port, "account_type": self.account}))
            .await?;
        match reply["error"].as_str() {
            None if reply["ok"] == true => Ok(()),
            code => Err(send_error(code.unwrap_or_default())),
        }
    }
}

fn valid_id(id: &str) -> bool {
    (1..=256).contains(&id.len())
        && id
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"_.:@-".contains(&b))
}

fn read_request(
    port: u16,
    chat: Option<&str>,
    limit: u16,
    cursor: Option<&str>,
) -> Result<Value, AppError> {
    if let Some(chat) = chat {
        check_chat(chat)?;
    }
    let after = cursor.map(decode_cursor).transpose()?;
    Ok(json!({
        "operation": "read",
        "port": port,
        "query": if chat.is_some() { "messages" } else { "chats" },
        "chat_id": chat,
        "limit": limit,
        "after": after,
    }))
}

/// A chat id as `teams chats` lists them; `48:notes` is the chat with yourself.
fn chat_id(id: &str) -> bool {
    id == NOTES || id.starts_with("19:") && valid_id(id)
}

const NOTES: &str = "48:notes";

/// Refuses anything but a chat id as `teams chats` lists them.
pub fn check_chat(chat: &str) -> Result<(), AppError> {
    if chat_id(chat) {
        Ok(())
    } else {
        Err(AppError::InvalidInput(
            "desktop chat ids look like `19:...@thread.v2`, `19:...@unq.gbl.spaces` or `48:notes`"
                .into(),
        ))
    }
}

/// Plain text Teams accepts as one message.
fn valid_body(body: &str) -> bool {
    !body.trim().is_empty() && body.chars().count() <= MAX_BODY && !body.contains('\0')
}

/// A send request with a fresh client message id, which Teams uses to recognise the message.
fn send_request(port: u16, chat: &str, body: &str) -> Result<Value, AppError> {
    check_chat(chat)?;
    if !valid_body(body) {
        return Err(AppError::InvalidInput(format!(
            "message body must be non-empty plain text of at most {MAX_BODY} characters"
        )));
    }
    let id: u64 = rand::Rng::random_range(
        &mut rand::rng(),
        100_000_000_000_000_000..1_000_000_000_000_000_000,
    );
    Ok(json!({
        "operation": "send",
        "port": port,
        "chat_id": chat,
        "body": body,
        "client_message_id": id.to_string(),
    }))
}

fn send_error(code: &str) -> AppError {
    match code {
        "not_found" => AppError::NotFound("chat not found in the Teams desktop cache".into()),
        "account_ambiguous" => account_selection_error(),
        "unconfirmed" => AppError::Unconfirmed(
            "Teams did not confirm the message; it may still be delivered. Check the chat before sending again".into(),
        ),
        "layout" => AppError::Desktop(
            "The Teams window's send interface was not recognised; this Teams version is not supported for sending yet".into(),
        ),
        "no_target" => AppError::Desktop(
            "No Teams window is available on the debugging endpoint; open Teams and sign in".into(),
        ),
        code => match serde_json::from_value::<ProbeStatus>(json!(code)) {
            Ok(status) => AppError::Desktop(status.detail().into()),
            Err(_) => AppError::Desktop(
                "The message was not sent; the Teams page could not be reached. Run `teams doctor`".into(),
            ),
        },
    }
}

/// Maps a send reply to the Graph send shape, plus Teams' own status label.
fn sent_message(reply: &Value, chat: &str) -> Result<Value, AppError> {
    if let Some(code) = reply.get("error").and_then(Value::as_str) {
        return Err(send_error(code));
    }
    let result = &reply["result"];
    if let Some(details) = result.get("exceptionDetails") {
        // The script reports every failure after handing the message to Teams itself, so an
        // exception means nothing was sent.
        let layout = details["exception"]["description"]
            .as_str()
            .is_some_and(|d| d.starts_with("Error: layout"));
        return Err(send_error(if layout { "layout" } else { "" }));
    }
    let value: Value = result["result"]["value"]
        .as_str()
        .and_then(|v| serde_json::from_str(v).ok())
        .ok_or_else(|| send_error("unconfirmed"))?;
    if let Some(code) = value["error"].as_str() {
        return Err(send_error(code));
    }
    let id = value["id"]
        .as_str()
        .filter(|id| valid_id(id))
        .ok_or_else(|| send_error("unconfirmed"))?;
    let label = |key: &str| {
        value[key]
            .as_str()
            .filter(|v| v.len() <= 64 && valid_id(v))
            .map(String::from)
    };
    let arrival = &value["originalArrivalTime"];
    let created = arrival
        .as_i64()
        .or_else(|| arrival.as_str().and_then(|t| t.parse().ok()))
        .and_then(|ms| jiff::Timestamp::from_millisecond(ms).ok())
        .or_else(|| arrival.as_str().and_then(|t| t.parse().ok()))
        .map(|t| t.to_string());
    let mut message = json!({
        "id": id,
        "chatId": chat,
        "createdDateTime": created,
        "webUrl": null,
        "clientMessageId": label("clientMessageId"),
        "status": label("status"),
        "source": "desktop",
    });
    message["delivery_state"] = json!(crate::delivery::State::from_message(&message));
    Ok(message)
}

/// Cursors are opaque to callers: base64 of the last item's sort key.
fn encode_cursor(next: &Value) -> Result<String, AppError> {
    let t = next.get("t").and_then(Value::as_i64);
    let id = next.get("id").and_then(Value::as_str);
    match (t, id) {
        (Some(t), Some(id)) if valid_id(id) => {
            Ok(URL_SAFE_NO_PAD.encode(json!({"t":t,"id":id}).to_string()))
        }
        _ => Err(AppError::Desktop(
            "Teams cache returned an invalid page position".into(),
        )),
    }
}

fn decode_cursor(cursor: &str) -> Result<Value, AppError> {
    let invalid = || AppError::InvalidInput("invalid desktop cursor".into());
    let bytes = URL_SAFE_NO_PAD
        .decode(cursor.as_bytes())
        .map_err(|_| invalid())?;
    let value: Value = serde_json::from_slice(&bytes).map_err(|_| invalid())?;
    let t = value.get("t").and_then(Value::as_i64).ok_or_else(invalid)?;
    let id = value
        .get("id")
        .and_then(Value::as_str)
        .ok_or_else(invalid)?;
    if t < 0 || !valid_id(id) {
        return Err(invalid());
    }
    Ok(json!({"t":t,"id":id}))
}

/// Maps a session reply: a refusal code, or the raw `Runtime.evaluate` result.
fn read_page(reply: &Value) -> Result<Page, AppError> {
    let invalid = || AppError::Desktop("the Teams page returned an invalid chat response".into());
    if let Some(code) = reply.get("error").and_then(Value::as_str) {
        let status = serde_json::from_value::<ProbeStatus>(json!(code)).ok();
        if code == "account_ambiguous" {
            return Err(account_selection_error());
        }
        return Err(AppError::Desktop(match (status, code) {
            (Some(status), _) => status.detail().into(),
            (None, "no_target") => {
                "No Teams window is available on the debugging endpoint; open Teams and sign in"
                    .into()
            }
            _ => "The Teams page could not be read over the debugging endpoint; run `teams doctor`"
                .into(),
        }));
    }
    let result = &reply["result"];
    if let Some(details) = result.get("exceptionDetails") {
        let layout = details["exception"]["description"]
            .as_str()
            .is_some_and(|d| d.starts_with("Error: layout"));
        return Err(AppError::Desktop(if layout {
            "The Teams cache layout was not recognised; this Teams version is not supported yet"
                .into()
        } else {
            "The Teams page could not read its local cache; run `teams doctor`".into()
        }));
    }
    let value: Value = result["result"]["value"]
        .as_str()
        .and_then(|v| serde_json::from_str(v).ok())
        .ok_or_else(invalid)?;
    if value["error"] == "not_found" {
        return Err(AppError::NotFound(
            "chat not found in the Teams desktop cache".into(),
        ));
    }
    if value["error"] == "account_ambiguous" {
        return Err(account_selection_error());
    }
    let items = value["items"].as_array().ok_or_else(invalid)?.clone();
    let next_cursor = match &value["next"] {
        Value::Null => None,
        next => Some(encode_cursor(next)?),
    };
    Ok(Page {
        items,
        truncated: next_cursor.is_some(),
        next_cursor,
        next_offset: None,
        source: Some("desktop_cache"),
        viewer: value["me"]
            .as_str()
            .filter(|me| valid_id(me))
            .map(String::from),
    })
}

pub fn platform() -> Result<&'static str, AppError> {
    if cfg!(target_os = "macos") {
        Ok("macos_loopback")
    } else if cfg!(windows) {
        Ok("windows_native")
    } else if cfg!(target_os = "linux")
        && std::fs::read_to_string("/proc/sys/kernel/osrelease")
            .unwrap_or_default()
            .to_ascii_lowercase()
            .contains("microsoft")
    {
        Ok("wsl_windows_helper")
    } else {
        Err(AppError::Unsupported(
            "desktop diagnostics require macOS, Windows, or WSL with Windows executable interop"
                .into(),
        ))
    }
}

/// Commands for manual setup and the confirmed WSL TUI restart. macOS uses
/// process-only environment; Windows/WSL preserve and restore the user's WebView2 variable.
#[derive(Debug, Serialize)]
pub struct DebuggingSetup {
    /// `zsh` on macOS, `wsl` for a WSL shell, `powershell` on Windows.
    pub shell: &'static str,
    pub open: String,
    pub close: String,
}

impl DebuggingSetup {
    pub fn new(port: u16) -> Option<Self> {
        let shell = match platform().ok()? {
            "wsl_windows_helper" => "wsl",
            "windows_native" => "powershell",
            "macos_loopback" => "zsh",
            _ => return None,
        };
        Some(Self::for_shell(shell, port))
    }

    fn for_shell(shell: &'static str, port: u16) -> Self {
        Self {
            shell,
            open: format!("teams desktop connect --port {port}"),
            close: format!("teams desktop disconnect --port {port}"),
        }
    }

    pub fn text(&self) -> String {
        let shell = match self.shell {
            "wsl" => "this WSL shell",
            "zsh" => "Terminal (zsh or bash)",
            _ => "PowerShell",
        };
        format!(
            "To open Teams' debugging port, run this in {shell}. It restarts Teams, which ends any call in progress:\n  {}\nTo close it again:\n  {}\nManaged setup preserves existing settings. `teams desktop recover` restores settings after an interrupted setup. While the port is open, any program running as you can read your chats and send as you.",
            self.open, self.close
        )
    }
}

/// The hidden `desktop-helper` command: answers the Linux CLI under WSL until stdin closes.
pub async fn serve_helper() -> Result<(), AppError> {
    #[cfg(windows)]
    {
        helper::serve(
            tokio::io::BufReader::new(tokio::io::stdin()),
            tokio::io::stdout(),
            &mut session::Session::new(windows::WindowsSystem),
        )
        .await
    }
    #[cfg(not(windows))]
    Err(AppError::Unsupported(
        "the desktop helper runs only on Windows".into(),
    ))
}

/// The WSL helper's install state for `doctor` as (status, detail); `None` where no
/// helper is involved. Never downloads.
pub fn helper_check() -> Option<(&'static str, String)> {
    #[cfg(not(windows))]
    if platform().ok() == Some("wsl_windows_helper") {
        return Some(match install::state() {
            Ok(install::HelperState::Override(path)) if !path.is_file() => (
                "fail",
                format!(
                    "TEAMS_DESKTOP_HELPER points to {}, which does not exist",
                    path.display()
                ),
            ),
            Ok(state @ install::HelperState::Missing(_)) => ("skip", state.describe()),
            Ok(state) => ("pass", state.describe()),
            Err(error) => ("fail", error.to_string()),
        });
    }
    None
}

pub fn local_prerequisites() -> Result<&'static str, AppError> {
    let transport = platform()?;
    if transport == "macos_loopback" {
        if !std::path::Path::new("/usr/sbin/lsof").is_file() {
            return Err(AppError::Desktop(
                "lsof is required for Teams listener ownership checks".into(),
            ));
        }
    } else if transport == "wsl_windows_helper"
        && !["WSLInterop", "WSLInterop-late"].iter().any(|name| {
            std::path::Path::new("/proc/sys/fs/binfmt_misc")
                .join(name)
                .exists()
        })
    {
        return Err(AppError::Desktop(
            "WSL cannot run Windows executables; enable interop in /etc/wsl.conf".into(),
        ));
    }
    Ok(transport)
}

/// Reads endpoint metadata into `metadata` for an already-verified listener and returns
/// the raw targets, which stay in-process.
#[cfg(any(target_os = "macos", windows, test))]
async fn fill_metadata(metadata: &mut ConnectionMetadata) -> Vec<Value> {
    let Ok((version, targets)) = read_metadata(metadata.port).await else {
        metadata.status = ProbeStatus::MetadataProbeFailed;
        return vec![];
    };
    let text = |key: &str| {
        version
            .get(key)
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string()
    };
    metadata.version = Some(BrowserVersion {
        browser: text("Browser"),
        protocol: text("Protocol-Version"),
    });
    metadata.browser_websocket_advertised = !text("webSocketDebuggerUrl").is_empty();
    metadata.targets = targets.iter().map(sanitize_target).collect();
    metadata.status = ProbeStatus::MetadataOk;
    targets
}

#[cfg(any(target_os = "macos", windows, test))]
async fn read_metadata(port: u16) -> Result<(Value, Vec<Value>), AppError> {
    let http = reqwest::Client::builder()
        .no_proxy()
        .redirect(reqwest::redirect::Policy::none())
        .timeout(Duration::from_secs(5))
        .user_agent("TeamsCLI-DesktopProbe/0.1")
        .build()
        .map_err(|_| AppError::Desktop("could not create metadata reader".into()))?;
    async fn read(http: &reqwest::Client, port: u16, route: &str) -> Result<Value, AppError> {
        let mut response = http
            .get(format!("http://127.0.0.1:{port}{route}"))
            .send()
            .await
            .map_err(|_| AppError::Desktop("metadata endpoint is unavailable".into()))?;
        if response.status() != reqwest::StatusCode::OK {
            return Err(AppError::Desktop(
                "metadata endpoint returned an unexpected status".into(),
            ));
        }
        let mut bytes = Vec::new();
        while let Some(chunk) = response
            .chunk()
            .await
            .map_err(|_| AppError::Desktop("metadata response failed".into()))?
        {
            if bytes.len() + chunk.len() > MAX_METADATA {
                return Err(AppError::Desktop("metadata size limit exceeded".into()));
            }
            bytes.extend_from_slice(&chunk);
        }
        serde_json::from_slice(&bytes)
            .map_err(|_| AppError::Desktop("invalid endpoint metadata".into()))
    }
    let version = read(&http, port, "/json/version").await?;
    let targets = read(&http, port, "/json/list").await?;
    if !version.is_object() {
        return Err(AppError::Desktop("invalid browser metadata".into()));
    }
    Ok((
        version,
        targets
            .as_array()
            .ok_or_else(|| AppError::Desktop("invalid target list".into()))?
            .clone(),
    ))
}

#[cfg(any(target_os = "macos", windows, test))]
fn sanitize_target(target: &Value) -> TargetMetadata {
    let uri = target
        .get("url")
        .and_then(Value::as_str)
        .and_then(|u| url::Url::parse(u).ok());
    let scheme = uri.as_ref().map(|u| u.scheme()).unwrap_or("");
    let host = uri.as_ref().and_then(|u| u.host_str()).unwrap_or("");
    let secure =
        scheme == "https" && uri.as_ref().and_then(|u| u.port_or_known_default()) == Some(443);
    let teams = secure
        && matches!(
            host,
            "teams.microsoft.com" | "teams.cloud.microsoft" | "teams.live.com"
        );
    let origin =
        if teams || (secure && matches!(host, "login.microsoftonline.com" | "login.live.com")) {
            format!("https://{host}")
        } else if matches!(scheme, "about" | "blob" | "file") {
            format!("{scheme}:")
        } else {
            "[other origin omitted]".into()
        };
    TargetMetadata {
        kind: target
            .get("type")
            .and_then(Value::as_str)
            .unwrap_or("other")
            .into(),
        url_scheme: scheme.into(),
        url_origin: origin,
        teams_origin: teams,
        websocket_advertised: target
            .get("webSocketDebuggerUrl")
            .and_then(Value::as_str)
            .is_some_and(|s| !s.is_empty()),
    }
}

#[cfg(test)]
mod tests {
    use super::macos::{loopback_address, parse_listeners};
    use super::*;
    use wiremock::{
        Mock, MockServer, ResponseTemplate,
        matchers::{header, method, path},
    };

    const CHAT: &str = "19:a@thread.v2";

    fn page_reply(value: Value) -> Value {
        json!({"result": {"result": {"type": "string", "value": value.to_string()}}})
    }

    #[test]
    fn debugging_setup_uses_managed_commands_on_every_shell() {
        for shell in ["wsl", "powershell", "zsh"] {
            let setup = DebuggingSetup::for_shell(shell, 9333);
            assert_eq!(setup.open, "teams desktop connect --port 9333");
            assert_eq!(setup.close, "teams desktop disconnect --port 9333");
            assert!(setup.text().contains("teams desktop recover"));
            assert!(setup.text().contains("any program running as you"));
        }
    }

    /// Helpers and CLIs of different versions talk to each other whenever their protocol
    /// numbers match, so everything that crosses between them is pinned here: the
    /// requests the CLI builds and the page scripts whose results it parses. When this
    /// fails, bump `helper::PROTOCOL` if a helper or CLI of the old protocol would misread
    /// the new one; otherwise just update the expectations.
    #[test]
    fn the_protocol_is_pinned() {
        assert_eq!(helper::PROTOCOL, 3);
        let cursor = encode_cursor(&json!({"t": 1, "id": "m1"})).unwrap();
        assert_eq!(
            read_request(9222, Some(NOTES), 20, Some(&cursor)).unwrap(),
            json!({"operation": "read", "port": 9222, "query": "messages",
                   "chat_id": NOTES, "limit": 20, "after": {"t": 1, "id": "m1"}})
        );
        assert_eq!(
            read_request(9222, None, 20, None).unwrap(),
            json!({"operation": "read", "port": 9222, "query": "chats",
                   "chat_id": null, "limit": 20, "after": null})
        );
        let mut send = send_request(9222, NOTES, "hi").unwrap();
        assert!(
            send["client_message_id"]
                .as_str()
                .is_some_and(|id| id.len() == 18)
        );
        send["client_message_id"] = json!("<id>");
        assert_eq!(
            send,
            json!({"operation": "send", "port": 9222, "chat_id": NOTES,
                   "body": "hi", "client_message_id": "<id>"})
        );
        let scripts = [
            include_str!("desktop.js"),
            include_str!("desktop_send.js"),
            include_str!("desktop_cache.js"),
        ]
        .map(|script| {
            use sha2::Digest;
            // Line endings depend on the checkout, not on the script.
            let digest = sha2::Sha256::digest(script.replace('\r', ""));
            digest[..6]
                .iter()
                .map(|b| format!("{b:02x}"))
                .collect::<String>()
        });
        // Timestamp normalization keeps the protocol-3 request/result shapes.
        assert_eq!(scripts, ["32ca0293d2d5", "f70826f76ef1", "3e837cc21336"]);
    }

    #[test]
    fn send_requests_validate_and_carry_a_fresh_client_message_id() {
        let request = send_request(9222, CHAT, "hello\nthere").unwrap();
        assert_eq!(request["operation"], "send");
        assert_eq!(request["chat_id"], CHAT);
        assert_eq!(request["body"], "hello\nthere");
        let id = request["client_message_id"].as_str().unwrap();
        assert!(id.len() == 18 && id.bytes().all(|b| b.is_ascii_digit()));
        assert_ne!(
            send_request(9222, CHAT, "x").unwrap()["client_message_id"],
            request["client_message_id"]
        );
        for (chat, body) in [
            ("fixture", "hello"),
            ("19:a b@thread.v2", "hello"),
            ("48:notes2", "hello"),
            ("48:other", "hello"),
            (CHAT, ""),
            (CHAT, " \n\t"),
            (CHAT, "a\0b"),
            (CHAT, &"x".repeat(MAX_BODY + 1)),
        ] {
            assert!(
                matches!(
                    send_request(9222, chat, body),
                    Err(AppError::InvalidInput(_))
                ),
                "{chat:?} accepted"
            );
        }
        assert!(send_request(9222, CHAT, &"é".repeat(MAX_BODY)).is_ok());
        assert!(send_request(9222, NOTES, "hello").is_ok());
    }

    #[test]
    fn sent_messages_map_to_the_graph_shape() {
        let reply = page_reply(
            json!({"id": "1760000000000", "clientMessageId": "123456789012345678",
            "originalArrivalTime": "1760000000000", "status": "Sent"}),
        );
        let message = sent_message(&reply, CHAT).unwrap();
        assert_eq!(message["id"], "1760000000000");
        assert_eq!(message["chatId"], CHAT);
        assert_eq!(message["createdDateTime"], "2025-10-09T08:53:20Z");
        assert_eq!(message["clientMessageId"], "123456789012345678");
        assert_eq!(message["status"], "Sent");
        assert_eq!(message["source"], "desktop");
        for arrival in [json!(1760000000000_i64), json!("2025-10-09T08:53:20Z")] {
            let reply = page_reply(json!({"id": "1", "originalArrivalTime": arrival}));
            assert_eq!(
                sent_message(&reply, CHAT).unwrap()["createdDateTime"],
                "2025-10-09T08:53:20Z"
            );
        }
        let reply = page_reply(json!({"id": "1", "status": "<b>not a label</b>"}));
        let message = sent_message(&reply, CHAT).unwrap();
        assert!(message["status"].is_null() && message["createdDateTime"].is_null());
    }

    #[test]
    fn send_failures_say_whether_the_message_may_have_gone() {
        let unconfirmed = |error: AppError| error.to_string().contains("may still be delivered");
        for reply in [
            json!({"error": "unconfirmed"}),
            page_reply(json!({"error": "unconfirmed"})),
            page_reply(json!({"id": "bad id"})),
            page_reply(json!({})),
            json!({"result": {"result": {"type": "undefined"}}}),
        ] {
            assert!(
                unconfirmed(sent_message(&reply, CHAT).unwrap_err()),
                "{reply}"
            );
        }
        assert!(matches!(
            sent_message(&page_reply(json!({"error": "not_found"})), CHAT),
            Err(AppError::NotFound(_))
        ));
        let thrown =
            json!({"result": {"exceptionDetails": {"exception": {"description": "TypeError: x"}}}});
        let error = sent_message(&thrown, CHAT).unwrap_err();
        assert!(
            !unconfirmed(error)
                && sent_message(&thrown, CHAT)
                    .unwrap_err()
                    .to_string()
                    .contains("not sent")
        );
        for code in [
            "layout",
            "no_target",
            "non_teams_listener_refused",
            "something_else",
        ] {
            let error = sent_message(&json!({"error": code}), CHAT).unwrap_err();
            assert!(
                matches!(error, AppError::Desktop(_)) && !unconfirmed(error),
                "{code}"
            );
        }
    }

    #[test]
    fn read_requests_validate_chat_ids_and_cursors() {
        let request = read_request(9222, None, 5, None).unwrap();
        assert_eq!(request["query"], "chats");
        assert!(request["after"].is_null());
        let cursor = encode_cursor(&json!({"t": 42, "id": "19:a@thread.v2"})).unwrap();
        let request = read_request(9222, Some("19:a@thread.v2"), 5, Some(&cursor)).unwrap();
        assert_eq!(request["query"], "messages");
        assert_eq!(request["chat_id"], "19:a@thread.v2");
        assert_eq!(request["after"], json!({"t": 42, "id": "19:a@thread.v2"}));
        for chat in ["fixture", "19:a b", "19:a'); x", ""] {
            assert!(matches!(
                read_request(9222, Some(chat), 5, None),
                Err(AppError::InvalidInput(_))
            ));
        }
        let negative = URL_SAFE_NO_PAD.encode(r#"{"t":-1,"id":"x"}"#);
        for cursor in ["%%%", "e30", negative.as_str()] {
            assert!(matches!(
                read_request(9222, None, 5, Some(cursor)),
                Err(AppError::InvalidInput(_))
            ));
        }
    }

    fn reply(value: Value) -> Value {
        json!({"result":{"result":{"type":"string","value":value.to_string()}}})
    }

    #[test]
    fn read_pages_map_cache_results_and_failures() {
        let page = read_page(&reply(json!({
            "me": "0f0e-guid",
            "items": [{"id": "19:a@thread.v2", "topic": null}],
            "next": {"t": 7, "id": "19:a@thread.v2"}
        })))
        .unwrap();
        assert_eq!(page.items.len(), 1);
        assert_eq!(page.viewer.as_deref(), Some("0f0e-guid"));
        assert!(serde_json::to_value(&page).unwrap().get("viewer").is_none());
        assert!(page.truncated);
        assert_eq!(page.source, Some("desktop_cache"));
        assert_eq!(
            decode_cursor(page.next_cursor.as_deref().unwrap()).unwrap(),
            json!({"t": 7, "id": "19:a@thread.v2"})
        );
        let last = read_page(&reply(json!({"me": "a b", "items": [], "next": null}))).unwrap();
        assert!(!last.truncated && last.next_cursor.is_none() && last.viewer.is_none());
        assert!(matches!(
            read_page(&reply(json!({"error": "not_found"}))),
            Err(AppError::NotFound(_))
        ));
        let layout = json!({"result":{"exceptionDetails":{"exception":{"description":"Error: layout\n    at x"}}}});
        for ambiguous in [
            json!({"error": "account_ambiguous"}),
            reply(json!({"error": "account_ambiguous"})),
        ] {
            assert!(
                matches!(read_page(&ambiguous), Err(AppError::Desktop(m)) if m.contains("--desktop-account"))
            );
            assert!(
                matches!(sent_message(&ambiguous, CHAT), Err(AppError::Desktop(m)) if m.contains("--desktop-account"))
            );
        }
        assert!(matches!(read_page(&layout), Err(AppError::Desktop(m)) if m.contains("layout")));
        for reply in [
            json!({"error": "no_target"}),
            json!({"error": "non_teams_listener_refused"}),
            json!({"error": "read_failed"}),
            json!("not an object"),
            reply(json!({"items": [], "next": {"t": 1, "id": "bad id"}})),
        ] {
            assert!(matches!(read_page(&reply), Err(AppError::Desktop(_))));
        }
    }

    #[test]
    fn listener_parser_keeps_every_binding_and_refuses_non_loopback() {
        let listeners =
            parse_listeners("p12\nn127.0.0.1:9222\nn[::1]:9222\np13\nn*:9222\n").unwrap();
        assert_eq!(listeners.len(), 3);
        assert!(loopback_address(&listeners[0].1, 9222));
        assert!(loopback_address(&listeners[1].1, 9222));
        assert!(!loopback_address(&listeners[2].1, 9222));
        assert!(!loopback_address("127.0.0.1:19222", 9222));
        assert!(parse_listeners("n127.0.0.1:9222").is_err());
    }

    #[test]
    fn origins_are_exact_and_private_metadata_is_removed() {
        let cases = [
            (
                "https://teams.microsoft.com/v2/?account=PRIVATE",
                true,
                "https://teams.microsoft.com",
            ),
            (
                "https://teams.cloud.microsoft/path",
                true,
                "https://teams.cloud.microsoft",
            ),
            (
                "https://teams.live.com/PRIVATE",
                true,
                "https://teams.live.com",
            ),
            (
                "https://teams.microsoft.com.evil.example/PRIVATE",
                false,
                "[other origin omitted]",
            ),
            (
                "https://teams.microsoft.com:444/PRIVATE",
                false,
                "[other origin omitted]",
            ),
            (
                "http://teams.microsoft.com/PRIVATE",
                false,
                "[other origin omitted]",
            ),
            ("file:///Users/PRIVATE/SECRET.html", false, "file:"),
            ("blob:https://private-tenant.example/SECRET", false, "blob:"),
            (
                "https://login.microsoftonline.com/PRIVATE",
                false,
                "https://login.microsoftonline.com",
            ),
        ];
        for (url, teams, origin) in cases {
            let target = sanitize_target(
                &json!({"type":"page","url":url,"title":"PRIVATE","id":"SECRET","webSocketDebuggerUrl":"ws://127.0.0.1/SECRET"}),
            );
            assert_eq!(target.teams_origin, teams);
            assert_eq!(target.url_origin, origin);
            let output = serde_json::to_string(&target).unwrap();
            assert!(!output.contains("PRIVATE") && !output.contains("SECRET"));
        }
    }

    #[tokio::test]
    async fn metadata_reader_uses_only_the_two_read_routes_and_generic_user_agent() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/json/version"))
            .and(header("User-Agent", "TeamsCLI-DesktopProbe/0.1"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(json!({"Browser":"Edg/fixture","Protocol-Version":"1.3"})),
            )
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/json/list"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(json!([{"type":"page","url":"https://teams.live.com/PRIVATE"}])),
            )
            .expect(1)
            .mount(&server)
            .await;
        let (version, targets) = read_metadata(server.address().port()).await.unwrap();
        assert_eq!(version["Protocol-Version"], "1.3");
        assert_eq!(
            sanitize_target(&targets[0]).url_origin,
            "https://teams.live.com"
        );
        let mut connection = ConnectionMetadata::empty(server.address().port());
        connection.status = ProbeStatus::MetadataOk;
        assert!(!connection.endpoint_available());
        connection.loopback_only = Some(true);
        connection.teams_owned = Some(true);
        assert!(connection.endpoint_available());
    }

    #[tokio::test]
    async fn metadata_reader_refuses_redirects_and_oversized_responses() {
        let server = MockServer::start().await;
        let sink = MockServer::start().await;
        Mock::given(method("GET"))
            .respond_with(ResponseTemplate::new(200))
            .expect(0)
            .mount(&sink)
            .await;
        Mock::given(path("/json/version"))
            .respond_with(ResponseTemplate::new(302).insert_header("Location", sink.uri()))
            .mount(&server)
            .await;
        assert!(read_metadata(server.address().port()).await.is_err());
        server.reset().await;
        Mock::given(path("/json/version"))
            .respond_with(ResponseTemplate::new(200).set_body_string("x".repeat(MAX_METADATA + 1)))
            .mount(&server)
            .await;
        assert!(read_metadata(server.address().port()).await.is_err());
    }
}