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