icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
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
//! Task control: the controller named tasks report to, the rules that hold or answer them,
//! and [`Tasks`], the test's view of every task the app started.

use std::any::TypeId;
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::panic::Location;
use std::rc::Rc;
use std::task::{Context, Waker};

use icedwright_probe::control::{Controller, Finish, Gate, Payload, ProbeId, ProbeMeta, Replace};
use icedwright_probe::{Fallible, TaskName};
use icedwright_types::{VirtualDuration, VirtualInstant};

use crate::error::{HarnessError, Result};
use crate::harness::{Harness, TestProgram};
use crate::runtime::{SharedBook, TaskRecord, current_task, lock};
use crate::time::VirtualClock;

/// A task, untyped: for listings and for actions that need no output type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct UntypedTaskId(u64);

impl UntypedTaskId {
    pub(crate) const fn new(ordinal: u64) -> Self {
        Self(ordinal)
    }

    /// The per-harness ordinal, from 1 in start order.
    #[must_use]
    pub const fn get(self) -> u64 {
        self.0
    }
}

impl fmt::Display for UntypedTaskId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "#{}", self.0)
    }
}

/// A named task, which remembers its name in its type.
pub struct TaskId<N> {
    id: UntypedTaskId,
    name: PhantomData<fn() -> N>,
}

impl<N> TaskId<N> {
    fn new(id: UntypedTaskId) -> Self {
        Self {
            id,
            name: PhantomData,
        }
    }

    /// The untyped id.
    #[must_use]
    pub fn untyped(self) -> UntypedTaskId {
        self.id
    }
}

impl<N> Clone for TaskId<N> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<N> Copy for TaskId<N> {}

impl<N> PartialEq for TaskId<N> {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl<N> Eq for TaskId<N> {}

impl<N> Hash for TaskId<N> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.id.hash(state);
    }
}

impl<N: TaskName> fmt::Debug for TaskId<N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "TaskId<{}>({})", N::NAME, self.id)
    }
}

impl<N> From<TaskId<N>> for UntypedTaskId {
    fn from(id: TaskId<N>) -> Self {
        id.id
    }
}

/// A rule, for removing it again.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RuleId(u64);

/// Where a task is in its life.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TaskState {
    /// Running, or waiting on something other than the test.
    Pending,
    /// Held until the test acts.
    Held,
    /// Answered by the test or a route without its real future running.
    Resolved,
    /// Finished on its own.
    Finished,
    /// Failed by the test, or it panicked.
    Failed,
    /// Dropped before it finished, or cancelled.
    Aborted,
}

impl TaskState {
    pub(crate) fn is_live(self) -> bool {
        matches!(self, TaskState::Pending | TaskState::Held)
    }
}

/// Where a task came from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Spawn {
    /// `boot`.
    Boot,
    /// The `update` for this message, by its `Debug` text.
    Update {
        /// The message.
        message: String,
    },
    /// A subscription.
    Subscription,
}

/// A declared source of work from threads the harness does not own.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExternalSource {
    /// Named tasks matching this pattern, which a thread of the app's finishes.
    Named(&'static str),
    /// Any subscription woken from a foreign thread.
    Subscriptions,
}

impl fmt::Display for ExternalSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ExternalSource::Named(pattern) => f.write_str(pattern),
            ExternalSource::Subscriptions => f.write_str("subscriptions"),
        }
    }
}

/// Everything known about one task.
#[derive(Debug, Clone)]
pub struct TaskInfo {
    id: UntypedTaskId,
    name: Option<&'static str>,
    name_type: Option<TypeId>,
    detail: Option<String>,
    location: Option<&'static Location<'static>>,
    spawn: Spawn,
    parent: Option<UntypedTaskId>,
    spawned_at: VirtualInstant,
    state: TaskState,
    external: bool,
    polls: u64,
    produced: Vec<String>,
    foreign_wakes: u32,
}

impl TaskInfo {
    /// Its id.
    #[must_use]
    pub fn id(&self) -> UntypedTaskId {
        self.id
    }

