icedwright-probe 0.1.3

What an iced app links for icedwright: semantic annotations, typed test ids and named tasks, all pass-through unless a feature turns them on
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
//! `Remote`, the program wrapper that adds the endpoint to an app.

use std::collections::BTreeMap;
use std::fmt;
use std::path::Path;
use std::sync::{Arc, Mutex, PoisonError};

use futures::channel::mpsc;
use futures::stream::{self, BoxStream, StreamExt};
use iced_core::window;
use iced_core::{Element, Settings, theme};
use iced_program::Program;
use iced_program::futures::Subscription;
use iced_program::runtime::{Task, task};
use icedwright_protocol::{
    Attachment, CursorReading, ErrorBody, Notification, RequestId, WireFrame,
};
use icedwright_types::Size;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};

use super::collect::{Collect, Recording, Slot, take};
use super::dispatch::{ClientId, Effect, ProbeState, dispatch};
use super::endpoint::{Inbound, Outbox, spawn_acceptor};
use super::policy::{Decision, ENV, Startup, decide};
use super::root::Root;
use super::tasks::{RemoteExecutor, TaskHub, install_global, resolver};
use super::transport::UnixEndpoint;
use crate::TaskName;

/// Set to `1` by `icedwright-remote`'s launcher: the app exits once its last client says
/// goodbye.
const EXIT_ON_BYE: &str = "ICEDWRIGHT_REMOTE_EXIT_ON_BYE";

/// The probe's own messages.
#[derive(Debug)]
pub enum ProbeMessage {
    /// Requests and connection changes from the socket threads, and task changes.
    Inbound(Vec<Inbound>),
    /// A window's root delivered its queued events up to `through`.
    Delivered {
        /// The window.
        window: window::Id,
        /// The last sequence number delivered.
        through: u64,
        /// Each delivered event's status, by sequence number.
        statuses: Vec<(u64, icedwright_protocol::WireStatus)>,
        /// The cursor each layer was handed during the delivery.
        cursors: Vec<CursorReading>,
    },
    /// A tree collection finished.
    Collected(Option<Recording>),
    /// A screenshot finished, or the window could not take one.
    Shot {
        /// The client.
        client: ClientId,
        /// The request.
        id: RequestId,
        /// The window.
        window: window::Id,
        /// The pixels.
        shot: Option<window::Screenshot>,
    },
    /// A window event.
    Window(window::Id, window::Event),
    /// The OS keyboard sent a client's keys, or could not.
    OsKeysSent {
        /// The client.
        client: ClientId,
        /// The request.
        id: RequestId,
        /// The window.
        window: icedwright_protocol::WindowOrdinal,
        /// How many events were sent, or why none were.
        sent: Result<usize, String>,
    },
    /// A real event reached a window's widgets while a client records.
    Observed {
        /// The window.
        window: window::Id,
        /// The event.
        event: iced_core::Event,
        /// What the widgets did with it.
        status: icedwright_protocol::WireStatus,
    },
    /// The real pointer in pick mode, at a position in the window; `pick` when it clicked.
    Pointed {
        /// The window.
        window: window::Id,
        /// Where the pointer is.
        position: iced_core::Point,
        /// Whether it clicked, which picks the node.
        pick: bool,
    },
}

/// The wrapped program's message: the app's own, or the probe's.
#[derive(Debug)]
pub enum Wrapped<M> {
    /// The app's message.
    App(M),
    /// The probe's message.
    Probe(ProbeMessage),
}

/// The wrapped program's state.
pub struct RemoteState<S> {
    app: S,
    core: Core,
}

impl<S> fmt::Debug for RemoteState<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RemoteState")
            .field("probe", &self.core.probe)
            .field("clients", &self.core.outboxes.len())
            .finish_non_exhaustive()
    }
}

impl<S> RemoteState<S> {
    /// The app's own state.
    #[must_use]
    pub fn app(&self) -> &S {
        &self.app
    }
}

