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
//! Recording every step a test takes, and writing it through `icedwright-trace` when the test
//! fails, or always under `ICEDWRIGHT_TRACE=always`.
//!
//! Steps are kept as plain values while the test runs and handed to a `TraceWriter` only
//! when the trace is written, so a passing test never pays for PNG encoding.

use std::collections::BTreeMap;
use std::panic::Location;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;

use icedwright_semantics::SemanticTree;
use icedwright_semantics::yaml::{self, YamlOptions};
use icedwright_trace::{
    BootInstant, FramePolicy, Png, RawSubscriptionId, RawTaskId, RawWindowId, RealSpan,
    SourceLocation, StepKind, StepOutcome, TraceConfig, TraceMessage, TraceMeta, TraceMode,
    TraceOrigin, TraceStart, TraceWriter, WindowMeta,
};
use icedwright_types::units::Logical;
use icedwright_types::{Frame, VirtualDuration};

use crate::error::{HarnessError, Result};
use crate::harness::{Harness, TestProgram};
use crate::headed::{Headed, HeadedLink, HeadedSession, Hello};
use crate::messages::MessageOrigin;

/// A message as the trace keeps it.
#[derive(Debug)]
struct Message {
    at: VirtualDuration,
    debug: String,
    origin: MessageOrigin,
}

/// A step as the trace keeps it until it is written.
#[derive(Debug)]
struct Pending {
    kind: StepKind,
    location: SourceLocation,
    start: VirtualDuration,
    end: VirtualDuration,
    messages: Vec<Message>,
    tree: Option<String>,
    frame: Option<Arc<Frame>>,
    outcome: StepOutcome,
    real: RealSpan,
}

/// One test's trace while it runs.
#[derive(Debug)]
pub(crate) struct TraceRecorder {
    config: TraceConfig,
    path: PathBuf,
    real_start: Instant,
    boot: Option<BootInstant>,
    boot_tree: String,
    boot_frame: Option<Arc<Frame>>,
    windows: Vec<(u64, Logical<icedwright_types::Size>)>,
    scale: icedwright_types::ScaleFactor,
    steps: Vec<Pending>,
    last_frame: Option<Arc<Frame>>,
    last_failure: Option<String>,
    widget_ids: BTreeMap<usize, usize>,
    /// Output directories whose paths failure messages may name.
    out_roots: Vec<PathBuf>,
}

/// The YAML of every window in a tree, one after another, with bounds and ids so a viewer can
/// outline nodes. Unique widget ids are renumbered in the order this trace first sees them.
fn tree_yaml(tree: &SemanticTree, widget_ids: &mut BTreeMap<usize, usize>) -> String {
    let mut tree = tree.clone();
    tree.renumber_widget_ids(|raw| {
        let next = widget_ids.len();
        *widget_ids.entry(raw).or_insert(next)
    });
    let options = YamlOptions {
        include_bounds: true,
        include_ids: true,
        ..YamlOptions::default()
    };
    tree.roots()
        .iter()
        .map(|root| yaml::write(&tree, *root, &options))
        .collect::<Vec<_>>()
        .join("\n")
}

/// What a stored failure message calls the output directory, so a trace reads the same
/// whichever directory a run wrote to.
pub(crate) const OUT_PLACEHOLDER: &str = "$ICEDWRIGHT_OUT_DIR";

/// `message` with every path under one of `roots` written relative to [`OUT_PLACEHOLDER`].
/// Longer roots are replaced first, so a root nested in another keeps its full length.
pub(crate) fn stable_message(message: &str, roots: &[PathBuf]) -> String {
    let mut roots: Vec<String> = roots
        .iter()
        .map(|root| root.to_string_lossy().trim_end_matches('/').to_owned())
        .filter(|root| !root.is_empty())
        .collect();
    roots.sort_by_key(|root| std::cmp::Reverse(root.len()));
    roots.dedup();
    roots.iter().fold(message.to_owned(), |text, root| {
        text.replace(root.as_str(), OUT_PLACEHOLDER)
    })
}

