standard-plugin-sdk 0.1.1

Write Standard Code plugins in Rust: wasm components against standard:plugin@2.0.0
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
//! Run a plugin under `cargo test`, against an in-process host.
//!
//! On targets other than wasm, every SDK call goes to the thread's
//! [`MockHost`] instead of the WIT imports. The mock checks grants exactly
//! as the viewer's host does (both use `standard-plugin-manifest`), keeps
//! values, records what the plugin emitted and committed, and lays out
//! surfaces. [`Harness`] drives a [`UiPlugin`] the way a viewer does:
//! activate, resize, frames, events.
//!
//! ```rust,ignore
#![doc = include_str!("../tests/testing_harness.rs")]
//! ```

mod http;
mod machine;

pub(crate) use http::send as http_send;

pub use machine::{MockPaneLaunch, MockProcess, MockWatch, MockWebSocket, ProcessScript};

use alloc::collections::{BTreeMap, BTreeSet};
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::cell::RefCell;

use standard_plugin_manifest::{GrantDenied, Grants};

use crate::api::Target;
use crate::api::account::{AccountState, Pane};
use crate::api::capabilities::Capabilities;
use crate::api::view::Theme;
use crate::error::{Error, Result};
use crate::geometry::{Geometry, Rect};
use crate::surface::{HEADER_LEN, Model, RegionLayout};
use crate::ui_runtime::{Event, Power, UiPlugin, UiRuntime};

/// How a plugin made a call.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CallKind {
    /// `calls.call`: it waited for the answer.
    Wait,
    /// `calls.send`: nothing answers.
    Send,
    /// `calls.call-async` with this id; the answer is delivered by
    /// [`Harness::answer_calls`].
    Async(u64),
}

/// One call as the host saw it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MockCall {
    pub method: String,
    pub payload: String,
    pub target: Target,
    pub kind: CallKind,
    pub timeout_ms: Option<u32>,
    /// A `call-async` whose answer was delivered.
    pub answered: bool,
}

/// One commit as the host saw it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MockCommit {
    /// The header sequence number the region carried.
    pub seq: u32,
    pub slot: u8,
    /// The rectangles the plugin sent.
    pub dirty: Vec<Rect>,
    /// The host treats it as fully dirty (the first after an attach).
    pub full: bool,
    pub geometry: Geometry,
    pub model: Model,
    /// The whole region (header and both slots) at commit time.
    pub region: Vec<u8>,
}

impl MockCommit {
    /// The committed slot's bytes.
    pub fn slot_bytes(&self) -> &[u8] {
        let layout = RegionLayout::new(self.model, self.geometry);
        let start = (HEADER_LEN + u32::from(self.slot) * layout.slot_len) as usize;
        &self.region[start..start + layout.slot_len as usize]
    }
}

#[derive(Clone, Debug)]
struct MockSurface {
    model: Model,
    geometry: Geometry,
    /// Address and length of the attached region in this process.
    region: Option<(usize, usize)>,
    pending: Option<(usize, usize)>,
    committed_once: bool,
    commits: Vec<MockCommit>,
}

/// The in-process host. Build one, [`install`] it (or hand it to a
/// [`Harness`]), and inspect it after the plugin ran.
#[derive(Clone, Debug)]
pub struct MockHost {
    plugin_id: String,
    granted: Vec<String>,
    grants: Grants,
    pub config: String,
    pub values: BTreeMap<String, String>,
    pub secrets: BTreeMap<String, String>,
    pub account: AccountState,
    pub driving: bool,
    pub theme: Theme,
    pub capabilities: Capabilities,
    pub focused_pane: Option<String>,
    /// Claims another viewer holds: claiming these fails.
    pub claimed_elsewhere: BTreeSet<String>,
    /// Claims this instance holds.
    pub claims: BTreeSet<String>,
    /// `events.emit` calls: name, payload, target.
    pub emitted: Vec<(String, String, Target)>,
    /// `live.publish` calls: key, payload.
    pub published: Vec<(String, String)>,
    /// `live.delete` calls: the keys withdrawn, in order.
    pub live_deleted: Vec<String>,
    /// Patterns `events.on` registered.
    pub listening: BTreeSet<String>,
    /// `calls.call` and `call-async` answers by method (the companion's
    /// side); a method without one answers `invalid`.
    pub call_answers: BTreeMap<String, String>,
    /// Every `calls.call`, `send` and `call-async`, in order.
    pub calls: Vec<MockCall>,
    /// Grants the plugin was denied, in order.
    pub denials: Vec<String>,
    pub panes: Vec<Pane>,
    /// A frame the plugin asked for outside `frame()`
    /// ([`crate::Context::request_frame`] or `wake_at`): the earliest
    /// viewer instant, `0` for "the next frame".
    pub frame_request: Option<u64>,
    /// Surfaces `open` opened, in order.
    pub opened: Vec<String>,
    /// URLs `url::open` opened, in order.
    pub opened_urls: Vec<String>,
    /// Panes `focus_pane` asked the viewer to focus, in order.
    pub focused_panes: Vec<String>,
    /// The viewer clock of the last `Harness::frame`, for the `url.open`
    /// input window.
    pub now_ms: u64,
    /// When the last user input was delivered (`now_ms` then), until a URL
    /// opened for it.
    pub url_gesture_ms: Option<u64>,
    /// Surfaces `close` closed, in order.
    pub closed: Vec<String>,
    /// Whether the plugin is handling a user gesture now (the harness sets
    /// it around key, paste, pointer-press and command events).
    pub gesture: bool,
    /// The machine the plugin runs on: a daemon's `Context::machine_id`, a
    /// viewer's `view::machine_id`.
    pub machine_id: Option<String>,
    /// A daemon's `Context::account_id`.
    pub account_id: Option<String>,
    /// `daemon-context.lease-epoch`: a singleton's epoch, `None` for fleet
    /// (`MockHost::singleton`).
    pub lease_epoch: Option<u64>,
    /// The build `daemon::Context::release` reports.
    pub release: Option<crate::daemon::Release>,
    /// A viewer's `view::instance_id`.
    pub instance_id: String,
    /// A daemon plugin's environment (`daemon::env`).
    pub environment: Vec<(String, String)>,
    /// `view::wall_ms`: milliseconds since the Unix epoch.
    pub wall_ms: u64,
    /// `view::utc_offset_minutes`.
    pub utc_offset_minutes: i32,
    /// `view::time_zone`.
    pub time_zone: Option<String>,
    /// The plugin's last `health::set`: its state and message.
    pub health: Option<(crate::health::Health, String)>,
    /// Identity tints by machine or project id (`view::surface_tint`,
    /// `view::identity_tint`).
    pub tints: BTreeMap<String, u32>,
    /// Sizes the plugin asked for, by surface (`request_size`), bounded as
    /// the host bounds them.
    pub requested: BTreeMap<String, (u32, u32)>,
    /// Labels the plugin set, by surface (`set_label`).
    pub labels: BTreeMap<String, String>,
    /// Carets the plugin set, by surface (`set_caret`): column and row.
    pub carets: BTreeMap<String, (u32, u32)>,
    /// Declared surfaces instanced per machine (`machine.after`).
    machine_surfaces: BTreeSet<String>,
    /// Declared surfaces instanced per project (`project.after`).
    project_surfaces: BTreeSet<String>,
    surfaces: BTreeMap<String, MockSurface>,
    /// Children and watches (the daemon world).
    machine: machine::Machine,
    /// Scripted `daemon::http` (`MockHost::http`).
    http: http::MockHttp,
}

