cua-sdk 0.7.0

The cua SDK: the MIT #[uniffi::export] crate. One Cua object (embedded or connected to `cua daemon`) exposing env, sandboxes, local and spaces modules to Python, TypeScript, Swift and Kotlin.
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
//! Unattended access: `Relay` (the account's machines on a cua-relay,
//! connected as spacesd clients through `<relay>/m/<id>`) and `Host`
//! (set this machine up as one; cua-host). Account tokens are passed in by
//! the caller (the app's or CLI's cua.ai sign-in); the SDK never stores them.

use super::{Auth, SpacesdClient, run};
use crate::{CuaError, Result};
use std::sync::Arc;

impl From<cua_host::Error> for CuaError {
    fn from(e: cua_host::Error) -> Self {
        use cua_host::Error as E;
        let m = e.to_string();
        match e {
            E::InvalidArgument(_) | E::Conflict(_) => CuaError::InvalidArgument(m),
            E::Unauthenticated(_) => CuaError::Unauthenticated(m),
            E::PermissionDenied(_) => CuaError::PermissionDenied(m),
            E::NotFound(_) => CuaError::NotFound(m),
            E::Relay(_) | E::Download(_) => CuaError::Http(m),
            // The plain sentence, then where to upgrade, as the CLI says it;
            // the Python and TypeScript SDKs read both back as `PlanLimitError`.
            E::PlanLimit(_) => {
                let url = cua_home::plan_limit::PlanLimit::parse(&m)
                    .map(|l| l.upgrade_url(&cua_home::env::account_app_url()));
                CuaError::Http(match url {
                    Some(url) => format!("{m} Upgrade: {url}"),
                    None => m,
                })
            }
            E::Service(_) => CuaError::Runtime(m),
            E::Io(_) | E::Internal(_) => CuaError::Internal(m),
        }
    }
}

/// Somebody connected to a machine through the relay.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct RelayClientInfo {
    /// User id.
    pub id: String,
    /// Email, when shared by the identity provider.
    pub email: Option<String>,
    /// Display name.
    pub name: Option<String>,
    /// Open streams.
    pub streams: u32,
    /// Unix seconds of the first open stream.
    pub since: u64,
}

impl From<cua_host::ConnectedClient> for RelayClientInfo {
    fn from(c: cua_host::ConnectedClient) -> Self {
        Self {
            id: c.id,
            email: c.email,
            name: c.name,
            streams: c.streams,
            since: c.since,
        }
    }
}

/// A machine of the account's relay directory (`relay:<id>`).
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct RelayMachine {
    /// Machine id.
    pub id: String,
    /// `relay:<id>`.
    pub space_id: String,
    /// Display name.
    pub name: String,
    /// Owner account id.
    pub owner_id: String,
    /// Owner email.
    pub owner_email: Option<String>,
    /// `owner` or `shared`.
    pub role: String,
    /// Connected to the relay.
    pub online: bool,
    /// Accepting clients.
    pub sharing: bool,
    /// spacesd version.
    pub version: String,
    /// `<relay>/m/<id>`.
    pub url: String,
    /// Allowlist (owner view only).
    pub allow: Vec<String>,
    /// Connected clients.
    pub clients: Vec<RelayClientInfo>,
    /// Registered with an enrolled device's signature or MFA, or confirmed
    /// since from one; `true` for anything a relay registered before this
    /// check existed. `false` shows the machine as "new" until an enrolled
    /// device confirms it ([`Devices::confirm_machine`]) (S5).
    pub confirmed: bool,
    /// The team you reach it through, for a team machine not shared with
    /// you directly.
    pub team: Option<String>,
    /// It creates Spaces for its owner's devices, when it said so at
    /// registration (`None` from a host or relay that predates it).
    pub provides_spaces: Option<bool>,
}

impl From<cua_host::Machine> for RelayMachine {
    fn from(m: cua_host::Machine) -> Self {
        Self {
            space_id: format!("relay:{}", m.id),
            id: m.id,
            name: m.name,
            owner_id: m.owner.id,
            owner_email: m.owner.email,
            role: m.role,
            online: m.online,
            sharing: m.sharing,
            version: m.version,
            url: m.url,
            allow: m.allow,
            clients: m.clients.into_iter().map(Into::into).collect(),
            confirmed: m.confirmed,
            provides_spaces: m
                .meta
                .get(cua_host::META_PROVIDES_SPACES)
                .map(|v| v == "on"),
            team: m.team.filter(|t| !t.trim().is_empty()),
        }
    }
}

/// A one-time code that adds a machine to the account ("Add a machine"
/// by link or QR code).
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct PairingCode {
    /// `pc_…` (to revoke it).
    pub id: String,
    /// `XXXX-XXXX-XXXX`: only when just made.
    pub code: Option<String>,
    /// `https://cua.ai/add/<code>` (the link and the QR code): only
    /// when just made.
    pub url: Option<String>,
    /// `curl … | sh -s -- --pair <code>` (macOS, Linux): only when just made.
    pub install_sh: Option<String>,
    /// The PowerShell one-liner (Windows): only when just made.
    pub install_powershell: Option<String>,
    /// `active`, `used`, `revoked` or `expired`.
    pub state: String,
    /// Team the machine is added for.
    pub team: Option<String>,
    /// Unix seconds.
    pub created_at: u64,
    /// Unix seconds.
    pub expires_at: u64,
    /// When a machine used it.
    pub used_at: Option<u64>,
    /// The machine it added (relay machine id).
    pub machine: Option<String>,
}

impl PairingCode {
    fn from_host(p: cua_host::PairingCode, relay: &str) -> Self {
        let made = |f: &dyn Fn(&str) -> String| p.code.as_deref().map(f);
        Self {
            url: made(&|c| cua_host::add_machine_url(c, relay)),
            install_sh: made(&|c| cua_host::install_command(c, relay, "linux")),
            install_powershell: made(&|c| cua_host::install_command(c, relay, "windows")),
            id: p.id,
            code: p.code,
            state: p.state,
            team: p.team,
            created_at: p.created_at,
            expires_at: p.expires_at,
            used_at: p.used_at,
            machine: p.machine,
        }
    }
}

