skim 4.4.0

Fuzzy Finder in rust!
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
use std::io::Cursor;

use clap::Parser;
use color_eyre::Result;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::backend::TestBackend;
use skim::{
    Skim, SkimItemReceiver,
    prelude::*,
    tui::{Event, Size, Tui, event::Action},
};

/// A test harness for running skim TUI tests with insta snapshots.
///
/// This struct wraps a [`Skim<TestBackend>`] instance, providing a synchronous,
/// event-driven interface that mirrors how the real application works. Events are
/// sent via the event channel and processed through the app's event loop.
///
/// The harness reuses as much of the production code path as possible:
/// - Items are loaded through the same `Reader` + `SkimItemReader` pipeline as
///   the real application
/// - Reload events use `Skim::handle_reload()`, the same logic as the production
///   event loop
/// - Reader completion is checked via `Skim::check_reader()`, identical to
///   production
pub struct TestHarness {
    /// The Skim instance backed by a TestBackend for snapshot testing.
    pub skim: Skim<TestBackend>,
    /// Tokio runtime for async operations (preview commands, etc.)
    pub runtime: tokio::runtime::Runtime,
    /// The final event that caused the app to quit (for determining exit code)
    pub final_event: Option<Event>,
}

impl TestHarness {
    /// Process all pending events from the event queue.
    ///
    /// This is the core method that processes events just like the real event loop
    /// in `lib.rs`. It drains the event_rx channel and calls `app.handle_event()`
    /// for each event, mimicking the actual application behavior.
    ///
    /// For `Event::Reload`, it delegates to `Skim::handle_reload()` — the same
    /// method used by the production event loop.
    pub fn tick(&mut self) -> Result<()> {
        // Drain-and-process in a loop so events queued during processing
        // are picked up on the next iteration.
        loop {
            let mut events = Vec::new();
            while let Ok(event) = self.skim.tui_mut().event_rx.try_recv() {
                events.push(event);
            }
            if events.is_empty() {
                break;
            }
            for event in events {
                self.process_event(event)?;
            }
        }
        Ok(())
    }

    /// Process a single event through the same logic as the production event loop.
    ///
    /// `Event::Reload` is handled via `Skim::handle_reload()` — the exact same
    /// method used in production. All other events are forwarded to
    /// `app.handle_event()`.
    fn process_event(&mut self, event: Event) -> Result<()> {
        if let Event::Reload(ref new_cmd) = event {
            let new_cmd = new_cmd.clone();
            self.skim.handle_reload(&new_cmd);
        } else {
            // Let the app handle the event (this may queue more events)
            // Enter the runtime context so that tokio::spawn() calls work
            let _guard = self.runtime.enter();
            let (app, tui) = self.skim.app_and_tui();
            app.handle_event(tui, &event)?;
        }

        // Check reader status, just like the production event loop
        self.skim.check_reader();

        // Track if app should quit and what the final event was
        if self.skim.app().should_quit && self.final_event.is_none() {
            self.final_event = Some(event);
        }

        Ok(())
    }

    /// Send an event to the event queue.
    ///
    /// This queues an event for processing. Call `tick()` to process queued events.
    pub fn send(&mut self, event: Event) -> Result<()> {
        self.skim.tui_mut().event_tx.try_send(event)?;
        Ok(())
    }

    /// Send a key event and process it immediately.
    ///
    /// This is the primary way to simulate user input. It:
    /// 1. Sends the key event to the queue
    /// 2. Processes all pending events (including any triggered by the key)
    /// 3. Waits for reader (if running) and matcher to complete
    pub fn key(&mut self, key: KeyEvent) -> Result<()> {
        self.send(Event::Key(key))?;
        self.tick()?;
        self.wait_for_completion()?;
        Ok(())
    }