impl MockHost {
    /// A host for plugin `plugin_id` with no grants, not driving.
    pub fn new(plugin_id: &str) -> Self {
        Self {
            plugin_id: plugin_id.to_string(),
            granted: Vec::new(),
            grants: Grants::new(plugin_id, []),
            config: String::new(),
            values: BTreeMap::new(),
            secrets: BTreeMap::new(),
            account: AccountState::default(),
            driving: false,
            theme: Theme::default(),
            capabilities: Capabilities {
                graphics: false,
                kitty: false,
                frame_rate: 60,
                cell_px: (0, 0),
                pixel_scale: 1,
            },
            focused_pane: None,
            claimed_elsewhere: BTreeSet::new(),
            claims: BTreeSet::new(),
            emitted: Vec::new(),
            published: Vec::new(),
            live_deleted: Vec::new(),
            listening: BTreeSet::new(),
            call_answers: BTreeMap::new(),
            calls: Vec::new(),
            denials: Vec::new(),
            panes: Vec::new(),
            frame_request: None,
            opened: Vec::new(),
            focused_panes: Vec::new(),
            opened_urls: Vec::new(),
            now_ms: 0,
            url_gesture_ms: None,
            closed: Vec::new(),
            gesture: false,
            machine_id: None,
            account_id: None,
            lease_epoch: None,
            release: None,
            instance_id: "test-viewer".to_string(),
            environment: Vec::new(),
            wall_ms: 0,
            utc_offset_minutes: 0,
            time_zone: None,
            health: None,
            tints: BTreeMap::new(),
            requested: BTreeMap::new(),
            labels: BTreeMap::new(),
            carets: BTreeMap::new(),
            machine_surfaces: BTreeSet::new(),
            project_surfaces: BTreeSet::new(),
            surfaces: BTreeMap::new(),
            machine: machine::Machine::default(),
            http: http::MockHttp::default(),
        }
    }

    /// The viewer's wall clock and time zone.
    pub fn clock(mut self, wall_ms: u64, utc_offset_minutes: i32, time_zone: Option<&str>) -> Self {
        self.wall_ms = wall_ms;
        self.utc_offset_minutes = utc_offset_minutes;
        self.time_zone = time_zone.map(str::to_string);
        self
    }

    /// Runs a daemon plugin as a singleton under lease `epoch`.
    pub fn singleton(mut self, epoch: u64) -> Self {
        self.lease_epoch = Some(epoch);
        self
    }

    /// The machine the plugin runs on.
    pub fn machine(mut self, machine_id: &str) -> Self {
        self.machine_id = Some(machine_id.to_string());
        self
    }

    /// Sets one variable of a daemon plugin's environment.
    pub fn env(mut self, name: &str, value: &str) -> Self {
        self.environment.retain(|(key, _)| key != name);
        self.environment.push((name.to_string(), value.to_string()));
        self.environment.sort();
        self
    }

    /// Adds grants (the manifest's grant keys).
    pub fn grant(mut self, grants: &[&str]) -> Self {
        self.granted
            .extend(grants.iter().map(|grant| grant.to_string()));
        self.grants = Grants::new(&self.plugin_id, self.granted.iter().cloned());
        self
    }

    /// Declares a surface the way a manifest does, with no size yet.
    pub fn surface(mut self, id: &str, model: Model) -> Self {
        self.surfaces.insert(
            id.to_string(),
            MockSurface {
                model,
                geometry: Geometry::default(),
                region: None,
                pending: None,
                committed_once: false,
                commits: Vec::new(),
            },
        );
        self
    }