/// The signed-in account's view of a cua-relay.
#[derive(uniffi::Object)]
pub struct Relay {
    client: cua_host::RelayClient,
    account_token: String,
}

#[uniffi::export]
impl Relay {
    /// A relay (`None` = the relay `cua` uses: `CUA_RELAY_URL`, else this
    /// machine's host setup, else `https://relay.cua.ai`) seen as the
    /// account behind `account_token` (a cua.ai access token).
    #[uniffi::constructor]
    pub fn new(relay_url: Option<String>, account_token: String) -> Result<Arc<Self>> {
        let url = cua_host::relay_url_for(relay_url.as_deref(), &cua_daemon::cua_home());
        Ok(Arc::new(Self {
            client: cua_host::RelayClient::new(&url)?,
            account_token,
        }))
    }

    /// Normalized relay base URL.
    pub fn url(&self) -> String {
        self.client.base().to_string()
    }

    /// Machines the account owns or that are shared with it.
    pub async fn machines(&self) -> Result<Vec<RelayMachine>> {
        let client = self.client.clone();
        let token = self.account_token.clone();
        run(async move {
            Ok(client
                .machines(&token)
                .await?
                .into_iter()
                .map(Into::into)
                .collect())
        })
        .await
    }

    /// One machine.
    pub async fn machine(&self, machine_id: String) -> Result<RelayMachine> {
        let client = self.client.clone();
        let token = self.account_token.clone();
        run(async move { Ok(client.machine(&token, &machine_id).await?.into()) }).await
    }

    /// Cuts every client of a machine the account owns and refuses new ones.
    pub async fn stop_sharing(&self, machine_id: String) -> Result<RelayMachine> {
        let client = self.client.clone();
        let token = self.account_token.clone();
        run(async move { Ok(client.stop_sharing(&token, &machine_id).await?.into()) }).await
    }

    /// Accepts clients again.
    pub async fn start_sharing(&self, machine_id: String) -> Result<RelayMachine> {
        let client = self.client.clone();
        let token = self.account_token.clone();
        run(async move { Ok(client.start_sharing(&token, &machine_id).await?.into()) }).await
    }

    /// Connects to a machine's spacesd through `<relay>/m/<id>`, with the
    /// account token as bearer (the relay swaps it for its signed identity).
    pub async fn connect(&self, machine_id: String) -> Result<Arc<SpacesdClient>> {
        let url = self.client.machine_url(&machine_id);
        let token = self.account_token.clone();
        run(async move {
            let o = cua_spacesd_client::ConnectOptions::parse(&url)?
                .gateway(Arc::new(cua_spacesd_client::StaticBearer(token)));
            let client = cua_spacesd_client::SpacesdClient::connect(o).await?;
            Ok(Arc::new(SpacesdClient::new(client, vec![]).at("relay")))
        })
        .await
    }
}

/// `cua host setup` options.
#[derive(Debug, Clone, Default, PartialEq, Eq, uniffi::Record)]
pub struct HostSetupOptions {
    /// `relay` (default) or `direct`.
    pub mode: Option<String>,
    /// Relay URL (relay mode; default `CUA_RELAY_URL` / `https://relay.cua.ai`).
    pub relay_url: Option<String>,
    /// `ip:port` (direct mode; default `0.0.0.0:3211`).
    pub direct: Option<String>,
    /// Display name (default: host name).
    pub name: Option<String>,
    /// Accounts (ids or emails) allowed besides the owner.
    pub allow: Vec<String>,
    /// Driver binary (else `CUA_SPACESD_BIN`, bundled, or download).
    pub driver_bin: Option<String>,
    /// `auto`, `systemd`, `launchd`, `windows-task` or `process`.
    pub runner: Option<String>,
    /// `desktop` (share this desktop; the default) or `spare` (do not
    /// share the desktop; provide Spaces). The two settings below override
    /// it.
    #[uniffi(default = None)]
    pub profile: Option<String>,
    /// Share this machine's own desktop as a Space.
    #[uniffi(default = None)]
    pub share_desktop: Option<bool>,
    /// Create Spaces for your enrolled devices on this machine (relay
    /// mode).
    #[uniffi(default = None)]
    pub provide_spaces: Option<bool>,
}

/// A change to this machine's Spaces settings (`None` keeps a value).
#[derive(Debug, Clone, Default, PartialEq, Eq, uniffi::Record)]
pub struct HostSettingsChange {
    /// Share this desktop.
    #[uniffi(default = None)]
    pub share_desktop: Option<bool>,
    /// Provide Spaces.
    #[uniffi(default = None)]
    pub provide_spaces: Option<bool>,
    /// Provided Spaces at once (0: no limit).
    #[uniffi(default = None)]
    pub max_spaces: Option<u32>,
    /// macOS VMs at once (0 to 2, Apple's license).
    #[uniffi(default = None)]
    pub max_macos_vms: Option<u32>,
}

/// A Space this machine provides to one of your devices.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct HostProvidedSpace {
    /// The relay machine it is reached as (`relay:<machine>`).
    pub relay_machine: String,
    /// The Space on this machine (`local:<name>`).
    pub local_space: String,
    /// Display name.
    pub name: String,
    /// The image, as requested.
    pub image: String,
    /// `linux`, `macos` (empty when unknown).
    pub os: String,
    /// `container` or `vm`.
    pub kind: String,
    /// Who created it.
    pub created_by: String,
    /// Epoch ms.
    pub created_at_ms: i64,
}