    /// Its name, for named tasks.
    #[must_use]
    pub fn name(&self) -> Option<&'static str> {
        self.name
    }

    /// Whether it was named `N`.
    #[must_use]
    pub fn is<N: TaskName>(&self) -> bool {
        self.name_type == Some(TypeId::of::<N>())
    }

    /// The name's detail text.
    #[must_use]
    pub fn detail(&self) -> Option<&str> {
        self.detail.as_deref()
    }

    /// Where it was named. Unnamed tasks have no location in iced 0.14.
    #[must_use]
    pub fn location(&self) -> Option<&'static Location<'static>> {
        self.location
    }

    /// Where it came from.
    #[must_use]
    pub fn spawn(&self) -> &Spawn {
        &self.spawn
    }

    /// The unnamed task a named task runs inside.
    #[must_use]
    pub fn parent(&self) -> Option<UntypedTaskId> {
        self.parent
    }

    /// When it started.
    #[must_use]
    pub fn spawned_at(&self) -> VirtualInstant {
        self.spawned_at
    }

    /// Its state.
    #[must_use]
    pub fn state(&self) -> TaskState {
        self.state
    }

    /// Whether a thread the harness does not own finishes it.
    #[must_use]
    pub fn is_external(&self) -> bool {
        self.external
    }

    /// How often it was polled.
    #[must_use]
    pub fn polls(&self) -> u64 {
        self.polls
    }

    /// The `Debug` text of every message it produced.
    #[must_use]
    pub fn produced(&self) -> &[String] {
        &self.produced
    }

    /// How often a foreign thread woke it.
    #[must_use]
    pub fn foreign_wakes(&self) -> u32 {
        self.foreign_wakes
    }

    pub(crate) fn from_record(id: UntypedTaskId, record: &TaskRecord) -> Self {
        Self {
            id,
            name: None,
            name_type: None,
            detail: None,
            location: None,
            spawn: record.spawn.clone(),
            parent: None,
            spawned_at: record.spawned_at,
            state: record.state,
            external: false,
            polls: record.polls,
            produced: record.produced.clone(),
            foreign_wakes: record.foreign_wakes,
        }
    }
}

/// Matches `*` against any run of characters; everything else literally.
pub(crate) fn pattern_matches(pattern: &str, name: &str) -> bool {
    let mut parts = pattern.split('*');
    let Some(first) = parts.next() else {
        return name.is_empty();
    };
    let Some(mut rest) = name.strip_prefix(first) else {
        return false;
    };
    let parts: Vec<&str> = parts.collect();
    let Some((last, middle)) = parts.split_last() else {
        return rest.is_empty();
    };
    for part in middle {
        let Some(found) = rest.find(part) else {
            return false;
        };
        rest = &rest[found + part.len()..];
    }
    rest.ends_with(last)
}

type Route = Box<dyn FnMut(&TaskInfo) -> Payload>;
type UnnamedMatch<M> = Box<dyn Fn(&M) -> bool>;

enum RuleKind<P: TestProgram> {
    Hold(TypeId),
    Route(TypeId, Route),
    HoldMatching(String),
    DenyUnrouted(String),
    HoldUnnamed(UnnamedMatch<P::Message>),
}

struct Rule<P: TestProgram> {
    id: RuleId,
    kind: RuleKind<P>,
}

/// Rules that hold or answer tasks, installed before boot through `HarnessConfig::tasks` or
/// mid-test through [`Tasks::rules`]. The most recent matching rule wins.
pub struct TaskRules<P: TestProgram> {
    next: u64,
    rules: Vec<Rule<P>>,
    used_patterns: BTreeSet<String>,
}

impl<P: TestProgram> Default for TaskRules<P> {
    fn default() -> Self {
        Self {
            next: 0,
            rules: Vec::new(),
            used_patterns: BTreeSet::new(),
        }
    }
}

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

/// What a rule decided for a named task's first poll.
pub(crate) enum Decision {
    Run,
    Hold,
    Resolve(Payload),
    Deny,
}

impl<P: TestProgram> TaskRules<P> {
    fn add(&mut self, kind: RuleKind<P>) -> RuleId {
        self.next += 1;
        let id = RuleId(self.next);
        self.rules.push(Rule { id, kind });
        id
    }

