victauri-core 0.2.0

Core types and protocol for Victauri — Verified Introspection & Control for Tauri
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
//! Test code generation from recorded sessions.
//!
//! Converts a [`RecordedSession`] into a self-contained Rust test file that
//! replays DOM interactions through the `VictauriClient` API and optionally
//! asserts on IPC outcomes and state transitions.

use chrono::Utc;

use crate::event::{AppEvent, InteractionKind, IpcResult};
use crate::recording::RecordedSession;

/// Options for controlling test code generation.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct CodegenOptions {
    /// Name of the generated test function.
    pub test_name: String,
    /// Whether to include IPC assertions after interactions.
    pub include_ipc_assertions: bool,
    /// Whether to include state verification assertions.
    pub include_state_checks: bool,
    /// Whether to add timing comments showing relative timestamps.
    pub include_timing_comments: bool,
}

impl Default for CodegenOptions {
    fn default() -> Self {
        Self {
            test_name: "recorded_flow".to_string(),
            include_ipc_assertions: true,
            include_state_checks: true,
            include_timing_comments: true,
        }
    }
}

/// Generates a Rust test file from a recorded session using default options.
///
/// This is a convenience wrapper around [`generate_test`] with
/// [`CodegenOptions::default()`].
#[must_use]
pub fn generate_test_default(session: &RecordedSession) -> String {
    generate_test(session, &CodegenOptions::default())
}

/// Generates a Rust test file from a recorded session.
///
/// Converts DOM interactions into `VictauriClient` API calls and IPC events
/// into verification assertions. The generated test is self-contained and
/// can be run with `cargo test`.
#[must_use]
pub fn generate_test(session: &RecordedSession, options: &CodegenOptions) -> String {
    let mut out = String::with_capacity(2048);

    // File header
    let date = Utc::now().format("%Y-%m-%d");
    out.push_str(&format!("// Generated by victauri record -- {date}\n"));
    out.push_str(&format!("// Session: {}\n", session.id));
    out.push_str("\nuse victauri_test::VictauriClient;\n\n");

    // Test function
    out.push_str("#[tokio::test]\n");
    out.push_str(&format!("async fn {}() {{\n", options.test_name));
    out.push_str(
        "    let mut client = VictauriClient::discover().await.expect(\"connect to Tauri app\");\n",
    );

    let session_start = session.started_at;

    for (i, recorded) in session.events.iter().enumerate() {
        // Timing comment: elapsed since session start, only when gap > 500ms
        if options.include_timing_comments {
            let elapsed_ms = recorded
                .timestamp
                .signed_duration_since(session_start)
                .num_milliseconds();

            let show_timing = if i == 0 {
                elapsed_ms > 500
            } else {
                let prev_ts = session.events[i - 1].timestamp;
                let gap_ms = recorded
                    .timestamp
                    .signed_duration_since(prev_ts)
                    .num_milliseconds();
                gap_ms > 500
            };

            if show_timing {
                out.push_str(&format!("\n    // +{elapsed_ms}ms\n"));
            }
        }

        match &recorded.event {
            AppEvent::DomInteraction {
                action,
                selector,
                value,
                ..
            } => {
                emit_interaction(&mut out, action, selector, value.as_deref());
            }

            AppEvent::Ipc(call) if options.include_ipc_assertions => {
                // Skip internal victauri plugin commands
                if call.command.starts_with("plugin:victauri|") {
                    continue;
                }
                if matches!(call.result, IpcResult::Ok(_)) {
                    let cmd = &call.command;
                    out.push_str(&format!("    // IPC: {cmd} completed successfully\n"));
                }
            }

            AppEvent::StateChange { key, caused_by, .. }
                if options.include_state_checks && caused_by.is_some() =>
            {
                out.push_str(&format!("    // State changed: {key}\n"));
            }

            // DomMutation, WindowEvent, and disabled variants are skipped
            _ => {}
        }
    }

    out.push_str("}\n");
    out
}