/// One line of this machine's Spaces audit (remote creates, deletes,
/// refusals and settings changes).
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct HostSpacesAuditRecord {
    /// Epoch ms.
    pub at_ms: i64,
    /// `create`, `delete`, `refused`, `failed` or `config`.
    pub action: String,
    /// Who (an account, or `local`).
    pub who: String,
    /// The relay machine or Space.
    pub space: String,
    /// Detail.
    pub detail: String,
}

/// A macOS privacy pane the user must grant.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct HostPermission {
    /// `screen-recording` or `accessibility`.
    pub id: String,
    /// Title.
    pub title: String,
    /// `x-apple.systempreferences:` URL.
    pub settings_url: String,
    /// Instructions.
    pub instructions: String,
}

/// Host status.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct HostStatus {
    /// Set up.
    pub configured: bool,
    /// `relay` or `direct`.
    pub mode: Option<String>,
    /// Relay URL.
    pub relay_url: Option<String>,
    /// Direct URL.
    pub direct_url: Option<String>,
    /// Env token file (direct mode).
    pub env_token_path: Option<String>,
    /// Machine id.
    pub machine_id: Option<String>,
    /// Name.
    pub name: Option<String>,
    /// Accepting clients.
    pub sharing: bool,
    /// Service installed.
    pub service_installed: bool,
    /// Service running.
    pub service_running: bool,
    /// Runner kind.
    pub service_kind: String,
    /// Online at the relay.
    pub online: Option<bool>,
    /// Connected clients.
    pub clients: Vec<RelayClientInfo>,
    /// Allowlist.
    pub allow: Vec<String>,
    /// Permission panes (macOS).
    pub permissions: Vec<HostPermission>,
    /// Relay error.
    pub error: Option<String>,
    /// Who reached this machine recently, newest first (the driver's
    /// hash-chained access log).
    #[uniffi(default = [])]
    pub recent_access: Vec<HostAccessRecord>,
    /// Set when the access log does not verify (edited or truncated).
    #[uniffi(default = None)]
    pub access_log_error: Option<String>,
    /// This machine's desktop is a Space.
    #[uniffi(default = true)]
    pub share_desktop: bool,
    /// This machine provides Spaces to your other devices.
    #[uniffi(default = false)]
    pub provide_spaces: bool,
    /// Provided Spaces at once (0: no limit).
    #[uniffi(default = 0)]
    pub max_spaces: u32,
    /// macOS VMs at once (at most two).
    #[uniffi(default = 0)]
    pub max_macos_vms: u32,
    /// The Spaces this machine provides now.
    #[uniffi(default = [])]
    pub provided_spaces: Vec<HostProvidedSpace>,
    /// The Spaces audit, newest first.
    #[uniffi(default = [])]
    pub spaces_audit: Vec<HostSpacesAuditRecord>,
    /// Set when the Spaces audit does not verify.
    #[uniffi(default = None)]
    pub spaces_audit_error: Option<String>,
    /// Relay sharing is paused until the owner signs in again
    /// ([`Host::pause_signed_out`]).
    #[uniffi(default = false)]
    pub paused_signed_out: bool,
    /// The account this machine is registered to (relay mode): its id.
    #[uniffi(default = None)]
    pub owner: Option<String>,
    /// The owner's email, when the relay gave one.
    #[uniffi(default = None)]
    pub owner_email: Option<String>,
}

/// One access to this machine.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct HostAccessRecord {
    /// Epoch ms.
    pub at_ms: i64,
    /// `relay`, `viewer` or `token`.
    pub via: String,
    /// Who.
    pub who: String,
    /// What they used (a service name, or `MCP`).
    pub what: String,
}

impl From<cua_host::HostStatus> for HostStatus {
    fn from(s: cua_host::HostStatus) -> Self {
        Self {
            configured: s.configured,
            mode: s.mode,
            relay_url: s.relay_url,
            direct_url: s.direct_url,
            env_token_path: s.env_token_path,
            machine_id: s.machine_id,
            name: s.name,
            sharing: s.sharing,
            service_installed: s.service.installed,
            service_running: s.service.running,
            service_kind: s.service.kind,
            online: s.online,
            clients: s.clients.into_iter().map(Into::into).collect(),
            allow: s.allow,
            permissions: s
                .permissions
                .into_iter()
                .map(|p| HostPermission {
                    id: p.id,
                    title: p.title,
                    settings_url: p.settings_url,
                    instructions: p.instructions,
                })
                .collect(),
            error: s.error,
            recent_access: s
                .recent_access
                .into_iter()
                .map(|a| HostAccessRecord {
                    at_ms: i64::try_from(a.at_ms).unwrap_or(i64::MAX),
                    via: a.via,
                    who: a.who,
                    what: a.what,
                })
                .collect(),
            access_log_error: s.access_log_error,
            share_desktop: s.share_desktop,
            provide_spaces: s.provide_spaces,
            max_spaces: s.max_spaces,
            max_macos_vms: s.max_macos_vms,
            provided_spaces: s
                .provided_spaces
                .into_iter()
                .map(|p| HostProvidedSpace {
                    relay_machine: p.relay_machine,
                    local_space: p.local_space,
                    name: p.name,
                    image: p.image,
                    os: p.os,
                    kind: p.kind,
                    created_by: p.created_by,
                    created_at_ms: i64::try_from(p.created_at_ms).unwrap_or(i64::MAX),
                })
                .collect(),
            spaces_audit: s
                .spaces_audit
                .into_iter()
                .map(|a| HostSpacesAuditRecord {
                    at_ms: i64::try_from(a.at_ms).unwrap_or(i64::MAX),
                    action: a.action,
                    who: a.who,
                    space: a.space,
                    detail: a.detail,
                })
                .collect(),
            spaces_audit_error: s.spaces_audit_error,
            paused_signed_out: s.paused_signed_out,
            owner: s.owner,
            owner_email: s.owner_email,
        }
    }
}

