eov-plugin-api 1.0.0

The plugin API and SDK for eov, the whole-slide image viewer
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
//! Unit-test support for plugins: run a [`Plugin`] against an in-memory
//! mock host.
//!
//! ```
//! use eov_plugin_api::prelude::*;
//! use eov_plugin_api::testing::TestHarness;
//!
//! struct Counter {
//!     host: Host,
//! }
//!
//! impl Plugin for Counter {
//!     fn create(host: Host, _init: PluginInit) -> Result<Self, String> {
//!         Ok(Self { host })
//!     }
//!
//!     fn on_event(&self, event: HostEvent) -> Result<(), String> {
//!         if let HostEvent::FileOpened { file } = event {
//!             self.host.info(format!("opened {}", file.filename));
//!         }
//!         Ok(())
//!     }
//! }
//!
//! let harness = TestHarness::<Counter>::new().unwrap();
//! harness
//!     .send(HostEvent::FileOpened {
//!         file: FileInfo {
//!             file_id: 1,
//!             filename: "a.svs".into(),
//!             ..Default::default()
//!         },
//!     })
//!     .unwrap();
//! assert_eq!(harness.calls_to("log").len(), 1);
//! ```
//!
//! The mock answers every method the real host knows with a plausible
//! result, keeps layers, surfaces, settings and contributions in memory so
//! tests can inspect them, and records every call.

use crate::abi::{
    FfiError, FfiErrorKind, FfiResult, FilterFrame, FilterView, HostFfi, HostFfi_TO, Pixels,
    PluginBox, RasterUpload, RegionRequest,
};
use crate::protocol::{methods, *};
use crate::sdk::{Image, Plugin, create_plugin, slide_source_of};
use abi_stable::{
    sabi_trait::TD_Opaque,
    std_types::{RErr, ROk, RSliceMut, RStr, RString},
};
use serde::de::DeserializeOwned;
use serde_json::{Map, Value, json};
use std::collections::BTreeMap;
use std::marker::PhantomData;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};

/// One recorded host call.
#[derive(Debug, Clone, PartialEq)]
pub struct RecordedCall {
    pub method: String,
    pub args: Value,
}

/// A layer as the mock host stores it.
#[derive(Debug, Clone, PartialEq)]
pub struct MockLayer {
    pub spec: LayerSpec,
    pub objects: BTreeMap<String, OverlayObject>,
    pub rasters: BTreeMap<String, RasterUpload>,
    pub selection: Vec<String>,
    /// Panes the plugin hid the layer in (`layer.set_pane_visibility`).
    pub hidden_panes: std::collections::BTreeSet<PaneId>,
    /// Objects drawn highlighted (`layer.highlight`).
    pub highlighted: Vec<String>,
    /// The only panes showing the layer (`layer.set_panes`).
    pub only_panes: Option<Vec<PaneId>>,
}

/// A surface as the mock host stores it.
#[derive(Debug, Clone, PartialEq)]
pub struct MockSurface {
    pub spec: SurfaceSpec,
    pub properties: Map<String, Value>,
    pub open: bool,
}

type RegionReader = dyn Fn(&RegionRequest) -> Result<Image, String> + Send + Sync;

/// Everything the mock host knows. Tests may read and modify it freely.
#[derive(Default)]
pub struct MockState {
    pub calls: Vec<RecordedCall>,
    pub snapshot: HostSnapshot,
    pub properties: BTreeMap<FileId, PropertyMap>,
    pub settings: Map<String, Value>,
    pub layers: BTreeMap<String, MockLayer>,
    pub surfaces: BTreeMap<String, MockSurface>,
    pub toolbar_buttons: BTreeMap<String, ToolbarButtonSpec>,
    pub hud_buttons: BTreeMap<String, HudButtonSpec>,
    pub tools: BTreeMap<String, ToolSpec>,
    pub hotkeys: BTreeMap<String, HotkeySpec>,
    /// Badges by id: (slide, text).
    pub badges: BTreeMap<String, (Option<FileId>, String)>,
    /// Batch commands registered, by id.
    pub batch_commands: BTreeMap<String, BatchCommandSpec>,
    /// `batch.progress` calls, in order.
    pub batch_progress: Vec<BatchProgressArgs>,
    /// `batch.finish` calls, in order.
    pub batch_finished: Vec<BatchFinishArgs>,
    pub active_tool: Option<String>,
    pub filters: BTreeMap<String, FilterSpec>,
    pub undo: Vec<UndoPushArgs>,
    pub notifications: Vec<NotifyArgs>,
    pub status: Option<String>,
    pub clipboard: Option<String>,
    pub roi: BTreeMap<FileId, Rect>,
    pub measurements: Vec<MeasurementInfo>,
    /// What `view.display` answers.
    pub display: DisplayAdjustments,
    pub posted: Vec<String>,
    /// The model store: what `model.resolve` and `model.list` answer, by
    /// the SHA-256 of the main file (lower case). See
    /// [`MockState::add_model`].
    pub models: BTreeMap<String, ModelRecord>,
    /// `model.fetch` requests, in order, with the request id each was
    /// answered with. Answer them with [`TestHarness::finish_model_fetch`]
    /// or [`TestHarness::cancel_model_fetch`].
    pub model_fetches: Vec<(String, ModelFetchArgs)>,
    /// Serves `read_region`; without one a mid-grey opaque image is returned.
    pub region_reader: Option<Box<RegionReader>>,
    /// Methods that fail with [`FfiErrorKind::Unsupported`], to emulate an
    /// older host.
    pub unsupported: Vec<String>,
}

impl MockState {
    /// Puts a model in the mock's model store.
    pub fn add_model(&mut self, record: ModelRecord) {
        self.models
            .insert(record.sha256.to_ascii_lowercase(), record);
    }