    /// Send a character key event.
    pub fn char(&mut self, c: char) -> Result<()> {
        self.key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE))
    }

    /// Type a string, sending each character as a key event.
    pub fn type_str(&mut self, s: &str) -> Result<()> {
        for c in s.chars() {
            self.char(c)?;
        }
        Ok(())
    }

    /// Send an action and process it immediately.
    pub fn action(&mut self, action: Action) -> Result<()> {
        self.send(Event::Action(action))?;
        self.tick()?;
        self.wait_for_completion()?;
        Ok(())
    }

    /// Wait for any in-flight reader and matcher to complete.
    ///
    /// If the reader is still running (e.g., after a reload in interactive mode),
    /// waits for it to finish first. Then waits for the matcher if it needs to run.
    ///
    /// If a debounced matcher restart is pending (e.g., because the query changed
    /// within the 50ms debounce window), this forces the restart immediately so
    /// tests don't see stale results.
    fn wait_for_completion(&mut self) -> Result<()> {
        // If a debounced matcher restart is pending, force it now.
        // In production, the Heartbeat event would trigger this, but in tests
        // we don't have a continuous heartbeat timer.
        if self.skim.app().pending_matcher_restart {
            self.skim.app_mut().restart_matcher(true);
        }

        // If the reader is running (not done), wait for it + matcher
        if !self.skim.reader_done() {
            self.wait_for_reader_and_matcher()?;
        } else {
            // Always wait for the matcher to ensure results are consumed.
            // Even if stopped() is already true, wait_for_matcher will
            // render and process heartbeat to consume processed_items.
            self.wait_for_matcher()?;
        }
        Ok(())
    }

    /// Get a string representation of the current buffer for snapshot testing.
    pub fn buffer_view(&self) -> String {
        self.skim.tui_ref().backend().to_string()
    }

    /// Prepare for taking a snapshot by waiting for preview and processing heartbeat.
    ///
    /// This ensures the state is up-to-date before taking a snapshot.
    /// Call `render()` and `buffer_view()` afterward to actually take the snapshot.
    pub fn prepare_snap(&mut self) -> Result<()> {
        // Send heartbeat first to trigger any debounced pending preview runs.
        // The debounce logic in run_preview() sets pending_preview_run=true when
        // a RunPreview is dropped. The Heartbeat handler checks this flag and
        // spawns the preview. We need this to happen BEFORE wait_for_preview()
        // so it can detect and wait for the spawned preview task.
        self.send(Event::Heartbeat)?;
        self.tick()?;

        self.handle_remaining_events()?;

        // Force a final render so that any state changes (e.g. PreviewReady) that
        // were processed inside handle_remaining_events are reflected in the buffer
        // before we take the snapshot.  We bypass the frame-rate throttle by sending
        // Render directly instead of relying on the Heartbeat path.
        self.send(Event::Render)?;
        self.tick()?;
        Ok(())
    }

    /// Take a snapshot of the current state.
    ///
    /// NOTE: This method should NOT be called from test code directly because
    /// insta will use the wrong file path for the snapshot. Use the snap! macro instead.
    #[doc(hidden)]
    pub fn snap(&mut self) -> Result<()> {
        self.prepare_snap()?;
        let buf = self.buffer_view();
        let cursor_pos = format!(
            "cursor: {}x{}",
            self.skim.app().cursor_pos.0,
            self.skim.app().cursor_pos.1
        );
        insta::assert_snapshot!(buf + &cursor_pos);
        Ok(())
    }

    /// Wait for the reader to finish producing items and the matcher to complete.
    ///
    /// This polls `Skim::reader_done()` and `Skim::check_reader()` — the same
    /// methods used by the production event loop — until the reader has finished,
    /// then waits for the matcher to process all items.
    pub fn wait_for_reader_and_matcher(&mut self) -> Result<()> {
        let timeout = std::time::Duration::from_secs(5);
        let start = std::time::Instant::now();
        let poll_interval = std::time::Duration::from_millis(10);

        // Wait for reader to finish
        while !self.skim.reader_done() {
            if start.elapsed() > timeout {
                return Err(color_eyre::eyre::eyre!("Timeout waiting for reader to finish"));
            }
            // Check reader status (may restart matcher)
            self.skim.check_reader();
            std::thread::sleep(poll_interval);
        }

        // Final check to restart matcher with remaining items
        self.skim.check_reader();

        self.wait_for_matcher()?;
        Ok(())
    }

    /// Wait for matcher to complete processing.
    pub fn wait_for_matcher(&mut self) -> Result<()> {
        let timeout = std::time::Duration::from_secs(5);
        let start = std::time::Instant::now();
        let poll_interval = std::time::Duration::from_millis(10);

        // Wait for matcher to complete
        while !self.skim.app().matcher_control.stopped() {
            if start.elapsed() > timeout {
                return Err(color_eyre::eyre::eyre!("Timeout waiting for matcher to stop"));
            }
            std::thread::sleep(poll_interval);
        }

        // Give the background processing thread time to receive items
        std::thread::sleep(std::time::Duration::from_millis(50));

        // Process heartbeat to update status counters
        self.send(Event::Heartbeat)?;
        self.tick()?;

        // Manually trigger preview if configured and an item is selected
        // Note: on_item_changed won't trigger automatically because the item was
        // already selected during render, so prev_item == new_item
        let needs_preview = self.skim.app().options.preview.is_some() && self.skim.app().item_list.selected().is_some();
        if needs_preview {
            self.send(Event::RunPreview)?;
            self.handle_remaining_events()?;
        }

        Ok(())
    }

    /// Wait for preview to be ready.
    pub fn handle_remaining_events(&mut self) -> Result<()> {
        // Process any queued events first (including RunPreview)
        self.tick()?;

        // If there's no preview task running, nothing to wait for
        let has_pending = match self.skim.app().preview.thread_handle {
            Some(ref handle) => !handle.is_finished(),
            None => false,
        };

        if !has_pending {
            // Thread is already done (or was never started). Drain any events it may
            // have sent (e.g. PreviewReady) that arrived after our initial tick().
            self.tick()?;
            return Ok(());
        }

        // Wait for the preview thread to finish, then drain its events.
        let timeout = std::time::Duration::from_secs(2);
        let start = std::time::Instant::now();

        loop {
            // Sleep to give the background thread time to make progress
            std::thread::sleep(std::time::Duration::from_millis(10));

            // Drain and process any events (including PreviewReady)
            self.tick()?;

            // Exit as soon as the thread is done and we have processed its events
            let finished = self
                .skim
                .app()
                .preview
                .thread_handle
                .as_ref()
                .map(|h| h.is_finished())
                .unwrap_or(true);
            if finished {
                // One final drain to catch any events emitted right at thread exit
                self.tick()?;
                return Ok(());
            }

            if start.elapsed() > timeout {
                return Ok(());
            }
        }
    }

    /// Process a heartbeat event to update status counters.
    pub fn heartbeat(&mut self) -> Result<()> {
        self.send(Event::Heartbeat)?;
        self.tick()
    }

    /// Get the exit code that skim would return based on the final event.
    ///
    /// This mimics the logic in `bin/main.rs`:
    /// - 130 if the app aborted (Ctrl+C, Ctrl+D, Esc, etc.)
    /// - 0 if the app accepted (Enter)
    /// - None if the app hasn't quit yet
    pub fn app_exit_code(&self) -> Option<i32> {
        if !self.skim.app().should_quit {
            return None;
        }

        // Check if the final event was an Accept action
        // This matches the logic in lib.rs:560
        let is_abort = self
            .final_event
            .as_ref()
            .map(|event| !matches!(event, Event::Action(Action::Accept(_))))
            .unwrap_or(true);

        Some(if is_abort { 130 } else { 0 })
    }
}