/// What host setup's usage data says about the account token: `provided`,
/// `expired` (its `exp` is past: the app passed a stale token), `missing`
/// (relay mode with none), `not_needed` (direct mode). Never the token.
pub(crate) fn setup_token_state(mode: &str, token: Option<&str>) -> &'static str {
    if mode.trim().eq_ignore_ascii_case("direct") {
        return "not_needed";
    }
    let Some(token) = token.filter(|t| !t.trim().is_empty()) else {
        return "missing";
    };
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs());
    match cua_auth::jwt_claims(token).and_then(|c| c["exp"].as_u64()) {
        Some(exp) if exp <= now => "expired",
        _ => "provided",
    }
}

/// Converts binding options to cua-host options.
pub(crate) fn setup_options(o: HostSetupOptions) -> Result<cua_host::SetupOptions> {
    let mut opts = match o.mode.as_deref().unwrap_or("relay") {
        "relay" => cua_host::SetupOptions::relay(
            o.relay_url
                .filter(|u| !u.trim().is_empty())
                .unwrap_or_else(cua_host::relay_url_from_env),
        ),
        "direct" => {
            let listen = o.direct.as_deref().unwrap_or("0.0.0.0:3211");
            cua_host::SetupOptions::direct(listen.parse().map_err(|_| {
                CuaError::InvalidArgument(format!("direct address {listen:?} is not ip:port"))
            })?)
        }
        other => {
            return Err(CuaError::InvalidArgument(format!(
                "mode {other:?} (use relay or direct)"
            )));
        }
    };
    opts.name = o.name;
    opts.allow = o.allow;
    opts.driver_bin = o.driver_bin.map(Into::into);
    opts.runner = cua_host::RunnerKind::parse(o.runner.as_deref().unwrap_or("auto"))?;
    if let Some(p) = o.profile.as_deref().filter(|p| !p.trim().is_empty()) {
        opts = opts.profile(cua_host::HostProfile::parse(p)?);
    }
    if let Some(d) = o.share_desktop {
        opts.share_desktop = d;
    }
    if let Some(p) = o.provide_spaces {
        opts.provide_spaces = p;
    }
    Ok(opts)
}

/// This machine as an unattended-access host.
#[derive(uniffi::Object)]
pub struct Host {
    home: std::path::PathBuf,
}

#[uniffi::export]
impl Host {
    /// Host state under `cua_home` (default `$CUA_HOME` or `~/.cua`).
    #[uniffi::constructor]
    pub fn new(cua_home: Option<String>) -> Arc<Self> {
        Arc::new(Self {
            home: cua_home
                .map(Into::into)
                .unwrap_or_else(cua_daemon::cua_home),
        })
    }

    /// Current state.
    pub async fn status(&self) -> Result<HostStatus> {
        let home = self.home.clone();
        run(async move { Ok(cua_host::Host::new(home).status().await?.into()) }).await
    }

    /// Installs and starts the host service (relay mode needs
    /// `account_token`).
    pub async fn setup(
        &self,
        options: HostSetupOptions,
        account_token: Option<String>,
    ) -> Result<HostStatus> {
        let home = self.home.clone();
        let mode = options.mode.clone().unwrap_or_else(|| "relay".into());
        let opts = setup_options(options);
        let (desktop, provide) = opts
            .as_ref()
            .map(|o| (o.share_desktop, o.provide_spaces))
            .unwrap_or((true, false));
        let account_token = account_token.filter(|t| !t.trim().is_empty());
        let token_state = setup_token_state(&mode, account_token.as_deref());
        let (r, failed_stage, http_status) = match opts {
            Ok(opts) => {
                let staged = run(async move {
                    let host = cua_host::Host::new(home);
                    let staged = match account_token {
                        Some(t) => host.setup_staged(opts, &cua_host::StaticToken(t)).await,
                        None => host.setup_staged(opts, &cua_host::NoAccount).await,
                    };
                    Ok(staged)
                })
                .await;
                match staged {
                    Ok(Ok(status)) => (Ok(status.into()), None, None),
                    Ok(Err((stage, e))) => {
                        let status = e.http_status();
                        (Err(e.into()), Some(stage.as_str()), status)
                    }
                    Err(e) => (Err(e), Some("preflight"), None),
                }
            }
            Err(e) => (Err(e), Some("preflight"), None),
        };
        // Host Spaces adoption: the mode and what the machine is for,
        // never its name, address or who it is shared with. A failure says
        // where it stopped, whether an account token was there (never the
        // token) and the HTTP status a server answered with.
        cua_telemetry::capture(cua_telemetry::events::host_setup(
            &mode,
            desktop,
            provide,
            if r.is_ok() {
                cua_telemetry::Outcome::Ok
            } else {
                cua_telemetry::Outcome::Error
            },
            super::telemetry::variant(&r),
            &cua_telemetry::events::HostSetupDetail {
                signed_in: token_state != "missing" && token_state != "not_needed"
                    || cua_auth::may_have_session(),
                token_state,
                failed_stage,
                http_status,
            },
        ));
        r
    }

    /// Changes what this machine shares: its own desktop, and whether it
    /// creates Spaces for your other devices (and their limits). Turning
    /// the desktop on or off restarts the host service.
    pub async fn configure(&self, change: HostSettingsChange) -> Result<HostStatus> {
        let home = self.home.clone();
        run(async move {
            Ok(cua_host::Host::new(home)
                .configure(cua_host::HostSettingsChange {
                    share_desktop: change.share_desktop,
                    provide_spaces: change.provide_spaces,
                    max_spaces: change.max_spaces,
                    max_macos_vms: change.max_macos_vms,
                    cua_bin: None,
                })
                .await?
                .into())
        })
        .await
    }

    /// Stop sharing (cut clients, refuse new ones).
    pub async fn stop_sharing(&self) -> Result<HostStatus> {
        let home = self.home.clone();
        run(async move { Ok(cua_host::Host::new(home).stop_sharing().await?.into()) }).await
    }