    /// The arguments of every recorded call to `method`.
    pub fn calls_to(&self, method: &str) -> Vec<Value> {
        self.calls
            .iter()
            .filter(|call| call.method == method)
            .map(|call| call.args.clone())
            .collect()
    }

    /// Objects of a layer, in id order.
    pub fn objects(&self, layer_id: &str) -> Vec<OverlayObject> {
        self.layers
            .get(layer_id)
            .map(|layer| layer.objects.values().cloned().collect())
            .unwrap_or_default()
    }
}

/// The mock host object handed to the plugin.
#[derive(Clone)]
pub struct MockHost {
    state: Arc<Mutex<MockState>>,
    next_id: Arc<AtomicU64>,
}

impl Default for MockHost {
    fn default() -> Self {
        Self::new()
    }
}

impl MockHost {
    pub fn new() -> Self {
        Self {
            state: Arc::new(Mutex::new(MockState::default())),
            next_id: Arc::new(AtomicU64::new(1)),
        }
    }

    /// The shared state (poison-tolerant).
    pub fn state(&self) -> MutexGuard<'_, MockState> {
        self.state.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// The FFI object to pass to a plugin.
    pub fn to_ffi(&self) -> crate::abi::HostBox {
        HostFfi_TO::from_value(self.clone(), TD_Opaque)
    }

    fn fresh_id(&self, prefix: &str) -> String {
        format!("{prefix}-{}", self.next_id.fetch_add(1, Ordering::Relaxed))
    }