/// An app's program with the endpoint added. Built with [`attach`], started with
/// [`Remote::run`] or [`run`].
pub struct Remote<P> {
    program: P,
    hub: Arc<TaskHub>,
    live: bool,
    exit_on_bye: bool,
}

impl<P> fmt::Debug for Remote<P> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Remote")
            .field("live", &self.live)
            .finish_non_exhaustive()
    }
}

/// Wraps `program`. The endpoint opens when the result runs, if `ICEDWRIGHT_REMOTE` says so.
pub fn attach<P: Program>(program: P) -> Remote<P> {
    Remote {
        program,
        hub: Arc::new(TaskHub::new()),
        live: false,
        exit_on_bye: false,
    }
}

/// Runs `program` with the endpoint, so the app needs no `iced_winit` dependency of its own.
pub fn run<P>(program: P) -> Result<(), iced_winit::Error>
where
    P: Program + 'static,
    P::Theme: theme::Base + 'static,
    P::Renderer: 'static,
{
    attach(program).run()
}

static INBOX: Mutex<Option<mpsc::UnboundedReceiver<Inbound>>> = Mutex::new(None);

fn inbox() -> BoxStream<'static, ProbeMessage> {
    let receiver = INBOX.lock().unwrap_or_else(PoisonError::into_inner).take();
    match receiver {
        Some(receiver) => receiver.ready_chunks(64).map(ProbeMessage::Inbound).boxed(),
        None => stream::pending().boxed(),
    }
}

impl<P: Program> Remote<P> {
    /// Lets clients resolve tasks named `N` with a value they send, which the probe
    /// deserialises into `N::Output`.
    #[must_use]
    pub fn resolvable<N: TaskName>(self) -> Self
    where
        N::Output: DeserializeOwned,
    {
        self.hub.register(N::NAME, resolver::<N>());
        self
    }

    /// Opens the endpoint if allowed and runs the app.
    pub fn run(self) -> Result<(), iced_winit::Error>
    where
        P: 'static,
        P::Theme: theme::Base + 'static,
        P::Renderer: 'static,
    {
        iced_winit::run(self.open())
    }

    fn open(mut self) -> Self {
        if let Some(opened) = open_endpoint(P::name(), &self.hub) {
            self.hub = opened.hub;
            self.live = true;
            self.exit_on_bye = opened.exit_on_bye;
        }
        self
    }
}

/// An endpoint that is listening.
struct Opened {
    hub: Arc<TaskHub>,
    exit_on_bye: bool,
}

/// Opens the endpoint for `app` if the environment allows it, logging why not otherwise.
fn open_endpoint(app: &str, hub: &Arc<TaskHub>) -> Option<Opened> {
    let env = std::env::var_os(ENV);
    let runtime = std::env::var_os("XDG_RUNTIME_DIR");
    let startup = Startup {
        debug_assertions: cfg!(debug_assertions),
        allow_in_release: cfg!(feature = "remote-in-release"),
        remote_env: env.as_deref(),
        runtime_dir: runtime.as_deref().map(Path::new),
        app,
        pid: std::process::id(),
    };
    let plan = match decide(&startup) {
        Ok(Decision::Off) => return None,
        Ok(Decision::Listen(plan)) => plan,
        Err(refusal) => {
            eprintln!("icedwright-remote: refused: {refusal}");
            return None;
        }
    };
    let endpoint = match UnixEndpoint::bind(&plan) {
        Ok(endpoint) => endpoint,
        Err(refusal) => {
            eprintln!("icedwright-remote: refused: {refusal}");
            return None;
        }
    };
    let path = endpoint.path().display().to_string();
    let (sender, receiver) = mpsc::unbounded();
    let hub = install_global(Arc::clone(hub));
    let tasks = sender.clone();
    hub.listen(move |event| {
        let _ = tasks.unbounded_send(Inbound::Task(event));
    });
    let sink = move |inbound| sender.unbounded_send(inbound).is_ok();
    if let Err(error) = spawn_acceptor(Box::new(endpoint), sink) {
        eprintln!("icedwright-remote: refused: the socket thread did not start: {error}");
        return None;
    }
    *INBOX.lock().unwrap_or_else(PoisonError::into_inner) = Some(receiver);
    if cfg!(not(debug_assertions)) {
        eprintln!("icedwright-remote: warning: the endpoint is open in a release build");
    }
    eprintln!("icedwright-remote: listening on {path}");
    Some(Opened {
        hub,
        exit_on_bye: std::env::var_os(EXIT_ON_BYE).is_some_and(|v| v == "1"),
    })
}