    /// Start sharing again.
    pub async fn start_sharing(&self) -> Result<HostStatus> {
        let home = self.home.clone();
        run(async move { Ok(cua_host::Host::new(home).start_sharing().await?.into()) }).await
    }

    /// Pause relay sharing while nobody is signed in to the owner's
    /// account: the host leaves the relay and stays off it (also across a
    /// restart) with its setup kept. Direct mode is left alone.
    pub async fn pause_signed_out(&self) -> Result<HostStatus> {
        let home = self.home.clone();
        run(async move { Ok(cua_host::Host::new(home).pause_signed_out().await?.into()) }).await
    }

    /// Resume relay sharing paused by [`Host::pause_signed_out`] once
    /// `account` (the signed-in account's id or email) is signed in; refused
    /// when it is not the machine's owner.
    pub async fn resume_signed_in(&self, account: String) -> Result<HostStatus> {
        let home = self.home.clone();
        run(async move {
            Ok(cua_host::Host::new(home)
                .resume_signed_in(&account)
                .await?
                .into())
        })
        .await
    }

    /// Unregister, uninstall the service and delete the host state.
    pub async fn remove(&self) -> Result<()> {
        let home = self.home.clone();
        run(async move {
            cua_host::Host::new(home).remove().await?;
            // Then the runtimes cua set up itself (the built-in Lume and the
            // built-in Linux runtime, set up again on the next create that
            // needs them); the user's own stay.
            if let Err(e) = cua_sandbox_core::remove_builtin_runtimes().await {
                tracing::warn!("could not remove the built-in runtimes: {e}");
            }
            Ok(())
        })
        .await
    }
}

// ---- This device as a client of the account on the relay -----------------

/// A client device of the account, as the relay lists it.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct RelayDevice {
    /// `dev_…`.
    pub id: String,
    /// Display name.
    pub name: String,
    /// `pending`, `enrolled`, `expired` or `revoked`.
    pub state: String,
    /// Operating system it reported (`macos`, `windows`, `linux`); empty
    /// when unknown.
    pub platform: String,
    /// Registered at (Unix seconds).
    pub created_at: u64,
    /// Re-verification due at (Unix seconds).
    pub enrolled_until: Option<u64>,
    /// Last session (Unix seconds).
    pub last_seen: Option<u64>,
    /// This device.
    pub current: bool,
}

impl From<cua_host::DeviceView> for RelayDevice {
    fn from(d: cua_host::DeviceView) -> Self {
        Self {
            state: match d.state {
                cua_host::DeviceState::Pending => "pending",
                cua_host::DeviceState::Enrolled => "enrolled",
                cua_host::DeviceState::Expired => "expired",
                cua_host::DeviceState::Revoked => "revoked",
            }
            .into(),
            id: d.id,
            name: d.name,
            platform: d.platform,
            created_at: d.created_at,
            enrolled_until: d.enrolled_until,
            last_seen: d.last_seen,
            current: d.current,
        }
    }
}

/// One event of the account's audit log.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct RelayAuditEvent {
    /// Unix seconds.
    pub ts: u64,
    /// Kind (`machine_access`, `device_enrolled`, `share_added`, ...).
    pub kind: String,
    /// Acting device.
    pub device: Option<String>,
    /// Machine id.
    pub machine: Option<String>,
    /// Other party.
    pub subject: Option<String>,
    /// Detail.
    pub detail: Option<String>,
}

impl From<cua_host::AuditEvent> for RelayAuditEvent {
    fn from(e: cua_host::AuditEvent) -> Self {
        Self {
            ts: e.ts,
            kind: e.kind,
            device: e.device,
            machine: e.machine,
            subject: e.subject,
            detail: e.detail,
        }
    }
}

/// Everything the Devices page reads, in one call.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct DevicesSnapshot {
    /// This device's id, when it has a key.
    pub local_device_id: Option<String>,
    /// The account's devices (this one marked `current` once enrolled).
    pub devices: Vec<RelayDevice>,
    /// End of the relay's grace period for unenrolled devices.
    pub enforce_after: Option<u64>,
    /// The account's audit log, newest last (empty when the relay refuses).
    pub audit: Vec<RelayAuditEvent>,
    /// Machine ids to names (empty when this device cannot list them).
    pub machine_names: std::collections::HashMap<String, String>,
    /// The account's relay machines, [`RelayMachine::confirmed`] included
    /// (S5; empty when this device cannot list them, same as
    /// `machine_names`).
    pub machines: Vec<RelayMachine>,
}

/// `Devices.enroll`'s result.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct DeviceEnrollment {
    /// This device.
    pub device: RelayDevice,
    /// Enrolled now (right after a fresh sign-in).
    pub enrolled: bool,
    /// The one-time code to approve from an enrolled device otherwise.
    pub code: Option<String>,
}

/// The session as `cua-host` account tokens.
pub(super) struct SessionTokens(pub(super) Arc<cua_auth::Session>);

#[async_trait::async_trait]
impl cua_host::AccountTokens for SessionTokens {
    async fn access_token(&self) -> cua_host::Result<String> {
        self.0
            .access_token(false)
            .await
            .map_err(|e| cua_host::Error::Unauthenticated(e.to_string()))
    }

    async fn signed_in(&self) -> bool {
        !matches!(self.0.credentials(), Ok(None))
    }
}

/// This device as a client of the signed-in account on a relay: its
/// enrollment, the account's other devices and its audit log. The device
/// key lives in the session's vault (shared with the `cua` CLI and daemon).
/// Nothing here prompts: approving is the caller's to gate behind presence.
#[derive(uniffi::Object)]
pub struct Devices {
    auth: Arc<cua_host::DeviceAuth>,
    tokens: Arc<SessionTokens>,
}