// ============================================================================
// Factory functions
// ============================================================================

/// Initialize a test harness with the given options, dimensions, and optional item source.
///
/// Uses [`Skim::init`] for the core initialization (App, Reader, theme, etc.)
/// and [`Skim::init_tui_with`] to inject a [`TestBackend`].
/// Then calls [`Skim::start`] to begin the reader and matcher — the same
/// production code path used by the real application.
fn enter_sized_with_source(
    options: SkimOptions,
    width: u16,
    height: u16,
    source: Option<SkimItemReceiver>,
) -> Result<TestHarness> {
    let backend = TestBackend::new(width, height);
    let tui = Tui::new_with_height_and_backend(backend, Size::Percent(100))?;
    let mut skim = Skim::<TestBackend>::init(options, source)?;
    skim.init_tui_with(tui);

    // Start the reader and matcher — the same call the production binary makes
    skim.start();

    // Create a multi-threaded tokio runtime for async operations (preview commands, etc.)
    let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build()?;

    let mut harness = TestHarness {
        skim,
        runtime,
        final_event: None,
    };

    // Wait for the reader to finish and matcher to complete
    harness.wait_for_reader_and_matcher()?;

    Ok(harness)
}

/// Initialize a test harness with the given options and dimensions.
pub fn enter_sized(options: SkimOptions, width: u16, height: u16) -> Result<TestHarness> {
    enter_sized_with_source(options, width, height, None)
}