    /// Declares a `machine.after` surface: its instances are
    /// `<surface>@<machine>`.
    pub fn machine_surface(mut self, id: &str, model: Model) -> Self {
        self.machine_surfaces.insert(id.to_string());
        self.surface(id, model)
    }

    /// Declares a `project.after` surface: its instances are
    /// `<surface>@<project>`.
    pub fn project_surface(mut self, id: &str, model: Model) -> Self {
        self.project_surfaces.insert(id.to_string());
        self.surface(id, model)
    }

    pub fn driving(mut self, driving: bool) -> Self {
        self.driving = driving;
        self
    }

    /// Sets a surface's size, as the viewer's layout does. Returns the
    /// resize event to deliver (the [`Harness`] delivers it).
    pub fn set_geometry(&mut self, id: &str, geometry: Geometry) -> Option<Event> {
        if !self.surfaces.contains_key(id)
            && let Some((base, _pane)) = id.split_once('@')
            && let Some(template) = self.surfaces.get(base)
        {
            // A pane instance of a declared footer or header surface.
            let mut instance = template.clone();
            instance.geometry = Geometry::default();
            instance.region = None;
            instance.pending = None;
            instance.committed_once = false;
            instance.commits.clear();
            self.surfaces.insert(id.to_string(), instance);
        }
        let surface = self.surfaces.get_mut(id)?;
        if surface.geometry == geometry {
            return None;
        }
        surface.geometry = geometry;
        Some(Event::Resize {
            surface: id.to_string(),
            geometry,
        })
    }

    /// Switches the model the viewer uses for a surface that lists
    /// several: the plugin sees it as a resize.
    pub fn set_model(&mut self, id: &str, model: Model) -> Option<Event> {
        let surface = self.surfaces.get_mut(id)?;
        if surface.model == model {
            return None;
        }
        surface.model = model;
        surface.region = None;
        surface.pending = None;
        surface.committed_once = false;
        Some(Event::Resize {
            surface: id.to_string(),
            geometry: surface.geometry,
        })
    }

    /// Every commit of a surface, oldest first.
    pub fn commits(&self, id: &str) -> Vec<MockCommit> {
        self.surfaces
            .get(id)
            .map(|surface| surface.commits.clone())
            .unwrap_or_default()
    }

    /// The companion's answer to `method`, as a call gets it.
    fn answer(&self, method: &str) -> Result<String> {
        self.call_answers
            .get(method)
            .cloned()
            .ok_or_else(|| Error::Invalid(alloc::format!("unknown method {method:?}")))
    }

    /// The `call-async`s not answered yet, marked answered, each with the
    /// event that answers it.
    fn take_async_answers(&mut self) -> Vec<Event> {
        let mut events = Vec::new();
        for index in 0..self.calls.len() {
            let CallKind::Async(id) = self.calls[index].kind else {
                continue;
            };
            if self.calls[index].answered {
                continue;
            }
            self.calls[index].answered = true;
            let result = self.answer(&self.calls[index].method).map(crate::Json);
            events.push(Event::CallResult {
                id: crate::api::calls::CallId(id),
                result,
            });
        }
        events
    }

    fn deny(&mut self, denial: GrantDenied) -> Error {
        self.denials.push(denial.grant.clone());
        Error::GrantDenied {
            grant: denial.grant,
        }
    }

    fn check(&mut self, grant: &str) -> Result<()> {
        self.grants.check(grant).map_err(|denial| self.deny(denial))
    }

    fn check_namespaced(&mut self, kind: &str, subject: &str) -> Result<()> {
        self.grants
            .check_namespaced(kind, subject)
            .map_err(|denial| self.deny(denial))
    }
}

std::thread_local! {
    static MOCK: RefCell<Option<MockHost>> = const { RefCell::new(None) };
}

/// Makes `host` this thread's host. A thread without one gets
/// `MockHost::new("test-plugin")` on its first call.
pub fn install(host: MockHost) {
    MOCK.with(|mock| *mock.borrow_mut() = Some(host));
}

/// Runs `f` on this thread's host.
pub fn with_host<R>(f: impl FnOnce(&mut MockHost) -> R) -> R {
    MOCK.with(|mock| {
        let mut mock = mock.borrow_mut();
        f(mock.get_or_insert_with(|| MockHost::new("test-plugin")))
    })
}

/// Drives a [`UiPlugin`] as a viewer does, on this thread's [`MockHost`].
pub struct Harness<P: UiPlugin> {
    runtime: UiRuntime<P>,
}

impl<P: UiPlugin> Harness<P> {
    /// Installs `host` and activates the plugin with `config`.
    pub fn activate(host: MockHost, config: &str) -> Self {
        let mut host = host;
        host.config = config.to_string();
        install(host);
        let runtime = UiRuntime::new();
        runtime.activate(config.to_string());
        Self { runtime }
    }

    /// Lays a surface out at `geometry` and delivers the resize event.
    pub fn resize(&mut self, surface: &str, geometry: Geometry) {
        if let Some(event) = with_host(|host| host.set_geometry(surface, geometry)) {
            self.runtime.event(event);
        }
    }

    /// Calls `frame` with the paced interval and power state a viewer
    /// passes; returns when the plugin wants the next one.
    pub fn frame(&mut self, now_ms: u64, interval_ms: u32, power: Power) -> Option<u64> {
        with_host(|host| {
            host.frame_request = None;
            host.now_ms = now_ms;
        });
        self.runtime.frame(now_ms, interval_ms, power)
    }