/// A relative output directory under `target/` names the target directory the test binary
/// was built into, wherever cargo runs it from: `target/icedwright` becomes
/// `<target dir>/icedwright`, which honours `CARGO_TARGET_DIR`.
pub(crate) fn resolve_out_dir(dir: &Path, exe: Option<&Path>) -> PathBuf {
    let Ok(under_target) = dir.strip_prefix("target") else {
        return dir.to_path_buf();
    };
    let target = exe
        .and_then(Path::parent)
        .filter(|deps| deps.ends_with("deps"))
        .and_then(Path::parent)
        .and_then(Path::parent);
    match target {
        Some(target) => target.join(under_target),
        None => dir.to_path_buf(),
    }
}

/// Where a test's trace goes: libtest names each test's thread after its path.
fn trace_path(config: &TraceConfig, trace_dir: Option<PathBuf>) -> PathBuf {
    let exe = std::env::current_exe().ok();
    let config = &config
        .clone()
        .out_dir(resolve_out_dir(config.output_dir(), exe.as_deref()));
    let crate_name = std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "unknown".to_owned());
    let thread = std::thread::current();
    let test = thread.name().unwrap_or("main").to_owned();
    let (module, name) = match test.rsplit_once("::") {
        Some((module, name)) => (format!("{crate_name}::{module}"), name.to_owned()),
        None => (crate_name, test),
    };
    match trace_dir {
        Some(dir) => {
            let mut path = dir;
            module.split("::").for_each(|part| path.push(part));
            path.push(format!("{name}.iwtrace"));
            path
        }
        None => config.trace_path(&module, &name),
    }
}

fn png(frame: Option<&Arc<Frame>>) -> Option<Png> {
    frame.and_then(|frame| Png::encode(frame).ok())
}

impl TraceRecorder {
    /// Starts a trace from what the app shows at boot, or nothing when tracing is off.
    pub(crate) fn start<P: TestProgram>(
        harness: &mut Harness<P>,
        config: &TraceConfig,
    ) -> Option<Self> {
        if config.trace_mode() == TraceMode::Off {
            return None;
        }
        let trace_dir = crate::config::EnvOverrides::from_env()
            .ok()
            .and_then(|env| env.trace_dir.clone());
        let exe = std::env::current_exe().ok();
        let mut out_roots = vec![resolve_out_dir(config.output_dir(), exe.as_deref())];
        out_roots.extend(trace_dir.clone());
        out_roots.extend(
            crate::snapshot::SnapshotEnv::from_vars(
                |name| std::env::var(name).ok(),
                exe.as_deref(),
                None,
            )
            .ok()
            .map(|env| env.out_dir),
        );
        let mut widget_ids = BTreeMap::new();
        let boot_tree = harness
            .tree()
            .map(|tree| tree_yaml(&tree, &mut widget_ids))
            .unwrap_or_default();
        let boot_frame = match config.trace_mode() {
            TraceMode::Always => harness.trace_frame(config.frame_policy(), true),
            _ => None,
        };
        Some(Self {
            config: config.clone(),
            path: trace_path(config, trace_dir),
            real_start: harness.hang.now(),
            boot: BootInstant::from_std(&harness.clock.epoch().into_std()),
            boot_tree,
            last_frame: boot_frame.clone(),
            boot_frame,
            windows: harness
                .set
                .windows
                .values()
                .map(|state| (state.ordinal, state.info.logical_size))
                .collect(),
            scale: harness.system_scale,
            steps: Vec::new(),
            last_failure: None,
            widget_ids,
            out_roots,
        })
    }

    /// Where the trace will be written.
    pub(crate) fn path(&self) -> &Path {
        &self.path
    }

    /// Whether the trace will be written: a test passed if it is not panicking and its last
    /// step did not fail.
    pub(crate) fn will_write(&self, panicking: bool) -> bool {
        let passed = !panicking && self.last_failure.is_none();
        self.config.trace_mode().writes(passed)
    }

    /// Under `on-failure`, steps keep no frames while the test runs, so the frame after the
    /// last step is rendered when the trace is written.
    pub(crate) fn needs_final_frame(&self) -> bool {
        self.config.trace_mode() == TraceMode::OnFailure
            && self.config.frame_policy() != FramePolicy::None
    }

    pub(crate) fn set_final_frame(&mut self, frame: Option<Arc<Frame>>) {
        if let Some(last) = self.steps.last_mut() {
            last.frame = frame;
        }
    }

    pub(crate) fn frame_policy(&self) -> FramePolicy {
        self.config.frame_policy()
    }