/// Initialize a test harness with default dimensions (80x24).
pub fn enter(options: SkimOptions) -> Result<TestHarness> {
    enter_sized(options, 80, 24)
}

/// Initialize a test harness with default options.
pub fn enter_default() -> Result<TestHarness> {
    enter_sized(SkimOptions::default().build(), 80, 24)
}

/// Initialize a test harness with pre-loaded items.
///
/// Items are fed through the production `Reader` + `SkimItemReader` pipeline
/// by converting them to a newline-separated byte stream and using
/// `SkimItemReader::of_bufread()`.
pub fn enter_items<I, S>(items: I, options: SkimOptions) -> Result<TestHarness>
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    // Build a newline-terminated string from items and feed through SkimItemReader.
    // Each item must end with '\n' so the reader produces one item per entry,
    // including empty-string items like "".
    let text: String = items
        .into_iter()
        .map(|s| {
            let mut line = s.as_ref().to_owned();
            line.push('\n');
            line
        })
        .collect();

    let reader_opts = SkimItemReaderOption::from_options(&options);
    let item_reader = SkimItemReader::new(reader_opts);
    let rx = item_reader.of_bufread(Cursor::new(text));

    enter_sized_with_source(options, 80, 24, Some(rx))
}

/// Initialize a test harness with raw bytes as input.
///
/// Feeds bytes directly through the `SkimItemReader` pipeline without spawning
/// a subprocess. Useful for inputs containing NUL bytes (e.g. `--read0` tests)
/// where the byte sequence cannot be expressed as a simple string.
pub fn enter_bytes(bytes: &'static [u8], options: SkimOptions) -> Result<TestHarness> {
    let reader_opts = SkimItemReaderOption::from_options(&options);
    let item_reader = SkimItemReader::new(reader_opts);
    let rx = item_reader.of_bufread(Cursor::new(bytes));
    enter_sized_with_source(options, 80, 24, Some(rx))
}

/// Initialize a test harness with command output as items.
///
/// The command is executed through the production `Reader` + `SkimItemReader`
/// pipeline, identical to how the real application works.
pub fn enter_cmd(cmd: &str, options: SkimOptions) -> Result<TestHarness> {
    let reader_opts = SkimItemReaderOption::from_options(&options);
    let item_reader = SkimItemReader::new(reader_opts);
    let rx = item_reader.of_bufread(std::io::BufReader::new(
        std::process::Command::new("sh")
            .arg("-c")
            .arg(cmd)
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::null())
            .spawn()?
            .stdout
            .ok_or_else(|| color_eyre::eyre::eyre!("Failed to capture stdout"))?,
    ));

    enter_sized_with_source(options, 80, 24, Some(rx))
}

/// Initialize a test harness for interactive mode.
///
/// Uses [`Skim::start`] which already handles interactive mode correctly:
/// it expands the command template with the initial query and starts the
/// reader pipeline.
pub fn enter_interactive(options: SkimOptions) -> Result<TestHarness> {
    // Skim::init() computes initial_cmd for interactive mode,
    // and Skim::start() kicks off the reader with it.
    // No special-casing needed here.
    enter(options)
}