/// The endpoint's state, shared by [`Remote`] and [`Probe`].
#[derive(Debug)]
struct Core {
    probe: ProbeState,
    outboxes: BTreeMap<ClientId, Outbox>,
}

impl Core {
    fn new(app: &str, hub: &Arc<TaskHub>, exit_on_bye: bool) -> Self {
        Self {
            probe: ProbeState::new(app, std::process::id(), Arc::clone(hub), exit_on_bye)
                .with_os_keyboard(super::oskeys::support()),
            outboxes: BTreeMap::new(),
        }
    }

    fn set_titles(&mut self, titles: Vec<(window::Id, String)>) {
        for (id, title) in titles {
            self.probe.set_title(id, title);
        }
    }

    /// Handles one probe message. `titles` gives each known window's title now.
    fn handle(
        &mut self,
        message: ProbeMessage,
        titles: &dyn Fn(&ProbeState) -> Vec<(window::Id, String)>,
    ) -> Vec<Effect> {
        match message {
            ProbeMessage::Inbound(batch) => {
                self.set_titles(titles(&self.probe));
                let mut effects = Vec::new();
                for inbound in batch {
                    effects.extend(self.inbound(inbound));
                }
                effects
            }
            ProbeMessage::Delivered {
                window,
                through,
                statuses,
                cursors,
            } => self.probe.delivered(window, through, statuses, cursors),
            ProbeMessage::Collected(recording) => {
                self.set_titles(titles(&self.probe));
                self.probe.collected(recording.unwrap_or_default())
            }
            ProbeMessage::Shot {
                client,
                id,
                window,
                shot,
            } => self.probe.screenshot_taken(client, id, window, shot),
            ProbeMessage::Window(id, event) => match event {
                window::Event::Opened { size, .. } => {
                    let effects = self
                        .probe
                        .window_opened(id, Size::new(size.width, size.height));
                    self.set_titles(titles(&self.probe));
                    effects
                }
                window::Event::Resized(size) => {
                    self.probe
                        .window_resized(id, Size::new(size.width, size.height));
                    Vec::new()
                }
                window::Event::Rescaled(factor) => {
                    self.probe.window_rescaled(id, factor);
                    Vec::new()
                }
                window::Event::Closed => self.probe.window_closed(id),
                _ => Vec::new(),
            },
            ProbeMessage::OsKeysSent {
                client,
                id,
                window,
                sent,
            } => self.probe.os_keys_sent(client, id, window, sent),
            ProbeMessage::Observed {
                window,
                event,
                status,
            } => self.probe.observed(window, &event, status),
            ProbeMessage::Pointed {
                window,
                position,
                pick,
            } => self.probe.pointed(
                window,
                icedwright_types::Point::new(position.x, position.y),
                pick,
            ),
        }
    }