/// Escapes a string for embedding in a Rust string literal.
fn escape_rust_str(s: &str) -> String {
    let mut escaped = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '\\' => escaped.push_str("\\\\"),
            '"' => escaped.push_str("\\\""),
            '\n' => escaped.push_str("\\n"),
            '\r' => escaped.push_str("\\r"),
            '\t' => escaped.push_str("\\t"),
            other => escaped.push(other),
        }
    }
    escaped
}

/// Resolved selector form for emitting idiomatic `VictauriClient` calls.
///
/// The JS observer produces raw CSS selectors; this classification maps them
/// to the high-level convenience methods on `VictauriClient` (`click_by_id`,
/// `click_by_text`, etc.) so generated tests read naturally.
enum ResolvedSelector {
    /// Selector started with `#` — strip the hash and use `*_by_id`.
    ById(String),
    /// Selector contained `:has-text("...")` — extract the text and use `*_by_text`.
    ByText(String),
    /// Everything else — pass the raw selector through.
    Raw(String),
}

/// Classifies a raw CSS selector into the most idiomatic `VictauriClient` form.
fn resolve_selector(selector: &str) -> ResolvedSelector {
    // Pattern 2: contains `:has-text("...")` — extract the quoted text.
    if let Some(start) = selector.find(":has-text(\"") {
        let text_start = start + ":has-text(\"".len();
        if let Some(end) = selector[text_start..].find("\")") {
            let text = &selector[text_start..text_start + end];
            return ResolvedSelector::ByText(text.to_string());
        }
    }

    // Pattern 1: starts with `#` (simple ID selector, no combinators).
    if selector.starts_with('#') && !selector[1..].contains(' ') {
        let id = &selector[1..];
        return ResolvedSelector::ById(id.to_string());
    }

    ResolvedSelector::Raw(selector.to_string())
}

/// Emits a single DOM interaction as a `VictauriClient` method call.
///
/// Selector-aware: emits `*_by_id` for `#id` selectors, `*_by_text` for
/// `:has-text("...")` selectors, and `*_by_selector` for raw CSS selectors
/// so the client resolves them to ref handles before interacting.
fn emit_interaction(
    out: &mut String,
    action: &InteractionKind,
    selector: &str,
    value: Option<&str>,
) {
    let resolved = resolve_selector(selector);

    match action {
        InteractionKind::Click => {
            emit_resolved_call(out, "click", &resolved, None);
        }
        InteractionKind::DoubleClick => {
            emit_resolved_call(out, "double_click", &resolved, None);
        }
        InteractionKind::Fill => {
            let val = value.map_or_else(String::new, escape_rust_str);
            emit_resolved_call(out, "fill", &resolved, Some(&val));
        }
        InteractionKind::KeyPress => {
            let val = value.map_or_else(String::new, escape_rust_str);
            out.push_str(&format!(
                "    client.press_key(\"{val}\").await.unwrap();\n"
            ));
        }
        InteractionKind::Select => {
            let val = value.map_or_else(String::new, escape_rust_str);
            emit_resolved_select(out, &resolved, &val);
        }
        InteractionKind::Navigate => {
            let val = value.map_or_else(String::new, escape_rust_str);
            out.push_str(&format!("    client.navigate(\"{val}\").await.unwrap();\n"));
        }
        InteractionKind::Scroll => {
            emit_resolved_scroll(out, &resolved);
        }
    }
}

/// Emits a resolved call for click-like and fill-like methods.
///
/// For `ById` selectors, emits `*_by_id`. For `ByText`, emits `*_by_text`.
/// For `Raw` CSS selectors, emits `*_by_selector` which resolves the selector
/// to a ref handle before interacting.
fn emit_resolved_call(
    out: &mut String,
    base_method: &str,
    resolved: &ResolvedSelector,
    extra_arg: Option<&str>,
) {
    let suffix = extra_arg.map_or_else(String::new, |v| format!(", \"{v}\""));
    match resolved {
        ResolvedSelector::ById(id) => {
            let escaped = escape_rust_str(id);
            out.push_str(&format!(
                "    client.{base_method}_by_id(\"{escaped}\"{suffix}).await.unwrap();\n"
            ));
        }
        ResolvedSelector::ByText(text) => {
            let escaped = escape_rust_str(text);
            out.push_str(&format!(
                "    client.{base_method}_by_text(\"{escaped}\"{suffix}).await.unwrap();\n"
            ));
        }
        ResolvedSelector::Raw(sel) => {
            let escaped = escape_rust_str(sel);
            out.push_str(&format!(
                "    client.{base_method}_by_selector(\"{escaped}\"{suffix}).await.unwrap();\n"
            ));
        }
    }
}

