day-script 0.7.4

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

//! The dayscript **recorder** (DESIGN.md §14.6): the inverse of playback. Where the engine turns a
//! script into synthesized Day events, the recorder turns the events an app receives back into a
//! script. It hooks one point, [`day_core::set_event_observer`], which every backend funnels its
//! native events through ([`day_core::enqueue_events`]), so it needs no per-toolkit code, and it
//! emits an ordinary dayscript that replays cross-toolkit through the same executor as any
//! hand-written one.
//!
//! Scope is narrow: **actions only, and only where the step is portable**. A tap, a text edit, a
//! selection/toggle, a navigation, a back: the id-addressed things a walkthrough is made of.
//! Positional taps, gestures, slider drags, and native OS chrome are dropped (see
//! `event_to_step`); the resulting script is a starting point to edit, not a pixel-exact replay.
//!
//! Everything here is main-thread state (the observer only ever runs on the main thread, where
//! day-core dispatches). On wasm there is no in-process playback ([`play`]); the WebSocket
//! transport drives the page instead (docs/web.md).

use std::cell::{OnceCell, RefCell};
use std::path::{Path, PathBuf};

use day_reactive::Signal;
use day_spec::{Event, NodeId};

use crate::Step;

// The recorder and CLI use the same canonical format; preserve the recorder's public paths.
pub use day_script_protocol::{steps_from_yaml, steps_to_yaml};

/// Like [`steps_to_yaml`], but each step's identifying line carries a trailing `# "label"` comment
/// naming the control it came from (§14.6): its accessibility label, or its visible text. The
/// comment sits on the `id:` line for a tap/input/select and the `route:` line for a navigate, so a
/// reader sees `route: focus # "Focus"`. Comments are ordinary YAML, so an annotated script parses
/// and replays exactly as the bare one does; this is the form the recorder streams and saves.
pub fn annotate_yaml(steps: &[Step], labels: &[Option<String>]) -> String {
    let yaml = steps_to_yaml(steps);
    // serde_norway renders each step as a `- <op>:` list item followed by indented params. Walk the
    // lines, tracking which step we are inside, and append the comment to that step's key line.
    let key_of = |step: &Step| match step {
        Step::Tap { .. }
        | Step::Input { .. }
        | Step::Select { .. }
        | Step::Activate { .. }
        | Step::WaitFor { .. } => Some("id:"),
        Step::Navigate { .. } => Some("route:"),
        _ => None,
    };
    let mut out = String::with_capacity(yaml.len());
    let mut idx: isize = -1;
    let mut done_this_step = false;
    for line in yaml.lines() {
        if let Some(rest) = line.strip_prefix("- ") {
            let _ = rest;
            idx += 1;
            done_this_step = false;
        }
        out.push_str(line);
        if !done_this_step
            && idx >= 0
            && let Some(Some(label)) = labels.get(idx as usize)
            && let Some(Some(key)) = steps.get(idx as usize).map(key_of)
            && line.trim_start().starts_with(key)
        {
            // A comment cannot span lines, and a quote would confuse the eye, so collapse
            // whitespace and drop any embedded quote so the annotation stays a clean single token.
            let clean = label
                .split_whitespace()
                .collect::<Vec<_>>()
                .join(" ")
                .replace('"', "");
            out.push_str(&format!(" # \"{clean}\""));
            done_this_step = true;
        }
        out.push('\n');
    }
    out
}

// ---------------------------------------------------------------------------
// Event -> Step
// ---------------------------------------------------------------------------

/// Map a native event to the dayscript step that reproduces it: **actions only, semantic only**.
/// Returns `None` for everything the recorder drops.
///
/// `Tap(Point)` records only when the node carries an id, and then as an id-addressed `Tap` step;
/// the coordinate is discarded. It has to: a `Button::style(…)` is not a native button but a
/// composed piece whose action rides `Decorate::on_tap`, so it delivers `Tap` and never `Pressed`
/// (day-pieces `leaves.rs`/`decorators.rs`), as does every tappable shape or card. Dropping it
/// silently omitted those controls from every recording while `Step::Tap` replayed them perfectly,
/// since playback emits both `Pressed` and `Tap` for exactly that reason. A node that delivers
/// both in one pump records once; see `on_event`.
///
/// Dropped, and why:
/// - an id-less `Tap`, and `LongPress`/`ContextMenu`: a bare coordinate is not portable;
/// - `Drag`/`ScrollChanged`/`Pointer`/`Key`/`WindowResized`/`FrameChanged`/`Submitted`/
///   `FocusChanged`: gesture and low-level input, no id-addressed step;
/// - `ValueChanged` (a slider mid-drag): the settled value arrives separately as
///   `ValueCommitted`, which is recorded (recording both would write a step per tick);
/// - `SelectionSet` (multi-select): no single-index step covers it;
/// - `ListReorder`/`NavRegroup`/`ListDelete` (the deferred commit of a native drag/swipe,
///   docs/list.md, docs/navigation.md): the `reorder:`/`delete_row:` steps replay them, but the
///   recorder does not yet write those steps; `CoverHidden` is teardown plumbing, not an action;
/// - lifecycle / menu / toolbar / present-result / custom / window events: not the user UI actions
///   the recorder targets.
///
/// An id-less `Pressed`/`TextChanged`/`SelectionChanged`/`ToggleChanged` is dropped too: without an
/// id there is no portable step to write.
fn event_to_step(id: Option<&str>, ev: &Event) -> Option<Step> {
    match ev {
        // Both tap shapes map to the same step: a native button's `Pressed`, and the `Tap` a
        // composed `.on_tap` piece gets. `on_event` collapses a node that delivers both.
        Event::Pressed | Event::Tap(_) => id.map(|id| Step::Tap {
            if_present: false,
            at: None,
            id: id.to_string(),
            repeat: Some(1),
            modifiers: Vec::new(),
        }),
        Event::TextChanged(text) => id.map(|id| Step::Input {
            id: id.to_string(),
            text: Some(text.clone()),
            key: None,
            args: None,
        }),
        Event::ListActivated(index) => id.map(|id| Step::Activate {
            id: id.to_string(),
            index: *index,
        }),
        Event::SelectionChanged(index) => id.map(|id| Step::Select {
            id: id.to_string(),
            index: *index,
            if_present: false,
        }),
        // Playback drives a toggle through `select` (index = the bool as 0/1), the pattern
        // Day-Skies' weather.yaml uses, so a recorded toggle replays without a `toggle` step.
        Event::ToggleChanged(on) => id.map(|id| Step::Select {
            id: id.to_string(),
            index: *on as i64,
            if_present: false,
        }),
        // The settled value of a slider, not the drag. `ValueChanged` fires on every tick (a
        // drag from 1 to 100 and back to 50 would write a hundred steps and print a hundred
        // lines), so the recorder ignores it and takes `ValueCommitted`, which fires once with
        // the value the user let go on (day-spec `Event::ValueCommitted`).
        Event::ValueCommitted(value) => id.map(|id| Step::SetValue {
            id: id.to_string(),
            value: *value,
        }),
        // Navigation (RouteRequested, NavBack, and every nav_link/sidebar/stack push that calls
        // `navigate` from an event handler) is captured by the nav observer via route changes,
        // not here; see `on_nav`. Mapping it here too would double-record RouteRequested.
        _ => None,
    }
}