    /// Writes the trace if the mode asks for it.
    pub(crate) fn finish(self, panicking: bool) {
        let passed = !panicking && self.last_failure.is_none();
        if !self.will_write(panicking) {
            return;
        }
        let path = self.path.clone();
        let Some(writer) = self.into_writer() else {
            return;
        };
        if let Some(parent) = path.parent()
            && std::fs::create_dir_all(parent).is_err()
        {
            return;
        }
        let Ok(mut file) = std::fs::File::create(&path) else {
            return;
        };
        if writer.write(&mut file).is_ok() && !passed {
            eprintln!("icedwright: trace written to {}", path.display());
        }
    }

    fn into_writer(self) -> Option<TraceWriter> {
        let thread = std::thread::current();
        let meta = TraceMeta {
            test: thread.name().unwrap_or("main").to_owned(),
            crate_name: std::env::var("CARGO_PKG_NAME").unwrap_or_default(),
            iced_version: "0.14".to_owned(),
            windows: Vec::new(),
            theme: None,
            scale_factor: self.scale,
            failure: self.last_failure.clone(),
        };
        let start = TraceStart {
            boot: self.boot,
            tree: self.boot_tree,
            frame: png(self.boot_frame.as_ref()),
        };
        let mut writer = TraceWriter::new(meta, &self.config, start);
        for (ordinal, size) in self.windows {
            let window = writer.ordinal(RawWindowId(ordinal));
            writer.meta_mut().windows.push(WindowMeta { window, size });
        }
        let mut previous: Option<Arc<Frame>> = self.boot_frame;
        for pending in self.steps {
            let _ = write_pending(&mut writer, pending, &mut previous);
        }
        Some(writer)
    }
}

/// Writes one recorded step. A frame is stored only when it differs from `previous`, the
/// last one stored, and its PNG is returned.
fn write_pending(
    writer: &mut TraceWriter,
    pending: Pending,
    previous: &mut Option<Arc<Frame>>,
) -> Option<Png> {
    let mut step = writer.begin_step(pending.kind, pending.location, pending.start);
    for message in pending.messages {
        let origin = match message.origin {
            MessageOrigin::Task(id) => TraceOrigin::Task(step.ordinal(RawTaskId(id.get()))),
            MessageOrigin::Subscription => {
                TraceOrigin::Subscription(step.ordinal(RawSubscriptionId(0)))
            }
            MessageOrigin::Input(_) => TraceOrigin::Widget { event: 0 },
            _ => TraceOrigin::Task(step.ordinal(RawTaskId(0))),
        };
        step.message(TraceMessage {
            at: message.at,
            debug: message.debug,
            full_len: None,
            variant: None,
            origin,
        });
    }
    if let Some(tree) = pending.tree {
        step.tree(tree);
    }
    let changed = match (&pending.frame, &*previous) {
        (Some(frame), Some(before)) => !Arc::ptr_eq(frame, before),
        (Some(_), None) => true,
        (None, _) => false,
    };
    let stored = changed.then(|| png(pending.frame.as_ref())).flatten();
    if let Some(frame) = &stored {
        step.frame(frame.clone());
    }
    if pending.frame.is_some() {
        *previous = pending.frame;
    }
    let _ = step.end(pending.outcome, pending.end, pending.real);
    stored
}

/// A headed test's stream: its own trace writer, so each step studio receives is the record a
/// trace would hold, and the link to studio.
#[derive(Debug)]
pub(crate) struct HeadedStream {
    session: HeadedSession,
    writer: TraceWriter,
    widget_ids: BTreeMap<usize, usize>,
    previous: Option<Arc<Frame>>,
    last_failure: Option<String>,
    real_start: Instant,
}

impl HeadedStream {
    pub(crate) fn pause(&mut self, next: Option<&str>) -> bool {
        self.session.pause(next)
    }
}