    fn handle(&self, method: &str, args: Value) -> Result<Value, FfiError> {
        let mut state = self.state();
        state.calls.push(RecordedCall {
            method: method.to_string(),
            args: args.clone(),
        });
        if state.unsupported.iter().any(|m| m == method) {
            return Err(FfiError::new(
                FfiErrorKind::Unsupported,
                format!("unknown method '{method}'"),
            ));
        }
        fn parse<T: DeserializeOwned>(args: Value) -> Result<T, FfiError> {
            serde_json::from_value(args)
                .map_err(|e| FfiError::new(FfiErrorKind::InvalidArguments, e.to_string()))
        }
        let null = Value::Null;
        Ok(match method {
            methods::LOG | methods::RENDER_REQUEST | methods::EVENTS_SUBSCRIBE => null,
            methods::NOTIFY => {
                let args: NotifyArgs = parse(args)?;
                state.notifications.push(args);
                null
            }
            methods::STATUS => {
                let args: StatusArgs = parse(args)?;
                state.status = args.text;
                null
            }
            methods::SNAPSHOT => json!(state.snapshot),
            methods::FILE_INFO => {
                let args: FileArgs = parse(args)?;
                let file =
                    state.snapshot.file(args.file_id).cloned().ok_or_else(|| {
                        FfiError::failed(format!("no open file {}", args.file_id))
                    })?;
                json!(file)
            }
            methods::FILE_PROPERTIES => {
                let args: FileArgs = parse(args)?;
                json!(
                    state
                        .properties
                        .get(&args.file_id)
                        .cloned()
                        .unwrap_or_default()
                )
            }
            methods::FILE_OPEN => null,
            methods::TOOLBAR_ADD => {
                let spec: ToolbarButtonSpec = parse(args)?;
                state.toolbar_buttons.insert(spec.button_id.clone(), spec);
                null
            }
            methods::TOOLBAR_UPDATE => {
                let update: ButtonUpdate = parse(args)?;
                let button = state
                    .toolbar_buttons
                    .get_mut(&update.button_id)
                    .ok_or_else(|| FfiError::failed("unknown toolbar button"))?;
                if let Some(active) = update.active {
                    button.active = active;
                }
                if let Some(enabled) = update.enabled {
                    button.enabled = enabled;
                }
                if let Some(tooltip) = update.tooltip {
                    button.tooltip = tooltip;
                }
                if let Some(icon) = update.icon_svg {
                    button.icon_svg = icon;
                }
                null
            }
            methods::TOOLBAR_REMOVE => {
                let args: IdArgs = parse(args)?;
                state.toolbar_buttons.remove(&args.id);
                null
            }
            methods::HUD_ADD => {
                let spec: HudButtonSpec = parse(args)?;
                state.hud_buttons.insert(spec.button_id.clone(), spec);
                null
            }
            methods::HUD_UPDATE => {
                let update: ButtonUpdate = parse(args)?;
                let button = state
                    .hud_buttons
                    .get_mut(&update.button_id)
                    .ok_or_else(|| FfiError::failed("unknown HUD button"))?;
                if let Some(active) = update.active {
                    button.active = active;
                }
                if let Some(menu) = update.menu {
                    button.menu = menu;
                }
                null
            }
            methods::HUD_REMOVE => {
                let args: IdArgs = parse(args)?;
                state.hud_buttons.remove(&args.id);
                null
            }
            methods::BATCH_REGISTER => {
                let spec: BatchCommandSpec = parse(args)?;
                state.batch_commands.insert(spec.command_id.clone(), spec);
                null
            }
            methods::BATCH_PROGRESS => {
                state.batch_progress.push(parse(args)?);
                null
            }
            methods::BATCH_FINISH => {
                state.batch_finished.push(parse(args)?);
                null
            }
            methods::BADGE_SET => {
                let args: BadgeArgs = parse(args)?;
                match args.text {
                    Some(text) => {
                        state.badges.insert(args.badge_id, (args.file_id, text));
                    }
                    None => {
                        state.badges.remove(&args.badge_id);
                    }
                }
                null
            }
            methods::HOTKEY_REGISTER => {
                let spec: HotkeySpec = parse(args)?;
                state.hotkeys.insert(spec.hotkey_id.clone(), spec);
                null
            }
            methods::HOTKEY_UNREGISTER => {
                let args: IdArgs = parse(args)?;
                state.hotkeys.remove(&args.id);
                null
            }
            methods::TOOL_REGISTER => {
                let spec: ToolSpec = parse(args)?;
                state.tools.insert(spec.tool_id.clone(), spec);
                null
            }
            methods::TOOL_UNREGISTER => {
                let args: IdArgs = parse(args)?;
                state.tools.remove(&args.id);
                if state.active_tool.as_deref() == Some(args.id.as_str()) {
                    state.active_tool = None;
                }
                null
            }
            methods::TOOL_ACTIVATE => {
                let args: IdArgs = parse(args)?;
                if !state.tools.contains_key(&args.id) {
                    return Err(FfiError::failed(format!("unknown tool '{}'", args.id)));
                }
                state.active_tool = Some(args.id);
                null
            }
            methods::TOOL_DEACTIVATE => {
                state.active_tool = None;
                null
            }
            methods::LAYER_CREATE => {
                let spec: LayerSpec = parse(args)?;
                state.layers.insert(
                    spec.layer_id.clone(),
                    MockLayer {
                        spec,
                        objects: BTreeMap::new(),
                        rasters: BTreeMap::new(),
                        selection: Vec::new(),
                        hidden_panes: Default::default(),
                        highlighted: Vec::new(),
                        only_panes: None,
                    },
                );
                null
            }
            methods::LAYER_UPDATE => {
                let update: LayerUpdate = parse(args)?;
                let layer = layer_mut(&mut state, &update.layer_id)?;
                if let Some(visible) = update.visible {
                    layer.spec.visible = visible;
                }
                if let Some(opacity) = update.opacity {
                    layer.spec.opacity = opacity;
                }
                if let Some(name) = update.name {
                    layer.spec.name = name;
                }
                if let Some(z) = update.z {
                    layer.spec.z = z;
                }
                if let Some(style) = update.style {
                    layer.spec.style = style;
                }
                null
            }
            methods::LAYER_REMOVE => {
                let args: IdArgs = parse(args)?;
                state.layers.remove(&args.id);
                null
            }
            methods::LAYER_HIGHLIGHT => {
                let args: SelectArgs = parse(args)?;
                layer_mut(&mut state, &args.layer_id)?.highlighted = args.object_ids;
                null
            }
            methods::LAYER_SET_MIN_ZOOM => {
                let args: MinZoomArgs = parse(args)?;
                layer_mut(&mut state, &args.layer_id)?.spec.min_zoom = args.min_zoom;
                null
            }
            methods::LAYER_SET_PANES => {
                let args: PaneFilterArgs = parse(args)?;
                layer_mut(&mut state, &args.layer_id)?.only_panes = args.panes;
                null
            }
            methods::LAYER_SET_PANE_VISIBILITY => {
                let args: PaneVisibilityArgs = parse(args)?;
                let layer = layer_mut(&mut state, &args.layer_id)?;
                if args.visible {
                    layer.hidden_panes.remove(&args.pane);
                } else {
                    layer.hidden_panes.insert(args.pane);
                }
                null
            }
            methods::VIEW_DISPLAY => json!(state.display),
            methods::LAYER_SELECT => {
                let args: SelectArgs = parse(args)?;
                layer_mut(&mut state, &args.layer_id)?.selection = args.object_ids;
                null
            }
            methods::LAYER_UPSERT => {
                let args: UpsertObjectsArgs = parse(args)?;
                if let Some(bad) = args.objects.iter().find(|o| !o.shape.is_valid()) {
                    return Err(FfiError::new(
                        FfiErrorKind::InvalidArguments,
                        format!("object '{}' has an invalid shape", bad.object_id),
                    ));
                }
                let layer = layer_mut(&mut state, &args.layer_id)?;
                if args.replace_all {
                    layer.objects.clear();
                    layer.rasters.clear();
                }
                for object in args.objects {
                    layer.objects.insert(object.object_id.clone(), object);
                }
                null
            }
            methods::LAYER_REMOVE_OBJECTS => {
                let args: RemoveObjectsArgs = parse(args)?;
                let layer = layer_mut(&mut state, &args.layer_id)?;
                for id in &args.object_ids {
                    layer.objects.remove(id);
                    layer.rasters.remove(id);
                }
                layer.selection.retain(|id| !args.object_ids.contains(id));
                null
            }
            methods::LAYER_CLEAR => {
                let args: IdArgs = parse(args)?;
                let layer = layer_mut(&mut state, &args.id)?;
                layer.objects.clear();
                layer.rasters.clear();
                layer.selection.clear();
                null
            }
            methods::SURFACE_OPEN => {
                let spec: SurfaceSpec = parse(args)?;
                drop(state);
                let surface_id = self.fresh_id("surface");
                let mut state = self.state();
                if spec.kind == SurfaceKind::Sidebar {
                    // One sidebar at a time, as in the real host.
                    for surface in state.surfaces.values_mut() {
                        if surface.spec.kind == SurfaceKind::Sidebar {
                            surface.open = false;
                        }
                    }
                }
                state.surfaces.insert(
                    surface_id.clone(),
                    MockSurface {
                        properties: spec.properties.clone(),
                        spec,
                        open: true,
                    },
                );
                json!(SurfaceOpened { surface_id })
            }
            methods::SURFACE_SET => {
                let args: SurfaceProperties = parse(args)?;
                let surface = state
                    .surfaces
                    .get_mut(&args.surface_id)
                    .filter(|s| s.open)
                    .ok_or_else(|| FfiError::failed("surface is not open"))?;
                surface.properties.extend(args.properties);
                null
            }
            methods::SURFACE_CLOSE => {
                let args: IdArgs = parse(args)?;
                if let Some(surface) = state.surfaces.get_mut(&args.id) {
                    surface.open = false;
                }
                null
            }
            methods::SURFACE_IS_OPEN => {
                let args: IdArgs = parse(args)?;
                json!(state.surfaces.get(&args.id).is_some_and(|s| s.open))
            }
            methods::DIALOG_CONFIRM | methods::DIALOG_OPEN_FILE | methods::DIALOG_SAVE_FILE => {
                drop(state);
                json!(RequestId {
                    request_id: self.fresh_id("request"),
                })
            }
            methods::VIEW_SET
            | methods::VIEW_PAN
            | methods::VIEW_ZOOM
            | methods::VIEW_FIT
            | methods::VIEW_FRAME
            | methods::VIEW_ORIENTATION
            | methods::APP_CYCLE_PANE
            | methods::APP_CYCLE_TAB
            | methods::APP_SERIES => null,
            methods::UNDO_PUSH => {
                let args: UndoPushArgs = parse(args)?;
                state.undo.push(args);
                null
            }
            methods::UNDO_CLEAR => {
                let args: UndoClearArgs = parse(args)?;
                match args.file_id {
                    Some(file_id) => state.undo.retain(|e| e.file_id != Some(file_id)),
                    None => state.undo.clear(),
                }
                null
            }
            methods::FILTER_REGISTER => {
                let spec: FilterSpec = parse(args)?;
                state.filters.insert(spec.filter_id.clone(), spec);
                null
            }
            methods::FILTER_SET_ENABLED => {
                let args: FilterEnableArgs = parse(args)?;
                state
                    .filters
                    .get_mut(&args.filter_id)
                    .ok_or_else(|| FfiError::failed("unknown filter"))?
                    .enabled = args.enabled;
                null
            }
            methods::FILTER_UNREGISTER => {
                let args: IdArgs = parse(args)?;
                state.filters.remove(&args.id);
                null
            }
            methods::SETTINGS_GET => {
                let args: KeyArgs = parse(args)?;
                state
                    .settings
                    .get(&args.key)
                    .cloned()
                    .unwrap_or(Value::Null)
            }
            methods::SETTINGS_SET => {
                let args: SettingsSetArgs = parse(args)?;
                if args.value.is_null() {
                    state.settings.remove(&args.key);
                } else {
                    state.settings.insert(args.key, args.value);
                }
                null
            }
            methods::JOB_START => {
                drop(state);
                json!(JobStarted {
                    job_id: self.fresh_id("job"),
                })
            }
            methods::JOB_UPDATE | methods::JOB_FINISH => null,
            methods::CLIPBOARD_SET_TEXT => {
                let args: TextArgs = parse(args)?;
                state.clipboard = Some(args.text);
                null
            }
            methods::ROI_GET => {
                let args: FileArgs = parse(args)?;
                json!(state.roi.get(&args.file_id))
            }
            methods::MEASUREMENTS_LIST => {
                let args: FileArgs = parse(args)?;
                json!(
                    state
                        .measurements
                        .iter()
                        .filter(|m| m.file_id == args.file_id)
                        .collect::<Vec<_>>()
                )
            }
            methods::POST => {
                let args: PostArgs = parse(args)?;
                state.posted.push(args.token);
                null
            }
            methods::MODEL_FETCH => {
                let args: ModelFetchArgs = parse(args)?;
                args.validate()
                    .map_err(|e| FfiError::new(FfiErrorKind::InvalidArguments, e))?;
                drop(state);
                let request_id = self.fresh_id("model");
                self.state().model_fetches.push((request_id.clone(), args));
                json!(RequestId { request_id })
            }
            methods::MODEL_RESOLVE => {
                let args: ModelResolveArgs = parse(args)?;
                if !is_sha256_hex(&args.sha256) {
                    return Err(FfiError::new(
                        FfiErrorKind::InvalidArguments,
                        "sha256 must be 64 hex digits",
                    ));
                }
                json!(state.models.get(&args.sha256.to_ascii_lowercase()))
            }
            methods::MODEL_LIST => json!(state.models.values().collect::<Vec<_>>()),
            other => {
                return Err(FfiError::new(
                    FfiErrorKind::Unsupported,
                    format!("unknown method '{other}'"),
                ));
            }
        })
    }
}