/// What the executor synthesizes for each step, and what the recorder must do with it.
///
/// The recorder and the executor are inverses, and they drifted: `Step::Tap` has always
/// synthesized both a `Pressed` and a positional `Tap` (a native button ignores `Tap` and a
/// composed `.on_tap` piece ignores `Pressed`), while `event_to_step` recognized only the first.
/// Every styled button and tappable shape therefore replayed perfectly and recorded as nothing at
/// all.
///
/// This table states the intended disposition of every event playback emits, and
/// [`playback_and_recording_agree`] holds `event_to_step` to it. The rule that matters is
/// [`Disposition::Records`]: every event a recordable step emits must map back to that same step.
/// One of them mapping is not enough, because different piece kinds receive different ones, so
/// an unmapped event means some class of control is silently unrecordable.
///
/// Adding an event to a step's emission means adding it here, which means choosing a disposition.
/// The table exists so that the choice cannot be made by omission.
#[cfg(test)]
const PLAYBACK_EMISSIONS: &[(&str, &[Event], Disposition)] = &[
    // lib.rs `Step::Tap`: both shapes, so one step drives either kind of control.
    ("tap", &[Event::Pressed], Disposition::Records("tap")),
    (
        "tap",
        &[Event::Tap(day_spec::Point::ZERO)],
        Disposition::Records("tap"),
    ),
    (
        "activate",
        &[Event::ListActivated(1)],
        Disposition::Records("activate"),
    ),
    // lib.rs `Step::Select`, and a toggle, which replays through `select`.
    (
        "select",
        &[Event::SelectionChanged(1)],
        Disposition::Records("select"),
    ),
    (
        "toggle",
        &[Event::ToggleChanged(true)],
        Disposition::Records("select"),
    ),
    // lib.rs `Step::Input` paints through `day_core::synthesize_text`, which lands as this.
    (
        "input",
        &[Event::TextChanged(String::new())],
        Disposition::Records("input"),
    ),
    // Not recorded. Each is a considered omission, not an oversight:
    (
        "submit",
        &[Event::Submitted],
        Disposition::Dropped("a submit follows the input that recorded it"),
    ),
    (
        "set_value",
        &[Event::ValueChanged(0.5)],
        Disposition::Dropped("mid-drag; the settled value arrives as ValueCommitted"),
    ),
    (
        "set_value",
        &[Event::ValueCommitted(0.5)],
        Disposition::Records("set_value"),
    ),
];

/// A step's on-disk op name (`tap`, `select`, …): the same tag [`step_to_entry`] writes, read back
/// through serde so the test compares what a script would say.
#[cfg(test)]
fn step_entry_op(step: &Step) -> String {
    match serde_json::to_value(step) {
        Ok(serde_json::Value::Object(m)) => m
            .get("op")
            .and_then(|v| v.as_str())
            .unwrap_or("<untagged>")
            .to_string(),
        _ => "<unserializable>".to_string(),
    }
}