#[uniffi::export]
impl Auth {
    /// This device on `relay_url` (`None` = the relay `cua` uses:
    /// `CUA_RELAY_URL`, else this machine's host setup, else
    /// `https://relay.cua.ai`) as the signed-in account, shown as `name`
    /// (default: this computer's name).
    pub fn devices(&self, relay_url: Option<String>, name: Option<String>) -> Result<Arc<Devices>> {
        let home = cua_daemon::cua_home();
        let url = cua_host::relay_url_for(relay_url.as_deref(), &home);
        let session = self.session();
        let tokens = Arc::new(SessionTokens(session.clone()));
        let auth = cua_host::DeviceAuth::new(
            &url,
            tokens.clone(),
            Arc::new(session.store().clone()),
            name.filter(|n| !n.trim().is_empty())
                .unwrap_or_else(cua_host::device_name),
        )?
        .with_pending_file(cua_host::device_pending_file(&home));
        Ok(Arc::new(Devices {
            auth: Arc::new(auth),
            tokens,
        }))
    }
}

#[uniffi::export]
impl Devices {
    /// The relay base URL.
    pub fn relay_url(&self) -> String {
        self.auth.relay_url().to_string()
    }

    /// This device's id, when it has a key (no network).
    pub fn device_id(&self) -> Result<Option<String>> {
        Ok(self.auth.device_id()?)
    }

    /// The account's devices, the grace period, the newest `audit_limit`
    /// audit events and the machines' names. Only the device list must
    /// succeed; the rest is empty when the relay refuses it.
    pub async fn snapshot(&self, audit_limit: u32) -> Result<DevicesSnapshot> {
        let auth = self.auth.clone();
        let tokens = self.tokens.clone();
        run(async move {
            let listing = auth.listing().await?;
            let audit = auth.audit(audit_limit as usize).await.unwrap_or_default();
            let machines: Vec<RelayMachine> = match auth.try_session().await {
                Some(session) => {
                    let token = cua_host::AccountTokens::access_token(tokens.as_ref()).await?;
                    cua_host::RelayClient::new(auth.relay_url())?
                        .with_device_session(Some(session))
                        .machines(&token)
                        .await
                        .map(|l| l.into_iter().map(Into::into).collect())
                        .unwrap_or_default()
                }
                None => Default::default(),
            };
            let machine_names = machines
                .iter()
                .map(|m| (m.id.clone(), m.name.clone()))
                .collect();
            Ok(DevicesSnapshot {
                local_device_id: auth.device_id()?,
                devices: listing.devices.into_iter().map(Into::into).collect(),
                enforce_after: (listing.enforce_after > 0).then_some(listing.enforce_after),
                audit: audit.into_iter().map(Into::into).collect(),
                machine_names,
                machines,
            })
        })
        .await
    }

    /// Registers this device (creating its key on first use). Right after
    /// a fresh sign-in it is enrolled at once (replacing this machine's
    /// older device key, if any); otherwise the result carries a one-time
    /// code to approve from an enrolled device.
    pub async fn enroll(&self) -> Result<DeviceEnrollment> {
        let auth = self.auth.clone();
        run(async move {
            let e = auth.enroll().await?;
            Ok(DeviceEnrollment {
                enrolled: e.device.state == cua_host::DeviceState::Enrolled,
                device: e.device.into(),
                code: e.code,
            })
        })
        .await
    }

    /// Whether the relay lets this device open a session now (enrolled),
    /// asked afresh. Polled while waiting for an approval.
    pub async fn check_enrolled(&self) -> bool {
        let auth = self.auth.clone();
        run(async move {
            auth.reset_session().await;
            Ok(auth.session().await.is_ok())
        })
        .await
        .unwrap_or(false)
    }

    /// Approves the device showing `code`, or re-verifies `device_id`,
    /// from this enrolled device.
    pub async fn approve(
        &self,
        code: Option<String>,
        device_id: Option<String>,
    ) -> Result<RelayDevice> {
        let auth = self.auth.clone();
        run(async move {
            Ok(auth
                .approve(code.as_deref(), device_id.as_deref())
                .await?
                .into())
        })
        .await
    }

    /// Renames a device (from this enrolled device).
    pub async fn rename(&self, id: String, name: String) -> Result<RelayDevice> {
        let auth = self.auth.clone();
        run(async move { Ok(auth.rename(&id, &name).await?.into()) }).await
    }

    /// Revokes a device (from this enrolled device). Revoking this device
    /// also deletes its key.
    pub async fn revoke(&self, id: String) -> Result<RelayDevice> {
        let auth = self.auth.clone();
        run(async move { Ok(auth.revoke(&id).await?.into()) }).await
    }

    /// Makes a one-time code (link, QR, install commands) that adds another
    /// computer to the account, or to `team` (from this enrolled device).
    /// It expires after `ttl_secs` (30 minutes when `None`).
    pub async fn create_pairing_code(
        &self,
        team: Option<String>,
        ttl_secs: Option<u64>,
    ) -> Result<PairingCode> {
        let auth = self.auth.clone();
        let tokens = self.tokens.clone();
        // `team` (an organization id) is only echoed back: the relay's own
        // teams are retired, and the machine becomes a team machine once it
        // joined, by sharing it with `team:<id>` (the Spaces API).
        run(async move {
            let session = auth.session().await?;
            let token = cua_host::AccountTokens::access_token(tokens.as_ref()).await?;
            let relay = auth.relay_url().to_string();
            let code = cua_host::RelayClient::new(&relay)?
                .with_device_session(Some(session))
                .create_pairing_code(
                    &token,
                    &cua_host::PairingCodeRequest {
                        name: None,
                        team: None,
                        ttl_secs,
                    },
                )
                .await?;
            let code = cua_host::PairingCode {
                team: team.filter(|t| !t.trim().is_empty()),
                ..code
            };
            Ok(PairingCode::from_host(code, &relay))
        })
        .await
    }