/// Emits a resolved `select_option` call.
///
/// For `Raw` selectors, emits `select_option_by_selector` which resolves the
/// CSS selector to a ref handle before selecting.
fn emit_resolved_select(out: &mut String, resolved: &ResolvedSelector, val: &str) {
    match resolved {
        ResolvedSelector::ById(id) => {
            let escaped = escape_rust_str(id);
            out.push_str(&format!(
                "    client.select_option_by_id(\"{escaped}\", &[\"{val}\"]).await.unwrap();\n"
            ));
        }
        ResolvedSelector::ByText(text) => {
            let escaped = escape_rust_str(text);
            out.push_str(&format!(
                "    client.select_option_by_text(\"{escaped}\", &[\"{val}\"]).await.unwrap();\n"
            ));
        }
        ResolvedSelector::Raw(sel) => {
            let escaped = escape_rust_str(sel);
            out.push_str(&format!(
                "    client.select_option_by_selector(\"{escaped}\", &[\"{val}\"]).await.unwrap();\n"
            ));
        }
    }
}

/// Emits a resolved `scroll_to` call.
///
/// For `Raw` selectors, emits `scroll_to_by_selector`. For `ById`, emits
/// `scroll_to_by_id`. For `ByText`, falls back to `scroll_to_by_selector`
/// with the original selector text (scroll has no text variant).
fn emit_resolved_scroll(out: &mut String, resolved: &ResolvedSelector) {
    match resolved {
        ResolvedSelector::ById(id) => {
            let escaped = escape_rust_str(id);
            out.push_str(&format!(
                "    client.scroll_to_by_id(\"{escaped}\").await.unwrap();\n"
            ));
        }
        ResolvedSelector::ByText(_) | ResolvedSelector::Raw(_) => {
            let sel = match resolved {
                ResolvedSelector::ByText(t) => escape_rust_str(t),
                ResolvedSelector::Raw(s) => escape_rust_str(s),
                _ => unreachable!(),
            };
            out.push_str(&format!(
                "    client.scroll_to_by_selector(\"{sel}\").await.unwrap();\n"
            ));
        }
    }
}

#[cfg(test)]
mod tests {
    use chrono::{Duration, Utc};

    use super::*;
    use crate::event::{AppEvent, InteractionKind, IpcCall, IpcResult};
    use crate::recording::{RecordedEvent, RecordedSession};

    fn make_session(events: Vec<RecordedEvent>) -> RecordedSession {
        RecordedSession {
            id: "test-session-001".to_string(),
            started_at: Utc::now(),
            events,
            checkpoints: vec![],
        }
    }

    fn interaction_event(
        index: usize,
        action: InteractionKind,
        selector: &str,
        value: Option<&str>,
        offset_ms: i64,
    ) -> RecordedEvent {
        RecordedEvent {
            index,
            timestamp: Utc::now() + Duration::milliseconds(offset_ms),
            event: AppEvent::DomInteraction {
                action,
                selector: selector.to_string(),
                value: value.map(String::from),
                timestamp: Utc::now() + Duration::milliseconds(offset_ms),
                webview_label: "main".to_string(),
            },
        }
    }

    #[test]
    fn empty_session_produces_valid_skeleton() {
        let session = make_session(vec![]);
        let code = generate_test_default(&session);

        assert!(code.contains("use victauri_test::VictauriClient;"));
        assert!(code.contains("#[tokio::test]"));
        assert!(code.contains("async fn recorded_flow()"));
        assert!(code.contains("VictauriClient::discover()"));
        assert!(code.contains("Session: test-session-001"));
    }