fn layer_mut<'a>(state: &'a mut MockState, layer_id: &str) -> Result<&'a mut MockLayer, FfiError> {
    state
        .layers
        .get_mut(layer_id)
        .ok_or_else(|| FfiError::failed(format!("unknown layer '{layer_id}'")))
}

impl HostFfi for MockHost {
    fn call(&self, method: RStr<'_>, args_json: RStr<'_>) -> FfiResult<RString> {
        let args: Value = match serde_json::from_str(args_json.as_str()) {
            Ok(args) => args,
            Err(e) => {
                return RErr(FfiError::new(FfiErrorKind::InvalidArguments, e.to_string()));
            }
        };
        match self.handle(method.as_str(), args) {
            Ok(value) => ROk(RString::from(value.to_string())),
            Err(error) => RErr(error),
        }
    }

    fn read_region(&self, request: RegionRequest) -> FfiResult<Pixels> {
        let pixels = u64::from(request.width) * u64::from(request.height);
        if pixels > crate::abi::MAX_REGION_PIXELS {
            return RErr(FfiError::new(
                FfiErrorKind::InvalidArguments,
                "region too large",
            ));
        }
        let state = self.state();
        let image = match &state.region_reader {
            Some(reader) => match reader(&request) {
                Ok(image) => image,
                Err(e) => return RErr(FfiError::failed(e)),
            },
            None => Image {
                width: request.width,
                height: request.height,
                data: [128, 128, 128, 255].repeat(pixels as usize),
            },
        };
        ROk(Pixels {
            width: image.width,
            height: image.height,
            data: image.data.into(),
        })
    }