    /// The account's pairing codes, newest first (without the codes).
    pub async fn pairing_codes(&self) -> Result<Vec<PairingCode>> {
        let auth = self.auth.clone();
        let tokens = self.tokens.clone();
        run(async move {
            let session = auth.session().await?;
            let token = cua_host::AccountTokens::access_token(tokens.as_ref()).await?;
            let relay = auth.relay_url().to_string();
            let codes = cua_host::RelayClient::new(&relay)?
                .with_device_session(Some(session))
                .pairing_codes(&token)
                .await?;
            Ok(codes
                .into_iter()
                .map(|c| PairingCode::from_host(c, &relay))
                .collect())
        })
        .await
    }

    /// Revokes an unused pairing code (`pc_…`).
    pub async fn revoke_pairing_code(&self, id: String) -> Result<()> {
        let auth = self.auth.clone();
        let tokens = self.tokens.clone();
        run(async move {
            let session = auth.session().await?;
            let token = cua_host::AccountTokens::access_token(tokens.as_ref()).await?;
            cua_host::RelayClient::new(auth.relay_url())?
                .with_device_session(Some(session))
                .revoke_pairing_code(&token, &id)
                .await?;
            Ok(())
        })
        .await
    }

    /// Renames `machine_id`, a machine the account owns, on the relay (from
    /// this enrolled device). When it is this machine's own registration,
    /// its host setup takes the new name too.
    pub async fn rename_machine(&self, machine_id: String, name: String) -> Result<RelayMachine> {
        let auth = self.auth.clone();
        let tokens = self.tokens.clone();
        run(async move {
            let name = name.trim().to_string();
            if name.is_empty() {
                return Err(
                    cua_host::Error::InvalidArgument("a machine needs a name".into()).into(),
                );
            }
            let session = auth.session().await?;
            let token = cua_host::AccountTokens::access_token(tokens.as_ref()).await?;
            let m: RelayMachine = cua_host::RelayClient::new(auth.relay_url())?
                .with_device_session(Some(session))
                .patch(
                    &token,
                    &machine_id,
                    &cua_host::MachinePatch {
                        name: Some(name.clone()),
                        ..Default::default()
                    },
                )
                .await?
                .into();
            cua_host::Host::new(cua_daemon::cua_home()).adopt_name(&machine_id, &name)?;
            Ok(m)
        })
        .await
    }