/// Format a slice of CLI-style option strings as a single space-separated string.
///
/// Used by `insta_test!` to build snapshot descriptions.  Accepting `&[&str]`
/// explicitly avoids the type-inference failure that occurs when the macro
/// passes an un-typed empty slice literal (`&[]`) to `.join()`.
pub fn fmt_opts(opts: &[&str]) -> String {
    opts.join(" ")
}

/// Parse SkimOptions from CLI-style arguments.
pub fn parse_options(args: &[&str]) -> SkimOptions {
    let mut full_args = vec!["sk"];
    full_args.extend(args);
    SkimOptions::try_parse_from(full_args)
        .expect("Failed to parse options")
        .build()
}

// ============================================================================
// Macros
// ============================================================================

#[macro_export]
macro_rules! snap {
    // With description and a 1-based counter — uses `snapshot_suffix` so that
    // insta names the file `test_name@001.snap`, `test_name@002.snap`, …
    // Files then sort correctly in `cargo insta review`.
    ($harness:ident, $desc:expr, $count:expr) => {{
        $harness.prepare_snap()?;
        let __buf = $harness.buffer_view();
        let __cursor_pos = format!(
            "cursor: ({}, {})",
            $harness.skim.app().cursor_pos.1 + 1,
            $harness.skim.app().cursor_pos.0 + 1
        );
        insta::with_settings!({
            description => $desc,
            snapshot_suffix => format!("{:03}", $count),
            omit_expression => true,
        }, {
            insta::assert_snapshot!(__buf + &__cursor_pos);
        });
    }};
    // With description only (simple/single-snapshot variants) — no suffix, so
    // the file is named `test_name.snap` as before.
    ($harness:ident, $desc:expr) => {{
        $harness.prepare_snap()?;
        let __buf = $harness.buffer_view();
        let __cursor_pos = format!(
            "cursor: ({}, {})",
            $harness.skim.app().cursor_pos.1 + 1,
            $harness.skim.app().cursor_pos.0 + 1
        );
        insta::with_settings!({ description => $desc, omit_expression => true }, {
            insta::assert_snapshot!(__buf + &__cursor_pos);
        });
    }};
    // Backward-compat form — no description, no suffix.
    ($harness:ident) => {
        $crate::snap!($harness, "")
    };
}