    /// Holds every task named `N` until the test acts.
    pub fn hold<N: TaskName>(&mut self) -> RuleId {
        self.add(RuleKind::Hold(TypeId::of::<N>()))
    }

    /// Answers every task named `N` with the closure's value; its real future never runs.
    pub fn route<N: TaskName>(
        &mut self,
        mut reply: impl FnMut(&TaskInfo) -> N::Output + 'static,
    ) -> RuleId {
        self.add(RuleKind::Route(
            TypeId::of::<N>(),
            Box::new(move |info| Payload::new::<N>(reply(info))),
        ))
    }

    /// Fails every task named `N` with the closure's error.
    pub fn route_err<N: Fallible>(
        &mut self,
        mut error: impl FnMut(&TaskInfo) -> N::Err + 'static,
    ) -> RuleId {
        self.add(RuleKind::Route(
            TypeId::of::<N>(),
            Box::new(move |info| Payload::fail::<N>(error(info))),
        ))
    }

    /// Holds every named task whose name matches `pattern`, where `*` matches anything.
    pub fn hold_matching(&mut self, pattern: &str) -> RuleId {
        self.add(RuleKind::HoldMatching(pattern.to_owned()))
    }

    /// Fails the step when a named task matching `pattern` starts with no route or hold.
    pub fn deny_unrouted(&mut self, pattern: &str) -> RuleId {
        self.add(RuleKind::DenyUnrouted(pattern.to_owned()))
    }

    /// Holds every unnamed task that the `update` for a matching message returns.
    pub fn hold_unnamed(&mut self, origin: impl Fn(&P::Message) -> bool + 'static) -> RuleId {
        self.add(RuleKind::HoldUnnamed(Box::new(origin)))
    }

    /// Removes a rule.
    pub fn remove(&mut self, rule: RuleId) {
        self.rules.retain(|r| r.id != rule);
    }

    pub(crate) fn decide(
        &mut self,
        info: &TaskInfo,
        name_type: TypeId,
        from_calls: bool,
    ) -> Decision {
        let name = info.name.unwrap_or_default();
        let mut used = None;
        let mut decision = None;
        for rule in self.rules.iter_mut().rev() {
            match &mut rule.kind {
                RuleKind::Hold(id) if *id == name_type => decision = Some(Decision::Hold),
                RuleKind::Route(id, reply) if *id == name_type => {
                    decision = Some(Decision::Resolve(reply(info)));
                }
                RuleKind::HoldMatching(pattern) if pattern_matches(pattern, name) => {
                    used = Some(pattern.clone());
                    decision = Some(Decision::Hold);
                }
                _ => continue,
            }
            break;
        }
        if decision.is_none() && !from_calls {
            for rule in self.rules.iter().rev() {
                if let RuleKind::DenyUnrouted(pattern) = &rule.kind
                    && pattern_matches(pattern, name)
                {
                    used = Some(pattern.clone());
                    decision = Some(Decision::Deny);
                    break;
                }
            }
        }
        if let Some(pattern) = used {
            self.used_patterns.insert(pattern);
        }
        decision.unwrap_or(Decision::Run)
    }

    pub(crate) fn holds_unnamed(&self, message: &P::Message) -> bool {
        self.rules
            .iter()
            .rev()
            .any(|rule| matches!(&rule.kind, RuleKind::HoldUnnamed(origin) if origin(message)))
    }

    /// Patterns that matched no task.
    pub(crate) fn unused_patterns(&self) -> Vec<String> {
        self.rules
            .iter()
            .filter_map(|rule| match &rule.kind {
                RuleKind::HoldMatching(p) | RuleKind::DenyUnrouted(p) => Some(p),
                _ => None,
            })
            .filter(|pattern| !self.used_patterns.contains(*pattern))
            .cloned()
            .collect()
    }
}

enum Pending {
    Nothing,
    Release,
    Resolve(Payload),
}

struct NamedTask {
    info: TaskInfo,
    pending: Pending,
    replace: Option<Replace>,
    waker: Option<Waker>,
    failing: bool,
}