    fn read_associated_image(&self, _file_id: i64, name: RStr<'_>) -> FfiResult<Pixels> {
        RErr(FfiError::failed(format!(
            "no associated image '{}'",
            name.as_str()
        )))
    }

    fn put_raster(&self, raster: RasterUpload) -> FfiResult<()> {
        if !raster.pixels.is_well_formed() {
            return RErr(FfiError::new(
                FfiErrorKind::InvalidArguments,
                "raster size does not match its data",
            ));
        }
        let mut state = self.state();
        let layer_id = raster.layer_id.to_string();
        match layer_mut(&mut state, &layer_id) {
            Ok(layer) => {
                layer.rasters.insert(raster.object_id.to_string(), raster);
                ROk(())
            }
            Err(e) => RErr(e),
        }
    }
}

/// Default init for tests: unique, writable temporary directories.
pub fn test_init(plugin_id: &str) -> PluginInit {
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let root = std::env::temp_dir().join(format!(
        "eov-plugin-test-{}-{}",
        std::process::id(),
        COUNTER.fetch_add(1, Ordering::Relaxed)
    ));
    let data_dir = root.join("data");
    let cache_dir = root.join("cache");
    let _ = std::fs::create_dir_all(&data_dir);
    let _ = std::fs::create_dir_all(&cache_dir);
    PluginInit {
        plugin_id: plugin_id.to_string(),
        plugin_version: "0.0.0".to_string(),
        host_name: "eov".to_string(),
        host_version: crate::abi::API_VERSION.to_string(),
        api_version: crate::abi::API_VERSION.to_string(),
        plugin_root: root.to_string_lossy().into_owned(),
        data_dir: data_dir.to_string_lossy().into_owned(),
        cache_dir: cache_dir.to_string_lossy().into_owned(),
        settings: Map::new(),
        legacy_config_dir: None,
        headless: false,
    }
}

/// Drives a plugin through the same FFI adapter the host uses.
pub struct TestHarness<P: Plugin> {
    host: MockHost,
    instance: PluginBox,
    _plugin: PhantomData<fn() -> P>,
}

impl<P: Plugin> TestHarness<P> {
    pub fn new() -> Result<Self, String> {
        Self::with_init(test_init("test_plugin"))
    }

    pub fn with_init(init: PluginInit) -> Result<Self, String> {
        Self::with_host(MockHost::new(), init)
    }

    /// Uses a prepared mock (e.g. with a snapshot or region reader set).
    pub fn with_host(host: MockHost, init: PluginInit) -> Result<Self, String> {
        let init_json = serde_json::to_string(&init).map_err(|e| e.to_string())?;
        let instance =
            create_plugin::<P>(host.to_ffi(), &init_json).map_err(|e| e.message.into_string())?;
        Ok(Self {
            host,
            instance,
            _plugin: PhantomData,
        })
    }

    pub fn host(&self) -> &MockHost {
        &self.host
    }

    pub fn state(&self) -> MutexGuard<'_, MockState> {
        self.host.state()
    }

    /// The arguments of every call to `method` so far.
    pub fn calls_to(&self, method: &str) -> Vec<Value> {
        self.state().calls_to(method)
    }

    /// Delivers an event; returns the plugin's JSON response.
    pub fn send(&self, event: HostEvent) -> Result<Value, FfiError> {
        let json = serde_json::to_string(&event).map_err(|e| FfiError::failed(e.to_string()))?;
        let reply = self
            .instance
            .handle_event(RStr::from_str(&json))
            .into_result()?;
        serde_json::from_str(reply.as_str()).map_err(|e| FfiError::failed(e.to_string()))
    }

    /// Requests context-menu items.
    pub fn context_menu(&self, context: MenuContext) -> Result<Vec<MenuItem>, FfiError> {
        let reply = self.send(HostEvent::ContextMenuRequested(context))?;
        let response: ContextMenuResponse =
            serde_json::from_value(reply).map_err(|e| FfiError::failed(e.to_string()))?;
        Ok(response.items)
    }

    /// Invokes a surface callback.
    /// Opens a slide through the plugin's slide source as eov does, through
    /// the FFI: what [`TestSlide`] returns is what eov would get.
    pub fn open_slide(&self, request: &SlideOpenRequest) -> Result<TestSlide, FfiError> {
        let source = slide_source_of::<P>(&self.instance).into_result()?;
        let json = serde_json::to_string(request).map_err(|e| FfiError::failed(e.to_string()))?;
        let slide = source.open(RStr::from_str(&json)).into_result()?;
        Ok(TestSlide { slide })
    }

    pub fn ui_callback(
        &self,
        surface_id: &str,
        name: &str,
        args: Vec<Value>,
    ) -> Result<Value, FfiError> {
        self.send(HostEvent::UiCallback {
            surface_id: surface_id.to_string(),
            name: name.to_string(),
            args,
        })
    }

    /// The last `model.fetch` request: the request id it was answered with
    /// and its arguments.
    pub fn last_model_fetch(&self) -> Option<(String, ModelFetchArgs)> {
        self.state().model_fetches.last().cloned()
    }

    /// Answers the `model.fetch` request `request_id` as eov does: with the
    /// stored model (which then also goes into the mock's model store, so
    /// `model.resolve` finds it) or with the error eov reported.
    pub fn finish_model_fetch(
        &self,
        request_id: &str,
        outcome: Result<ModelRecord, String>,
    ) -> Result<Value, FfiError> {
        let event = match outcome {
            Ok(record) => {
                self.state().add_model(record.clone());
                HostEvent::ModelFetched {
                    request_id: request_id.to_string(),
                    path: Some(record.path.clone()),
                    model: Some(record),
                    error: None,
                    cancelled: false,
                }
            }
            Err(error) => HostEvent::ModelFetched {
                request_id: request_id.to_string(),
                path: None,
                model: None,
                error: Some(error),
                cancelled: false,
            },
        };
        self.send(event)
    }

    /// Answers `request_id` as eov does when the user declines or cancels
    /// the download.
    pub fn cancel_model_fetch(&self, request_id: &str) -> Result<Value, FfiError> {
        self.send(HostEvent::ModelFetched {
            request_id: request_id.to_string(),
            path: None,
            model: None,
            error: Some("The download was cancelled.".to_string()),
            cancelled: true,
        })
    }

    /// Runs a filter over a tightly packed RGBA buffer.
    pub fn apply_filter(
        &self,
        filter_id: &str,
        pixels: &mut [u8],
        width: u32,
        height: u32,
        view: FilterView,
    ) -> Result<(), FfiError> {
        self.instance
            .apply_filter(
                RStr::from_str(filter_id),
                FilterFrame {
                    pixels: RSliceMut::from_mut_slice(pixels),
                    width,
                    height,
                    stride: width * 4,
                    view,
                },
            )
            .into_result()
    }
}