    fn inbound(&mut self, inbound: Inbound) -> Vec<Effect> {
        match inbound {
            Inbound::Opened { client, outbox } => {
                self.outboxes.insert(client, outbox);
                Vec::new()
            }
            Inbound::Call {
                client,
                id,
                method,
                params,
            } => dispatch(&mut self.probe, client, id, &method, params),
            Inbound::Malformed {
                client,
                id: Some(id),
                message,
            } => vec![Effect::Reply {
                client,
                id,
                result: Err(ErrorBody::new(
                    icedwright_protocol::ErrorCode::BadRequest,
                    message,
                )),
                attachment: None,
            }],
            Inbound::Malformed { id: None, .. } => Vec::new(),
            Inbound::Closed { client } => {
                self.outboxes.remove(&client);
                self.probe.client_closed(client)
            }
            Inbound::Task(event) => self.probe.task_event(event),
        }
    }

    fn subscription() -> Subscription<ProbeMessage> {
        Subscription::batch([
            Subscription::run(inbox),
            iced_program::runtime::window::events()
                .map(|(id, event)| ProbeMessage::Window(id, event)),
        ])
    }
}

/// The endpoint for apps that cannot use [`attach`], such as ones that build their own
/// `Program` or want the probe's messages in their own message type. It takes four calls:
/// [`subscription`](Self::subscription) in the app's subscription,
/// [`update`](Self::update) for each [`ProbeMessage`], [`observe`](Self::observe) for each of
/// the app's own messages, and [`root`](Self::root) around each window's view.
///
/// Named tasks report to the endpoint only when the app also runs on [`RemoteExecutor`], for
/// example with `.executor::<RemoteExecutor<iced::executor::Default>>()`. Window titles are
/// whatever [`set_title`](Self::set_title) last said.
pub struct Probe {
    core: Core,
    titles: BTreeMap<window::Id, String>,
}

impl fmt::Debug for Probe {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Probe")
            .field("probe", &self.core.probe)
            .field("clients", &self.core.outboxes.len())
            .finish_non_exhaustive()
    }
}

impl Probe {
    /// Opens the endpoint if `ICEDWRIGHT_REMOTE` asks for it and the build allows it, named
    /// after the executable. `None` when it stays closed; the reason is on stderr.
    #[must_use]
    pub fn from_env() -> Option<Self> {
        let exe = std::env::current_exe().ok();
        let app = exe
            .as_deref()
            .and_then(Path::file_stem)
            .and_then(|stem| stem.to_str())
            .unwrap_or("app")
            .to_owned();
        Self::open(&app, Arc::new(TaskHub::new()))
    }

    fn open(app: &str, hub: Arc<TaskHub>) -> Option<Self> {
        let opened = open_endpoint(app, &hub)?;
        Some(Self::with_hub(app, &opened.hub, opened.exit_on_bye))
    }

    fn with_hub(app: &str, hub: &Arc<TaskHub>, exit_on_bye: bool) -> Self {
        Self {
            core: Core::new(app, hub, exit_on_bye),
            titles: BTreeMap::new(),
        }
    }

    /// Requests from the socket and window events, for the app's subscription.
    pub fn subscription(&self) -> Subscription<ProbeMessage> {
        Core::subscription()
    }

    /// Handles one of the probe's messages.
    pub fn update(&mut self, message: ProbeMessage) -> Task<ProbeMessage> {
        let titles = &self.titles;
        let effects = self.core.handle(message, &|probe| {
            probe
                .window_ids()
                .filter_map(|id| titles.get(&id).map(|title| (id, title.clone())))
                .collect()
        });
        carry_out(&mut self.core, effects, std::convert::identity)
    }

    /// Records that the app handled one of its own messages, which is how clients waiting
    /// for the app to change learn that it did.
    pub fn observe(&mut self) -> Task<ProbeMessage> {
        let effects = self.core.probe.app_message();
        carry_out(&mut self.core, effects, std::convert::identity)
    }

    /// The title clients see for `window`.
    pub fn set_title(&mut self, window: window::Id, title: impl Into<String>) {
        let title = title.into();
        self.core.probe.set_title(window, title.clone());
        self.titles.insert(window, title);
    }