impl<P: TestProgram> Harness<P> {
    /// Connects headed mode once boot has settled, when the configuration asks for it.
    pub(crate) fn start_headed(
        &mut self,
        mode: Headed,
        slow_mo: Option<std::time::Duration>,
        socket: Option<PathBuf>,
        link: Option<Box<dyn HeadedLink>>,
    ) {
        if mode == Headed::Off {
            return;
        }
        let answer_within = crate::headed::answer_within(self.hang.window(), slow_mo);
        let link = match (link, socket) {
            (Some(link), _) => Some(link),
            (None, Some(socket)) => crate::headed::connect(&socket, answer_within),
            (None, None) => {
                eprintln!(
                    "icedwright: headed mode needs XDG_RUNTIME_DIR or a headed socket; running headless"
                );
                None
            }
        };
        let Some(link) = link else {
            return;
        };
        let thread = std::thread::current();
        let test = thread.name().unwrap_or("main");
        let scale = self
            .set
            .windows
            .values()
            .min_by_key(|state| state.ordinal)
            .map_or(1.0, |state| state.info.scale_factor.get());
        let hello = Hello {
            test,
            mode,
            slow_mo,
            scale,
            answer_within,
        };
        let Some(session) = HeadedSession::start(link, hello) else {
            return;
        };
        let mut widget_ids = BTreeMap::new();
        let tree = self
            .tree()
            .map(|tree| tree_yaml(&tree, &mut widget_ids))
            .unwrap_or_default();
        let meta = TraceMeta {
            test: test.to_owned(),
            crate_name: std::env::var("CARGO_PKG_NAME").unwrap_or_default(),
            iced_version: "0.14".to_owned(),
            windows: Vec::new(),
            theme: None,
            scale_factor: self.system_scale,
            failure: None,
        };
        let start = TraceStart {
            boot: BootInstant::from_std(&self.clock.epoch().into_std()),
            tree,
            frame: None,
        };
        let config = TraceConfig::new().frames(FramePolicy::EveryStep);
        self.headed = Some(HeadedStream {
            session,
            writer: TraceWriter::new(meta, &config, start),
            widget_ids,
            previous: None,
            last_failure: None,
            real_start: self.hang.now(),
        });
    }

    /// Sends a finished step and the frame after it to studio, and waits for studio to
    /// acknowledge it. The frame is drawn as a trace frame is, which changes nothing. Returns
    /// the hang when studio stalled.
    fn stream_step<T>(
        &mut self,
        kind: &StepKind,
        location: &'static Location<'static>,
        started: icedwright_types::VirtualInstant,
        first_message: usize,
        result: &Result<T>,
    ) -> Option<HarnessError> {
        self.headed.as_ref()?;
        let ended = self.now();
        let tree = self.tree().ok();
        let frame = self.trace_frame(FramePolicy::EveryStep, true);
        let real_ended = self.hang.now();
        let mut headed = self.headed.take()?;
        let outcome = match result {
            Ok(_) => {
                headed.last_failure = None;
                StepOutcome::Passed
            }
            Err(error) => {
                let message = error.to_string();
                headed.last_failure = Some(message.clone());
                StepOutcome::Failed { message }
            }
        };
        let messages = self
            .messages
            .get(first_message..)
            .unwrap_or_default()
            .iter()
            .map(|record| Message {
                at: record.at.since_boot(),
                debug: record.debug.clone(),
                origin: record.origin,
            })
            .collect();
        let real = RealSpan {
            start: std::time::Duration::ZERO,
            end: real_ended.saturating_duration_since(headed.real_start),
        };
        let pending = Pending {
            kind: kind.clone(),
            location: SourceLocation::from(location),
            start: started.since_boot(),
            end: ended.since_boot(),
            messages,
            tree: tree.map(|tree| tree_yaml(&tree, &mut headed.widget_ids)),
            frame,
            outcome,
            real,
        };
        let png = write_pending(&mut headed.writer, pending, &mut headed.previous);
        let stalled = headed.writer.last_step().cloned().and_then(|step| {
            headed
                .session
                .step(&step, png.as_ref().map(Png::as_bytes))
                .err()
        });
        if headed.session.connected() {
            self.headed = Some(headed);
        }
        if let Some(stalled) = stalled {
            return Some(HarnessError::Hung {
                step: format!("{}:{}", location.file(), location.line()),
                since_progress: stalled.after,
                cause: crate::error::HangCause::HeadedStudio,
            });
        }
        self.hang.progress();
        None
    }