impl<P: Plugin> Drop for TestHarness<P> {
    fn drop(&mut self) {
        self.instance.shutdown();
    }
}

/// A slide opened with [`TestHarness::open_slide`].
pub struct TestSlide {
    slide: crate::abi::SlideBox,
}

impl TestSlide {
    /// The slide's metadata, checked as eov checks it.
    pub fn info(&self) -> Result<SlideInfo, String> {
        let json = self
            .slide
            .info()
            .into_result()
            .map_err(|e| e.message.into_string())?;
        let info: SlideInfo = serde_json::from_str(json.as_str()).map_err(|e| e.to_string())?;
        info.validate()?;
        Ok(info)
    }

    /// The RGBA pixels of `region`, read into a zeroed buffer as eov reads
    /// them.
    pub fn read_region(&self, region: crate::abi::SlideRegion) -> Result<Vec<u8>, FfiError> {
        let mut out = vec![0u8; region.width as usize * region.height as usize * 4];
        self.slide
            .read_region(
                region,
                abi_stable::std_types::RSliceMut::from_mut_slice(&mut out),
            )
            .into_result()?;
        Ok(out)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sdk::{Frame, Host};

    struct Probe {
        host: Host,
    }

    impl Plugin for Probe {
        fn create(host: Host, init: PluginInit) -> Result<Self, String> {
            if init.plugin_id == "refuse" {
                return Err("refused".into());
            }
            host.add_toolbar_button(ToolbarButtonSpec {
                button_id: "go".into(),
                tooltip: "Go".into(),
                icon_svg: "<svg/>".into(),
                ..Default::default()
            })
            .map_err(String::from)?;
            Ok(Self { host })
        }

        fn on_event(&self, event: HostEvent) -> Result<(), String> {
            match event {
                HostEvent::ToolbarButtonClicked { button_id } if button_id == "panic" => {
                    panic!("boom")
                }
                HostEvent::ToolbarButtonClicked { .. } => {
                    let layer = self
                        .host
                        .create_layer(LayerSpec::new("cells", 1).named("Cells").interactive(true))
                        .map_err(String::from)?;
                    layer
                        .upsert(vec![OverlayObject::new(
                            "c1",
                            Shape::Point { x: 1.0, y: 2.0 },
                        )])
                        .map_err(String::from)?;
                    Ok(())
                }
                HostEvent::FileClosed { .. } => Err("cannot close".into()),
                _ => Ok(()),
            }
        }

        fn context_menu(&self, context: &MenuContext) -> Vec<MenuItem> {
            vec![MenuItem {
                item_id: format!("at-{}", context.image_x),
                label: "Here".into(),
                ..Default::default()
            }]
        }

        fn ui_callback(&self, _surface: &str, name: &str, args: &[Value]) -> Result<Value, String> {
            Ok(json!({ "name": name, "argc": args.len() }))
        }

        fn apply_filter(&self, _filter_id: &str, frame: &mut Frame<'_>) -> Result<(), String> {
            frame.for_each_pixel(|_, _, px| px[0] = 255 - px[0]);
            Ok(())
        }
    }

    fn view() -> ViewInfo {
        ViewInfo {
            pane: 1,
            file_id: 1,
            zoom: 1.0,
            ..Default::default()
        }
    }

    #[test]
    fn layers_take_min_zoom_and_pane_visibility() {
        use crate::sdk::{Host, Image};
        let mock = MockHost::new();
        let host = Host::from_ffi(mock.to_ffi());
        host.create_layer(LayerSpec::new("heat", 1)).unwrap();
        let layer = host.layer("heat");
        layer.set_min_zoom(Some(0.25)).unwrap();
        layer.set_visible_in_pane(3, false).unwrap();
        let rect = Rect {
            x: 0.0,
            y: 0.0,
            width: 10.0,
            height: 10.0,
        };
        let blank = Image {
            width: 2,
            height: 2,
            data: vec![0; 16],
        };
        layer.put_raster("map", rect, blank, false).unwrap();
        let state = mock.state();
        let mock_layer = &state.layers["heat"];
        assert_eq!(mock_layer.spec.min_zoom, Some(0.25));
        assert!(mock_layer.hidden_panes.contains(&3));
        assert!(mock_layer.rasters.contains_key("map"));
        drop(state);
        assert_eq!(host.display_adjustments(None).unwrap().gamma, 1.0);
    }

    #[test]
    fn hotkeys_badges_and_highlights_reach_the_host() {
        use crate::sdk::Host;
        let mock = MockHost::new();
        let host = Host::from_ffi(mock.to_ffi());
        host.register_hotkey(HotkeySpec {
            hotkey_id: "next".into(),
            hotkey: Hotkey::key("j"),
            description: "Next object".into(),
        })
        .unwrap();
        host.set_badge("predicted", Some(1), Some("Predicted"))
            .unwrap();
        host.create_layer(LayerSpec::new("cells", 1)).unwrap();
        host.layer("cells").highlight(vec!["a".into()]).unwrap();
        {
            let state = mock.state();
            assert!(state.hotkeys.contains_key("next"));
            assert_eq!(
                state.badges["predicted"],
                (Some(1), "Predicted".to_string())
            );
            assert_eq!(state.layers["cells"].highlighted, ["a"]);
        }
        host.set_badge("predicted", None, None).unwrap();
        host.unregister_hotkey("next").unwrap();
        let state = mock.state();
        assert!(state.badges.is_empty() && state.hotkeys.is_empty());
    }

    #[test]
    fn create_registers_contributions() {
        let harness = TestHarness::<Probe>::new().unwrap();
        // Built with `..Default::default()`, it arrives enabled.
        assert!(harness.state().toolbar_buttons["go"].enabled);
    }

    #[test]
    fn create_errors_are_reported() {
        let error = TestHarness::<Probe>::with_init(test_init("refuse"))
            .err()
            .unwrap();
        assert_eq!(error, "refused");
    }

    #[test]
    fn events_reach_the_plugin_and_overlays_are_stored() {
        let harness = TestHarness::<Probe>::new().unwrap();
        harness
            .send(HostEvent::ToolbarButtonClicked {
                button_id: "go".into(),
            })
            .unwrap();
        let objects = harness.state().objects("cells");
        assert_eq!(objects.len(), 1);
        assert_eq!(objects[0].shape, Shape::Point { x: 1.0, y: 2.0 });
    }

    #[test]
    fn panics_become_errors() {
        let harness = TestHarness::<Probe>::new().unwrap();
        let error = harness
            .send(HostEvent::ToolbarButtonClicked {
                button_id: "panic".into(),
            })
            .unwrap_err();
        assert_eq!(error.kind(), FfiErrorKind::Panicked);
        assert!(error.message.contains("boom"));
        // The instance is still usable afterwards.
        harness
            .send(HostEvent::Ready {
                restore_sidebar: false,
            })
            .unwrap();
    }

    #[test]
    fn handler_errors_are_failures() {
        let harness = TestHarness::<Probe>::new().unwrap();
        let error = harness
            .send(HostEvent::FileClosed { file_id: 1 })
            .unwrap_err();
        assert_eq!(error.kind(), FfiErrorKind::Failed);
        assert_eq!(error.message.as_str(), "cannot close");
    }

    #[test]
    fn context_menus_and_callbacks_return_values() {
        let harness = TestHarness::<Probe>::new().unwrap();
        let items = harness
            .context_menu(MenuContext {
                pane: 1,
                view: view(),
                image_x: 5.0,
                image_y: 6.0,
                hit: None,
                selection: Vec::new(),
            })
            .unwrap();
        assert_eq!(items[0].item_id, "at-5");
        assert!(items[0].enabled, "built with `..Default::default()`");
        let reply = harness
            .ui_callback("surface-1", "clicked", vec![json!(1), json!("x")])
            .unwrap();
        assert_eq!(reply, json!({ "name": "clicked", "argc": 2 }));
    }

    #[test]
    fn filters_modify_frames_in_place() {
        let harness = TestHarness::<Probe>::new().unwrap();
        let mut pixels = vec![10, 20, 30, 255, 40, 50, 60, 255];
        harness
            .apply_filter("invert", &mut pixels, 2, 1, FilterView::default())
            .unwrap();
        assert_eq!(pixels, vec![245, 20, 30, 255, 215, 50, 60, 255]);
    }

    #[test]
    fn short_frames_are_rejected() {
        let harness = TestHarness::<Probe>::new().unwrap();
        let mut pixels = vec![0u8; 7];
        let error = harness
            .apply_filter("invert", &mut pixels, 2, 1, FilterView::default())
            .unwrap_err();
        assert_eq!(error.kind(), FfiErrorKind::InvalidArguments);
    }

    #[test]
    fn unknown_methods_are_unsupported() {
        let host = MockHost::new();
        let sdk_host = Host::from_ffi(host.to_ffi());
        let error = sdk_host
            .call::<_, Value>("does.not.exist", &json!({}))
            .unwrap_err();
        assert!(error.is_unsupported());
    }

    #[test]
    fn invalid_shapes_are_rejected() {
        let host = MockHost::new();
        let sdk_host = Host::from_ffi(host.to_ffi());
        let layer = sdk_host.create_layer(LayerSpec::new("l", 1)).unwrap();
        let error = layer
            .upsert(vec![OverlayObject::new(
                "bad",
                Shape::Polyline {
                    points: vec![[0.0, f64::NAN]],
                },
            )])
            .unwrap_err();
        assert_eq!(error.kind, FfiErrorKind::InvalidArguments);
    }

    #[test]
    fn settings_round_trip() {
        let host = MockHost::new();
        let sdk_host = Host::from_ffi(host.to_ffi());
        sdk_host.set_setting("threshold", &0.5).unwrap();
        assert_eq!(sdk_host.setting::<f64>("threshold").unwrap(), Some(0.5));
        sdk_host.remove_setting("threshold").unwrap();
        assert_eq!(sdk_host.setting::<f64>("threshold").unwrap(), None);
    }

    const MODEL_SHA: &str = "70a8deef1f01716efbc87feb181ea398425d08b5e4984ad9d4ab2b83fd354f92";

    /// Uses a stored model, or asks eov for it, on a toolbar click.
    struct ModelUser {
        host: Host,
        request: std::sync::Mutex<Option<String>>,
    }

    impl Plugin for ModelUser {
        fn create(host: Host, _init: PluginInit) -> Result<Self, String> {
            Ok(Self {
                host,
                request: std::sync::Mutex::new(None),
            })
        }

        fn on_event(&self, event: HostEvent) -> Result<(), String> {
            match event {
                HostEvent::ToolbarButtonClicked { .. } => {
                    if let Some(model) = self.host.resolve_model(MODEL_SHA).map_err(String::from)? {
                        self.host.info(format!("using {}", model.path));
                        return Ok(());
                    }
                    let request = self
                        .host
                        .fetch_model(ModelFetchArgs {
                            url: Some("https://models.example.org/m.onnx".into()),
                            sha256: MODEL_SHA.into(),
                            name: Some("Reference".into()),
                            companions: vec![ModelFileSpec {
                                sha256: "cd2735866bd69648eb17df97f196f266e6e2569f8c21fa1e9779fb7e3a233ef8"
                                    .into(),
                                file_name: Some("m.onnx.data".into()),
                                ..Default::default()
                            }],
                            ..Default::default()
                        })
                        .map_err(String::from)?;
                    *self.request.lock().unwrap() = Some(request);
                }
                HostEvent::ModelFetched {
                    request_id,
                    path,
                    error,
                    cancelled,
                    ..
                } if self.request.lock().unwrap().as_deref() == Some(request_id.as_str()) => {
                    match (path, error) {
                        (Some(path), _) => self.host.info(format!("using {path}")),
                        (None, _) if cancelled => self.host.info("not now"),
                        (None, error) => self.host.info(format!("failed: {error:?}")),
                    }
                }
                _ => {}
            }
            Ok(())
        }
    }

    fn logged(harness: &TestHarness<ModelUser>) -> Vec<String> {
        harness
            .calls_to("log")
            .iter()
            .map(|args| args["message"].as_str().unwrap_or_default().to_string())
            .collect()
    }

    #[test]
    fn models_are_fetched_once_and_then_resolved() {
        let harness = TestHarness::<ModelUser>::new().unwrap();
        let click = || {
            harness
                .send(HostEvent::ToolbarButtonClicked {
                    button_id: "x".into(),
                })
                .unwrap()
        };
        click();
        let (request, args) = harness.last_model_fetch().expect("the plugin asked");
        assert_eq!(args.sha256, MODEL_SHA);
        assert_eq!(args.companions.len(), 1);
        harness
            .finish_model_fetch(
                &request,
                Ok(ModelRecord {
                    sha256: MODEL_SHA.into(),
                    path: "/models/70a8/m.onnx".into(),
                    file_name: "m.onnx".into(),
                    size: 10,
                    ..Default::default()
                }),
            )
            .unwrap();
        assert_eq!(logged(&harness), ["using /models/70a8/m.onnx"]);
        // Stored now: the next click resolves it without a download.
        click();
        assert_eq!(harness.state().model_fetches.len(), 1);
        assert_eq!(logged(&harness).len(), 2);
        let listed = Host::from_ffi(harness.host().to_ffi()).models().unwrap();
        assert_eq!(listed.len(), 1);
    }

    #[test]
    fn declined_and_failed_fetches_reach_the_plugin() {
        let harness = TestHarness::<ModelUser>::new().unwrap();
        let click = || {
            harness
                .send(HostEvent::ToolbarButtonClicked {
                    button_id: "x".into(),
                })
                .unwrap()
        };
        click();
        let (request, _) = harness.last_model_fetch().unwrap();
        harness.cancel_model_fetch(&request).unwrap();
        click();
        let (request, _) = harness.last_model_fetch().unwrap();
        harness
            .finish_model_fetch(&request, Err("SHA-256 mismatch".into()))
            .unwrap();
        assert_eq!(
            logged(&harness),
            ["not now", "failed: Some(\"SHA-256 mismatch\")"]
        );
        assert!(harness.state().models.is_empty());
    }

    #[test]
    fn model_requests_are_checked_and_old_hosts_refuse_them() {
        let mock = MockHost::new();
        let host = Host::from_ffi(mock.to_ffi());
        let bad = host
            .fetch_model(ModelFetchArgs {
                sha256: "abc".into(),
                ..Default::default()
            })
            .unwrap_err();
        assert_eq!(bad.kind, FfiErrorKind::InvalidArguments);
        let nameless = host
            .fetch_model(ModelFetchArgs {
                sha256: MODEL_SHA.into(),
                companions: vec![ModelFileSpec {
                    sha256: MODEL_SHA.into(),
                    ..Default::default()
                }],
                ..Default::default()
            })
            .unwrap_err();
        assert!(nameless.message.contains("file_name"), "{nameless}");
        assert_eq!(host.resolve_model(MODEL_SHA).unwrap(), None);
        mock.state()
            .unsupported
            .push(methods::MODEL_FETCH.to_string());
        assert!(
            host.fetch_model(ModelFetchArgs {
                sha256: MODEL_SHA.into(),
                ..Default::default()
            })
            .unwrap_err()
            .is_unsupported()
        );
    }
}