    /// Wraps a window's view so clients can drive and read it.
    pub fn root<'a, M: 'a, Theme: 'a, R: iced_core::Renderer + 'a>(
        &'a self,
        window: window::Id,
        content: impl Into<Element<'a, M, Theme, R>>,
        on_probe: fn(ProbeMessage) -> M,
    ) -> Element<'a, M, Theme, R> {
        Root::new(window, self.core.probe.feed(window), content, on_probe).into()
    }
}

fn frames_for(
    id: RequestId,
    result: Result<Value, ErrorBody>,
    attachment: Option<Vec<u8>>,
) -> Vec<WireFrame> {
    let mut reply = match result {
        Ok(value) => json!({ "id": id, "result": value }),
        Err(body) => json!({ "id": id, "error": body }),
    };
    let mut frames = Vec::new();
    if let Some(bytes) = &attachment
        && let Some(object) = reply.as_object_mut()
    {
        let announce = Attachment {
            bytes: u64::try_from(bytes.len()).unwrap_or(u64::MAX),
            media: "image/x-rgba".into(),
        };
        object.insert(
            "attachment".to_owned(),
            serde_json::to_value(announce).unwrap_or(Value::Null),
        );
    }
    let Ok(payload) = serde_json::to_vec(&reply) else {
        return frames;
    };
    frames.push(WireFrame::json(payload));
    if let Some(bytes) = attachment {
        frames.push(WireFrame::binary(bytes));
    }
    frames
}

fn notification_frame(notification: &Notification) -> Option<WireFrame> {
    serde_json::to_vec(notification).ok().map(WireFrame::json)
}

fn collect_task<T: Send + 'static>(wrap: fn(ProbeMessage) -> T) -> Task<T> {
    let slot: Slot = Arc::default();
    let read = Arc::clone(&slot);
    task::widget(Collect::new(slot)).map(move |()| wrap(ProbeMessage::Collected(take(&read))))
}

/// Sends replies and notifications, and turns the other effects into tasks whose probe
/// messages `wrap` puts into the program's message type.
fn carry_out<T: Send + 'static>(
    core: &mut Core,
    effects: Vec<Effect>,
    wrap: fn(ProbeMessage) -> T,
) -> Task<T> {
    let mut tasks = Vec::new();
    for effect in effects {
        match effect {
            Effect::Reply {
                client,
                id,
                result,
                attachment,
            } => {
                let Some(outbox) = core.outboxes.get(&client) else {
                    continue;
                };
                if !outbox.send(frames_for(id, result, attachment)) {
                    core.outboxes.remove(&client);
                }
            }
            Effect::Notify(notification) => {
                let Some(frame) = notification_frame(&notification) else {
                    continue;
                };
                core.outboxes
                    .retain(|_, outbox| outbox.send(vec![frame.clone()]));
            }
            Effect::Collect => tasks.push(collect_task(wrap)),
            Effect::Screenshot { client, id, window } => tasks.push(
                iced_program::runtime::window::screenshot(window)
                    .collect()
                    .map(move |shots| {
                        wrap(ProbeMessage::Shot {
                            client,
                            id,
                            window,
                            shot: shots.into_iter().next(),
                        })
                    }),
            ),
            Effect::Focus(window) => tasks.push(iced_program::runtime::window::gain_focus(window)),
            Effect::Close(client) => {
                core.outboxes.remove(&client);
            }
            Effect::Size(window) => tasks.push(
                iced_program::runtime::window::size(window).map(move |size| {
                    wrap(ProbeMessage::Window(window, window::Event::Resized(size)))
                }),
            ),
            Effect::Exit => tasks.push(iced_program::runtime::exit()),
            Effect::OsKeys {
                client,
                id,
                window,
                ordinal,
                events,
            } => {
                let send = iced_program::runtime::window::run(window, super::oskeys::x11_window)
                    .then(move |xid| {
                        let events = events.clone();
                        Task::perform(async move { send_os_keys(xid, &events) }, move |sent| {
                            wrap(ProbeMessage::OsKeysSent {
                                client,
                                id,
                                window: ordinal,
                                sent,
                            })
                        })
                    });
                tasks.push(iced_program::runtime::window::gain_focus(window).chain(send));
            }
        }
    }
    Task::batch(tasks)
}