    /// Vouches for `machine_id`, a machine that registered without an
    /// enrolled device's signature or MFA (from this enrolled device) (S5).
    /// Clears [`RelayMachine::confirmed`]'s "new" flag for every account
    /// member, not just this device.
    pub async fn confirm_machine(&self, machine_id: String) -> Result<RelayMachine> {
        let auth = self.auth.clone();
        let tokens = self.tokens.clone();
        run(async move {
            let session = auth.session().await?;
            let token = cua_host::AccountTokens::access_token(tokens.as_ref()).await?;
            Ok(cua_host::RelayClient::new(auth.relay_url())?
                .with_device_session(Some(session))
                .confirm(&token, &machine_id)
                .await?
                .into())
        })
        .await
    }
}

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

    /// The Machines page groups team machines and says whether a machine
    /// provides Spaces from what the relay recorded at registration.
    #[test]
    fn a_relay_machine_carries_its_team_and_whether_it_provides_spaces() {
        let mut m = cua_host::Machine {
            id: "m1".into(),
            role: "shared".into(),
            team: Some("team-1".into()),
            ..Default::default()
        };
        m.meta
            .insert(cua_host::META_PROVIDES_SPACES.into(), "on".into());
        let r = RelayMachine::from(m.clone());
        assert_eq!(r.team.as_deref(), Some("team-1"));
        assert_eq!(r.provides_spaces, Some(true));
        m.meta
            .insert(cua_host::META_PROVIDES_SPACES.into(), "off".into());
        m.team = Some(" ".into());
        let r = RelayMachine::from(m.clone());
        assert_eq!((r.team, r.provides_spaces), (None, Some(false)));
        m.meta.clear();
        assert_eq!(RelayMachine::from(m).provides_spaces, None);
    }

    #[test]
    fn setup_reports_whether_it_had_a_token_never_the_token() {
        use base64::Engine;
        let jwt = |exp: u64| {
            let claims = base64::engine::general_purpose::URL_SAFE_NO_PAD
                .encode(format!(r#"{{"sub":"u","exp":{exp}}}"#));
            format!("h.{claims}.s")
        };
        assert_eq!(setup_token_state("relay", None), "missing");
        assert_eq!(setup_token_state("relay", Some("  ")), "missing");
        assert_eq!(setup_token_state("relay", Some(&jwt(1))), "expired");
        assert_eq!(
            setup_token_state("relay", Some(&jwt(u64::MAX / 2))),
            "provided"
        );
        // Opaque tokens are taken as given.
        assert_eq!(setup_token_state("relay", Some("opaque")), "provided");
        assert_eq!(setup_token_state("Direct", None), "not_needed");
    }

    /// A relay setup with no account token stops before the relay with
    /// `Unauthenticated` (what 0.3.0/0.3.1 sent when the app's token read
    /// failed): the app must sign in first, never call this without one.
    #[tokio::test]
    async fn relay_setup_without_a_token_is_unauthenticated() {
        let relay = cua_host::testing::FakeRelay::start().await;
        let dir = tempfile::tempdir().unwrap();
        let host = Host::new(Some(dir.path().join(".cua").to_string_lossy().into()));
        let err = host
            .setup(
                HostSetupOptions {
                    mode: Some("relay".into()),
                    relay_url: Some(relay.url.clone()),
                    driver_bin: Some(dir.path().join("x").to_string_lossy().into()),
                    runner: Some("process".into()),
                    ..Default::default()
                },
                None,
            )
            .await
            .unwrap_err();
        assert!(matches!(err, CuaError::Unauthenticated(_)), "{err}");
        assert_eq!(relay.register_calls(), 0);
    }

    #[tokio::test]
    async fn devices_enroll_approve_rename_and_revoke_through_the_relay() {
        let relay = cua_host::testing::FakeRelay::start().await;
        relay.add_account("a.eyJlbWFpbCI6ImFAYi5jIn0.s", "user-1", None);
        relay.set_enforce_after(1_900_000_000);
        let signed_in = |dir: &std::path::Path| {
            let store = cua_auth::Store::File(dir.join("credentials.json"));
            store
                .save(
                    &cua_auth::Credentials::from_token_response(&serde_json::json!({
                        "access_token": "a.eyJlbWFpbCI6ImFAYi5jIn0.s", "expires_in": 3600,
                    }))
                    .unwrap(),
                )
                .unwrap();
            super::super::Auth::with_session(cua_auth::Session::new(
                cua_auth::Oidc::new("http://127.0.0.1:9", "cua-cli"),
                store,
            ))
        };
        // Both devices run on this machine: play a relay that ignores
        // machine ids (re-keying is cua-host's to test).
        relay.legacy_enrollment(true);
        let (d1, d2) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
        let mac = signed_in(d1.path())
            .devices(Some(relay.url.clone()), Some("MacBook".into()))
            .unwrap();
        let phone = signed_in(d2.path())
            .devices(Some(relay.url.clone()), Some("Phone".into()))
            .unwrap();
        assert_eq!(mac.device_id().unwrap(), None);
        // The first device enrolls at once; the second shows a code.
        let first = mac.enroll().await.unwrap();
        assert!(first.enrolled && first.code.is_none());
        assert_eq!(first.device.platform, std::env::consts::OS);
        assert!(mac.check_enrolled().await);
        let second = phone.enroll().await.unwrap();
        assert!(!second.enrolled);
        assert!(!phone.check_enrolled().await);
        let snap = mac.snapshot(50).await.unwrap();
        assert_eq!(snap.enforce_after, Some(1_900_000_000));
        assert_eq!(snap.devices.len(), 2);
        assert!(
            snap.devices
                .iter()
                .any(|d| d.current && d.name == "MacBook")
        );
        assert!(snap.audit.iter().any(|e| e.kind == "device_registered"));
        // A pending device cannot approve; the enrolled one can, by code.
        assert!(matches!(
            phone.approve(second.code.clone(), None).await.unwrap_err(),
            CuaError::PermissionDenied(_)
        ));
        let approved = mac.approve(second.code.clone(), None).await.unwrap();
        assert_eq!(approved.state, "enrolled");
        assert!(phone.check_enrolled().await);
        let phone_id = phone.device_id().unwrap().unwrap();
        assert_eq!(
            mac.rename(phone_id.clone(), "Work phone".into())
                .await
                .unwrap()
                .name,
            "Work phone"
        );
        assert_eq!(mac.revoke(phone_id.clone()).await.unwrap().state, "revoked");
        assert!(!phone.check_enrolled().await);
        // A revoked device enrolls again with a new key.
        let again = phone.enroll().await.unwrap();
        assert_ne!(again.device.id, phone_id);
        assert!(!again.enrolled && again.code.is_some());
    }

    #[test]
    fn setup_options_map_modes() {
        let o = setup_options(HostSetupOptions {
            mode: Some("direct".into()),
            direct: Some("10.0.0.2:4000".into()),
            ..Default::default()
        })
        .unwrap();
        assert_eq!(
            o.mode,
            cua_host::HostMode::Direct {
                listen: "10.0.0.2:4000".parse().unwrap()
            }
        );
        let o = setup_options(HostSetupOptions {
            relay_url: Some("https://relay.example".into()),
            allow: vec!["a@b".into()],
            runner: Some("process".into()),
            ..Default::default()
        })
        .unwrap();
        assert_eq!(
            o.mode,
            cua_host::HostMode::Relay {
                url: "https://relay.example".into()
            }
        );
        assert_eq!(o.runner, cua_host::RunnerKind::Process);
        assert!(o.share_desktop && !o.provide_spaces, "the desktop profile");
        // A spare machine, and each setting on its own.
        let o = setup_options(HostSetupOptions {
            profile: Some("spare".into()),
            ..Default::default()
        })
        .unwrap();
        assert!(!o.share_desktop && o.provide_spaces);
        let o = setup_options(HostSetupOptions {
            profile: Some("spare".into()),
            share_desktop: Some(true),
            ..Default::default()
        })
        .unwrap();
        assert!(o.share_desktop && o.provide_spaces);
        assert!(
            setup_options(HostSetupOptions {
                mode: Some("carrier-pigeon".into()),
                ..Default::default()
            })
            .is_err()
        );
        assert!(
            setup_options(HostSetupOptions {
                mode: Some("direct".into()),
                direct: Some("nope".into()),
                ..Default::default()
            })
            .is_err()
        );
    }

    #[tokio::test]
    async fn relay_lists_machines_from_the_directory() {
        let relay = cua_host::testing::FakeRelay::start().await;
        relay.add_account("tok", "user-1", None);
        cua_host::RelayClient::new(&relay.url)
            .unwrap()
            .register(
                "tok",
                &cua_host::relay::RegisterRequest {
                    id: "0123abcd4567ef89".into(),
                    name: "mini".into(),
                    allow: vec![],
                    host: None,
                    meta: Default::default(),
                },
            )
            .await
            .unwrap();
        let r = Relay::new(Some(relay.url.clone()), "tok".into()).unwrap();
        let machines = r.machines().await.unwrap();
        assert_eq!(machines.len(), 1);
        assert_eq!(machines[0].space_id, "relay:0123abcd4567ef89");
        assert_eq!(machines[0].role, "owner");
        let bad = Relay::new(Some(relay.url.clone()), "nope".into()).unwrap();
        assert!(matches!(
            bad.machines().await.unwrap_err(),
            CuaError::Unauthenticated(_)
        ));
    }
}