    /// Tells studio the test ended.
    pub(crate) fn finish_headed(&mut self) {
        let Some(headed) = self.headed.take() else {
            return;
        };
        let failure = headed
            .last_failure
            .or_else(|| std::thread::panicking().then(|| "the test panicked".to_owned()));
        headed.session.finish(failure.as_deref());
    }
}

impl<P: TestProgram> Harness<P> {
    /// Stops recording this harness's trace, so nothing is written for it whatever the mode.
    /// Tracing never changes what the app does, so the rest of the test runs the same.
    pub fn stop_tracing(&mut self) {
        self.trace = None;
    }

    /// Whether this harness is recording a trace.
    #[must_use]
    pub fn is_tracing(&self) -> bool {
        self.trace.is_some()
    }

    /// Writes the trace, if the test's outcome asks for one.
    pub(crate) fn finish_trace(&mut self) {
        let Some(mut trace) = self.trace.take() else {
            return;
        };
        let panicking = std::thread::panicking();
        if !trace.will_write(panicking) {
            return;
        }
        if trace.needs_final_frame() {
            let frame = self.trace_frame(trace.frame_policy(), true);
            trace.set_final_frame(frame);
        }
        trace.finish(panicking);
    }

    /// A frame for the trace, when the frame policy keeps one for this kind of step.
    fn trace_frame(&mut self, policy: FramePolicy, is_action: bool) -> Option<Arc<Frame>> {
        let keep = match policy {
            FramePolicy::None => false,
            FramePolicy::EveryStep => true,
            FramePolicy::ActionsOnly => is_action,
        };
        if !keep {
            return None;
        }
        let window = self.set.windows.values().min_by_key(|s| s.ordinal)?.info.id;
        self.render_caret_hidden(window).ok().map(Arc::new)
    }

    /// Runs one public step, recording it in the trace when it is the outermost step.
    #[track_caller]
    pub(crate) fn step<T>(
        &mut self,
        kind: impl FnOnce() -> StepKind,
        run: impl FnOnce(&mut Self) -> Result<T>,
    ) -> Result<T> {
        let location = Location::caller();
        self.steps += 1;
        if self.step_depth == 0 {
            self.watch.context().set_step(location);
        }
        let recorded = self.trace.is_some() || self.headed.is_some() || !self.observers.is_empty();
        if self.step_depth > 0 || !recorded {
            self.step_depth += 1;
            let result = run(self);
            self.step_depth -= 1;
            return result;
        }
        if let Some(headed) = &mut self.headed {
            let next = format!("{}:{}", location.file(), location.line());
            if headed.pause(Some(&next)) {
                self.hang.progress();
            }
        }
        let started = self.now();
        self.observe(|observer| observer.step_started(location, started));
        let real_started = self.hang.now();
        let first_message = self.messages.len();
        self.step_depth += 1;
        let result = run(self);
        self.step_depth -= 1;
        let kind = kind();
        self.record_step(
            kind.clone(),
            location,
            started,
            real_started,
            first_message,
            &result,
        );
        let stalled = self.stream_step(&kind, location, started, first_message, &result);
        let result = match (result, stalled) {
            (Ok(_), Some(hung)) => Err(hung.into()),
            (result, _) => result,
        };
        let ended = self.now();
        let error = result.as_ref().err();
        self.observe(|observer| {
            observer.step_ended(&crate::observer::StepRecord {
                kind: &kind,
                location,
                started,
                ended,
                error,
            });
        });
        result
    }

