Skip to main content

day_script/
record.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! The dayscript **recorder** (DESIGN.md §14.6): the inverse of playback. Where the engine turns a
5//! script into synthesized Day events, the recorder turns the events an app receives back into a
6//! script. It hooks one point, [`day_core::set_event_observer`], which every backend funnels its
7//! native events through ([`day_core::enqueue_events`]), so it needs no per-toolkit code, and it
8//! emits an ordinary dayscript that replays cross-toolkit through the same executor as any
9//! hand-written one.
10//!
11//! Scope is narrow: **actions only, and only where the step is portable**. A tap, a text edit, a
12//! selection/toggle, a navigation, a back: the id-addressed things a walkthrough is made of.
13//! Positional taps, gestures, slider drags, and native OS chrome are dropped (see
14//! `event_to_step`); the resulting script is a starting point to edit, not a pixel-exact replay.
15//!
16//! Everything here is main-thread state (the observer only ever runs on the main thread, where
17//! day-core dispatches). On wasm there is no in-process playback ([`play`]); the WebSocket
18//! transport drives the page instead (docs/web.md).
19
20use std::cell::{OnceCell, RefCell};
21use std::path::{Path, PathBuf};
22
23use day_reactive::Signal;
24use day_spec::{Event, NodeId};
25
26use crate::Step;
27
28// The recorder and CLI use the same canonical format; preserve the recorder's public paths.
29pub use day_script_protocol::{steps_from_yaml, steps_to_yaml};
30
31/// Like [`steps_to_yaml`], but each step's identifying line carries a trailing `# "label"` comment
32/// naming the control it came from (§14.6): its accessibility label, or its visible text. The
33/// comment sits on the `id:` line for a tap/input/select and the `route:` line for a navigate, so a
34/// reader sees `route: focus # "Focus"`. Comments are ordinary YAML, so an annotated script parses
35/// and replays exactly as the bare one does; this is the form the recorder streams and saves.
36pub fn annotate_yaml(steps: &[Step], labels: &[Option<String>]) -> String {
37    let yaml = steps_to_yaml(steps);
38    // serde_norway renders each step as a `- <op>:` list item followed by indented params. Walk the
39    // lines, tracking which step we are inside, and append the comment to that step's key line.
40    let key_of = |step: &Step| match step {
41        Step::Tap { .. }
42        | Step::Input { .. }
43        | Step::Select { .. }
44        | Step::Activate { .. }
45        | Step::WaitFor { .. } => Some("id:"),
46        Step::Navigate { .. } => Some("route:"),
47        _ => None,
48    };
49    let mut out = String::with_capacity(yaml.len());
50    let mut idx: isize = -1;
51    let mut done_this_step = false;
52    for line in yaml.lines() {
53        if let Some(rest) = line.strip_prefix("- ") {
54            let _ = rest;
55            idx += 1;
56            done_this_step = false;
57        }
58        out.push_str(line);
59        if !done_this_step
60            && idx >= 0
61            && let Some(Some(label)) = labels.get(idx as usize)
62            && let Some(Some(key)) = steps.get(idx as usize).map(key_of)
63            && line.trim_start().starts_with(key)
64        {
65            // A comment cannot span lines, and a quote would confuse the eye, so collapse
66            // whitespace and drop any embedded quote so the annotation stays a clean single token.
67            let clean = label
68                .split_whitespace()
69                .collect::<Vec<_>>()
70                .join(" ")
71                .replace('"', "");
72            out.push_str(&format!(" # \"{clean}\""));
73            done_this_step = true;
74        }
75        out.push('\n');
76    }
77    out
78}
79
80// ---------------------------------------------------------------------------
81// Event -> Step
82// ---------------------------------------------------------------------------
83
84/// Map a native event to the dayscript step that reproduces it: **actions only, semantic only**.
85/// Returns `None` for everything the recorder drops.
86///
87/// `Tap(Point)` records only when the node carries an id, and then as an id-addressed `Tap` step;
88/// the coordinate is discarded. It has to: a `Button::style(…)` is not a native button but a
89/// composed piece whose action rides `Decorate::on_tap`, so it delivers `Tap` and never `Pressed`
90/// (day-pieces `leaves.rs`/`decorators.rs`), as does every tappable shape or card. Dropping it
91/// silently omitted those controls from every recording while `Step::Tap` replayed them perfectly,
92/// since playback emits both `Pressed` and `Tap` for exactly that reason. A node that delivers
93/// both in one pump records once; see `on_event`.
94///
95/// Dropped, and why:
96/// - an id-less `Tap`, and `LongPress`/`ContextMenu`: a bare coordinate is not portable;
97/// - `Drag`/`ScrollChanged`/`Pointer`/`Key`/`WindowResized`/`FrameChanged`/`Submitted`/
98///   `FocusChanged`: gesture and low-level input, no id-addressed step;
99/// - `ValueChanged` (a slider mid-drag): the settled value arrives separately as
100///   `ValueCommitted`, which is recorded (recording both would write a step per tick);
101/// - `SelectionSet` (multi-select): no single-index step covers it;
102/// - `ListReorder`/`NavRegroup`/`ListDelete` (the deferred commit of a native drag/swipe,
103///   docs/list.md, docs/navigation.md): the `reorder:`/`delete_row:` steps replay them, but the
104///   recorder does not yet write those steps; `CoverHidden` is teardown plumbing, not an action;
105/// - lifecycle / menu / toolbar / present-result / custom / window events: not the user UI actions
106///   the recorder targets.
107///
108/// An id-less `Pressed`/`TextChanged`/`SelectionChanged`/`ToggleChanged` is dropped too: without an
109/// id there is no portable step to write.
110fn event_to_step(id: Option<&str>, ev: &Event) -> Option<Step> {
111    match ev {
112        // Both tap shapes map to the same step: a native button's `Pressed`, and the `Tap` a
113        // composed `.on_tap` piece gets. `on_event` collapses a node that delivers both.
114        Event::Pressed | Event::Tap(_) => id.map(|id| Step::Tap {
115            if_present: false,
116            at: None,
117            id: id.to_string(),
118            repeat: Some(1),
119            modifiers: Vec::new(),
120        }),
121        Event::TextChanged(text) => id.map(|id| Step::Input {
122            id: id.to_string(),
123            text: Some(text.clone()),
124            key: None,
125            args: None,
126        }),
127        Event::ListActivated(index) => id.map(|id| Step::Activate {
128            id: id.to_string(),
129            index: *index,
130        }),
131        Event::SelectionChanged(index) => id.map(|id| Step::Select {
132            id: id.to_string(),
133            index: *index,
134            if_present: false,
135        }),
136        // Playback drives a toggle through `select` (index = the bool as 0/1), the pattern
137        // Day-Skies' weather.yaml uses, so a recorded toggle replays without a `toggle` step.
138        Event::ToggleChanged(on) => id.map(|id| Step::Select {
139            id: id.to_string(),
140            index: *on as i64,
141            if_present: false,
142        }),
143        // The settled value of a slider, not the drag. `ValueChanged` fires on every tick (a
144        // drag from 1 to 100 and back to 50 would write a hundred steps and print a hundred
145        // lines), so the recorder ignores it and takes `ValueCommitted`, which fires once with
146        // the value the user let go on (day-spec `Event::ValueCommitted`).
147        Event::ValueCommitted(value) => id.map(|id| Step::SetValue {
148            id: id.to_string(),
149            value: *value,
150        }),
151        // Navigation (RouteRequested, NavBack, and every nav_link/sidebar/stack push that calls
152        // `navigate` from an event handler) is captured by the nav observer via route changes,
153        // not here; see `on_nav`. Mapping it here too would double-record RouteRequested.
154        _ => None,
155    }
156}
157
158/// What the executor synthesizes for each step, and what the recorder must do with it.
159///
160/// The recorder and the executor are inverses, and they drifted: `Step::Tap` has always
161/// synthesized both a `Pressed` and a positional `Tap` (a native button ignores `Tap` and a
162/// composed `.on_tap` piece ignores `Pressed`), while `event_to_step` recognized only the first.
163/// Every styled button and tappable shape therefore replayed perfectly and recorded as nothing at
164/// all.
165///
166/// This table states the intended disposition of every event playback emits, and
167/// [`playback_and_recording_agree`] holds `event_to_step` to it. The rule that matters is
168/// [`Disposition::Records`]: every event a recordable step emits must map back to that same step.
169/// One of them mapping is not enough, because different piece kinds receive different ones, so
170/// an unmapped event means some class of control is silently unrecordable.
171///
172/// Adding an event to a step's emission means adding it here, which means choosing a disposition.
173/// The table exists so that the choice cannot be made by omission.
174#[cfg(test)]
175const PLAYBACK_EMISSIONS: &[(&str, &[Event], Disposition)] = &[
176    // lib.rs `Step::Tap`: both shapes, so one step drives either kind of control.
177    ("tap", &[Event::Pressed], Disposition::Records("tap")),
178    (
179        "tap",
180        &[Event::Tap(day_spec::Point::ZERO)],
181        Disposition::Records("tap"),
182    ),
183    (
184        "activate",
185        &[Event::ListActivated(1)],
186        Disposition::Records("activate"),
187    ),
188    // lib.rs `Step::Select`, and a toggle, which replays through `select`.
189    (
190        "select",
191        &[Event::SelectionChanged(1)],
192        Disposition::Records("select"),
193    ),
194    (
195        "toggle",
196        &[Event::ToggleChanged(true)],
197        Disposition::Records("select"),
198    ),
199    // lib.rs `Step::Input` paints through `day_core::synthesize_text`, which lands as this.
200    (
201        "input",
202        &[Event::TextChanged(String::new())],
203        Disposition::Records("input"),
204    ),
205    // Not recorded. Each is a considered omission, not an oversight:
206    (
207        "submit",
208        &[Event::Submitted],
209        Disposition::Dropped("a submit follows the input that recorded it"),
210    ),
211    (
212        "set_value",
213        &[Event::ValueChanged(0.5)],
214        Disposition::Dropped("mid-drag; the settled value arrives as ValueCommitted"),
215    ),
216    (
217        "set_value",
218        &[Event::ValueCommitted(0.5)],
219        Disposition::Records("set_value"),
220    ),
221];
222
223/// A step's on-disk op name (`tap`, `select`, …): the same tag [`step_to_entry`] writes, read back
224/// through serde so the test compares what a script would say.
225#[cfg(test)]
226fn step_entry_op(step: &Step) -> String {
227    match serde_json::to_value(step) {
228        Ok(serde_json::Value::Object(m)) => m
229            .get("op")
230            .and_then(|v| v.as_str())
231            .unwrap_or("<untagged>")
232            .to_string(),
233        _ => "<unserializable>".to_string(),
234    }
235}
236
237/// The recorder's intended treatment of an emitted event.
238#[cfg(test)]
239enum Disposition {
240    /// Must map back to the named step op.
241    Records(&'static str),
242    /// Must map to nothing, for the stated reason.
243    Dropped(&'static str),
244}
245
246/// Whether appending `next` should replace the last step rather than push a new one: the
247/// coalescing rules that keep a recording readable. Every keystroke in a field, or every step of a
248/// multi-step selection, collapses to the final value; consecutive navigations collapse to the last
249/// destination. Taps never coalesce (each is its own action).
250fn coalesces(last: &Step, next: &Step) -> bool {
251    match (last, next) {
252        (Step::Input { id: a, .. }, Step::Input { id: b, .. }) => a == b,
253        (Step::Select { id: a, .. }, Step::Select { id: b, .. }) => a == b,
254        (Step::Navigate { .. }, Step::Navigate { .. }) => true,
255        _ => false,
256    }
257}
258
259// ---------------------------------------------------------------------------
260// Recorder state (main-thread thread-local)
261// ---------------------------------------------------------------------------
262
263#[derive(Default)]
264struct Recorder {
265    /// Whether events are being captured. A plain bool (not the reactive flag) so the event path's
266    /// guard is a cheap thread-local read, not a reactive-runtime access.
267    active: bool,
268    /// Action logging without capture (§14.6): echo every action to the console in the recorder's
269    /// vocabulary, but keep no steps and write no file. Independent of `active`: an app can log
270    /// continuously and still start and stop recordings underneath it.
271    echo: bool,
272    steps: Vec<Step>,
273    /// A signal mirrored with the current script text on every change (the showcase's editable
274    /// buffer). `None` when recording headlessly.
275    into: Option<Signal<String>>,
276    /// A file rewritten with the current script on every change, so a `--record` run that is
277    /// killed still leaves everything captured up to the last event.
278    file: Option<PathBuf>,
279    /// Events whose id starts with this prefix are skipped, so a UI's own record/stop controls
280    /// never record themselves (else playback would re-tap Stop and the replay would never run).
281    exclude: String,
282    /// The pump generation in which the last `Tap`/`Select` was recorded, or `None` if the last
283    /// step is not a foldable input. A navigation folds that input into one portable `Navigate`
284    /// (a sidebar row, a stack push) when it happened in the same or the immediately following
285    /// pump: a signal-bound remount settles one pump late, so "same pump" alone would miss it,
286    /// and "any time" would wrongly swallow an unrelated earlier tap. See `on_nav`.
287    input_gen: Option<u64>,
288    /// The id whose `Pressed` was just recorded, if the immediately preceding recorded event was
289    /// one. It exists to drop the `Tap` twin that follows: a node wearing both shapes
290    /// (a legacy button with an extra tap recognizer, and every playback-while-recording,
291    /// since `Step::Tap` synthesizes `Pressed` then `Tap`) would otherwise record two taps
292    /// for one press.
293    ///
294    /// Keyed on "immediately preceding", not on a pump generation: the executor enqueues the two
295    /// separately and `enqueue_events` pumps between them, so the twin lands a generation later.
296    /// Adjacency is what holds. A composed piece sends `Tap` with no `Pressed` before it and
297    /// records normally; two real taps arrive as two pairs and record twice.
298    last_pressed: Option<String>,
299    /// Per-step annotation (a control's a11y label or visible text), index-aligned with `steps`.
300    /// Rendered as a trailing `# "label"` comment by [`annotate_yaml`].
301    labels: Vec<Option<String>>,
302}
303
304impl Recorder {
305    /// Append `step` with its annotation `label` (the control's a11y label or text, §14.6),
306    /// applying the [`coalesces`] rules. `labels` stays index-aligned with `steps`.
307    fn push(&mut self, step: Step, label: Option<String>) {
308        if let Some(last) = self.steps.last_mut()
309            && coalesces(last, &step)
310        {
311            *last = step;
312            *self.labels.last_mut().expect("labels align with steps") = label;
313            return;
314        }
315        self.steps.push(step);
316        self.labels.push(label);
317    }
318
319    /// Write the current script to the live sinks (buffer signal and/or file). Takes `&self` and
320    /// touches no recorder thread-local, so it is safe to call while the recorder is borrowed.
321    fn flush(&self) {
322        let script = annotate_yaml(&self.steps, &self.labels);
323        if let Some(sig) = self.into {
324            // A disposed buffer (its page navigated away) is a defined no-op write; the recorder
325            // keeps capturing regardless, and a fresh page re-targets it via `start_into`.
326            sig.set(script.clone());
327        }
328        if let Some(path) = &self.file {
329            let _ = std::fs::write(path, script.as_bytes());
330        }
331    }
332}
333
334day_reactive::tls_group! {
335    static REC: RefCell<Recorder> = RefCell::new(Recorder::default());
336    /// The reactive on/off flag a UI binds to (label/style). Lazily created in the root scope so it
337    /// survives the page that first reads it (Signal::global, docs/reactivity.md).
338    static FLAG: OnceCell<Signal<bool>> = const { OnceCell::new() };
339    /// A counter bumped on every recorded/cleared step (see [`version`]).
340    static VERSION: OnceCell<Signal<u64>> = const { OnceCell::new() };
341}
342
343/// The reactive recording flag: `true` while recording. Bind a control's label/style to it (the
344/// showcase's Record↔Stop button does). The same global handle every call, so reads from any page
345/// track the one signal.
346pub fn recording_signal() -> Signal<bool> {
347    FLAG.with(|c| *c.get_or_init(|| Signal::global(false)))
348}
349
350/// A counter that increments each time a step is recorded (or the recording is cleared). A UI can
351/// watch it to react to recording *progress* (a live step count, say) without owning the mirrored
352/// buffer signal. Global-scoped, so it survives page rebuilds.
353pub fn version() -> Signal<u64> {
354    VERSION.with(|c| *c.get_or_init(|| Signal::global(0)))
355}
356
357fn bump_version() {
358    version().update(|n| *n += 1);
359}
360
361/// Whether `ev` is the positional twin of the press just recorded, and so must not record a second
362/// tap for the same press.
363///
364/// One tap can deliver two events. A native `button` leaf sends `Pressed`; a piece composed from
365/// `Decorate::on_tap` (every `Button::style(…)`, every tappable shape) sends `Tap`; a node
366/// wearing both sends `Pressed` then `Tap`. So does playback: `Step::Tap` synthesizes the pair so
367/// that one step drives either kind of control, which means recording a replay would otherwise
368/// double every tap in it.
369///
370/// The test is adjacency, not a pump generation: the executor enqueues the two separately and
371/// `enqueue_events` pumps between them, so the twin usually lands a generation later. What holds is
372/// that nothing else records in between. A composed piece's `Tap` has no `Pressed` before it and
373/// records normally; two real taps arrive as two pairs and record twice.
374fn is_press_twin(ev: &Event, step: &Step, last_pressed: Option<&str>) -> bool {
375    matches!(
376        (ev, step),
377        (Event::Tap(_), Step::Tap { id, .. }) if last_pressed == Some(id.as_str())
378    )
379}
380
381/// Whether an event on `id` is excluded by `prefix`: the rule that keeps a UI's own record/stop
382/// controls out of its own recording. An empty prefix excludes nothing; an id-less event is never
383/// excluded (it has no id to match, and is dropped later for lack of a portable step anyway).
384fn is_excluded(id: Option<&str>, prefix: &str) -> bool {
385    !prefix.is_empty() && id.is_some_and(|id| id.starts_with(prefix))
386}
387
388/// Echo a recorded action to stdout, so it shows up in the console while the app runs (each line
389/// carries the `[target]` prefix `day launch` adds). Runs from the event/nav observer, a native
390/// trampoline path, so it uses a non-panicking write: a raw `println!` on a broken stdout pipe
391/// (routine when `day launch` tears the app down) would unwind into non-Rust frames and abort the
392/// process (`panic_cannot_unwind`, the reason `day_core::diag` exists). Errors are dropped.
393fn echo_action(step: &Step, label: Option<&str>, recording: bool) {
394    use std::fmt::Write as _;
395    // The prefix says which mode produced the line: a recording is accumulating a script you can
396    // save, action logging is only narrating. Same vocabulary either way: a logged line and the
397    // step a recording would have written are the same thing.
398    let mut line = String::from(if recording {
399        "day record ▸ "
400    } else {
401        "dayscript ▸ "
402    });
403    match step {
404        Step::Tap { id, .. } => {
405            let _ = write!(line, "tap {id}");
406        }
407        Step::Input { id, text, .. } => {
408            let _ = write!(line, "input {id} = {:?}", text.as_deref().unwrap_or(""));
409        }
410        Step::Activate { id, index } => {
411            let _ = write!(line, "activate {id} = {index}");
412        }
413        Step::Select { id, index, .. } => {
414            let _ = write!(line, "select {id} = {index}");
415        }
416        Step::SetValue { id, value } => {
417            let _ = write!(line, "set_value {id} = {value}");
418        }
419        Step::Navigate { route } => {
420            let _ = write!(
421                line,
422                "navigate → {}",
423                if route.is_empty() { "/" } else { route }
424            );
425        }
426        Step::NavBack { native } => {
427            line.push_str("nav_back");
428            if *native {
429                line.push_str(": { native: true }");
430            }
431        }
432        // The recorder never emits the other step kinds; nothing to echo.
433        _ => return,
434    }
435    if let Some(label) = label {
436        let _ = write!(
437            line,
438            "  \"{}\"",
439            label.split_whitespace().collect::<Vec<_>>().join(" ")
440        );
441    }
442    let mut out = std::io::stdout();
443    use std::io::Write as _;
444    let _ = writeln!(out, "{line}");
445    let _ = out.flush();
446}
447
448/// The event observer: resolve the node's id, drop the recorder's own controls, map to a step, and
449/// append. Installed by the `start*` fns; removed by [`stop`].
450fn on_event(node: NodeId, ev: &Event) {
451    // Cheap guard first: the observer stays installed only while observing, but a stop() racing
452    // an in-flight dispatch can land here after the flag cleared.
453    if !is_observing() {
454        return;
455    }
456    // Resolve the id with no recorder borrow held: `id_of` reads the tree, and keeping the borrow
457    // out means it can never overlap the append below, even if that tree read re-enters dispatch.
458    let id = day_core::id_of(node);
459    let Some(step) = event_to_step(id.as_deref(), ev) else {
460        return;
461    };
462    // The control's label: a11y label preferred, its text as the fallback (§14.6). Read with
463    // no recorder borrow held, same as `id_of`.
464    let label = day_core::label_of(node);
465    REC.with(|r| {
466        let mut rec = r.borrow_mut();
467        // The exclude prefix applies to both modes: an app's own record/stop controls are noise in
468        // a log for the same reason they are wrong in a recording.
469        if is_excluded(id.as_deref(), &rec.exclude) {
470            return;
471        }
472        // One press, one step: drop the positional twin that follows a `Pressed` on the same node.
473        if is_press_twin(ev, &step, rec.last_pressed.as_deref()) {
474            return;
475        }
476        rec.last_pressed = match (ev, &step) {
477            (Event::Pressed, Step::Tap { id, .. }) => Some(id.clone()),
478            _ => None,
479        };
480        echo_action(&step, label.as_deref(), rec.active);
481        // Logging narrates and keeps nothing; only a recording accumulates.
482        if !rec.active {
483            return;
484        }
485        let is_input = matches!(step, Step::Tap { .. } | Step::Select { .. });
486        rec.push(step, label);
487        rec.input_gen = is_input.then(day_core::pump_generation);
488        rec.flush();
489    });
490    bump_version();
491}
492
493/// The navigation observer: every route change, from any source (§14.6). Records the new full
494/// route as one absolute `Navigate`, which replays multi-level stacks (`items/item-1`) in a
495/// single step, folding in the tap/select that triggered it when there was one.
496fn on_nav(route: &str, label: Option<&str>) {
497    if !is_observing() {
498        return;
499    }
500    let step = Step::Navigate {
501        route: route.to_string(),
502    };
503    let label = label.map(str::to_string);
504    REC.with(|r| {
505        let mut rec = r.borrow_mut();
506        if !rec.active {
507            echo_action(&step, label.as_deref(), false);
508            return;
509        }
510        let foldable = rec
511            .input_gen
512            .is_some_and(|g| day_core::pump_generation().saturating_sub(g) <= 1)
513            && matches!(
514                rec.steps.last(),
515                Some(Step::Tap { .. } | Step::Select { .. })
516            );
517        echo_action(&step, label.as_deref(), true);
518        if foldable {
519            // The tap/select that caused this navigation is this navigation, so replace the
520            // non-portable `Select { id: nav, index }` / stack-push tap with the absolute route,
521            // and carry the nav host's label (the sidebar row title).
522            *rec.steps.last_mut().expect("input_gen implies a last step") = step;
523            *rec.labels.last_mut().expect("labels align with steps") = label;
524        } else {
525            rec.push(step, label);
526        }
527        rec.input_gen = None;
528        rec.flush();
529    });
530    bump_version();
531}
532
533fn install_observer() {
534    day_core::set_event_observer(Some(Box::new(on_event)));
535    // Navigation is delivered by day-core's nav observer (§14.6): it fires on every route change
536    // (sidebar, nav_link, imperative `navigate`, native back, and the signal-bound stack/tab
537    // pushes, caught at the event-pump tail once their reactive reconcile settles). A reactive
538    // watch on current_route() does not suffice: navigate()/push mutate controller state that
539    // current_route() reads without a tracked dependency, so the watch never re-runs.
540    day_core::set_nav_observer(Some(Box::new(on_nav)));
541}
542
543/// Shared start path. A **fresh** start (nothing was recording) begins from an empty script and
544/// resets the sinks; re-calling while already recording only re-targets the sinks that are given
545/// (so returning to a rebuilt page keeps the live stream flowing into the new buffer without losing
546/// what was captured while it was gone).
547fn start_common(into: Option<Signal<String>>, file: Option<PathBuf>) {
548    REC.with(|r| {
549        let mut rec = r.borrow_mut();
550        if !rec.active {
551            rec.steps.clear();
552            rec.labels.clear();
553            rec.input_gen = None;
554            rec.into = None;
555            rec.file = None;
556            rec.active = true;
557        }
558        if into.is_some() {
559            rec.into = into;
560        }
561        if file.is_some() {
562            rec.file = file;
563        }
564        rec.flush();
565    });
566    install_observer();
567    recording_signal().set_if_changed(true);
568    bump_version();
569}
570
571/// Start recording into memory only (read it back with [`script`] / [`steps`] / [`save`]).
572pub fn start() {
573    start_common(None, None);
574}
575
576/// Start recording, mirroring the script text into `sig` on every event: the streaming, editable
577/// buffer an app binds a `text_area` to. Called again while already recording, it re-targets the
578/// stream at `sig` (keeping the recording so far) rather than restarting, which is what a page
579/// needs after it was disposed and rebuilt mid-recording.
580pub fn start_into(sig: Signal<String>) {
581    start_common(Some(sig), None);
582}
583
584/// Start recording, continuously flushing the script to `path`; this is how `DAY_RECORD` /
585/// `day launch --record` capture headlessly. Crash-resilient: the file holds everything up to the
586/// last event even if the app is killed.
587pub fn start_to_file(path: impl AsRef<Path>) {
588    start_common(None, Some(path.as_ref().to_path_buf()));
589}
590
591/// Stop recording and remove the observer. The captured script is kept (read it with [`script`] /
592/// [`steps`] / [`save`], or resume with a `start*`).
593pub fn stop() {
594    REC.with(|r| r.borrow_mut().active = false);
595    // Only unhook when nothing else wants the events: action logging (`log_actions`) rides the
596    // same observers, and an app that logs continuously must keep doing so after a recording ends.
597    if !is_logging_actions() {
598        day_core::set_event_observer(None);
599        day_core::set_nav_observer(None);
600    }
601    recording_signal().set_if_changed(false);
602}
603
604/// Whether a recording is currently live.
605pub fn is_recording() -> bool {
606    REC.with(|r| r.borrow().active)
607}
608
609/// Whether the observers should run at all: a recording, action logging, or both.
610fn is_observing() -> bool {
611    REC.with(|r| {
612        let rec = r.borrow();
613        rec.active || rec.echo
614    })
615}
616
617/// Log every action the app receives to stdout, in the recorder's vocabulary, the same lines a
618/// recording echoes, minus the recording:
619///
620/// ```text
621/// dayscript ▸ navigate → dates  "Date & time"
622/// dayscript ▸ tap list-shuffle  "Shuffle"
623/// dayscript ▸ select unit-picker = 1  "Units"
624/// ```
625///
626/// It hooks the same two observers a recording does ([`start`]), so it sees exactly what the app
627/// sees, on every backend, with no per-toolkit code. It stores neither steps nor a file, so no
628/// buffer grows and it is safe to leave on for an app's whole life. `exclude_prefix` applies, so a
629/// UI's own scripting controls stay out of the log as they stay out of a recording.
630///
631/// Independent of recording. Turning logging off while a recording is live leaves the recording
632/// alone, and stopping a recording leaves logging on.
633pub fn log_actions(on: bool) {
634    REC.with(|r| r.borrow_mut().echo = on);
635    if on {
636        install_observer();
637    } else if !is_recording() {
638        // Nothing left to observe; take the observers back off the event path.
639        day_core::set_event_observer(None);
640        day_core::set_nav_observer(None);
641    }
642}
643
644/// Whether [`log_actions`] is on.
645pub fn is_logging_actions() -> bool {
646    REC.with(|r| r.borrow().echo)
647}
648
649/// The recorded script as canonical dayscript YAML ([`steps_to_yaml`]); `flow: []` when empty.
650pub fn script() -> String {
651    REC.with(|r| steps_to_yaml(&r.borrow().steps))
652}
653
654/// The recorded steps, cloned.
655pub fn steps() -> Vec<Step> {
656    REC.with(|r| r.borrow().steps.clone())
657}
658
659/// Discard the recorded steps (recording, if live, continues from empty). Mirrors the emptied
660/// script into any live sink.
661pub fn clear() {
662    REC.with(|r| {
663        let mut rec = r.borrow_mut();
664        rec.steps.clear();
665        rec.labels.clear();
666        rec.input_gen = None;
667        rec.flush();
668    });
669    bump_version();
670}
671
672/// Write the recorded script to `path`.
673pub fn save(path: &Path) -> std::io::Result<()> {
674    std::fs::write(path, script().as_bytes())
675}
676
677/// Skip events whose element id starts with `prefix`: set it to the id prefix an app gives its
678/// record/stop/play controls so they never record themselves. Set before `start*`.
679pub fn exclude_prefix(prefix: &str) {
680    REC.with(|r| r.borrow_mut().exclude = prefix.to_string());
681}
682
683// ---------------------------------------------------------------------------
684// In-process playback
685// ---------------------------------------------------------------------------
686
687/// Play a dayscript in-process (§14.6): parse `yaml` and run each step through the same executor
688/// the socket runner uses (`crate::run_step_with_wait`), on a spawned thread that dispatches each
689/// step to the main thread and awaits its reply, mirroring the engine's connection loop. Returns
690/// as soon as the run is *dispatched* (the steps then run asynchronously against the live UI).
691/// Refuses while a recording is live, so a replay never records itself.
692#[cfg(not(target_arch = "wasm32"))]
693pub fn play(yaml: &str) -> Result<(), String> {
694    play_with_delay(yaml, 0.0)
695}
696
697/// Play with an artificial pause (seconds) between each step: a slow-motion replay for watching a
698/// script drive the UI. Returns `Err` without spawning when the script is empty or does not parse,
699/// so a UI can call it to validate (see [`is_playable`]) and to run from one path.
700///
701/// A run can be suspended and resumed with [`pause_playback`] / [`resume_playback`], and abandoned
702/// with [`stop_playback`]; [`playing_signal`] and [`paused_signal`] are what a transport control
703/// binds to. Refuses while a run is already live, so two Play presses cannot interleave two scripts
704/// against the same UI.
705#[cfg(not(target_arch = "wasm32"))]
706pub fn play_with_delay(yaml: &str, step_delay_secs: f64) -> Result<(), String> {
707    if is_recording() {
708        return Err("cannot play while recording — stop the recording first".to_string());
709    }
710    if is_playing() {
711        return Err("a script is already playing".to_string());
712    }
713    let steps = steps_from_yaml(yaml)?;
714    if steps.is_empty() {
715        return Err("script has no steps to play".to_string());
716    }
717    let delay = std::time::Duration::from_secs_f64(step_delay_secs.max(0.0));
718    set_playing(true);
719    set_paused(false);
720    std::thread::spawn(move || {
721        replay_steps(
722            steps,
723            delay,
724            is_playing,
725            is_paused,
726            std::thread::sleep,
727            |step| {
728                // Best-effort: driven over a socket a failed step reports through the reply path, but
729                // here there is no runner to read it, so carry on to the next step.
730                let _ = crate::run_step_with_wait(step);
731            },
732        );
733        set_playing(false);
734        set_paused(false);
735    });
736    Ok(())
737}
738
739/// Keep the scheduling boundary testable without real timers or the process-wide UI dispatcher.
740#[cfg(not(target_arch = "wasm32"))]
741fn replay_steps(
742    steps: Vec<Step>,
743    delay: std::time::Duration,
744    playing: impl Fn() -> bool,
745    paused: impl Fn() -> bool,
746    mut sleep: impl FnMut(std::time::Duration),
747    mut dispatch: impl FnMut(Step),
748) {
749    for (i, step) in steps.into_iter().enumerate() {
750        if !playing() {
751            break;
752        }
753        if i > 0 && !delay.is_zero() {
754            sleep(delay);
755        }
756        // A pause or stop can arrive during the inter-step delay. Check AFTER that wait,
757        // before dispatching; otherwise the final step runs while paused and clears Resume.
758        while paused() && playing() {
759            sleep(std::time::Duration::from_millis(PAUSE_POLL_MS));
760        }
761        if !playing() {
762            break;
763        }
764        dispatch(step);
765    }
766}
767
768/// How often a paused run checks whether it has been resumed or stopped.
769#[cfg(not(target_arch = "wasm32"))]
770const PAUSE_POLL_MS: u64 = 50;
771
772/// Whether in-process playback exists on this target: false on wasm, which has no background
773/// thread to drive the steps from (drive the page over the dayscript WebSocket transport there,
774/// docs/web.md).
775///
776/// A UI should gate its Play control on this rather than calling and ignoring the `Err`: an
777/// enabled button that silently does nothing is worse than a disabled one. Recording has no such
778/// limit: it rides the event observer on the main thread and works on every target.
779#[cfg(not(target_arch = "wasm32"))]
780pub fn playback_supported() -> bool {
781    true
782}
783
784#[cfg(target_arch = "wasm32")]
785pub fn playback_supported() -> bool {
786    false
787}
788
789// The replay runs on a spawned thread, so its live state is atomic; the signals below mirror it
790// for the UI, and are only ever written on the main thread.
791#[cfg(not(target_arch = "wasm32"))]
792static PLAYING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
793#[cfg(not(target_arch = "wasm32"))]
794static PAUSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
795
796#[cfg(not(target_arch = "wasm32"))]
797thread_local! {
798    static PLAYING_SIG: OnceCell<Signal<bool>> = const { OnceCell::new() };
799    static PAUSED_SIG: OnceCell<Signal<bool>> = const { OnceCell::new() };
800}
801
802/// The reactive "a script is playing" flag, which a Play/Pause button binds its icon to.
803#[cfg(not(target_arch = "wasm32"))]
804pub fn playing_signal() -> Signal<bool> {
805    PLAYING_SIG.with(|c| *c.get_or_init(|| Signal::global(false)))
806}
807
808/// The reactive "playback is paused" flag. Only meaningful while [`playing_signal`] is set.
809#[cfg(not(target_arch = "wasm32"))]
810pub fn paused_signal() -> Signal<bool> {
811    PAUSED_SIG.with(|c| *c.get_or_init(|| Signal::global(false)))
812}
813
814/// Set the atomic and mirror it into the signal. The mirror hops to the main thread, since the
815/// replay thread calls this when a run ends and a `Signal` may only be touched there.
816#[cfg(not(target_arch = "wasm32"))]
817fn set_playing(on: bool) {
818    PLAYING.store(on, std::sync::atomic::Ordering::SeqCst);
819    day_reactive::on_main(move || playing_signal().set_if_changed(on));
820}
821
822#[cfg(not(target_arch = "wasm32"))]
823fn set_paused(on: bool) {
824    PAUSED.store(on, std::sync::atomic::Ordering::SeqCst);
825    day_reactive::on_main(move || paused_signal().set_if_changed(on));
826}
827
828/// Whether a script is playing right now; paused counts as playing.
829#[cfg(not(target_arch = "wasm32"))]
830pub fn is_playing() -> bool {
831    PLAYING.load(std::sync::atomic::Ordering::SeqCst)
832}
833
834/// Whether a live run is suspended.
835#[cfg(not(target_arch = "wasm32"))]
836pub fn is_paused() -> bool {
837    PAUSED.load(std::sync::atomic::Ordering::SeqCst)
838}
839
840/// Suspend the running script between steps. The step in flight finishes, because a step is one
841/// synthesized action dispatched to the main thread, and abandoning it mid-flight would leave the
842/// UI in a state no script describes.
843#[cfg(not(target_arch = "wasm32"))]
844pub fn pause_playback() {
845    if is_playing() {
846        set_paused(true);
847    }
848}
849
850/// Resume a paused run.
851#[cfg(not(target_arch = "wasm32"))]
852pub fn resume_playback() {
853    if is_playing() {
854        set_paused(false);
855    }
856}
857
858/// Abandon the run: the replay thread stops before its next step (immediately if it is paused).
859/// The steps already played are not undone; there is nothing to undo them with.
860#[cfg(not(target_arch = "wasm32"))]
861pub fn stop_playback() {
862    set_playing(false);
863    set_paused(false);
864}
865
866/// Whether `yaml` is a non-empty, parseable script, which a Play button binds its enabled state to.
867pub fn is_playable(yaml: &str) -> bool {
868    steps_from_yaml(yaml).is_ok_and(|s| !s.is_empty())
869}
870
871/// wasm has no background thread and no `Instant` (the executor's wait loop traps there), so
872/// in-process playback isn't available; drive the page over the dayscript WebSocket transport
873/// instead (docs/web.md).
874#[cfg(target_arch = "wasm32")]
875pub fn play(_yaml: &str) -> Result<(), String> {
876    play_with_delay(_yaml, 0.0)
877}
878
879#[cfg(target_arch = "wasm32")]
880pub fn play_with_delay(_yaml: &str, _step_delay_secs: f64) -> Result<(), String> {
881    Err(
882        "day::play_script is not available on web (no background thread); drive the page over the \
883         dayscript WebSocket transport instead"
884            .to_string(),
885    )
886}
887
888// `is_playable` (above) is pure parsing, with neither threads nor `Instant`, so it serves every
889// target, wasm included; there is no wasm-specific copy.
890
891// Transport controls, present on wasm so a UI compiles unchanged there: nothing plays, so nothing
892// can be paused or stopped, and the flags a Play/Pause button binds to are permanently off.
893#[cfg(target_arch = "wasm32")]
894pub fn playing_signal() -> Signal<bool> {
895    PLAYING_SIG.with(|c| *c.get_or_init(|| Signal::global(false)))
896}
897
898#[cfg(target_arch = "wasm32")]
899pub fn paused_signal() -> Signal<bool> {
900    PAUSED_SIG.with(|c| *c.get_or_init(|| Signal::global(false)))
901}
902
903#[cfg(target_arch = "wasm32")]
904thread_local! {
905    static PLAYING_SIG: OnceCell<Signal<bool>> = const { OnceCell::new() };
906    static PAUSED_SIG: OnceCell<Signal<bool>> = const { OnceCell::new() };
907}
908
909#[cfg(target_arch = "wasm32")]
910pub fn is_playing() -> bool {
911    false
912}
913
914#[cfg(target_arch = "wasm32")]
915pub fn is_paused() -> bool {
916    false
917}
918
919#[cfg(target_arch = "wasm32")]
920pub fn pause_playback() {}
921
922#[cfg(target_arch = "wasm32")]
923pub fn resume_playback() {}
924
925#[cfg(target_arch = "wasm32")]
926pub fn stop_playback() {}
927
928#[cfg(test)]
929mod tests {
930    use super::*;
931
932    #[test]
933    fn round_trips_recorder_steps() {
934        let steps = vec![
935            Step::Navigate {
936                route: "controls".into(),
937            },
938            Step::Tap {
939                if_present: false,
940                id: "inc".into(),
941                repeat: Some(1),
942                at: None,
943                modifiers: Vec::new(),
944            },
945            Step::Input {
946                id: "name-field".into(),
947                text: Some("Ada".into()),
948                key: None,
949                args: None,
950            },
951            Step::Select {
952                id: "size".into(),
953                index: 2,
954                if_present: false,
955            },
956            Step::NavBack { native: false },
957            Step::SizeClass {
958                width: "compact".into(),
959                height: Some("regular".into()),
960            },
961        ];
962        let yaml = steps_to_yaml(&steps);
963        let back = steps_from_yaml(&yaml).expect("re-parse");
964        // Step-level round trip (not byte-for-byte YAML): parse(emit(x)) == x.
965        assert_eq!(
966            format!("{steps:?}"),
967            format!("{back:?}"),
968            "yaml was:\n{yaml}"
969        );
970        // The emitted form is the on-disk `- <op>: {…}` shape day-cli reads, null params stripped.
971        assert!(yaml.contains("tap:"), "yaml was:\n{yaml}");
972        assert!(
973            !yaml.contains("key:"),
974            "null params must be stripped:\n{yaml}"
975        );
976    }
977
978    #[test]
979    fn accepts_cli_demo_template() {
980        // Fixture: the scaffold's demo must parse and round-trip through the shared format.
981        let demo = include_str!("../../day-cli/templates/app/dayscript/demo.yaml");
982        let steps = steps_from_yaml(demo).expect("demo.yaml parses");
983        assert!(
984            steps
985                .iter()
986                .any(|s| matches!(s, Step::Screenshot { name, .. } if name == "welcome")),
987            "demo.yaml carries `screenshot: welcome` as a scalar"
988        );
989        assert!(
990            steps
991                .iter()
992                .any(|s| matches!(s, Step::Navigate { route } if route == "items")),
993            "demo.yaml navigates to the Items smoke test"
994        );
995        let reparsed = steps_from_yaml(&steps_to_yaml(&steps)).expect("re-parse");
996        assert_eq!(format!("{steps:?}"), format!("{reparsed:?}"));
997    }
998
999    #[test]
1000    fn event_to_step_maps_actions_and_drops_the_rest() {
1001        use day_spec::Point;
1002        // Actions with an id become steps.
1003        assert!(matches!(
1004            event_to_step(Some("inc"), &Event::Pressed),
1005            Some(Step::Tap { .. })
1006        ));
1007        assert!(matches!(
1008            event_to_step(Some("field"), &Event::TextChanged("hi".into())),
1009            Some(Step::Input { .. })
1010        ));
1011        assert!(matches!(
1012            event_to_step(Some("t"), &Event::ToggleChanged(true)),
1013            Some(Step::Select { index: 1, .. })
1014        ));
1015        // Navigation is not an event-to-step concern (the nav observer captures route changes);
1016        // a RouteRequested must not also map to a Navigate here, or it would double-record.
1017        assert!(event_to_step(None, &Event::RouteRequested("home".into())).is_none());
1018        // A gesture `Tap` on an ID'd node records like a press: that is the only event a
1019        // `Button::style(…)` or any other composed `.on_tap` piece ever delivers, so dropping it
1020        // left those controls out of every recording (see `event_to_step`'s doc).
1021        assert!(matches!(
1022            event_to_step(Some("list-shuffle"), &Event::Tap(Point::new(1.0, 2.0))),
1023            Some(Step::Tap { .. })
1024        ));
1025        // Without an id there is still no portable step; a bare coordinate is not one.
1026        assert!(event_to_step(None, &Event::Tap(Point::new(1.0, 2.0))).is_none());
1027        assert!(event_to_step(Some("s"), &Event::ValueChanged(0.5)).is_none());
1028        assert!(event_to_step(None, &Event::Pressed).is_none());
1029    }
1030
1031    /// The guard for the whole class: playback and recording must agree about every event.
1032    ///
1033    /// This is what would have caught `Button::style(…)` recording as nothing. `Step::Tap` emits
1034    /// `Pressed` and `Tap`; a styled button only ever receives the second; the recorder only ever
1035    /// mapped the first. Each half was self-consistent, so only comparing them finds it.
1036    #[test]
1037    fn playback_and_recording_agree() {
1038        for (step_op, events, disposition) in PLAYBACK_EMISSIONS {
1039            for ev in *events {
1040                let got = event_to_step(Some("probe"), ev);
1041                match disposition {
1042                    Disposition::Records(expected_op) => {
1043                        let got = got.unwrap_or_else(|| {
1044                            panic!(
1045                                "playback's `{step_op}` step emits {ev:?}, but the recorder drops \
1046                                 it — every control that receives only this event records as \
1047                                 nothing. Map it in `event_to_step`, or declare it Dropped in \
1048                                 PLAYBACK_EMISSIONS and say why."
1049                            )
1050                        });
1051                        assert_eq!(
1052                            step_entry_op(&got),
1053                            *expected_op,
1054                            "playback's `{step_op}` step emits {ev:?}; the recorder turns that \
1055                             into a `{}` step, not the `{expected_op}` the table declares",
1056                            step_entry_op(&got),
1057                        );
1058                    }
1059                    Disposition::Dropped(why) => assert!(
1060                        got.is_none(),
1061                        "PLAYBACK_EMISSIONS says {ev:?} is dropped ({why}), but the recorder now \
1062                         maps it to {got:?} — update the table if that is intended"
1063                    ),
1064                }
1065            }
1066        }
1067    }
1068
1069    /// Every id-addressed event the recorder maps must survive a round trip through the on-disk
1070    /// form: a step it can produce but not re-read would record a script that will not replay.
1071    #[test]
1072    fn every_recorded_step_round_trips_through_yaml() {
1073        let mapped: Vec<Step> = PLAYBACK_EMISSIONS
1074            .iter()
1075            .filter(|(_, _, d)| matches!(d, Disposition::Records(_)))
1076            .flat_map(|(_, events, _)| *events)
1077            .filter_map(|ev| event_to_step(Some("probe"), ev))
1078            .collect();
1079        assert!(
1080            !mapped.is_empty(),
1081            "the table declares some recordable steps"
1082        );
1083        let reparsed = steps_from_yaml(&steps_to_yaml(&mapped)).expect("recorded yaml re-parses");
1084        assert_eq!(format!("{mapped:?}"), format!("{reparsed:?}"));
1085    }
1086
1087    #[test]
1088    fn annotate_yaml_comments_the_identifying_line() {
1089        let steps = vec![
1090            Step::Navigate {
1091                route: "focus".into(),
1092            },
1093            Step::Tap {
1094                if_present: false,
1095                id: "focus-next-button".into(),
1096                repeat: Some(1),
1097                at: None,
1098                modifiers: Vec::new(),
1099            },
1100        ];
1101        let labels = vec![Some("Focus".to_string()), Some("Focus next".to_string())];
1102        let yaml = annotate_yaml(&steps, &labels);
1103        assert!(
1104            yaml.contains("route: focus # \"Focus\""),
1105            "nav label on route line:\n{yaml}"
1106        );
1107        assert!(
1108            yaml.contains("id: focus-next-button # \"Focus next\""),
1109            "tap label on id line:\n{yaml}"
1110        );
1111        // Comments are ignored on parse; the annotated script still round-trips to the same steps.
1112        let reparsed = steps_from_yaml(&yaml).expect("annotated yaml parses");
1113        assert_eq!(format!("{steps:?}"), format!("{reparsed:?}"));
1114    }
1115
1116    #[test]
1117    fn is_playable_rejects_empty_and_garbage() {
1118        assert!(!is_playable(""));
1119        assert!(!is_playable("flow: []\n"));
1120        assert!(!is_playable("not: a script"));
1121        assert!(is_playable("flow:\n- tap: { id: go }\n"));
1122    }
1123
1124    #[cfg(not(target_arch = "wasm32"))]
1125    #[test]
1126    fn playback_honors_pause_and_stop_during_the_step_delay() {
1127        use std::cell::Cell;
1128        use std::time::Duration;
1129
1130        for stop in [false, true] {
1131            let playing = Cell::new(true);
1132            let paused = Cell::new(false);
1133            let dispatched = Cell::new(0);
1134            let delay = Duration::from_millis(250);
1135            let mut waits = Vec::new();
1136            replay_steps(
1137                steps_from_yaml("flow:\n- tap: { id: fixture-one }\n- tap: { id: fixture-two }\n")
1138                    .unwrap(),
1139                delay,
1140                || playing.get(),
1141                || paused.get(),
1142                |duration| {
1143                    waits.push(duration);
1144                    assert_eq!(dispatched.get(), 1, "only the first step has run");
1145                    if duration == delay {
1146                        paused.set(true);
1147                        playing.set(!stop);
1148                    } else {
1149                        assert!(paused.replace(false), "resume a paused replay");
1150                    }
1151                },
1152                |_| {
1153                    assert!(playing.get());
1154                    assert!(!paused.get(), "never dispatch a new step while paused");
1155                    dispatched.set(dispatched.get() + 1);
1156                },
1157            );
1158            if stop {
1159                assert_eq!(dispatched.get(), 1);
1160                assert_eq!(waits, [delay]);
1161            } else {
1162                assert_eq!(dispatched.get(), 2);
1163                assert_eq!(waits, [delay, Duration::from_millis(PAUSE_POLL_MS)]);
1164            }
1165        }
1166    }
1167
1168    #[test]
1169    fn coalesces_input_select_and_navigate() {
1170        let inp = |id: &str, t: &str| Step::Input {
1171            id: id.into(),
1172            text: Some(t.into()),
1173            key: None,
1174            args: None,
1175        };
1176        let mut rec = Recorder::default();
1177        rec.push(inp("f", "A"), None);
1178        rec.push(inp("f", "Ab"), None); // same id -> replaces
1179        rec.push(inp("g", "x"), None); // different id -> new step
1180        rec.push(Step::Navigate { route: "a".into() }, None);
1181        rec.push(Step::Navigate { route: "b".into() }, Some("B page".into())); // consecutive nav -> replaces
1182        assert_eq!(rec.steps.len(), 3);
1183        assert!(matches!(&rec.steps[0], Step::Input { text: Some(t), .. } if t == "Ab"));
1184        assert!(matches!(&rec.steps[2], Step::Navigate { route } if route == "b"));
1185    }
1186
1187    /// One user tap must produce one step, whatever mix of events the control delivers for it.
1188    #[test]
1189    fn a_press_and_its_positional_twin_record_once() {
1190        use day_spec::Point;
1191        let tap = |id: &str| Step::Tap {
1192            if_present: false,
1193            id: id.into(),
1194            repeat: Some(1),
1195            at: None,
1196            modifiers: Vec::new(),
1197        };
1198        let press = Event::Pressed;
1199        let gesture = Event::Tap(Point::new(3.0, 4.0));
1200
1201        // A native button: `Pressed`, then the `Tap` playback pairs with it. The twin is dropped.
1202        assert!(!is_press_twin(&press, &tap("inc"), None));
1203        assert!(is_press_twin(&gesture, &tap("inc"), Some("inc")));
1204
1205        // A composed `.on_tap` piece sends only the gesture, with nothing pressed before it, so it
1206        // records. This is the case that was silently lost.
1207        assert!(!is_press_twin(&gesture, &tap("list_shuffle"), None));
1208
1209        // A gesture on a different node than the last press is its own tap, not a twin.
1210        assert!(!is_press_twin(
1211            &gesture,
1212            &tap("list_reset"),
1213            Some("list-shuffle")
1214        ));
1215
1216        // Two real presses in a row are two taps: a `Pressed` is never anyone's twin.
1217        assert!(!is_press_twin(&press, &tap("inc"), Some("inc")));
1218
1219        // Non-tap steps are unaffected.
1220        assert!(!is_press_twin(
1221            &Event::SelectionChanged(1),
1222            &Step::Select {
1223                id: "picker".into(),
1224                index: 1,
1225                if_present: false,
1226            },
1227            Some("picker")
1228        ));
1229    }
1230
1231    /// Logging and recording are independent modes over one observer, and the failure that
1232    /// matters is a mode silently switching the other off: `stop()` used to unhook the observers
1233    /// unconditionally, which would have left an app that logs continuously deaf after its first
1234    /// recording.
1235    #[test]
1236    fn logging_and_recording_do_not_switch_each_other_off() {
1237        assert!(!is_logging_actions());
1238        assert!(!is_recording());
1239        assert!(!is_observing());
1240
1241        log_actions(true);
1242        assert!(is_logging_actions());
1243        assert!(is_observing(), "logging alone has to run the observers");
1244        assert!(!is_recording(), "logging is not recording");
1245
1246        start(); // a recording underneath the log
1247        assert!(is_recording());
1248        assert!(
1249            is_logging_actions(),
1250            "starting a recording must not end the log"
1251        );
1252
1253        stop();
1254        assert!(!is_recording());
1255        assert!(
1256            is_logging_actions(),
1257            "stopping a recording must not end the log"
1258        );
1259        assert!(is_observing());
1260
1261        log_actions(false);
1262        assert!(!is_observing(), "nothing left to watch");
1263        clear();
1264    }
1265
1266    #[test]
1267    fn exclude_prefix_drops_control_ids() {
1268        // The exact predicate the observer applies before recording an event.
1269        assert!(is_excluded(Some("scripting-record"), "scripting-"));
1270        assert!(!is_excluded(Some("inc"), "scripting-"));
1271        assert!(!is_excluded(None, "scripting-")); // id-less: nothing to match
1272        assert!(!is_excluded(Some("scripting-record"), "")); // empty prefix excludes nothing
1273    }
1274}