    pub fn event(&mut self, event: Event) {
        let gesture = matches!(
            &event,
            Event::Key(_)
                | Event::Paste { .. }
                | Event::Command(_)
                | Event::Pointer(crate::Pointer {
                    kind: crate::PointerKind::Down,
                    ..
                })
        );
        with_host(|host| {
            host.gesture = gesture;
            if gesture {
                host.url_gesture_ms = Some(host.now_ms);
            }
        });
        self.runtime.event(event);
        with_host(|host| host.gesture = false);
    }

    /// Shows or hides a surface, as the viewer does when it places it.
    pub fn show(&mut self, surface: &str, visible: bool) {
        self.event(Event::Visibility {
            surface: surface.to_string(),
            visible,
        });
    }

    /// Changes what the viewer can show and tells the plugin.
    pub fn set_capabilities(&mut self, capabilities: Capabilities) {
        with_host(|host| host.capabilities = capabilities);
        self.event(Event::CapabilitiesChanged);
    }

    /// Changes the theme and tells the plugin.
    pub fn set_theme(&mut self, theme: Theme) {
        with_host(|host| host.theme = theme);
        self.event(Event::ThemeChanged);
    }

    /// Switches a multi-model surface to `model`, as the viewer does when
    /// its graphics support changes.
    pub fn set_model(&mut self, surface: &str, model: Model) {
        if let Some(event) = with_host(|host| host.set_model(surface, model)) {
            self.runtime.event(event);
        }
    }

    /// A key press on `surface`.
    pub fn key(&mut self, surface: &str, code: crate::KeyCode) {
        self.event(Event::Key(crate::Key::press(surface, code)));
    }

    /// Text pasted into `surface`.
    pub fn paste(&mut self, surface: &str, text: &str) {
        self.event(Event::Paste {
            surface: surface.to_string(),
            text: text.to_string(),
        });
    }

    /// A pointer event at `(x, y)` in the surface's units.
    pub fn pointer(&mut self, surface: &str, kind: crate::PointerKind, x: u32, y: u32) {
        let cell = with_host(|host| {
            host.surfaces
                .get(surface)
                .map_or((1, 1), |surface| match surface.model {
                    Model::Cells => (1, 1),
                    Model::Pixels => (
                        surface.geometry.cell_px_w.max(1),
                        surface.geometry.cell_px_h.max(1),
                    ),
                })
        });
        self.event(Event::Pointer(crate::Pointer {
            surface: surface.to_string(),
            x,
            y,
            col: x / cell.0,
            row: y / cell.1,
            button: if matches!(kind, crate::PointerKind::Move) {
                crate::Button::None
            } else {
                crate::Button::Left
            },
            kind,
            modifiers: crate::Modifiers::NONE,
        }));
    }

    /// Runs one of the manifest's commands.
    pub fn command(&mut self, id: &str) {
        self.event(Event::Command(id.to_string()));
    }

    /// Answers every `call-async` the plugin made so far from
    /// [`MockHost::call_answers`], delivering one
    /// [`Event::CallResult`] each, in order. Returns how many.
    pub fn answer_calls(&mut self) -> usize {
        let events = with_host(MockHost::take_async_answers);
        let count = events.len();
        for event in events {
            self.event(event);
        }
        count
    }

    /// The frame the plugin asked for from an event, and clears it.
    pub fn take_frame_request(&mut self) -> Option<u64> {
        with_host(|host| host.frame_request.take())
    }

    /// The plugin, to assert on its state.
    pub fn plugin<R>(&self, f: impl FnOnce(&mut P) -> R) -> R {
        self.runtime
            .with_plugin(f)
            .unwrap_or_else(|| panic!("the plugin is not active"))
    }

    pub fn commits(&self, surface: &str) -> Vec<MockCommit> {
        with_host(|host| host.commits(surface))
    }

    pub fn host<R>(&self, f: impl FnOnce(&mut MockHost) -> R) -> R {
        with_host(f)
    }

    pub fn deactivate(self) {
        self.runtime.deactivate();
    }
}

/// Drives a [`DaemonPlugin`](crate::daemon::DaemonPlugin) as `standardd`
/// would: activate, `drive` at the instants it asks for, events and calls.
pub struct DaemonHarness<P: crate::daemon::DaemonPlugin> {
    runtime: crate::daemon::runtime::DaemonRuntime<P>,
}

impl<P: crate::daemon::DaemonPlugin> DaemonHarness<P> {
    /// Installs `host` and activates the plugin with `config`.
    pub fn activate(host: MockHost, config: &str) -> Self {
        let mut host = host;
        host.config = config.to_string();
        install(host);
        let runtime = crate::daemon::runtime::DaemonRuntime::new();
        runtime.activate(config.to_string());
        Self { runtime }
    }

    /// Delivers what happened on the machine since the last drive (a
    /// scripted child's output and exit, file changes), then runs the
    /// plugin's tasks at `now_ms`; when it next wants to run.
    pub fn drive(&mut self, now_ms: u64) -> Option<u64> {
        loop {
            let pending = with_host(|host| host.machine.pending.pop_front());
            let Some(event) = pending else {
                break;
            };
            self.runtime.event(event);
        }
        self.runtime.drive(now_ms)
    }

    /// Output of a running child, as its piped stream carries it; delivered
    /// on the next [`DaemonHarness::drive`].
    pub fn output(&mut self, pid: u32, stderr: bool, bytes: &[u8]) {
        with_host(|host| host.output(pid, stderr, bytes));
    }

    /// A running child exits with `status`; delivered on the next drive.
    pub fn exit(&mut self, pid: u32, status: i32) {
        with_host(|host| host.exited(pid, status));
    }