    fn record_step<T>(
        &mut self,
        kind: StepKind,
        location: &'static Location<'static>,
        started: icedwright_types::VirtualInstant,
        real_started: Instant,
        first_message: usize,
        result: &Result<T>,
    ) {
        if self.trace.is_none() {
            return;
        }
        let ended = self.now();
        let real_ended = self.hang.now();
        let tree = self.tree().ok();
        let Some(mut trace) = self.trace.take() else {
            return;
        };
        let tree = tree.map(|tree| tree_yaml(&tree, &mut trace.widget_ids));
        let frame = if trace.config.trace_mode() != TraceMode::Always {
            None
        } else if self.traced_generation == Some(self.generation) {
            trace.last_frame.clone()
        } else {
            self.trace_frame(trace.config.frame_policy(), kind.is_action())
        };
        if frame.is_some() {
            self.traced_generation = Some(self.generation);
            trace.last_frame = frame.clone();
        }
        let outcome = match result {
            Ok(_) => {
                trace.last_failure = None;
                StepOutcome::Passed
            }
            Err(error) => {
                let message = stable_message(&error.to_string(), &trace.out_roots);
                trace.last_failure = Some(message.clone());
                StepOutcome::Failed { message }
            }
        };
        let messages = self
            .messages
            .get(first_message..)
            .unwrap_or_default()
            .iter()
            .map(|record| Message {
                at: record.at.since_boot(),
                debug: stable_message(&record.debug, &trace.out_roots),
                origin: record.origin,
            })
            .collect();
        trace.steps.push(Pending {
            kind,
            location: SourceLocation::from(location),
            start: started.since_boot(),
            end: ended.since_boot(),
            messages,
            tree,
            frame,
            outcome,
            real: RealSpan {
                start: real_started.saturating_duration_since(trace.real_start),
                end: real_ended.saturating_duration_since(trace.real_start),
            },
        });
        self.trace = Some(trace);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use iced::widget::{column, text_input};
    use iced::{Element, Theme};
    use icedwright_semantics::TreeBuilder;
    use icedwright_types::role;

    use crate::snapshot::RenderOptions;

    #[derive(Debug, Default)]
    struct Field {
        typed: String,
    }

    impl Field {
        fn update(&mut self, typed: String) {
            self.typed = typed;
        }

        fn view(&self) -> Element<'_, String> {
            column![text_input("Field", &self.typed).on_input(|typed| typed)].into()
        }
    }

    #[test]
    fn trace_frames_hide_the_caret_as_snapshots_do_and_change_nothing() -> Result {
        let mut h = Harness::new(
            iced::application(Field::default, Field::update, Field::view).theme(Theme::Light),
        )?;
        let _ = h.get_by_role(role::TextBox).fill("abc")?;
        let window = h.focused().ok_or(crate::error::HarnessError::NoWindow)?;
        let messages = h.messages.len();
        let generation = h.generation;
        let traced = h.render_caret_hidden(window)?;
        assert_eq!(h.messages.len(), messages);
        assert_eq!(h.generation, generation);
        let still_focused = h.tree()?.iter().any(|node| {
            node.role == icedwright_types::Role::TextBox && node.states.focused == Some(true)
        });
        assert!(still_focused, "the field lost focus");
        let snapshot = h.render_with(window, &RenderOptions::new())?;
        assert!(
            traced == snapshot,
            "the trace frame differs from the snapshot's"
        );
        Ok(())
    }

    #[test]
    fn stored_messages_name_paths_relative_to_the_output_root() {
        let roots = [
            PathBuf::from("/work/target/icedwright/determinism/a"),
            PathBuf::from("/work/target/icedwright/determinism/a/traces/"),
        ];
        assert_eq!(
            stable_message(
                "never stable\n  previous: /work/target/icedwright/determinism/a/snapshots-failed/x/previous.png\n  trace: /work/target/icedwright/determinism/a/traces/t.iwtrace",
                &roots,
            ),
            "never stable\n  previous: $ICEDWRIGHT_OUT_DIR/snapshots-failed/x/previous.png\n  trace: $ICEDWRIGHT_OUT_DIR/t.iwtrace"
        );
        assert_eq!(stable_message("no paths here", &roots), "no paths here");
        let picked = format!(
            "Picked({:?})",
            Some(PathBuf::from(
                "/work/target/icedwright/determinism/a/tmp/notes/plan.md"
            ))
        );
        assert_eq!(
            stable_message(&picked, &roots),
            "Picked(Some(\"$ICEDWRIGHT_OUT_DIR/tmp/notes/plan.md\"))"
        );
        assert_eq!(
            stable_message("/elsewhere/file", &[PathBuf::new()]),
            "/elsewhere/file"
        );
    }

    #[test]
    fn trace_trees_carry_bounds_and_ids_renumbered_per_trace() {
        let tree = TreeBuilder::window("Todo")
            .child(role::Button, "Add", |b| b.test_id("add"))
            .build();
        let mut ids = BTreeMap::new();
        let yaml = tree_yaml(&tree, &mut ids);
        assert!(yaml.contains("test-id=\"add\""), "{yaml}");
        assert!(yaml.contains(" @ "), "{yaml}");
        assert_eq!(yaml, tree_yaml(&tree, &mut BTreeMap::new()));
    }