    #[test]
    fn click_by_id_generated_for_hash_selector() {
        let session = make_session(vec![interaction_event(
            0,
            InteractionKind::Click,
            "#submit-btn",
            None,
            0,
        )]);
        let code = generate_test_default(&session);

        assert!(
            code.contains("client.click_by_id(\"submit-btn\").await.unwrap();"),
            "expected click_by_id for # selector, got:\n{code}"
        );
    }

    #[test]
    fn fill_generates_correct_call() {
        let session = make_session(vec![interaction_event(
            0,
            InteractionKind::Fill,
            "input[name=\"email\"]",
            Some("user@example.com"),
            0,
        )]);
        let code = generate_test_default(&session);

        assert!(code.contains(
            "client.fill_by_selector(\"input[name=\\\"email\\\"]\", \"user@example.com\").await.unwrap();"
        ));
    }

    #[test]
    fn ipc_comment_included_when_enabled() {
        let session = make_session(vec![RecordedEvent {
            index: 0,
            timestamp: Utc::now(),
            event: AppEvent::Ipc(IpcCall {
                id: "c1".to_string(),
                command: "save_settings".to_string(),
                timestamp: Utc::now(),
                duration_ms: Some(10),
                result: IpcResult::Ok(serde_json::json!(true)),
                arg_size_bytes: 0,
                webview_label: "main".to_string(),
            }),
        }]);
        let code = generate_test_default(&session);

        assert!(code.contains("// IPC: save_settings completed successfully"));
    }

    #[test]
    fn internal_victauri_ipc_skipped() {
        let session = make_session(vec![RecordedEvent {
            index: 0,
            timestamp: Utc::now(),
            event: AppEvent::Ipc(IpcCall {
                id: "c2".to_string(),
                command: "plugin:victauri|get_snapshot".to_string(),
                timestamp: Utc::now(),
                duration_ms: Some(2),
                result: IpcResult::Ok(serde_json::json!({})),
                arg_size_bytes: 0,
                webview_label: "main".to_string(),
            }),
        }]);
        let code = generate_test_default(&session);

        assert!(!code.contains("plugin:victauri"));
    }

    #[test]
    fn ipc_omitted_when_disabled() {
        let session = make_session(vec![RecordedEvent {
            index: 0,
            timestamp: Utc::now(),
            event: AppEvent::Ipc(IpcCall {
                id: "c1".to_string(),
                command: "save_settings".to_string(),
                timestamp: Utc::now(),
                duration_ms: Some(10),
                result: IpcResult::Ok(serde_json::json!(true)),
                arg_size_bytes: 0,
                webview_label: "main".to_string(),
            }),
        }]);
        let opts = CodegenOptions {
            include_ipc_assertions: false,
            ..CodegenOptions::default()
        };
        let code = generate_test(&session, &opts);

        assert!(!code.contains("IPC:"));
    }

    #[test]
    fn state_change_comment_included() {
        let session = make_session(vec![RecordedEvent {
            index: 0,
            timestamp: Utc::now(),
            event: AppEvent::StateChange {
                key: "user.theme".to_string(),
                timestamp: Utc::now(),
                caused_by: Some("toggle_theme".to_string()),
            },
        }]);
        let code = generate_test_default(&session);

        assert!(code.contains("// State changed: user.theme"));
    }

    #[test]
    fn custom_test_name() {
        let session = make_session(vec![]);
        let opts = CodegenOptions {
            test_name: "my_custom_test".to_string(),
            ..CodegenOptions::default()
        };
        let code = generate_test(&session, &opts);

        assert!(code.contains("async fn my_custom_test()"));
    }

    #[test]
    fn special_chars_escaped() {
        let session = make_session(vec![interaction_event(
            0,
            InteractionKind::Fill,
            "input",
            Some("line1\nline2\ttab\"quote\\back"),
            0,
        )]);
        let code = generate_test_default(&session);

        assert!(code.contains("\\n"));
        assert!(code.contains("\\t"));
        assert!(code.contains("\\\""));
        assert!(code.contains("\\\\"));
    }