#[cfg(feature = "os-keyboard")]
fn send_os_keys(
    window: Option<u32>,
    events: &[icedwright_protocol::WireEvent],
) -> Result<usize, String> {
    use super::oskeys::{KeyInjector, connect, inject};

    static KEYBOARD: Mutex<Option<Box<dyn KeyInjector>>> = Mutex::new(None);
    let mut keyboard = KEYBOARD.lock().unwrap_or_else(PoisonError::into_inner);
    if keyboard.is_none() {
        *keyboard = Some(connect()?);
    }
    let Some(injector) = keyboard.as_mut() else {
        return Err("the OS keyboard is not connected".to_owned());
    };
    inject(injector.as_mut(), window, events)
}

#[cfg(not(feature = "os-keyboard"))]
fn send_os_keys(
    _window: Option<u32>,
    _events: &[icedwright_protocol::WireEvent],
) -> Result<usize, String> {
    Err("this app was built without the probe's os-keyboard feature".to_owned())
}

fn wrap_probe<M>(message: ProbeMessage) -> Wrapped<M> {
    Wrapped::Probe(message)
}

impl<P> Program for Remote<P>
where
    P: Program,
    P::Theme: 'static,
    P::Renderer: 'static,
{
    type State = RemoteState<P::State>;
    type Message = Wrapped<P::Message>;
    type Theme = P::Theme;
    type Renderer = P::Renderer;
    type Executor = RemoteExecutor<P::Executor>;

    fn name() -> &'static str {
        P::name()
    }

    fn settings(&self) -> Settings {
        self.program.settings()
    }

    fn window(&self) -> Option<window::Settings> {
        self.program.window()
    }

    fn boot(&self) -> (Self::State, Task<Self::Message>) {
        let (app, task) = self.program.boot();
        let state = RemoteState {
            app,
            core: Core::new(P::name(), &self.hub, self.exit_on_bye),
        };
        (state, task.map(Wrapped::App))
    }

    fn update(&self, state: &mut Self::State, message: Self::Message) -> Task<Self::Message> {
        match message {
            Wrapped::App(message) => {
                let app = self
                    .program
                    .update(&mut state.app, message)
                    .map(Wrapped::App);
                if !self.live {
                    return app;
                }
                let effects = state.core.probe.app_message();
                Task::batch([app, carry_out(&mut state.core, effects, wrap_probe)])
            }
            Wrapped::Probe(message) => {
                let (app, program) = (&state.app, &self.program);
                let titles = |probe: &ProbeState| {
                    probe
                        .window_ids()
                        .map(|id| (id, program.title(app, id)))
                        .collect()
                };
                let effects = state.core.handle(message, &titles);
                carry_out(&mut state.core, effects, wrap_probe)
            }
        }
    }

    fn view<'a>(
        &self,
        state: &'a Self::State,
        window: window::Id,
    ) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> {
        let content = self.program.view(&state.app, window).map(Wrapped::App);
        Root::new(
            window,
            state.core.probe.feed(window),
            content,
            Wrapped::Probe,
        )
        .into()
    }

    fn title(&self, state: &Self::State, window: window::Id) -> String {
        self.program.title(&state.app, window)
    }

    fn subscription(&self, state: &Self::State) -> Subscription<Self::Message> {
        let app = self.program.subscription(&state.app).map(Wrapped::App);
        if !self.live {
            return app;
        }
        Subscription::batch([app, Core::subscription().map(Wrapped::Probe)])
    }

    fn theme(&self, state: &Self::State, window: window::Id) -> Option<Self::Theme> {
        self.program.theme(&state.app, window)
    }

    fn style(&self, state: &Self::State, theme: &Self::Theme) -> theme::Style {
        self.program.style(&state.app, theme)
    }

    fn scale_factor(&self, state: &Self::State, window: window::Id) -> f32 {
        self.program.scale_factor(&state.app, window)
    }
}