    /// A tree whose two buttons have unique widget ids from iced's counter at `base`.
    fn uniquely_numbered(base: usize) -> SemanticTree {
        let builder = TreeBuilder::window("Todo")
            .child(role::Button, "Add", |b| b.widget_id("first"))
            .child(role::Button, "Clear", |b| b.widget_id("second"));
        let mut raw = builder.raw();
        fn number(node: &mut icedwright_protocol::RawNode, next: &mut usize) {
            if node.widget_id.is_some() {
                node.widget_id = Some(icedwright_protocol::WidgetId::Unique(*next));
                *next += 1;
            }
            node.children
                .iter_mut()
                .for_each(|child| number(child, next));
        }
        let mut next = base;
        raw.windows
            .iter_mut()
            .for_each(|window| number(&mut window.root, &mut next));
        icedwright_semantics::infer(&raw)
    }

    #[test]
    fn unique_widget_ids_are_numbered_from_zero_in_each_trace() {
        let mut first = BTreeMap::new();
        let mut second = BTreeMap::new();
        let early = tree_yaml(&uniquely_numbered(3), &mut first);
        let late = tree_yaml(&uniquely_numbered(9000), &mut second);
        assert_eq!(early, late);
        assert!(early.contains("widget-id=#0"), "{early}");
        assert!(early.contains("widget-id=#1"), "{early}");
        assert_eq!(tree_yaml(&uniquely_numbered(3), &mut first), early);
    }

    #[test]
    fn the_default_out_dir_follows_the_target_directory() {
        let exe = Path::new("/work/target/agent/debug/deps/counter-1234");
        assert_eq!(
            resolve_out_dir(Path::new("target/icedwright"), Some(exe)),
            PathBuf::from("/work/target/agent/icedwright")
        );
    }

    #[test]
    fn other_directories_are_left_alone() {
        let exe = Path::new("/work/target/debug/deps/counter-1234");
        assert_eq!(
            resolve_out_dir(Path::new("/tmp/out"), Some(exe)),
            PathBuf::from("/tmp/out")
        );
        assert_eq!(
            resolve_out_dir(Path::new("out"), Some(exe)),
            PathBuf::from("out")
        );
        assert_eq!(
            resolve_out_dir(
                Path::new("target/icedwright"),
                Some(Path::new("/usr/bin/tool"))
            ),
            PathBuf::from("target/icedwright")
        );
    }

    #[test]
    fn traces_are_laid_out_by_test_path() {
        let config = TraceConfig::new().out_dir("/out");
        let path = trace_path(&config, None);
        let text = path.to_string_lossy();
        assert!(text.starts_with("/out/traces/"), "{text}");
        assert!(
            text.ends_with("traces_are_laid_out_by_test_path.iwtrace"),
            "{text}"
        );
        assert!(text.contains("/trace/tests/"), "{text}");
        let elsewhere = trace_path(&config, Some(PathBuf::from("/traces")));
        assert!(elsewhere.starts_with("/traces"), "{}", elsewhere.display());
    }

    #[test]
    fn a_stopped_trace_is_never_written() -> Result {
        let out =
            std::env::temp_dir().join(format!("icedwright-stop-tracing-{}", std::process::id()));
        let config = crate::config::HarnessConfig::default()
            .trace(TraceConfig::new().mode(TraceMode::Always).out_dir(&out));
        let mut h = Harness::with_config(
            iced::application(Field::default, Field::update, Field::view).theme(Theme::Light),
            config,
        )?;
        let env_off = crate::config::EnvOverrides::from_env()?.trace == Some(TraceMode::Off);
        assert_eq!(h.is_tracing(), !env_off);
        if env_off {
            return Ok(());
        }
        let path = h.trace.as_ref().map(|trace| trace.path().to_path_buf());
        let path = path.ok_or(crate::error::HarnessError::NoWindow)?;
        let _ = std::fs::remove_file(&path);
        h.stop_tracing();
        assert!(!h.is_tracing());
        let _ = h.get_by_role(role::TextBox).fill("abc")?;
        drop(h);
        assert!(!path.exists(), "{} was written", path.display());
        let _ = std::fs::remove_dir_all(&out);
        Ok(())
    }
}