    #[test]
    fn all_interaction_kinds_generate_code() {
        let session = make_session(vec![
            interaction_event(0, InteractionKind::Click, "[data-testid=\"a\"]", None, 0),
            interaction_event(
                1,
                InteractionKind::DoubleClick,
                "[data-testid=\"b\"]",
                None,
                10,
            ),
            interaction_event(
                2,
                InteractionKind::Fill,
                "[data-testid=\"c\"]",
                Some("val"),
                20,
            ),
            interaction_event(3, InteractionKind::KeyPress, "#d", Some("Enter"), 30),
            interaction_event(
                4,
                InteractionKind::Select,
                "[data-testid=\"e\"]",
                Some("opt1"),
                40,
            ),
            interaction_event(5, InteractionKind::Navigate, "#f", Some("/page"), 50),
            interaction_event(6, InteractionKind::Scroll, "#g", None, 60),
        ]);
        let code = generate_test(
            &session,
            &CodegenOptions {
                include_timing_comments: false,
                ..CodegenOptions::default()
            },
        );

        assert!(code.contains("client.click_by_selector(\"[data-testid=\\\"a\\\"]\")"));
        assert!(code.contains("client.double_click_by_selector(\"[data-testid=\\\"b\\\"]\")"));
        assert!(code.contains("client.fill_by_selector(\"[data-testid=\\\"c\\\"]\", \"val\")"));
        assert!(code.contains("client.press_key(\"Enter\")"));
        assert!(code.contains(
            "client.select_option_by_selector(\"[data-testid=\\\"e\\\"]\", &[\"opt1\"])"
        ));
        assert!(code.contains("client.navigate(\"/page\")"));
        assert!(code.contains("client.scroll_to_by_id(\"g\")"));
    }

    #[test]
    fn dom_mutation_and_window_event_skipped() {
        let ts = Utc::now();
        let session = make_session(vec![
            RecordedEvent {
                index: 0,
                timestamp: ts,
                event: AppEvent::DomMutation {
                    webview_label: "main".to_string(),
                    timestamp: ts,
                    mutation_count: 5,
                },
            },
            RecordedEvent {
                index: 1,
                timestamp: ts,
                event: AppEvent::WindowEvent {
                    label: "main".to_string(),
                    event: "focus".to_string(),
                    timestamp: ts,
                },
            },
        ]);
        let code = generate_test_default(&session);

        // Should only have the skeleton, no interaction or assertion lines
        assert!(!code.contains("client."));
        assert!(!code.contains("// IPC:"));
        assert!(!code.contains("// State"));
    }

    #[test]
    fn default_options_are_correct() {
        let opts = CodegenOptions::default();
        assert_eq!(opts.test_name, "recorded_flow");
        assert!(opts.include_ipc_assertions);
        assert!(opts.include_state_checks);
        assert!(opts.include_timing_comments);
    }

    // --- Timing comment tests ---

    fn make_session_at(base: chrono::DateTime<Utc>, events: Vec<RecordedEvent>) -> RecordedSession {
        RecordedSession {
            id: "timing-session".to_string(),
            started_at: base,
            events,
            checkpoints: vec![],
        }
    }

    fn interaction_event_at(
        base: chrono::DateTime<Utc>,
        index: usize,
        action: InteractionKind,
        selector: &str,
        value: Option<&str>,
        offset_ms: i64,
    ) -> RecordedEvent {
        let ts = base + Duration::milliseconds(offset_ms);
        RecordedEvent {
            index,
            timestamp: ts,
            event: AppEvent::DomInteraction {
                action,
                selector: selector.to_string(),
                value: value.map(String::from),
                timestamp: ts,
                webview_label: "main".to_string(),
            },
        }
    }

    #[test]
    fn timing_comment_emitted_for_large_gap() {
        let base = Utc::now();
        let session = make_session_at(
            base,
            vec![
                interaction_event_at(base, 0, InteractionKind::Click, ".btn-a", None, 0),
                interaction_event_at(base, 1, InteractionKind::Click, ".btn-b", None, 1000),
            ],
        );
        let opts = CodegenOptions {
            include_timing_comments: true,
            ..CodegenOptions::default()
        };
        let code = generate_test(&session, &opts);

        assert!(
            code.contains("// +1000ms"),
            "expected timing comment for 1000ms gap, got:\n{code}"
        );
    }