    /// Something changed at `path`: every watch that covers it, at its
    /// depth and outside its exclude globs, hears it on the next drive.
    /// How many watches hear it.
    pub fn file_changed(&mut self, path: &str) -> usize {
        with_host(|host| host.changed(path))
    }

    /// The plugin, to assert on its state.
    pub fn plugin<R>(&self, f: impl FnOnce(&P) -> R) -> R {
        self.runtime
            .with_plugin(f)
            .unwrap_or_else(|| panic!("the plugin is not active"))
    }

    /// Delivers an event (drive afterwards to let the plugin see it).
    pub fn event(&mut self, event: Event) {
        self.runtime.event(event);
    }

    /// The account's viewers now show exactly `surfaces` of the plugin, as
    /// the host reports it (the [`INTEREST_EVENT`](crate::daemon::INTEREST_EVENT)
    /// plugin event); the plugin hears
    /// [`Event::Interest`](crate::Event::Interest) on the next drive when it
    /// changed. `&[]`: nobody looks.
    pub fn interest(&mut self, surfaces: &[&str]) {
        let payload = serde_json::json!({ "surfaces": surfaces }).to_string();
        self.runtime.event(Event::Plugin {
            name: crate::daemon::INTEREST_EVENT.to_string(),
            payload: crate::Json(payload),
        });
    }

    /// Calls the plugin's `call` handler as its UI half would.
    pub fn call(&mut self, method: &str, request: &str) -> Result<String> {
        self.call_from(method, request, crate::daemon::Caller::default())
    }

    /// Calls the plugin's `call` handler as `caller`.
    pub fn call_from(
        &mut self,
        method: &str,
        request: &str,
        caller: crate::daemon::Caller,
    ) -> Result<String> {
        self.runtime
            .handle_call(method, request.to_string(), caller)
    }

    pub fn host<R>(&self, f: impl FnOnce(&mut MockHost) -> R) -> R {
        with_host(f)
    }

    pub fn deactivate(self) {
        self.runtime.deactivate();
    }
}

/// The host calls, as `crate::host` names them.
pub(crate) mod host_calls {
    use super::*;