/// The named tasks of one harness, kept on the harness thread.
#[derive(Default)]
pub(crate) struct Control {
    named: BTreeMap<UntypedTaskId, NamedTask>,
    returned: BTreeSet<UntypedTaskId>,
    pub(crate) errors: Vec<HarnessError>,
    external: Vec<&'static str>,
}

impl fmt::Debug for Control {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Control")
            .field("named", &self.named.len())
            .field("errors", &self.errors)
            .finish_non_exhaustive()
    }
}

impl Control {
    pub(crate) fn new(external: Vec<&'static str>) -> Self {
        Self {
            external,
            ..Self::default()
        }
    }

    pub(crate) fn infos(&self) -> impl DoubleEndedIterator<Item = &TaskInfo> {
        self.named.values().map(|task| &task.info)
    }

    /// Named tasks finished by a thread the harness does not own, still running.
    pub(crate) fn external_in_flight(&self) -> Vec<&TaskInfo> {
        self.infos()
            .filter(|info| info.external && info.state == TaskState::Pending)
            .collect()
    }

    pub(crate) fn held(&self) -> Vec<UntypedTaskId> {
        self.infos()
            .filter(|info| info.state == TaskState::Held)
            .map(|info| info.id)
            .collect()
    }

    fn oldest_held(&self, name_type: TypeId) -> Option<UntypedTaskId> {
        self.infos()
            .find(|info| info.state == TaskState::Held && info.name_type == Some(name_type))
            .map(|info| info.id)
    }

    fn next_unreturned(&self, name_type: TypeId) -> Option<UntypedTaskId> {
        self.infos()
            .find(|info| {
                info.state == TaskState::Held
                    && info.name_type == Some(name_type)
                    && !self.returned.contains(&info.id)
            })
            .map(|info| info.id)
    }

    fn started_names(&self) -> Vec<&'static str> {
        let mut names: Vec<&'static str> =
            self.infos().rev().filter_map(|info| info.name).collect();
        names.dedup();
        names
    }

    /// Gives a held task what the test decided and wakes it.
    fn act(
        &mut self,
        id: UntypedTaskId,
        pending: Pending,
        replace: Option<Replace>,
        failing: bool,
    ) -> Result {
        let Some(task) = self.named.get_mut(&id) else {
            return Err(HarnessError::UnknownTask(id).into());
        };
        if task.info.state != TaskState::Held {
            return Err(HarnessError::TaskGone {
                task: id,
                state: task.info.state,
            }
            .into());
        }
        task.pending = pending;
        task.replace = replace;
        task.failing = failing;
        if let Some(waker) = task.waker.take() {
            waker.wake();
        }
        Ok(())
    }
}

thread_local! {
    /// Where code running inside the harness, such as a fake, reports an error that fails
    /// the current step.
    static SINK: RefCell<Option<Rc<RefCell<Control>>>> = const { RefCell::new(None) };
}

/// Fails the current step of the harness on this thread with `error`. Outside a harness it
/// does nothing.
pub(crate) fn report(error: HarnessError) {
    SINK.with(|sink| {
        if let Some(control) = sink.borrow().as_ref() {
            control.borrow_mut().errors.push(error);
        }
    });
}

/// Keeps a harness's error sink installed on its thread.
#[derive(Debug)]
pub(crate) struct SinkGuard {
    previous: Option<Rc<RefCell<Control>>>,
}

impl SinkGuard {
    pub(crate) fn install(control: Rc<RefCell<Control>>) -> Self {
        let previous = SINK.with(|sink| sink.borrow_mut().replace(control));
        Self { previous }
    }
}

impl Drop for SinkGuard {
    fn drop(&mut self) {
        let previous = self.previous.take();
        SINK.with(|sink| *sink.borrow_mut() = previous);
    }
}

/// The controller the harness installs for its thread.
pub(crate) struct HarnessController<P: TestProgram> {
    control: Rc<RefCell<Control>>,
    rules: Rc<RefCell<TaskRules<P>>>,
    book: SharedBook,
    clock: VirtualClock,
}