    #[test]
    fn timing_comment_omitted_for_small_gap() {
        let base = Utc::now();
        let session = make_session_at(
            base,
            vec![
                interaction_event_at(base, 0, InteractionKind::Click, ".btn-a", None, 0),
                interaction_event_at(base, 1, InteractionKind::Click, ".btn-b", None, 200),
            ],
        );
        let opts = CodegenOptions {
            include_timing_comments: true,
            ..CodegenOptions::default()
        };
        let code = generate_test(&session, &opts);

        assert!(
            !code.contains("// +"),
            "expected no timing comment for 200ms gap, got:\n{code}"
        );
    }

    // --- Selector resolution tests ---

    #[test]
    fn id_selector_emits_click_by_id() {
        let session = make_session(vec![interaction_event(
            0,
            InteractionKind::Click,
            "#my-id",
            None,
            0,
        )]);
        let code = generate_test_default(&session);

        assert!(
            code.contains("client.click_by_id(\"my-id\").await.unwrap();"),
            "expected click_by_id, got:\n{code}"
        );
    }

    #[test]
    fn has_text_selector_emits_click_by_text() {
        let session = make_session(vec![interaction_event(
            0,
            InteractionKind::Click,
            "button:has-text(\"Submit\")",
            None,
            0,
        )]);
        let code = generate_test_default(&session);

        assert!(
            code.contains("client.click_by_text(\"Submit\").await.unwrap();"),
            "expected click_by_text, got:\n{code}"
        );
    }

    #[test]
    fn role_has_text_selector_emits_click_by_text() {
        let session = make_session(vec![interaction_event(
            0,
            InteractionKind::Click,
            "[role=\"button\"]:has-text(\"Save\")",
            None,
            0,
        )]);
        let code = generate_test_default(&session);

        assert!(
            code.contains("client.click_by_text(\"Save\").await.unwrap();"),
            "expected click_by_text for role selector, got:\n{code}"
        );
    }

    #[test]
    fn data_testid_selector_emits_click_by_selector() {
        let session = make_session(vec![interaction_event(
            0,
            InteractionKind::Click,
            "[data-testid=\"foo\"]",
            None,
            0,
        )]);
        let code = generate_test_default(&session);

        assert!(
            code.contains(
                "client.click_by_selector(\"[data-testid=\\\"foo\\\"]\").await.unwrap();"
            ),
            "expected click_by_selector for data-testid selector, got:\n{code}"
        );
    }

    #[test]
    fn fill_with_id_selector_emits_fill_by_id() {
        let session = make_session(vec![interaction_event(
            0,
            InteractionKind::Fill,
            "#email",
            Some("user@example.com"),
            0,
        )]);
        let code = generate_test_default(&session);

        assert!(
            code.contains("client.fill_by_id(\"email\", \"user@example.com\").await.unwrap();"),
            "expected fill_by_id, got:\n{code}"
        );
    }

    #[test]
    fn double_click_with_has_text_emits_by_text() {
        let session = make_session(vec![interaction_event(
            0,
            InteractionKind::DoubleClick,
            "span:has-text(\"Edit\")",
            None,
            0,
        )]);
        let code = generate_test_default(&session);

        assert!(
            code.contains("client.double_click_by_text(\"Edit\").await.unwrap();"),
            "expected double_click_by_text, got:\n{code}"
        );
    }

    #[test]
    fn select_with_id_emits_select_option_by_id() {
        let session = make_session(vec![interaction_event(
            0,
            InteractionKind::Select,
            "#country",
            Some("AU"),
            0,
        )]);
        let code = generate_test_default(&session);

        assert!(
            code.contains("client.select_option_by_id(\"country\", &[\"AU\"]).await.unwrap();"),
            "expected select_option_by_id, got:\n{code}"
        );
    }