#[cfg(test)]
mod tests {
    use icedwright_protocol::{ErrorCode, Generation};

    use super::*;

    #[test]
    fn a_reply_with_an_attachment_announces_it_before_the_bytes() -> Result<(), serde_json::Error> {
        let frames = frames_for(RequestId(4), Ok(json!({ "w": 1 })), Some(vec![1, 2, 3, 4]));
        assert_eq!(frames.len(), 2);
        let first: Value = serde_json::from_slice(&frames[0].payload)?;
        assert_eq!(first["id"], 4);
        assert_eq!(first["attachment"]["bytes"], 4);
        assert_eq!(first["attachment"]["media"], "image/x-rgba");
        assert_eq!(frames[1], WireFrame::binary(vec![1, 2, 3, 4]));
        Ok(())
    }

    fn hello_from(client: u64) -> Inbound {
        Inbound::Call {
            client: ClientId(client),
            id: RequestId(1),
            method: "hello".to_owned(),
            params: json!({ "protocol": icedwright_protocol::PROTOCOL, "client": "test" }),
        }
    }

    fn replies(frames: &std::sync::mpsc::Receiver<WireFrame>) -> Vec<Value> {
        frames
            .try_iter()
            .filter_map(|frame| serde_json::from_slice(&frame.payload).ok())
            .collect()
    }

    #[test]
    fn the_three_call_probe_answers_hello_and_names_titled_windows() {
        let mut probe = Probe::with_hub("demo", &Arc::new(TaskHub::new()), false);
        let window = window::Id::unique();
        let opened = window::Event::Opened {
            position: None,
            size: iced_core::Size::new(100.0, 50.0),
        };
        let _ = probe.update(ProbeMessage::Window(window, opened));
        probe.set_title(window, "Main");
        let (outbox, frames) = Outbox::channel();
        let client = ClientId(3);
        let _ = probe.update(ProbeMessage::Inbound(vec![
            Inbound::Opened { client, outbox },
            hello_from(3),
        ]));
        let answers = replies(&frames);
        assert_eq!(answers.len(), 1, "{answers:?}");
        assert_eq!(answers[0]["result"]["app"], "demo");
        assert_eq!(answers[0]["result"]["windows"][0]["title"], "Main");
    }

    #[test]
    fn observing_an_app_message_notifies_clients_of_the_new_generation() {
        let mut probe = Probe::with_hub("demo", &Arc::new(TaskHub::new()), false);
        let (outbox, frames) = Outbox::channel();
        let _ = probe.update(ProbeMessage::Inbound(vec![
            Inbound::Opened {
                client: ClientId(1),
                outbox,
            },
            hello_from(1),
        ]));
        let _ = replies(&frames);
        assert_eq!(probe.core.probe.generation(), Generation(0));
        let _ = probe.observe();
        assert_eq!(probe.core.probe.generation(), Generation(1));
        let pushed = replies(&frames);
        assert_eq!(pushed.len(), 1, "{pushed:?}");
        assert_eq!(pushed[0]["event"], "generation");
    }

    #[test]
    fn an_error_reply_carries_its_code() -> Result<(), serde_json::Error> {
        let frames = frames_for(
            RequestId(1),
            Err(ErrorBody::new(ErrorCode::Stale, "moved")),
            None,
        );
        let reply: Value = serde_json::from_slice(&frames[0].payload)?;
        assert_eq!(reply["error"]["code"], "stale");
        assert!(reply.get("result").is_none());
        Ok(())
    }
}