impl<P: TestProgram> HarnessController<P> {
    pub(crate) fn new(
        control: Rc<RefCell<Control>>,
        rules: Rc<RefCell<TaskRules<P>>>,
        book: SharedBook,
        clock: VirtualClock,
    ) -> Self {
        Self {
            control,
            rules,
            book,
            clock,
        }
    }
}

impl<P: TestProgram> Controller for HarnessController<P> {
    fn start(&self, meta: ProbeMeta) -> ProbeId {
        let parent = current_task();
        let (id, spawn) = {
            let mut book = lock(&self.book);
            let spawn = parent
                .and_then(|parent| book.tasks.get(&parent))
                .map_or(Spawn::Subscription, |record| record.spawn.clone());
            (book.allocate(), spawn)
        };
        let external = meta.external
            || self
                .control
                .borrow()
                .external
                .iter()
                .any(|pattern| pattern_matches(pattern, meta.name));
        let info = TaskInfo {
            id,
            name: Some(meta.name),
            name_type: Some(meta.name_type),
            detail: meta.detail,
            location: Some(meta.location),
            spawn,
            parent,
            spawned_at: self.clock.of(tokio::time::Instant::now()),
            state: TaskState::Pending,
            external,
            polls: 0,
            produced: Vec::new(),
            foreign_wakes: 0,
        };
        let from_calls = meta.location.file() == crate::fakes::calls::FILE;
        let decision = self
            .rules
            .borrow_mut()
            .decide(&info, meta.name_type, from_calls);
        let mut task = NamedTask {
            info,
            pending: Pending::Nothing,
            replace: None,
            waker: None,
            failing: false,
        };
        let mut control = self.control.borrow_mut();
        match decision {
            Decision::Run => {}
            Decision::Hold => task.info.state = TaskState::Held,
            Decision::Resolve(payload) => task.pending = Pending::Resolve(payload),
            Decision::Deny => {
                task.info.state = TaskState::Held;
                control.errors.push(HarnessError::Unrouted {
                    task: id,
                    name: meta.name,
                    location: meta.location.to_string(),
                });
            }
        }
        control.named.insert(id, task);
        ProbeId(id.get())
    }

    fn gate(&self, id: ProbeId, cx: &mut Context<'_>) -> Gate {
        let mut control = self.control.borrow_mut();
        let Some(task) = control.named.get_mut(&UntypedTaskId::new(id.0)) else {
            return Gate::Run;
        };
        task.info.polls += 1;
        match std::mem::replace(&mut task.pending, Pending::Nothing) {
            Pending::Resolve(payload) => return Gate::Resolve(payload),
            Pending::Release => {
                task.info.state = TaskState::Pending;
                return Gate::Run;
            }
            Pending::Nothing => {}
        }
        if task.info.state == TaskState::Held {
            task.waker = Some(cx.waker().clone());
            return Gate::Hold;
        }
        Gate::Run
    }

    fn complete(&self, id: ProbeId) -> Option<Replace> {
        let mut control = self.control.borrow_mut();
        control
            .named
            .get_mut(&UntypedTaskId::new(id.0))
            .and_then(|task| task.replace.take())
    }

    fn finish(&self, id: ProbeId, how: Finish) {
        let mut control = self.control.borrow_mut();
        let Some(task) = control.named.get_mut(&UntypedTaskId::new(id.0)) else {
            return;
        };
        task.info.state = match how {
            Finish::Completed => TaskState::Finished,
            Finish::Resolved if task.failing => TaskState::Failed,
            Finish::Resolved => TaskState::Resolved,
            Finish::Dropped => TaskState::Aborted,
        };
    }

    fn rejected(&self, id: ProbeId, payload: Payload) {
        self.control
            .borrow_mut()
            .errors
            .push(HarnessError::RejectedPayload {
                task: UntypedTaskId::new(id.0),
                name: payload.name(),
            });
    }

    fn real_timer(&self, component: &'static str) {
        self.control
            .borrow_mut()
            .errors
            .push(HarnessError::RealTimer { component });
    }
}

/// The test's view of the app's tasks: `ui.tasks()`.
#[must_use]
pub struct Tasks<'h, P: TestProgram> {
    harness: &'h mut Harness<P>,
    snapshot: Vec<TaskInfo>,
}

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