    /// The account service's rule for a value or live key's name (after
    /// `<namespace>.`): it starts with a letter, digit or `_`, then only
    /// those, `.`, `:`, `/` and `-`. The mock refuses what the account
    /// would, so a plugin's tests catch a key it could never write.
    fn check_key_name(key: &str) -> Result<()> {
        let name = key.split_once('.').map_or("", |(_, name)| name);
        let allowed =
            |c: char| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | ':' | '/' | '-');
        let first = name.chars().next();
        if first.is_some_and(|c| c.is_ascii_alphanumeric() || c == '_') && name.chars().all(allowed)
        {
            Ok(())
        } else {
            Err(Error::Invalid(alloc::format!(
                "{key:?}: a key is <namespace>.<name>, the name of letters, digits and _ . : / -"
            )))
        }
    }

    pub(crate) fn values_get(key: &str) -> Result<Option<String>> {
        with_host(|host| {
            host.check_namespaced("values.read", key)?;
            Ok(host.values.get(key).cloned())
        })
    }

    pub(crate) fn values_set(key: &str, value: &str) -> Result<()> {
        with_host(|host| {
            host.check_namespaced("values.write", key)?;
            check_key_name(key)?;
            host.values.insert(key.to_string(), value.to_string());
            Ok(())
        })
    }

    pub(crate) fn values_delete(key: &str) -> Result<()> {
        with_host(|host| {
            host.check_namespaced("values.write", key)?;
            host.values.remove(key);
            Ok(())
        })
    }

    pub(crate) fn values_keys(prefix: &str) -> Result<Vec<String>> {
        with_host(|host| {
            host.check_namespaced("values.read", prefix)?;
            Ok(host
                .values
                .keys()
                .filter(|key| key.starts_with(prefix))
                .cloned()
                .collect())
        })
    }

    pub(crate) fn values_watch(prefix: &str) -> Result<()> {
        with_host(|host| host.check_namespaced("values.read", prefix))
    }

    pub(crate) fn live_publish(key: &str, payload: &str) -> Result<()> {
        with_host(|host| {
            host.check_namespaced("live.publish", key)?;
            check_key_name(key)?;
            host.published.push((key.to_string(), payload.to_string()));
            Ok(())
        })
    }

    pub(crate) fn live_delete(key: &str) -> Result<()> {
        with_host(|host| {
            host.check_namespaced("live.publish", key)?;
            host.live_deleted.push(key.to_string());
            Ok(())
        })
    }

    pub(crate) fn live_subscribe(prefix: &str) -> Result<()> {
        with_host(|host| host.check_namespaced("live.subscribe", prefix))
    }

    pub(crate) fn live_unsubscribe(prefix: &str) -> Result<()> {
        with_host(|host| host.check_namespaced("live.subscribe", prefix))
    }

    pub(crate) fn events_emit(name: &str, payload: &str, to: &Target) -> Result<()> {
        with_host(|host| {
            if name.starts_with("system.") {
                return Err(host.deny(GrantDenied {
                    grant: alloc::format!("events.emit:{name}"),
                }));
            }
            host.check_namespaced("events.emit", name)?;
            host.emitted
                .push((name.to_string(), payload.to_string(), to.clone()));
            Ok(())
        })
    }

    pub(crate) fn events_on(pattern: &str) -> Result<()> {
        with_host(|host| {
            host.check_namespaced("events.on", pattern)?;
            host.listening.insert(pattern.to_string());
            Ok(())
        })
    }

    pub(crate) fn events_off(pattern: &str) -> Result<()> {
        with_host(|host| {
            host.check_namespaced("events.on", pattern)?;
            host.listening.remove(pattern);
            Ok(())
        })
    }

    fn record_call(
        host: &mut MockHost,
        method: &str,
        payload: &str,
        to: &Target,
        kind: CallKind,
        timeout_ms: Option<u32>,
    ) -> Result<()> {
        let own = alloc::format!("call:{}", host.grants.plugin_id());
        host.check(&own)?;
        host.calls.push(MockCall {
            method: method.to_string(),
            payload: payload.to_string(),
            target: to.clone(),
            kind,
            timeout_ms,
            answered: false,
        });
        Ok(())
    }

    pub(crate) fn call(
        method: &str,
        payload: &str,
        to: &Target,
        timeout_ms: Option<u32>,
    ) -> Result<String> {
        with_host(|host| {
            record_call(host, method, payload, to, CallKind::Wait, timeout_ms)?;
            host.answer(method)
        })
    }

    pub(crate) fn call_send(method: &str, payload: &str, to: &Target) -> Result<()> {
        with_host(|host| record_call(host, method, payload, to, CallKind::Send, None))
    }

    pub(crate) fn call_async(
        method: &str,
        payload: &str,
        to: &Target,
        timeout_ms: Option<u32>,
    ) -> Result<u64> {
        with_host(|host| {
            let id = host
                .calls
                .iter()
                .filter(|call| matches!(call.kind, CallKind::Async(_)))
                .count() as u64
                + 1;
            record_call(host, method, payload, to, CallKind::Async(id), timeout_ms)?;
            Ok(id)
        })
    }

    pub(crate) fn config() -> String {
        with_host(|host| host.config.clone())
    }

    pub(crate) fn health_set(health: crate::health::Health, message: &str) {
        with_host(|host| host.health = Some((health, message.to_string())));
    }

    pub(crate) fn secret(name: &str) -> Result<Option<String>> {
        with_host(|host| {
            host.check(&alloc::format!("secret:{name}"))?;
            Ok(host.secrets.get(name).cloned())
        })
    }

    pub(crate) fn account_state() -> Result<AccountState> {
        with_host(|host| {
            host.check("account.read")?;
            Ok(host.account.clone())
        })
    }

    pub(crate) fn account_watch() -> Result<()> {
        with_host(|host| host.check("account.read"))
    }

    pub(crate) fn claim(key: &str, _ttl_ms: u32) -> Result<bool> {
        with_host(|host| {
            if host.claimed_elsewhere.contains(key) {
                return Ok(false);
            }
            host.claims.insert(key.to_string());
            Ok(true)
        })
    }

    pub(crate) fn release(key: &str) -> Result<()> {
        with_host(|host| {
            host.claims.remove(key);
            Ok(())
        })
    }

    fn unknown(id: &str) -> Error {
        Error::Invalid(alloc::format!("no surface {id:?} in the manifest"))
    }

    pub(crate) fn surface_layout(id: &str) -> Result<RegionLayout> {
        with_host(|host| {
            let surface = host.surfaces.get(id).ok_or_else(|| unknown(id))?;
            Ok(RegionLayout::new(surface.model, surface.geometry))
        })
    }

    pub(crate) fn surface_attach(id: &str, region: &[u8]) -> Result<()> {
        with_host(|host| {
            let surface = host.surfaces.get_mut(id).ok_or_else(|| unknown(id))?;
            let layout = RegionLayout::new(surface.model, surface.geometry);
            if surface.geometry.is_empty() {
                return Err(Error::Invalid(alloc::format!(
                    "surface {id:?} has no size yet"
                )));
            }
            if region.len() < layout.len as usize {
                return Err(Error::Invalid("region too small".into()));
            }
            let word = |index: usize| {
                u32::from_le_bytes([
                    region[index * 4],
                    region[index * 4 + 1],
                    region[index * 4 + 2],
                    region[index * 4 + 3],
                ])
            };
            let g = surface.geometry;
            let expected = [
                match surface.model {
                    Model::Cells => 0,
                    Model::Pixels => 1,
                },
                g.cols,
                g.rows,
                g.px_w,
                g.px_h,
                g.cell_px_w,
                g.cell_px_h,
            ];
            if (1..8).any(|index| word(index) != expected[index - 1]) {
                return Err(Error::Invalid(
                    "region header does not describe the current layout".into(),
                ));
            }
            let bound = (region.as_ptr() as usize, region.len());
            if surface.region.is_none() {
                surface.region = Some(bound);
            } else {
                surface.pending = Some(bound);
            }
            Ok(())
        })
    }

    pub(crate) fn surface_commit(id: &str, slot: u8, dirty: &[Rect]) -> Result<()> {
        with_host(|host| {
            let surface = host.surfaces.get_mut(id).ok_or_else(|| unknown(id))?;
            if surface.region.is_none() && surface.pending.is_none() {
                return Err(Error::Invalid(alloc::format!(
                    "surface {id:?} has no region attached"
                )));
            }
            if slot > 1 {
                return Err(Error::Invalid("slot must be 0 or 1".into()));
            }
            let full = surface.pending.is_some() || !surface.committed_once;
            if let Some(pending) = surface.pending.take() {
                surface.region = Some(pending);
            }
            let Some((address, len)) = surface.region else {
                return Err(Error::Invalid("no region".into()));
            };
            // SAFETY: the SDK keeps an attached region alive until the
            // first commit after its replacement, the same guarantee the
            // viewer's host relies on to read guest memory; this is that
            // commit's region, read while the plugin is inside the call.
            let bytes = unsafe { core::slice::from_raw_parts(address as *const u8, len) };
            let seq = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
            surface.committed_once = true;
            surface.commits.push(MockCommit {
                seq,
                slot,
                dirty: dirty.to_vec(),
                full,
                geometry: surface.geometry,
                model: surface.model,
                region: bytes.to_vec(),
            });
            Ok(())
        })
    }

    pub(crate) fn surface_detach(id: &str) -> Result<()> {
        with_host(|host| {
            let surface = host.surfaces.get_mut(id).ok_or_else(|| unknown(id))?;
            surface.region = None;
            surface.pending = None;
            Ok(())
        })
    }

    pub(crate) fn is_driving() -> bool {
        with_host(|host| host.driving)
    }

    pub(crate) fn theme() -> Theme {
        with_host(|host| host.theme)
    }

    pub(crate) fn capabilities() -> Capabilities {
        with_host(|host| host.capabilities)
    }

    pub(crate) fn focused_pane() -> Option<String> {
        with_host(|host| host.focused_pane.clone())
    }

    /// The template and owner of an instance id (`<surface>@<owner>`).
    fn instance(surface: &str) -> Option<(&str, &str)> {
        surface
            .split_once('@')
            .filter(|(_, owner)| !owner.is_empty())
    }

    pub(crate) fn surface_machine(surface: &str) -> Option<String> {
        let (template, machine) = instance(surface)?;
        with_host(|host| host.machine_surfaces.contains(template)).then(|| machine.to_string())
    }

    pub(crate) fn surface_project(surface: &str) -> Option<String> {
        let (template, project) = instance(surface)?;
        with_host(|host| host.project_surfaces.contains(template)).then(|| project.to_string())
    }

    pub(crate) fn surface_tint(surface: &str) -> Option<u32> {
        if let Some(owner) = surface_machine(surface).or_else(|| surface_project(surface)) {
            return with_host(|host| host.tints.get(&owner).copied());
        }
        let pane = surface_pane(surface)?;
        with_host(|host| {
            let pane = host
                .account
                .panes
                .iter()
                .find(|known| known.id == pane.id)?;
            pane.project
                .as_ref()
                .and_then(|project| host.tints.get(project))
                .or_else(|| host.tints.get(&pane.machine))
                .copied()
        })
    }

    pub(crate) fn identity_tint(id: &str) -> Option<u32> {
        with_host(|host| host.tints.get(id).copied())
    }

    pub(crate) fn surface_request_size(id: &str, cols: u32, rows: u32) -> Result<()> {
        with_host(|host| {
            let known = host.surfaces.contains_key(id)
                || instance(id).is_some_and(|(template, _)| host.surfaces.contains_key(template));
            if !known {
                return Err(unknown(id));
            }
            host.requested
                .insert(id.to_string(), (cols.min(1024), rows.min(512)));
            Ok(())
        })
    }

    pub(crate) fn surface_set_label(id: &str, label: Option<&str>) -> Result<()> {
        with_host(|host| {
            let known = host.surfaces.contains_key(id)
                || instance(id).is_some_and(|(template, _)| host.surfaces.contains_key(template));
            if !known {
                return Err(unknown(id));
            }
            match label {
                Some(label)
                    if label.chars().count() > 48 || label.chars().any(char::is_control) =>
                {
                    return Err(crate::Error::Invalid(
                        "a label is at most 48 characters with no control characters".into(),
                    ));
                }
                Some(label) => {
                    host.labels.insert(id.to_string(), label.to_string());
                }
                None => {
                    host.labels.remove(id);
                }
            }
            Ok(())
        })
    }

    pub(crate) fn surface_set_caret(id: &str, caret: Option<(u32, u32)>) -> Result<()> {
        with_host(|host| {
            let known = host.surfaces.contains_key(id)
                || instance(id).is_some_and(|(template, _)| host.surfaces.contains_key(template));
            if !known {
                return Err(unknown(id));
            }
            match caret {
                Some(caret) => {
                    host.carets.insert(id.to_string(), caret);
                }
                None => {
                    host.carets.remove(id);
                }
            }
            Ok(())
        })
    }

    pub(crate) fn surface_pane(surface: &str) -> Option<crate::api::view::PaneRef> {
        let (template, pane) = instance(surface)?;
        if with_host(|host| {
            host.machine_surfaces.contains(template) || host.project_surfaces.contains(template)
        }) {
            return None;
        }
        let id = pane.to_string();
        let generation = with_host(|host| {
            host.account
                .panes
                .iter()
                .find(|pane| pane.id == id)
                .map_or(0, |pane| pane.generation)
        });
        Some(crate::api::view::PaneRef { id, generation })
    }

    pub(crate) fn machine_id() -> Option<String> {
        with_host(|host| host.machine_id.clone())
    }

    pub(crate) fn instance_id() -> String {
        with_host(|host| host.instance_id.clone())
    }

    pub(crate) fn wall_ms() -> u64 {
        with_host(|host| host.wall_ms)
    }

    pub(crate) fn utc_offset_minutes() -> i32 {
        with_host(|host| host.utc_offset_minutes)
    }

    pub(crate) fn time_zone() -> Option<String> {
        with_host(|host| host.time_zone.clone())
    }

    pub(crate) fn daemon_machine_id() -> String {
        with_host(|host| host.machine_id.clone().unwrap_or_default())
    }

    pub(crate) fn daemon_account_id() -> Option<String> {
        with_host(|host| host.account_id.clone())
    }

    pub(crate) fn daemon_lease_epoch() -> Option<u64> {
        with_host(|host| host.lease_epoch)
    }

    pub(crate) fn daemon_release() -> Option<crate::daemon::Release> {
        with_host(|host| host.release.clone())
    }

    pub(crate) fn daemon_environment() -> Vec<(String, String)> {
        with_host(|host| host.environment.clone())
    }

    pub(crate) fn request_frame() {
        wake_at(0);
    }

    pub(crate) fn wake_at(at_ms: u64) {
        with_host(|host| {
            host.frame_request = Some(host.frame_request.map_or(at_ms, |at| at.min(at_ms)));
        });
    }

    pub(crate) fn url_open(url: &str) -> Result<()> {
        use standard_plugin_manifest::url::{URL_OPEN_WINDOW_MS, https_host};
        with_host(|host| {
            let domain = https_host(url).map_err(Error::Invalid)?;
            if !host.grants.allows_url_open(&domain) {
                return Err(host.deny(GrantDenied {
                    grant: alloc::format!("url.open:{domain}"),
                }));
            }
            let now = host.now_ms;
            if !host
                .url_gesture_ms
                .is_some_and(|at| host.gesture || now.saturating_sub(at) <= URL_OPEN_WINDOW_MS)
            {
                return Err(Error::Invalid(
                    "url.open needs user input within the last second".into(),
                ));
            }
            host.url_gesture_ms = None;
            host.opened_urls.push(url.to_string());
            Ok(())
        })
    }

    pub(crate) fn surface_open(id: &str) -> Result<()> {
        with_host(|host| {
            if !host.surfaces.contains_key(id) {
                return Err(unknown(id));
            }
            if !host.gesture {
                return Err(Error::Invalid(
                    "surface.open needs a user gesture or a command".into(),
                ));
            }
            host.opened.push(id.to_string());
            Ok(())
        })
    }

    pub(crate) fn focus_pane(pane: &str) -> Result<()> {
        with_host(|host| {
            if !host.gesture {
                return Err(Error::Invalid(
                    "view.focus-pane needs a user gesture or a command".into(),
                ));
            }
            host.focused_panes.push(pane.to_string());
            Ok(())
        })
    }

    pub(crate) fn surface_close(id: &str) -> Result<()> {
        with_host(|host| {
            host.closed.push(id.to_string());
            Ok(())
        })
    }

    pub(crate) fn process_spawn(program: &str, args: &[String], cwd: Option<&str>) -> Result<u32> {
        let mut command = crate::daemon::process::Command::new(program);
        command.args = args.to_vec();
        command.cwd = cwd.map(ToString::to_string);
        with_host(|host| host.spawn(&command))
    }

    pub(crate) fn process_run(command: &crate::daemon::process::Command) -> Result<u32> {
        with_host(|host| host.spawn(command))
    }

    pub(crate) fn process_write(pid: u32, bytes: &[u8]) -> Result<()> {
        with_host(|host| host.write(pid, bytes))
    }

    pub(crate) fn process_close_stdin(pid: u32) -> Result<()> {
        with_host(|host| host.close_stdin(pid))
    }

    pub(crate) fn process_try_wait(pid: u32) -> Result<Option<i32>> {
        with_host(|host| host.try_wait(pid))
    }

    pub(crate) fn process_wait(pid: u32) -> Result<i32> {
        with_host(|host| host.wait(pid))
    }

    pub(crate) fn process_kill(pid: u32) -> Result<()> {
        with_host(|host| host.kill(pid))
    }

    pub(crate) fn watch(path: &str, options: &crate::daemon::watch::Options) -> Result<u32> {
        with_host(|host| host.watch(path, options.recursive, &options.exclude))
    }

    pub(crate) fn unwatch(handle: u32) -> Result<()> {
        with_host(|host| host.unwatch(handle))
    }

    pub(crate) fn websocket_open(url: &str, headers: &[(String, String)]) -> Result<u32> {
        with_host(|host| host.websocket_open(url, headers))
    }

    pub(crate) fn websocket_send(socket: u32, text: &str) -> Result<()> {
        with_host(|host| host.websocket_send(socket, text))
    }

    pub(crate) fn websocket_close(socket: u32) {
        with_host(|host| host.websocket_close(socket));
    }

    pub(crate) fn panes() -> Result<Vec<Pane>> {
        with_host(|host| {
            host.check("panes.read")?;
            Ok(host.panes.clone())
        })
    }

    pub(crate) fn pane_create(
        cwd: &str,
        command: Option<&str>,
        env: &[(String, String)],
    ) -> Result<(String, u64)> {
        with_host(|host| {
            host.check("panes.write")?;
            host.create_pane(cwd, command, env, None)
        })
    }

    pub(crate) fn pane_create_with(
        cwd: &str,
        command: Option<&str>,
        env: &[(String, String)],
        title: Option<&str>,
    ) -> Result<(String, u64)> {
        with_host(|host| {
            host.check("panes.write")?;
            host.create_pane(cwd, command, env, title)
        })
    }

    pub(crate) fn pane_input(_pane: &str, _bytes: &[u8]) -> Result<()> {
        with_host(|host| host.check("panes.write"))
    }

    pub(crate) fn pane_close(_pane: &str) -> Result<()> {
        with_host(|host| host.check("panes.write"))
    }

    pub(crate) fn panes_subscribe(_on: bool) -> Result<()> {
        with_host(|host| host.check("panes.read"))
    }

    pub(crate) fn pane_wait(_pane: &str, _timeout_ms: u32) -> Result<bool> {
        with_host(|host| {
            host.check("panes.read")?;
            Ok(true)
        })
    }
}