/// The recorder's intended treatment of an emitted event.
#[cfg(test)]
enum Disposition {
    /// Must map back to the named step op.
    Records(&'static str),
    /// Must map to nothing, for the stated reason.
    Dropped(&'static str),
}

/// Whether appending `next` should replace the last step rather than push a new one: the
/// coalescing rules that keep a recording readable. Every keystroke in a field, or every step of a
/// multi-step selection, collapses to the final value; consecutive navigations collapse to the last
/// destination. Taps never coalesce (each is its own action).
fn coalesces(last: &Step, next: &Step) -> bool {
    match (last, next) {
        (Step::Input { id: a, .. }, Step::Input { id: b, .. }) => a == b,
        (Step::Select { id: a, .. }, Step::Select { id: b, .. }) => a == b,
        (Step::Navigate { .. }, Step::Navigate { .. }) => true,
        _ => false,
    }
}

// ---------------------------------------------------------------------------
// Recorder state (main-thread thread-local)
// ---------------------------------------------------------------------------

#[derive(Default)]
struct Recorder {
    /// Whether events are being captured. A plain bool (not the reactive flag) so the event path's
    /// guard is a cheap thread-local read, not a reactive-runtime access.
    active: bool,
    /// Action logging without capture (§14.6): echo every action to the console in the recorder's
    /// vocabulary, but keep no steps and write no file. Independent of `active`: an app can log
    /// continuously and still start and stop recordings underneath it.
    echo: bool,
    steps: Vec<Step>,
    /// A signal mirrored with the current script text on every change (the showcase's editable
    /// buffer). `None` when recording headlessly.
    into: Option<Signal<String>>,
    /// A file rewritten with the current script on every change, so a `--record` run that is
    /// killed still leaves everything captured up to the last event.
    file: Option<PathBuf>,
    /// Events whose id starts with this prefix are skipped, so a UI's own record/stop controls
    /// never record themselves (else playback would re-tap Stop and the replay would never run).
    exclude: String,
    /// The pump generation in which the last `Tap`/`Select` was recorded, or `None` if the last
    /// step is not a foldable input. A navigation folds that input into one portable `Navigate`
    /// (a sidebar row, a stack push) when it happened in the same or the immediately following
    /// pump: a signal-bound remount settles one pump late, so "same pump" alone would miss it,
    /// and "any time" would wrongly swallow an unrelated earlier tap. See `on_nav`.
    input_gen: Option<u64>,
    /// The id whose `Pressed` was just recorded, if the immediately preceding recorded event was
    /// one. It exists to drop the `Tap` twin that follows: a node wearing both shapes
    /// (a legacy button with an extra tap recognizer, and every playback-while-recording,
    /// since `Step::Tap` synthesizes `Pressed` then `Tap`) would otherwise record two taps
    /// for one press.
    ///
    /// Keyed on "immediately preceding", not on a pump generation: the executor enqueues the two
    /// separately and `enqueue_events` pumps between them, so the twin lands a generation later.
    /// Adjacency is what holds. A composed piece sends `Tap` with no `Pressed` before it and
    /// records normally; two real taps arrive as two pairs and record twice.
    last_pressed: Option<String>,
    /// Per-step annotation (a control's a11y label or visible text), index-aligned with `steps`.
    /// Rendered as a trailing `# "label"` comment by [`annotate_yaml`].
    labels: Vec<Option<String>>,
}

impl Recorder {
    /// Append `step` with its annotation `label` (the control's a11y label or text, §14.6),
    /// applying the [`coalesces`] rules. `labels` stays index-aligned with `steps`.
    fn push(&mut self, step: Step, label: Option<String>) {
        if let Some(last) = self.steps.last_mut()
            && coalesces(last, &step)
        {
            *last = step;
            *self.labels.last_mut().expect("labels align with steps") = label;
            return;
        }
        self.steps.push(step);
        self.labels.push(label);
    }

    /// Write the current script to the live sinks (buffer signal and/or file). Takes `&self` and
    /// touches no recorder thread-local, so it is safe to call while the recorder is borrowed.
    fn flush(&self) {
        let script = annotate_yaml(&self.steps, &self.labels);
        if let Some(sig) = self.into {
            // A disposed buffer (its page navigated away) is a defined no-op write; the recorder
            // keeps capturing regardless, and a fresh page re-targets it via `start_into`.
            sig.set(script.clone());
        }
        if let Some(path) = &self.file {
            let _ = std::fs::write(path, script.as_bytes());
        }
    }
}

day_reactive::tls_group! {
    static REC: RefCell<Recorder> = RefCell::new(Recorder::default());
    /// The reactive on/off flag a UI binds to (label/style). Lazily created in the root scope so it
    /// survives the page that first reads it (Signal::global, docs/reactivity.md).
    static FLAG: OnceCell<Signal<bool>> = const { OnceCell::new() };
    /// A counter bumped on every recorded/cleared step (see [`version`]).
    static VERSION: OnceCell<Signal<u64>> = const { OnceCell::new() };
}

/// The reactive recording flag: `true` while recording. Bind a control's label/style to it (the
/// showcase's Record↔Stop button does). The same global handle every call, so reads from any page
/// track the one signal.
pub fn recording_signal() -> Signal<bool> {
    FLAG.with(|c| *c.get_or_init(|| Signal::global(false)))
}

/// A counter that increments each time a step is recorded (or the recording is cleared). A UI can
/// watch it to react to recording *progress* (a live step count, say) without owning the mirrored
/// buffer signal. Global-scoped, so it survives page rebuilds.
pub fn version() -> Signal<u64> {
    VERSION.with(|c| *c.get_or_init(|| Signal::global(0)))
}

fn bump_version() {
    version().update(|n| *n += 1);
}

/// Whether `ev` is the positional twin of the press just recorded, and so must not record a second
/// tap for the same press.
///
/// One tap can deliver two events. A native `button` leaf sends `Pressed`; a piece composed from
/// `Decorate::on_tap` (every `Button::style(…)`, every tappable shape) sends `Tap`; a node
/// wearing both sends `Pressed` then `Tap`. So does playback: `Step::Tap` synthesizes the pair so
/// that one step drives either kind of control, which means recording a replay would otherwise
/// double every tap in it.
///
/// The test is adjacency, not a pump generation: the executor enqueues the two separately and
/// `enqueue_events` pumps between them, so the twin usually lands a generation later. What holds is
/// that nothing else records in between. A composed piece's `Tap` has no `Pressed` before it and
/// records normally; two real taps arrive as two pairs and record twice.
fn is_press_twin(ev: &Event, step: &Step, last_pressed: Option<&str>) -> bool {
    matches!(
        (ev, step),
        (Event::Tap(_), Step::Tap { id, .. }) if last_pressed == Some(id.as_str())
    )
}

/// Whether an event on `id` is excluded by `prefix`: the rule that keeps a UI's own record/stop
/// controls out of its own recording. An empty prefix excludes nothing; an id-less event is never
/// excluded (it has no id to match, and is dropped later for lack of a portable step anyway).
fn is_excluded(id: Option<&str>, prefix: &str) -> bool {
    !prefix.is_empty() && id.is_some_and(|id| id.starts_with(prefix))
}

/// Echo a recorded action to stdout, so it shows up in the console while the app runs (each line
/// carries the `[target]` prefix `day launch` adds). Runs from the event/nav observer, a native
/// trampoline path, so it uses a non-panicking write: a raw `println!` on a broken stdout pipe
/// (routine when `day launch` tears the app down) would unwind into non-Rust frames and abort the
/// process (`panic_cannot_unwind`, the reason `day_core::diag` exists). Errors are dropped.
fn echo_action(step: &Step, label: Option<&str>, recording: bool) {
    use std::fmt::Write as _;
    // The prefix says which mode produced the line: a recording is accumulating a script you can
    // save, action logging is only narrating. Same vocabulary either way: a logged line and the
    // step a recording would have written are the same thing.
    let mut line = String::from(if recording {
        "day record ▸ "
    } else {
        "dayscript ▸ "
    });
    match step {
        Step::Tap { id, .. } => {
            let _ = write!(line, "tap {id}");
        }
        Step::Input { id, text, .. } => {
            let _ = write!(line, "input {id} = {:?}", text.as_deref().unwrap_or(""));
        }
        Step::Activate { id, index } => {
            let _ = write!(line, "activate {id} = {index}");
        }
        Step::Select { id, index, .. } => {
            let _ = write!(line, "select {id} = {index}");
        }
        Step::SetValue { id, value } => {
            let _ = write!(line, "set_value {id} = {value}");
        }
        Step::Navigate { route } => {
            let _ = write!(
                line,
                "navigate → {}",
                if route.is_empty() { "/" } else { route }
            );
        }
        Step::NavBack { native } => {
            line.push_str("nav_back");
            if *native {
                line.push_str(": { native: true }");
            }
        }
        // The recorder never emits the other step kinds; nothing to echo.
        _ => return,
    }
    if let Some(label) = label {
        let _ = write!(
            line,
            "  \"{}\"",
            label.split_whitespace().collect::<Vec<_>>().join(" ")
        );
    }
    let mut out = std::io::stdout();
    use std::io::Write as _;
    let _ = writeln!(out, "{line}");
    let _ = out.flush();
}

/// The event observer: resolve the node's id, drop the recorder's own controls, map to a step, and
/// append. Installed by the `start*` fns; removed by [`stop`].
fn on_event(node: NodeId, ev: &Event) {
    // Cheap guard first: the observer stays installed only while observing, but a stop() racing
    // an in-flight dispatch can land here after the flag cleared.
    if !is_observing() {
        return;
    }
    // Resolve the id with no recorder borrow held: `id_of` reads the tree, and keeping the borrow
    // out means it can never overlap the append below, even if that tree read re-enters dispatch.
    let id = day_core::id_of(node);
    let Some(step) = event_to_step(id.as_deref(), ev) else {
        return;
    };
    // The control's label: a11y label preferred, its text as the fallback (§14.6). Read with
    // no recorder borrow held, same as `id_of`.
    let label = day_core::label_of(node);
    REC.with(|r| {
        let mut rec = r.borrow_mut();
        // The exclude prefix applies to both modes: an app's own record/stop controls are noise in
        // a log for the same reason they are wrong in a recording.
        if is_excluded(id.as_deref(), &rec.exclude) {
            return;
        }
        // One press, one step: drop the positional twin that follows a `Pressed` on the same node.
        if is_press_twin(ev, &step, rec.last_pressed.as_deref()) {
            return;
        }
        rec.last_pressed = match (ev, &step) {
            (Event::Pressed, Step::Tap { id, .. }) => Some(id.clone()),
            _ => None,
        };
        echo_action(&step, label.as_deref(), rec.active);
        // Logging narrates and keeps nothing; only a recording accumulates.
        if !rec.active {
            return;
        }
        let is_input = matches!(step, Step::Tap { .. } | Step::Select { .. });
        rec.push(step, label);
        rec.input_gen = is_input.then(day_core::pump_generation);
        rec.flush();
    });
    bump_version();
}

/// The navigation observer: every route change, from any source (§14.6). Records the new full
/// route as one absolute `Navigate`, which replays multi-level stacks (`items/item-1`) in a
/// single step, folding in the tap/select that triggered it when there was one.
fn on_nav(route: &str, label: Option<&str>) {
    if !is_observing() {
        return;
    }
    let step = Step::Navigate {
        route: route.to_string(),
    };
    let label = label.map(str::to_string);
    REC.with(|r| {
        let mut rec = r.borrow_mut();
        if !rec.active {
            echo_action(&step, label.as_deref(), false);
            return;
        }
        let foldable = rec
            .input_gen
            .is_some_and(|g| day_core::pump_generation().saturating_sub(g) <= 1)
            && matches!(
                rec.steps.last(),
                Some(Step::Tap { .. } | Step::Select { .. })
            );
        echo_action(&step, label.as_deref(), true);
        if foldable {
            // The tap/select that caused this navigation is this navigation, so replace the
            // non-portable `Select { id: nav, index }` / stack-push tap with the absolute route,
            // and carry the nav host's label (the sidebar row title).
            *rec.steps.last_mut().expect("input_gen implies a last step") = step;
            *rec.labels.last_mut().expect("labels align with steps") = label;
        } else {
            rec.push(step, label);
        }
        rec.input_gen = None;
        rec.flush();
    });
    bump_version();
}

fn install_observer() {
    day_core::set_event_observer(Some(Box::new(on_event)));
    // Navigation is delivered by day-core's nav observer (§14.6): it fires on every route change
    // (sidebar, nav_link, imperative `navigate`, native back, and the signal-bound stack/tab
    // pushes, caught at the event-pump tail once their reactive reconcile settles). A reactive
    // watch on current_route() does not suffice: navigate()/push mutate controller state that
    // current_route() reads without a tracked dependency, so the watch never re-runs.
    day_core::set_nav_observer(Some(Box::new(on_nav)));
}

/// Shared start path. A **fresh** start (nothing was recording) begins from an empty script and
/// resets the sinks; re-calling while already recording only re-targets the sinks that are given
/// (so returning to a rebuilt page keeps the live stream flowing into the new buffer without losing
/// what was captured while it was gone).
fn start_common(into: Option<Signal<String>>, file: Option<PathBuf>) {
    REC.with(|r| {
        let mut rec = r.borrow_mut();
        if !rec.active {
            rec.steps.clear();
            rec.labels.clear();
            rec.input_gen = None;
            rec.into = None;
            rec.file = None;
            rec.active = true;
        }
        if into.is_some() {
            rec.into = into;
        }
        if file.is_some() {
            rec.file = file;
        }
        rec.flush();
    });
    install_observer();
    recording_signal().set_if_changed(true);
    bump_version();
}

/// Start recording into memory only (read it back with [`script`] / [`steps`] / [`save`]).
pub fn start() {
    start_common(None, None);
}

/// Start recording, mirroring the script text into `sig` on every event: the streaming, editable
/// buffer an app binds a `text_area` to. Called again while already recording, it re-targets the
/// stream at `sig` (keeping the recording so far) rather than restarting, which is what a page
/// needs after it was disposed and rebuilt mid-recording.
pub fn start_into(sig: Signal<String>) {
    start_common(Some(sig), None);
}

/// Start recording, continuously flushing the script to `path`; this is how `DAY_RECORD` /
/// `day launch --record` capture headlessly. Crash-resilient: the file holds everything up to the
/// last event even if the app is killed.
pub fn start_to_file(path: impl AsRef<Path>) {
    start_common(None, Some(path.as_ref().to_path_buf()));
}

/// Stop recording and remove the observer. The captured script is kept (read it with [`script`] /
/// [`steps`] / [`save`], or resume with a `start*`).
pub fn stop() {
    REC.with(|r| r.borrow_mut().active = false);
    // Only unhook when nothing else wants the events: action logging (`log_actions`) rides the
    // same observers, and an app that logs continuously must keep doing so after a recording ends.
    if !is_logging_actions() {
        day_core::set_event_observer(None);
        day_core::set_nav_observer(None);
    }
    recording_signal().set_if_changed(false);
}

/// Whether a recording is currently live.
pub fn is_recording() -> bool {
    REC.with(|r| r.borrow().active)
}

/// Whether the observers should run at all: a recording, action logging, or both.
fn is_observing() -> bool {
    REC.with(|r| {
        let rec = r.borrow();
        rec.active || rec.echo
    })
}

/// Log every action the app receives to stdout, in the recorder's vocabulary, the same lines a
/// recording echoes, minus the recording:
///
/// ```text
/// dayscript ▸ navigate → dates  "Date & time"
/// dayscript ▸ tap list-shuffle  "Shuffle"
/// dayscript ▸ select unit-picker = 1  "Units"
/// ```
///
/// It hooks the same two observers a recording does ([`start`]), so it sees exactly what the app
/// sees, on every backend, with no per-toolkit code. It stores neither steps nor a file, so no
/// buffer grows and it is safe to leave on for an app's whole life. `exclude_prefix` applies, so a
/// UI's own scripting controls stay out of the log as they stay out of a recording.
///
/// Independent of recording. Turning logging off while a recording is live leaves the recording
/// alone, and stopping a recording leaves logging on.
pub fn log_actions(on: bool) {
    REC.with(|r| r.borrow_mut().echo = on);
    if on {
        install_observer();
    } else if !is_recording() {
        // Nothing left to observe; take the observers back off the event path.
        day_core::set_event_observer(None);
        day_core::set_nav_observer(None);
    }
}

/// Whether [`log_actions`] is on.
pub fn is_logging_actions() -> bool {
    REC.with(|r| r.borrow().echo)
}

/// The recorded script as canonical dayscript YAML ([`steps_to_yaml`]); `flow: []` when empty.
pub fn script() -> String {
    REC.with(|r| steps_to_yaml(&r.borrow().steps))
}

/// The recorded steps, cloned.
pub fn steps() -> Vec<Step> {
    REC.with(|r| r.borrow().steps.clone())
}

/// Discard the recorded steps (recording, if live, continues from empty). Mirrors the emptied
/// script into any live sink.
pub fn clear() {
    REC.with(|r| {
        let mut rec = r.borrow_mut();
        rec.steps.clear();
        rec.labels.clear();
        rec.input_gen = None;
        rec.flush();
    });
    bump_version();
}

/// Write the recorded script to `path`.
pub fn save(path: &Path) -> std::io::Result<()> {
    std::fs::write(path, script().as_bytes())
}

/// Skip events whose element id starts with `prefix`: set it to the id prefix an app gives its
/// record/stop/play controls so they never record themselves. Set before `start*`.
pub fn exclude_prefix(prefix: &str) {
    REC.with(|r| r.borrow_mut().exclude = prefix.to_string());
}

// ---------------------------------------------------------------------------
// In-process playback
// ---------------------------------------------------------------------------

/// Play a dayscript in-process (§14.6): parse `yaml` and run each step through the same executor
/// the socket runner uses (`crate::run_step_with_wait`), on a spawned thread that dispatches each
/// step to the main thread and awaits its reply, mirroring the engine's connection loop. Returns
/// as soon as the run is *dispatched* (the steps then run asynchronously against the live UI).
/// Refuses while a recording is live, so a replay never records itself.
#[cfg(not(target_arch = "wasm32"))]
pub fn play(yaml: &str) -> Result<(), String> {
    play_with_delay(yaml, 0.0)
}

/// Play with an artificial pause (seconds) between each step: a slow-motion replay for watching a
/// script drive the UI. Returns `Err` without spawning when the script is empty or does not parse,
/// so a UI can call it to validate (see [`is_playable`]) and to run from one path.
///
/// A run can be suspended and resumed with [`pause_playback`] / [`resume_playback`], and abandoned
/// with [`stop_playback`]; [`playing_signal`] and [`paused_signal`] are what a transport control
/// binds to. Refuses while a run is already live, so two Play presses cannot interleave two scripts
/// against the same UI.
#[cfg(not(target_arch = "wasm32"))]
pub fn play_with_delay(yaml: &str, step_delay_secs: f64) -> Result<(), String> {
    if is_recording() {
        return Err("cannot play while recording — stop the recording first".to_string());
    }
    if is_playing() {
        return Err("a script is already playing".to_string());
    }
    let steps = steps_from_yaml(yaml)?;
    if steps.is_empty() {
        return Err("script has no steps to play".to_string());
    }
    let delay = std::time::Duration::from_secs_f64(step_delay_secs.max(0.0));
    set_playing(true);
    set_paused(false);
    std::thread::spawn(move || {
        replay_steps(
            steps,
            delay,
            is_playing,
            is_paused,
            std::thread::sleep,
            |step| {
                // Best-effort: driven over a socket a failed step reports through the reply path, but
                // here there is no runner to read it, so carry on to the next step.
                let _ = crate::run_step_with_wait(step);
            },
        );
        set_playing(false);
        set_paused(false);
    });
    Ok(())
}

/// Keep the scheduling boundary testable without real timers or the process-wide UI dispatcher.
#[cfg(not(target_arch = "wasm32"))]
fn replay_steps(
    steps: Vec<Step>,
    delay: std::time::Duration,
    playing: impl Fn() -> bool,
    paused: impl Fn() -> bool,
    mut sleep: impl FnMut(std::time::Duration),
    mut dispatch: impl FnMut(Step),
) {
    for (i, step) in steps.into_iter().enumerate() {
        if !playing() {
            break;
        }
        if i > 0 && !delay.is_zero() {
            sleep(delay);
        }
        // A pause or stop can arrive during the inter-step delay. Check AFTER that wait,
        // before dispatching; otherwise the final step runs while paused and clears Resume.
        while paused() && playing() {
            sleep(std::time::Duration::from_millis(PAUSE_POLL_MS));
        }
        if !playing() {
            break;
        }
        dispatch(step);
    }
}

/// How often a paused run checks whether it has been resumed or stopped.
#[cfg(not(target_arch = "wasm32"))]
const PAUSE_POLL_MS: u64 = 50;

/// Whether in-process playback exists on this target: false on wasm, which has no background
/// thread to drive the steps from (drive the page over the dayscript WebSocket transport there,
/// docs/web.md).
///
/// A UI should gate its Play control on this rather than calling and ignoring the `Err`: an
/// enabled button that silently does nothing is worse than a disabled one. Recording has no such
/// limit: it rides the event observer on the main thread and works on every target.
#[cfg(not(target_arch = "wasm32"))]
pub fn playback_supported() -> bool {
    true
}

#[cfg(target_arch = "wasm32")]
pub fn playback_supported() -> bool {
    false
}

// The replay runs on a spawned thread, so its live state is atomic; the signals below mirror it
// for the UI, and are only ever written on the main thread.
#[cfg(not(target_arch = "wasm32"))]
static PLAYING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
#[cfg(not(target_arch = "wasm32"))]
static PAUSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

#[cfg(not(target_arch = "wasm32"))]
thread_local! {
    static PLAYING_SIG: OnceCell<Signal<bool>> = const { OnceCell::new() };
    static PAUSED_SIG: OnceCell<Signal<bool>> = const { OnceCell::new() };
}

/// The reactive "a script is playing" flag, which a Play/Pause button binds its icon to.
#[cfg(not(target_arch = "wasm32"))]
pub fn playing_signal() -> Signal<bool> {
    PLAYING_SIG.with(|c| *c.get_or_init(|| Signal::global(false)))
}

/// The reactive "playback is paused" flag. Only meaningful while [`playing_signal`] is set.
#[cfg(not(target_arch = "wasm32"))]
pub fn paused_signal() -> Signal<bool> {
    PAUSED_SIG.with(|c| *c.get_or_init(|| Signal::global(false)))
}

/// Set the atomic and mirror it into the signal. The mirror hops to the main thread, since the
/// replay thread calls this when a run ends and a `Signal` may only be touched there.
#[cfg(not(target_arch = "wasm32"))]
fn set_playing(on: bool) {
    PLAYING.store(on, std::sync::atomic::Ordering::SeqCst);
    day_reactive::on_main(move || playing_signal().set_if_changed(on));
}

#[cfg(not(target_arch = "wasm32"))]
fn set_paused(on: bool) {
    PAUSED.store(on, std::sync::atomic::Ordering::SeqCst);
    day_reactive::on_main(move || paused_signal().set_if_changed(on));
}

/// Whether a script is playing right now; paused counts as playing.
#[cfg(not(target_arch = "wasm32"))]
pub fn is_playing() -> bool {
    PLAYING.load(std::sync::atomic::Ordering::SeqCst)
}

/// Whether a live run is suspended.
#[cfg(not(target_arch = "wasm32"))]
pub fn is_paused() -> bool {
    PAUSED.load(std::sync::atomic::Ordering::SeqCst)
}

/// Suspend the running script between steps. The step in flight finishes, because a step is one
/// synthesized action dispatched to the main thread, and abandoning it mid-flight would leave the
/// UI in a state no script describes.
#[cfg(not(target_arch = "wasm32"))]
pub fn pause_playback() {
    if is_playing() {
        set_paused(true);
    }
}

/// Resume a paused run.
#[cfg(not(target_arch = "wasm32"))]
pub fn resume_playback() {
    if is_playing() {
        set_paused(false);
    }
}

/// Abandon the run: the replay thread stops before its next step (immediately if it is paused).
/// The steps already played are not undone; there is nothing to undo them with.
#[cfg(not(target_arch = "wasm32"))]
pub fn stop_playback() {
    set_playing(false);
    set_paused(false);
}

/// Whether `yaml` is a non-empty, parseable script, which a Play button binds its enabled state to.
pub fn is_playable(yaml: &str) -> bool {
    steps_from_yaml(yaml).is_ok_and(|s| !s.is_empty())
}

/// wasm has no background thread and no `Instant` (the executor's wait loop traps there), so
/// in-process playback isn't available; drive the page over the dayscript WebSocket transport
/// instead (docs/web.md).
#[cfg(target_arch = "wasm32")]
pub fn play(_yaml: &str) -> Result<(), String> {
    play_with_delay(_yaml, 0.0)
}

#[cfg(target_arch = "wasm32")]
pub fn play_with_delay(_yaml: &str, _step_delay_secs: f64) -> Result<(), String> {
    Err(
        "day::play_script is not available on web (no background thread); drive the page over the \
         dayscript WebSocket transport instead"
            .to_string(),
    )
}

// `is_playable` (above) is pure parsing, with neither threads nor `Instant`, so it serves every
// target, wasm included; there is no wasm-specific copy.

// Transport controls, present on wasm so a UI compiles unchanged there: nothing plays, so nothing
// can be paused or stopped, and the flags a Play/Pause button binds to are permanently off.
#[cfg(target_arch = "wasm32")]
pub fn playing_signal() -> Signal<bool> {
    PLAYING_SIG.with(|c| *c.get_or_init(|| Signal::global(false)))
}

#[cfg(target_arch = "wasm32")]
pub fn paused_signal() -> Signal<bool> {
    PAUSED_SIG.with(|c| *c.get_or_init(|| Signal::global(false)))
}

#[cfg(target_arch = "wasm32")]
thread_local! {
    static PLAYING_SIG: OnceCell<Signal<bool>> = const { OnceCell::new() };
    static PAUSED_SIG: OnceCell<Signal<bool>> = const { OnceCell::new() };
}

#[cfg(target_arch = "wasm32")]
pub fn is_playing() -> bool {
    false
}

#[cfg(target_arch = "wasm32")]
pub fn is_paused() -> bool {
    false
}

#[cfg(target_arch = "wasm32")]
pub fn pause_playback() {}

#[cfg(target_arch = "wasm32")]
pub fn resume_playback() {}

#[cfg(target_arch = "wasm32")]
pub fn stop_playback() {}

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

    #[test]
    fn round_trips_recorder_steps() {
        let steps = vec![
            Step::Navigate {
                route: "controls".into(),
            },
            Step::Tap {
                if_present: false,
                id: "inc".into(),
                repeat: Some(1),
                at: None,
                modifiers: Vec::new(),
            },
            Step::Input {
                id: "name-field".into(),
                text: Some("Ada".into()),
                key: None,
                args: None,
            },
            Step::Select {
                id: "size".into(),
                index: 2,
                if_present: false,
            },
            Step::NavBack { native: false },
            Step::SizeClass {
                width: "compact".into(),
                height: Some("regular".into()),
            },
        ];
        let yaml = steps_to_yaml(&steps);
        let back = steps_from_yaml(&yaml).expect("re-parse");
        // Step-level round trip (not byte-for-byte YAML): parse(emit(x)) == x.
        assert_eq!(
            format!("{steps:?}"),
            format!("{back:?}"),
            "yaml was:\n{yaml}"
        );
        // The emitted form is the on-disk `- <op>: {…}` shape day-cli reads, null params stripped.
        assert!(yaml.contains("tap:"), "yaml was:\n{yaml}");
        assert!(
            !yaml.contains("key:"),
            "null params must be stripped:\n{yaml}"
        );
    }

    #[test]
    fn accepts_cli_demo_template() {
        // Fixture: the scaffold's demo must parse and round-trip through the shared format.
        let demo = include_str!("../../day-cli/templates/app/dayscript/demo.yaml");
        let steps = steps_from_yaml(demo).expect("demo.yaml parses");
        assert!(
            steps
                .iter()
                .any(|s| matches!(s, Step::Screenshot { name, .. } if name == "welcome")),
            "demo.yaml carries `screenshot: welcome` as a scalar"
        );
        assert!(
            steps
                .iter()
                .any(|s| matches!(s, Step::Navigate { route } if route == "items")),
            "demo.yaml navigates to the Items smoke test"
        );
        let reparsed = steps_from_yaml(&steps_to_yaml(&steps)).expect("re-parse");
        assert_eq!(format!("{steps:?}"), format!("{reparsed:?}"));
    }

    #[test]
    fn event_to_step_maps_actions_and_drops_the_rest() {
        use day_spec::Point;
        // Actions with an id become steps.
        assert!(matches!(
            event_to_step(Some("inc"), &Event::Pressed),
            Some(Step::Tap { .. })
        ));
        assert!(matches!(
            event_to_step(Some("field"), &Event::TextChanged("hi".into())),
            Some(Step::Input { .. })
        ));
        assert!(matches!(
            event_to_step(Some("t"), &Event::ToggleChanged(true)),
            Some(Step::Select { index: 1, .. })
        ));
        // Navigation is not an event-to-step concern (the nav observer captures route changes);
        // a RouteRequested must not also map to a Navigate here, or it would double-record.
        assert!(event_to_step(None, &Event::RouteRequested("home".into())).is_none());
        // A gesture `Tap` on an ID'd node records like a press: that is the only event a
        // `Button::style(…)` or any other composed `.on_tap` piece ever delivers, so dropping it
        // left those controls out of every recording (see `event_to_step`'s doc).
        assert!(matches!(
            event_to_step(Some("list-shuffle"), &Event::Tap(Point::new(1.0, 2.0))),
            Some(Step::Tap { .. })
        ));
        // Without an id there is still no portable step; a bare coordinate is not one.
        assert!(event_to_step(None, &Event::Tap(Point::new(1.0, 2.0))).is_none());
        assert!(event_to_step(Some("s"), &Event::ValueChanged(0.5)).is_none());
        assert!(event_to_step(None, &Event::Pressed).is_none());
    }

    /// The guard for the whole class: playback and recording must agree about every event.
    ///
    /// This is what would have caught `Button::style(…)` recording as nothing. `Step::Tap` emits
    /// `Pressed` and `Tap`; a styled button only ever receives the second; the recorder only ever
    /// mapped the first. Each half was self-consistent, so only comparing them finds it.
    #[test]
    fn playback_and_recording_agree() {
        for (step_op, events, disposition) in PLAYBACK_EMISSIONS {
            for ev in *events {
                let got = event_to_step(Some("probe"), ev);
                match disposition {
                    Disposition::Records(expected_op) => {
                        let got = got.unwrap_or_else(|| {
                            panic!(
                                "playback's `{step_op}` step emits {ev:?}, but the recorder drops \
                                 it — every control that receives only this event records as \
                                 nothing. Map it in `event_to_step`, or declare it Dropped in \
                                 PLAYBACK_EMISSIONS and say why."
                            )
                        });
                        assert_eq!(
                            step_entry_op(&got),
                            *expected_op,
                            "playback's `{step_op}` step emits {ev:?}; the recorder turns that \
                             into a `{}` step, not the `{expected_op}` the table declares",
                            step_entry_op(&got),
                        );
                    }
                    Disposition::Dropped(why) => assert!(
                        got.is_none(),
                        "PLAYBACK_EMISSIONS says {ev:?} is dropped ({why}), but the recorder now \
                         maps it to {got:?} — update the table if that is intended"
                    ),
                }
            }
        }
    }

    /// Every id-addressed event the recorder maps must survive a round trip through the on-disk
    /// form: a step it can produce but not re-read would record a script that will not replay.
    #[test]
    fn every_recorded_step_round_trips_through_yaml() {
        let mapped: Vec<Step> = PLAYBACK_EMISSIONS
            .iter()
            .filter(|(_, _, d)| matches!(d, Disposition::Records(_)))
            .flat_map(|(_, events, _)| *events)
            .filter_map(|ev| event_to_step(Some("probe"), ev))
            .collect();
        assert!(
            !mapped.is_empty(),
            "the table declares some recordable steps"
        );
        let reparsed = steps_from_yaml(&steps_to_yaml(&mapped)).expect("recorded yaml re-parses");
        assert_eq!(format!("{mapped:?}"), format!("{reparsed:?}"));
    }

    #[test]
    fn annotate_yaml_comments_the_identifying_line() {
        let steps = vec![
            Step::Navigate {
                route: "focus".into(),
            },
            Step::Tap {
                if_present: false,
                id: "focus-next-button".into(),
                repeat: Some(1),
                at: None,
                modifiers: Vec::new(),
            },
        ];
        let labels = vec![Some("Focus".to_string()), Some("Focus next".to_string())];
        let yaml = annotate_yaml(&steps, &labels);
        assert!(
            yaml.contains("route: focus # \"Focus\""),
            "nav label on route line:\n{yaml}"
        );
        assert!(
            yaml.contains("id: focus-next-button # \"Focus next\""),
            "tap label on id line:\n{yaml}"
        );
        // Comments are ignored on parse; the annotated script still round-trips to the same steps.
        let reparsed = steps_from_yaml(&yaml).expect("annotated yaml parses");
        assert_eq!(format!("{steps:?}"), format!("{reparsed:?}"));
    }

    #[test]
    fn is_playable_rejects_empty_and_garbage() {
        assert!(!is_playable(""));
        assert!(!is_playable("flow: []\n"));
        assert!(!is_playable("not: a script"));
        assert!(is_playable("flow:\n- tap: { id: go }\n"));
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn playback_honors_pause_and_stop_during_the_step_delay() {
        use std::cell::Cell;
        use std::time::Duration;

        for stop in [false, true] {
            let playing = Cell::new(true);
            let paused = Cell::new(false);
            let dispatched = Cell::new(0);
            let delay = Duration::from_millis(250);
            let mut waits = Vec::new();
            replay_steps(
                steps_from_yaml("flow:\n- tap: { id: fixture-one }\n- tap: { id: fixture-two }\n")
                    .unwrap(),
                delay,
                || playing.get(),
                || paused.get(),
                |duration| {
                    waits.push(duration);
                    assert_eq!(dispatched.get(), 1, "only the first step has run");
                    if duration == delay {
                        paused.set(true);
                        playing.set(!stop);
                    } else {
                        assert!(paused.replace(false), "resume a paused replay");
                    }
                },
                |_| {
                    assert!(playing.get());
                    assert!(!paused.get(), "never dispatch a new step while paused");
                    dispatched.set(dispatched.get() + 1);
                },
            );
            if stop {
                assert_eq!(dispatched.get(), 1);
                assert_eq!(waits, [delay]);
            } else {
                assert_eq!(dispatched.get(), 2);
                assert_eq!(waits, [delay, Duration::from_millis(PAUSE_POLL_MS)]);
            }
        }
    }

    #[test]
    fn coalesces_input_select_and_navigate() {
        let inp = |id: &str, t: &str| Step::Input {
            id: id.into(),
            text: Some(t.into()),
            key: None,
            args: None,
        };
        let mut rec = Recorder::default();
        rec.push(inp("f", "A"), None);
        rec.push(inp("f", "Ab"), None); // same id -> replaces
        rec.push(inp("g", "x"), None); // different id -> new step
        rec.push(Step::Navigate { route: "a".into() }, None);
        rec.push(Step::Navigate { route: "b".into() }, Some("B page".into())); // consecutive nav -> replaces
        assert_eq!(rec.steps.len(), 3);
        assert!(matches!(&rec.steps[0], Step::Input { text: Some(t), .. } if t == "Ab"));
        assert!(matches!(&rec.steps[2], Step::Navigate { route } if route == "b"));
    }

    /// One user tap must produce one step, whatever mix of events the control delivers for it.
    #[test]
    fn a_press_and_its_positional_twin_record_once() {
        use day_spec::Point;
        let tap = |id: &str| Step::Tap {
            if_present: false,
            id: id.into(),
            repeat: Some(1),
            at: None,
            modifiers: Vec::new(),
        };
        let press = Event::Pressed;
        let gesture = Event::Tap(Point::new(3.0, 4.0));

        // A native button: `Pressed`, then the `Tap` playback pairs with it. The twin is dropped.
        assert!(!is_press_twin(&press, &tap("inc"), None));
        assert!(is_press_twin(&gesture, &tap("inc"), Some("inc")));

        // A composed `.on_tap` piece sends only the gesture, with nothing pressed before it, so it
        // records. This is the case that was silently lost.
        assert!(!is_press_twin(&gesture, &tap("list_shuffle"), None));

        // A gesture on a different node than the last press is its own tap, not a twin.
        assert!(!is_press_twin(
            &gesture,
            &tap("list_reset"),
            Some("list-shuffle")
        ));

        // Two real presses in a row are two taps: a `Pressed` is never anyone's twin.
        assert!(!is_press_twin(&press, &tap("inc"), Some("inc")));

        // Non-tap steps are unaffected.
        assert!(!is_press_twin(
            &Event::SelectionChanged(1),
            &Step::Select {
                id: "picker".into(),
                index: 1,
                if_present: false,
            },
            Some("picker")
        ));
    }

    /// Logging and recording are independent modes over one observer, and the failure that
    /// matters is a mode silently switching the other off: `stop()` used to unhook the observers
    /// unconditionally, which would have left an app that logs continuously deaf after its first
    /// recording.
    #[test]
    fn logging_and_recording_do_not_switch_each_other_off() {
        assert!(!is_logging_actions());
        assert!(!is_recording());
        assert!(!is_observing());

        log_actions(true);
        assert!(is_logging_actions());
        assert!(is_observing(), "logging alone has to run the observers");
        assert!(!is_recording(), "logging is not recording");

        start(); // a recording underneath the log
        assert!(is_recording());
        assert!(
            is_logging_actions(),
            "starting a recording must not end the log"
        );

        stop();
        assert!(!is_recording());
        assert!(
            is_logging_actions(),
            "stopping a recording must not end the log"
        );
        assert!(is_observing());

        log_actions(false);
        assert!(!is_observing(), "nothing left to watch");
        clear();
    }

    #[test]
    fn exclude_prefix_drops_control_ids() {
        // The exact predicate the observer applies before recording an event.
        assert!(is_excluded(Some("scripting-record"), "scripting-"));
        assert!(!is_excluded(Some("inc"), "scripting-"));
        assert!(!is_excluded(None, "scripting-")); // id-less: nothing to match
        assert!(!is_excluded(Some("scripting-record"), "")); // empty prefix excludes nothing
    }
}