/// Macro for writing compact insta snapshot tests.
///
/// # Usage
///
/// ## Input syntax:
/// - `["a", "b", "c"]` - items array
/// - `@cmd "seq 1 100"` - command output as items
/// - `@interactive` - interactive mode with `--cmd`
///
/// ## Basic usage (just takes a snapshot):
/// ```ignore
/// insta_test!(test_name, ["item1", "item2"], &["--opts"]);
/// ```
///
/// ## DSL usage (with commands):
/// ```ignore
/// insta_test!(test_name, ["a", "b", "c"], &["--multi"], {
///     @snap;              // Take snapshot
///     @char 'f';          // Send single character
///     @type "foo";        // Type string
///     @action Down(1);    // Send action
///     @key Enter;         // Send special key
///     @exited 0;          // Assert command exited with status code 0
/// });
/// ```
#[macro_export]
macro_rules! insta_test {
    // Simple variant with items array - just snapshot
    ($name:ident, [$($item:expr),* $(,)?], $options:expr) => {
        #[test]
        fn $name() -> color_eyre::Result<()> {
            let options = $crate::common::insta::parse_options($options);
            let mut h = $crate::common::insta::enter_items([$($item),*], options)?;
            let __desc = format!(
                "input: items [{}]\noptions: {}",
                stringify!($($item),*),
                $crate::common::insta::fmt_opts($options),
            );
            $crate::snap!(h, &__desc);
            Ok(())
        }
    };

    // Simple variant with items expression (identifier or expression) - just snapshot
    ($name:ident, $items:expr, $options:expr) => {
        #[test]
        fn $name() -> color_eyre::Result<()> {
            let options = $crate::common::insta::parse_options($options);
            let mut h = $crate::common::insta::enter_items($items, options)?;
            let __desc = format!(
                "input: items {}\noptions: {}",
                stringify!($items),
                $crate::common::insta::fmt_opts($options),
            );
            $crate::snap!(h, &__desc);
            Ok(())
        }
    };

    // Simple variant with @cmd - just snapshot
    ($name:ident, @cmd $cmd:expr, $options:expr) => {
        #[test]
        fn $name() -> color_eyre::Result<()> {
            let options = $crate::common::insta::parse_options($options);
            let mut h = $crate::common::insta::enter_cmd($cmd, options)?;
            let __desc = format!(
                "input: cmd {}\noptions: {}",
                stringify!($cmd),
                $crate::common::insta::fmt_opts($options),
            );
            $crate::snap!(h, &__desc);
            Ok(())
        }
    };

    // Simple variant with @bytes - just snapshot
    ($name:ident, @bytes $bytes:expr, $options:expr) => {
        #[test]
        fn $name() -> color_eyre::Result<()> {
            let options = $crate::common::insta::parse_options($options);
            let mut h = $crate::common::insta::enter_bytes($bytes, options)?;
            let __desc = format!(
                "input: bytes {}\noptions: {}",
                stringify!($bytes),
                $crate::common::insta::fmt_opts($options),
            );
            $crate::snap!(h, &__desc);
            Ok(())
        }
    };

    // Simple variant with @interactive - just snapshot
    ($name:ident, @interactive, $options:expr) => {
        #[test]
        fn $name() -> color_eyre::Result<()> {
            let options = $crate::common::insta::parse_options($options);
            let mut h = $crate::common::insta::enter_interactive(options)?;
            let __desc = format!(
                "input: interactive\noptions: {}",
                $crate::common::insta::fmt_opts($options),
            );
            $crate::snap!(h, &__desc);
            Ok(())
        }
    };

    // DSL variant with items expression (identifier or expression)
    ($name:ident, $items:expr, $options:expr, { $($content:tt)* }) => {
        #[test]
        fn $name() -> color_eyre::Result<()> {
            let options = $crate::common::insta::parse_options($options);
            let mut h = $crate::common::insta::enter_items($items, options)?;
            let __base_desc = format!(
                "input: items {}\noptions: {}",
                stringify!($items),
                $crate::common::insta::fmt_opts($options),
            );
            let mut __cmds: Vec<&'static str> = Vec::new();
            let mut __snap_count: u32 = 0;
            insta_test!(@expand h, __base_desc, __cmds, __snap_count; $($content)*);

            Ok(())
        }
    };

    // DSL variant with @cmd
    ($name:ident, @cmd $cmd:expr, $options:expr, { $($content:tt)* }) => {
        #[test]
        fn $name() -> color_eyre::Result<()> {
            let options = $crate::common::insta::parse_options($options);
            let mut h = $crate::common::insta::enter_cmd($cmd, options)?;
            let __base_desc = format!(
                "input: cmd {}\noptions: {}",
                stringify!($cmd),
                $crate::common::insta::fmt_opts($options),
            );
            let mut __cmds: Vec<&'static str> = Vec::new();
            let mut __snap_count: u32 = 0;
            insta_test!(@expand h, __base_desc, __cmds, __snap_count; $($content)*);

            Ok(())
        }
    };

    // DSL variant with @bytes
    ($name:ident, @bytes $bytes:expr, $options:expr, { $($content:tt)* }) => {
        #[test]
        fn $name() -> color_eyre::Result<()> {
            let options = $crate::common::insta::parse_options($options);
            let mut h = $crate::common::insta::enter_bytes($bytes, options)?;
            let __base_desc = format!(
                "input: bytes {}\noptions: {}",
                stringify!($bytes),
                $crate::common::insta::fmt_opts($options),
            );
            let mut __cmds: Vec<&'static str> = Vec::new();
            let mut __snap_count: u32 = 0;
            insta_test!(@expand h, __base_desc, __cmds, __snap_count; $($content)*);

            Ok(())
        }
    };

    // DSL variant with @interactive
    ($name:ident, @interactive, $options:expr, { $($content:tt)* }) => {
        #[test]
        fn $name() -> color_eyre::Result<()> {
            let options = $crate::common::insta::parse_options($options);
            let mut h = $crate::common::insta::enter_interactive(options)?;
            let __base_desc = format!(
                "input: interactive\noptions: {}",
                $crate::common::insta::fmt_opts($options),
            );
            let mut __cmds: Vec<&'static str> = Vec::new();
            let mut __snap_count: u32 = 0;
            insta_test!(@expand h, __base_desc, __cmds, __snap_count; $($content)*);

            Ok(())
        }
    };

    // Token processing rules
    (@expand $h:ident, $base:ident, $cmds:ident, $count:ident; ) => {};

    // @snap - increment counter, build description, snapshot with sorted suffix, clear
    (@expand $h:ident, $base:ident, $cmds:ident, $count:ident; @snap; $($rest:tt)*) => {
        {
            $count += 1;
            let __snap_desc = if $cmds.is_empty() {
                $base.clone()
            } else {
                format!("{}\nafter:\n  {}", $base, $cmds.join("\n  "))
            };
            $crate::snap!($h, &__snap_desc, $count);
            $cmds.clear();
        }
        insta_test!(@expand $h, $base, $cmds, $count; $($rest)*);
    };

    // @char - send single character
    (@expand $h:ident, $base:ident, $cmds:ident, $count:ident; @char $c:expr ; $($rest:tt)*) => {
        $cmds.push(concat!("@char ", stringify!($c)));
        $h.char($c)?;
        insta_test!(@expand $h, $base, $cmds, $count; $($rest)*);
    };

    // @type - type a string
    (@expand $h:ident, $base:ident, $cmds:ident, $count:ident; @type $text:expr ; $($rest:tt)*) => {
        $cmds.push(concat!("@type ", stringify!($text)));
        $h.type_str($text)?;
        insta_test!(@expand $h, $base, $cmds, $count; $($rest)*);
    };

    // @action - send an action (e.g., @action Down(1); or @action BackwardChar;)
    (@expand $h:ident, $base:ident, $cmds:ident, $count:ident; @action $action:ident ; $($rest:tt)*) => {
        $cmds.push(concat!("@action ", stringify!($action)));
        $h.action(skim::tui::event::Action::$action)?;
        insta_test!(@expand $h, $base, $cmds, $count; $($rest)*);
    };

    // @action with parenthesized args (e.g., @action Down(1);)
    (@expand $h:ident, $base:ident, $cmds:ident, $count:ident; @action $action:ident ($($args:tt)*) ; $($rest:tt)*) => {
        $cmds.push(concat!("@action ", stringify!($action), "(", stringify!($($args)*), ")"));
        $h.action(skim::tui::event::Action::$action($($args)*))?;
        insta_test!(@expand $h, $base, $cmds, $count; $($rest)*);
    };

    // @key - send a special key (Enter, Escape, Tab, etc.)
    (@expand $h:ident, $base:ident, $cmds:ident, $count:ident; @key $key:ident ; $($rest:tt)*) => {
        $cmds.push(concat!("@key ", stringify!($key)));
        $h.key(crossterm::event::KeyEvent::new(
            crossterm::event::KeyCode::$key,
            crossterm::event::KeyModifiers::NONE
        ))?;
        insta_test!(@expand $h, $base, $cmds, $count; $($rest)*);
    };

    // @ctrl - send a key with Ctrl modifier
    (@expand $h:ident, $base:ident, $cmds:ident, $count:ident; @ctrl $key:ident ; $($rest:tt)*) => {
        $cmds.push(concat!("@ctrl ", stringify!($key)));
        $h.key(crossterm::event::KeyEvent::new(
            crossterm::event::KeyCode::$key,
            crossterm::event::KeyModifiers::CONTROL
        ))?;
        insta_test!(@expand $h, $base, $cmds, $count; $($rest)*);
    };

    // @ctrl with char
    (@expand $h:ident, $base:ident, $cmds:ident, $count:ident; @ctrl $key:literal ; $($rest:tt)*) => {
        $cmds.push(concat!("@ctrl ", stringify!($key)));
        $h.key(crossterm::event::KeyEvent::new(
            crossterm::event::KeyCode::Char($key),
            crossterm::event::KeyModifiers::CONTROL
        ))?;
        insta_test!(@expand $h, $base, $cmds, $count; $($rest)*);
    };

    // @alt - send a key with Alt modifier
    (@expand $h:ident, $base:ident, $cmds:ident, $count:ident; @alt $key:ident ; $($rest:tt)*) => {
        $cmds.push(concat!("@alt ", stringify!($key)));
        $h.key(crossterm::event::KeyEvent::new(
            crossterm::event::KeyCode::$key,
            crossterm::event::KeyModifiers::ALT
        ))?;
        insta_test!(@expand $h, $base, $cmds, $count; $($rest)*);
    };

    // @alt with char
    (@expand $h:ident, $base:ident, $cmds:ident, $count:ident; @alt $key:literal ; $($rest:tt)*) => {
        $cmds.push(concat!("@alt ", stringify!($key)));
        $h.key(crossterm::event::KeyEvent::new(
            crossterm::event::KeyCode::Char($key),
            crossterm::event::KeyModifiers::ALT
        ))?;
        insta_test!(@expand $h, $base, $cmds, $count; $($rest)*);
    };

    // @shift - send a key with Shift modifier
    (@expand $h:ident, $base:ident, $cmds:ident, $count:ident; @shift $key:ident ; $($rest:tt)*) => {
        $cmds.push(concat!("@shift ", stringify!($key)));
        $h.key(crossterm::event::KeyEvent::new(
            crossterm::event::KeyCode::$key,
            crossterm::event::KeyModifiers::SHIFT
        ))?;
        insta_test!(@expand $h, $base, $cmds, $count; $($rest)*);
    };

    // @shift with char
    (@expand $h:ident, $base:ident, $cmds:ident, $count:ident; @shift $key:literal ; $($rest:tt)*) => {
        $cmds.push(concat!("@shift ", stringify!($key)));
        $h.key(crossterm::event::KeyEvent::new(
            crossterm::event::KeyCode::Char($key),
            crossterm::event::KeyModifiers::SHIFT
        ))?;
        insta_test!(@expand $h, $base, $cmds, $count; $($rest)*);
    };

    // @dbg - debug print current buffer (not recorded in command history)
    (@expand $h:ident, $base:ident, $cmds:ident, $count:ident; @dbg; $($rest:tt)*) => {
        $h.render()?;
        println!("DBG buffer:\n{}", $h.buffer_view());
        insta_test!(@expand $h, $base, $cmds, $count; $($rest)*);
    };

    // @assert - run an assertion closure
    // Pass a closure that takes the harness as parameter
    // Usage: @assert(|h| h.skim.app().should_quit);
    //        @assert(|h| h.skim.app().item_list.selected().unwrap().text() == "1");
    (@expand $h:ident, $base:ident, $cmds:ident, $count:ident; @assert ( $assertion:expr ) ; $($rest:tt)*) => {
        assert!(($assertion)(&$h));
        insta_test!(@expand $h, $base, $cmds, $count; $($rest)*);
    };

    // @exited - assert that the app would exit with a specific status code
    // Usage: @exited 0;      // Assert successful exit (Accept)
    //        @exited 130;    // Assert abort (Ctrl+C, Ctrl+D, Esc)
    (@expand $h:ident, $base:ident, $cmds:ident, $count:ident; @exited $code:expr ; $($rest:tt)*) => {
        assert_eq!(
            $h.app_exit_code(),
            Some($code),
            "Expected app to exit with status code {}, but got {:?}",
            $code,
            $h.app_exit_code()
        );
        insta_test!(@expand $h, $base, $cmds, $count; $($rest)*);
    };
}