    /// Round-trip test: builds a realistic multi-event session and verifies
    /// the generated Rust source contains valid structural elements for every
    /// event kind — click, fill, key-press, IPC, and state-change.
    #[test]
    fn round_trip_realistic_session() {
        let base = Utc::now();

        let events = vec![
            // 0: Click on #submit-btn  (should resolve to click_by_id)
            interaction_event_at(base, 0, InteractionKind::Click, "#submit-btn", None, 0),
            // 1: Fill on input[name=email]  (raw selector — should use client.fill_by_selector)
            interaction_event_at(
                base,
                1,
                InteractionKind::Fill,
                "input[name=email]",
                Some("test@example.com"),
                100,
            ),
            // 2: KeyPress "Enter"
            interaction_event_at(
                base,
                2,
                InteractionKind::KeyPress,
                "body",
                Some("Enter"),
                200,
            ),
            // 3: IPC call — save_draft completed successfully
            RecordedEvent {
                index: 3,
                timestamp: base + Duration::milliseconds(300),
                event: AppEvent::Ipc(IpcCall {
                    id: "ipc-1".to_string(),
                    command: "save_draft".to_string(),
                    timestamp: base + Duration::milliseconds(300),
                    duration_ms: Some(15),
                    result: IpcResult::Ok(serde_json::json!({"saved": true})),
                    arg_size_bytes: 42,
                    webview_label: "main".to_string(),
                }),
            },
            // 4: StateChange caused by save_draft
            RecordedEvent {
                index: 4,
                timestamp: base + Duration::milliseconds(350),
                event: AppEvent::StateChange {
                    key: "draft.status".to_string(),
                    timestamp: base + Duration::milliseconds(350),
                    caused_by: Some("save_draft".to_string()),
                },
            },
        ];

        let session = make_session_at(base, events);
        let code = generate_test(&session, &CodegenOptions::default());

        // --- Structural validity: the generated code is a well-formed async test ---
        assert!(
            code.contains("#[tokio::test]"),
            "missing #[tokio::test] attribute:\n{code}"
        );
        assert!(
            code.contains("async fn recorded_flow()"),
            "missing async fn declaration:\n{code}"
        );
        assert!(
            code.contains("VictauriClient::discover()"),
            "missing VictauriClient::discover() call:\n{code}"
        );
        assert!(
            code.ends_with("}\n"),
            "missing closing brace at end of generated code:\n{code}"
        );

        // --- Event-specific assertions ---

        // Click on #submit-btn should resolve to click_by_id (not raw click with "#submit-btn")
        assert!(
            code.contains("client.click_by_id(\"submit-btn\").await.unwrap();"),
            "expected click_by_id for #submit-btn:\n{code}"
        );
        assert!(
            !code.contains("client.click(\"#submit-btn\")"),
            "#submit-btn should NOT appear as raw client.click:\n{code}"
        );

        // Fill on input[name=email] — raw selector, should use fill_by_selector
        assert!(
            code.contains(
                "client.fill_by_selector(\"input[name=email]\", \"test@example.com\").await.unwrap();"
            ),
            "expected fill_by_selector for input[name=email]:\n{code}"
        );
        assert!(
            !code.contains("client.fill_by_id(\"input[name=email]\""),
            "input[name=email] should NOT resolve to fill_by_id:\n{code}"
        );

        // KeyPress "Enter"
        assert!(
            code.contains("client.press_key(\"Enter\").await.unwrap();"),
            "expected press_key(\"Enter\"):\n{code}"
        );

        // IPC comment for save_draft
        assert!(
            code.contains("// IPC: save_draft completed successfully"),
            "expected IPC comment for save_draft:\n{code}"
        );

        // State change comment for draft.status
        assert!(
            code.contains("// State changed: draft.status"),
            "expected state change comment for draft.status:\n{code}"
        );

        // --- Brace matching: count opening and closing braces ---
        let open_braces = code.matches('{').count();
        let close_braces = code.matches('}').count();
        assert_eq!(
            open_braces, close_braces,
            "unbalanced braces: {open_braces} open vs {close_braces} close in:\n{code}"
        );
    }
}