impl<'h, P: TestProgram> Tasks<'h, P> {
    pub(crate) fn new(harness: &'h mut Harness<P>) -> Self {
        let snapshot = harness.task_infos();
        Self { harness, snapshot }
    }

    fn refresh(&mut self) {
        self.snapshot = self.harness.task_infos();
    }

    /// The rules, to add or remove one mid-test.
    pub fn rules(&mut self) -> std::cell::RefMut<'_, TaskRules<P>> {
        self.harness.rules()
    }

    /// Tasks still running or held.
    pub fn pending(&self) -> impl Iterator<Item = &TaskInfo> {
        self.snapshot.iter().filter(|info| info.state.is_live())
    }

    /// Tasks held until the test acts.
    pub fn held(&self) -> impl Iterator<Item = &TaskInfo> {
        self.snapshot
            .iter()
            .filter(|info| info.state == TaskState::Held)
    }

    /// Every task the app started.
    pub fn all(&self) -> impl Iterator<Item = &TaskInfo> {
        self.snapshot.iter()
    }

    /// One task.
    pub fn info(&self, id: impl Into<UntypedTaskId>) -> Result<&TaskInfo> {
        let id = id.into();
        self.snapshot
            .iter()
            .find(|info| info.id == id)
            .ok_or_else(|| HarnessError::UnknownTask(id).into())
    }

    /// The typed id of a task named `N`, for callers that learnt the task by its untyped id,
    /// such as a connection speaking the remote protocol. Fails if the task has another name.
    pub fn typed<N: TaskName>(&self, id: UntypedTaskId) -> Result<TaskId<N>> {
        if !self.info(id)?.is::<N>() {
            return Err(HarnessError::UnknownTask(id).into());
        }
        Ok(TaskId::new(id))
    }

    /// Waits, up to the default timeout, for a held task named `N` not returned before, and
    /// returns the oldest.
    pub fn next_held<N: TaskName>(&mut self) -> Result<TaskId<N>> {
        let timeout = self.harness.default_timeout();
        self.next_held_within::<N>(timeout)
    }

    /// [`next_held`](Self::next_held) with its own timeout.
    pub fn next_held_within<N: TaskName>(
        &mut self,
        timeout: impl Into<VirtualDuration>,
    ) -> Result<TaskId<N>> {
        let timeout = timeout.into();
        let name_type = TypeId::of::<N>();
        let control = self.harness.control();
        self.harness.wait_for(timeout, |_| {
            control.borrow().next_unreturned(name_type).is_some()
        })?;
        self.refresh();
        let mut control = control.borrow_mut();
        let Some(id) = control.next_unreturned(name_type) else {
            return Err(HarnessError::NoTask {
                name: N::NAME,
                timeout,
                started: control.started_names(),
            }
            .into());
        };
        control.returned.insert(id);
        Ok(TaskId::new(id))
    }

    fn oldest<N: TaskName>(&mut self) -> Result<UntypedTaskId> {
        let timeout = self.harness.default_timeout();
        let name_type = TypeId::of::<N>();
        let control = self.harness.control();
        self.harness.wait_for(timeout, |_| {
            control.borrow().oldest_held(name_type).is_some()
        })?;
        let control = control.borrow();
        control.oldest_held(name_type).ok_or_else(|| {
            HarnessError::NoTask {
                name: N::NAME,
                timeout,
                started: control.started_names(),
            }
            .into()
        })
    }

    fn act(
        &mut self,
        id: UntypedTaskId,
        pending: Pending,
        replace: Option<Replace>,
        failing: bool,
    ) -> Result {
        self.harness
            .control()
            .borrow_mut()
            .act(id, pending, replace, failing)?;
        let settled = self.harness.settle();
        self.refresh();
        settled
    }

    /// Lets the oldest held task named `N` run its real future.
    pub fn release<N: TaskName>(&mut self) -> Result {
        let id = self.oldest::<N>()?;
        self.act(id, Pending::Release, None, false)
    }

    /// Answers the oldest held task named `N`; its real future never runs.
    pub fn resolve<N: TaskName>(&mut self, output: N::Output) -> Result {
        let id = self.oldest::<N>()?;
        self.act(id, Pending::Resolve(Payload::new::<N>(output)), None, false)
    }

    /// Fails the oldest held task named `N` with its error type.
    pub fn fail<N: Fallible>(&mut self, error: N::Err) -> Result {
        let id = self.oldest::<N>()?;
        self.act(id, Pending::Resolve(Payload::fail::<N>(error)), None, true)
    }

    /// Runs the oldest held task named `N` and maps its real output.
    pub fn replace<N: TaskName>(
        &mut self,
        map: impl FnOnce(N::Output) -> N::Output + 'static,
    ) -> Result {
        let id = self.oldest::<N>()?;
        self.act(id, Pending::Release, Some(Replace::new::<N>(map)), false)
    }

    /// [`release`](Self::release) for one task.
    pub fn release_task<N: TaskName>(&mut self, id: TaskId<N>) -> Result {
        self.act(id.id, Pending::Release, None, false)
    }

    /// [`resolve`](Self::resolve) for one task.
    pub fn resolve_task<N: TaskName>(&mut self, id: TaskId<N>, output: N::Output) -> Result {
        self.act(
            id.id,
            Pending::Resolve(Payload::new::<N>(output)),
            None,
            false,
        )
    }

    /// [`fail`](Self::fail) for one task.
    pub fn fail_task<N: Fallible>(&mut self, id: TaskId<N>, error: N::Err) -> Result {
        self.act(
            id.id,
            Pending::Resolve(Payload::fail::<N>(error)),
            None,
            true,
        )
    }

    /// [`replace`](Self::replace) for one task.
    pub fn replace_task<N: TaskName>(
        &mut self,
        id: TaskId<N>,
        map: impl FnOnce(N::Output) -> N::Output + 'static,
    ) -> Result {
        self.act(id.id, Pending::Release, Some(Replace::new::<N>(map)), false)
    }

    /// Lets an unnamed task held by [`TaskRules::hold_unnamed`] run.
    pub fn release_unnamed(&mut self, id: UntypedTaskId) -> Result {
        self.harness.release_unnamed(id)?;
        let settled = self.harness.settle();
        self.refresh();
        settled
    }

    /// Drops a task. A named task is cancelled with the unnamed task it runs inside.
    pub fn cancel(&mut self, id: impl Into<UntypedTaskId>) -> Result {
        self.harness.cancel_task(id.into(), None)?;
        let settled = self.harness.settle();
        self.refresh();
        settled
    }

    /// Drops an unnamed task's stream and queues `message` as if the task had produced it.
    pub fn replace_with_message(
        &mut self,
        id: impl Into<UntypedTaskId>,
        message: P::Message,
    ) -> Result {
        self.harness.cancel_task(id.into(), Some(message))?;
        let settled = self.harness.settle();
        self.refresh();
        settled
    }
}

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

    #[test]
    fn patterns_match_module_paths() {
        assert!(pattern_matches("notes::api::*", "notes::api::SaveNote"));
        assert!(!pattern_matches("notes::api::*", "notes::apis::SaveNote"));
        assert!(pattern_matches(
            "notes::api::SaveNote",
            "notes::api::SaveNote"
        ));
        assert!(!pattern_matches(
            "notes::api::SaveNote",
            "notes::api::SaveNotes"
        ));
        assert!(pattern_matches("*::SaveNote", "notes::api::SaveNote"));
        assert!(pattern_matches("notes::*::Save*", "notes::api::SaveNote"));
        assert!(!pattern_matches("notes::*::Open*", "notes::api::SaveNote"));
        assert!(pattern_matches("*", "anything"));
    }

    #[test]
    fn task_ids_are_copy_and_compare_by_id() {
        icedwright_probe::task_name!(Save: Result<u32, String>);
        let a: TaskId<Save> = TaskId::new(UntypedTaskId::new(3));
        let b = a;
        assert_eq!(a, b);
        assert_eq!(UntypedTaskId::from(a).to_string(), "#3");
        assert_eq!(format!("{a:?}"), format!("TaskId<{}>(#3)", Save::NAME));
    }
}