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