rust-expect 0.1.0

Next-generation Expect-style terminal automation library for 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
//! Interactive session with pattern hooks.
//!
//! This module provides the interactive session functionality with pattern-based
//! callbacks. When patterns match in the output, registered callbacks are triggered.
//!
//! # Example
//!
//! ```ignore
//! use rust_expect::Session;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), rust_expect::ExpectError> {
//!     let mut session = Session::spawn("/bin/bash", &[]).await?;
//!
//!     session.interact()
//!         .on_output("password:", |ctx| {
//!             println!("Password prompt detected!");
//!             ctx.send("secret\n")
//!         })
//!         .on_output("logout", |_| {
//!             InteractAction::Stop
//!         })
//!         .start()
//!         .await?;
//!
//!     Ok(())
//! }
//! ```

use std::sync::Arc;
use std::time::Duration;

use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::Mutex;

use super::hooks::{HookManager, InteractionEvent};
use super::mode::InteractionMode;
use super::terminal::TerminalSize;
use crate::error::{ExpectError, Result};
use crate::expect::Pattern;

/// Action to take after a pattern match in interactive mode.
#[derive(Debug, Clone)]
pub enum InteractAction {
    /// Continue interaction.
    Continue,
    /// Send data to the session.
    Send(Vec<u8>),
    /// Stop the interaction.
    Stop,
    /// Stop with an error.
    Error(String),
}

impl InteractAction {
    /// Create a send action from a string.
    pub fn send(s: impl Into<String>) -> Self {
        Self::Send(s.into().into_bytes())
    }

    /// Create a send action from bytes.
    pub fn send_bytes(data: impl Into<Vec<u8>>) -> Self {
        Self::Send(data.into())
    }
}

/// Context passed to pattern hook callbacks.
pub struct InteractContext<'a> {
    /// The matched text.
    pub matched: &'a str,
    /// Text before the match.
    pub before: &'a str,
    /// Text after the match.
    pub after: &'a str,
    /// The full buffer contents.
    pub buffer: &'a str,
    /// The pattern index that matched.
    pub pattern_index: usize,
}

impl InteractContext<'_> {
    /// Create a send action for convenience.
    pub fn send(&self, data: impl Into<String>) -> InteractAction {
        InteractAction::send(data)
    }

    /// Create a send action with line ending.
    pub fn send_line(&self, data: impl Into<String>) -> InteractAction {
        let mut s = data.into();
        s.push('\n');
        InteractAction::send(s)
    }
}

/// Type alias for pattern hook callbacks.
pub type PatternHook = Box<dyn Fn(&InteractContext<'_>) -> InteractAction + Send + Sync>;

/// Context passed to resize hook callbacks.
#[derive(Debug, Clone, Copy)]
pub struct ResizeContext {
    /// New terminal size.
    pub size: TerminalSize,
    /// Previous terminal size (if known).
    pub previous: Option<TerminalSize>,
}

/// Type alias for resize hook callbacks.
pub type ResizeHook = Box<dyn Fn(&ResizeContext) -> InteractAction + Send + Sync>;

/// Output pattern hook registration.
struct OutputPatternHook {
    pattern: Pattern,
    callback: PatternHook,
}

/// Input pattern hook registration.
struct InputPatternHook {
    pattern: Pattern,
    callback: PatternHook,
}

/// Builder for configuring interactive sessions.
pub struct InteractBuilder<'a, T>
where
    T: AsyncReadExt + AsyncWriteExt + Unpin + Send + 'static,
{
    /// Reference to the transport.
    transport: &'a Arc<Mutex<T>>,
    /// Output pattern hooks.
    output_hooks: Vec<OutputPatternHook>,
    /// Input pattern hooks.
    input_hooks: Vec<InputPatternHook>,
    /// Resize hook.
    resize_hook: Option<ResizeHook>,
    /// Byte-level hook manager.
    hook_manager: HookManager,
    /// Interaction mode configuration.
    mode: InteractionMode,
    /// Buffer for accumulating output.
    buffer_size: usize,
    /// Escape string to exit interact mode.
    escape_sequence: Option<Vec<u8>>,
    /// Default timeout for the interaction.
    timeout: Option<Duration>,
}

impl<'a, T> InteractBuilder<'a, T>
where
    T: AsyncReadExt + AsyncWriteExt + Unpin + Send + 'static,
{
    /// Create a new interact builder.
    pub(crate) fn new(transport: &'a Arc<Mutex<T>>) -> Self {
        Self {
            transport,
            output_hooks: Vec::new(),
            input_hooks: Vec::new(),
            resize_hook: None,
            hook_manager: HookManager::new(),
            mode: InteractionMode::default(),
            buffer_size: 8192,
            escape_sequence: Some(vec![0x1d]), // Ctrl+] by default
            timeout: None,
        }
    }

    /// Register a pattern hook for output.
    ///
    /// When the output matches the pattern, the callback is invoked.
    ///
    /// # Example
    ///
    /// ```ignore
    /// session.interact()
    ///     .on_output("password:", |ctx| {
    ///         ctx.send("my_password\n")
    ///     })
    ///     .start()
    ///     .await?;
    /// ```
    #[must_use]
    pub fn on_output<F>(mut self, pattern: impl Into<Pattern>, callback: F) -> Self
    where
        F: Fn(&InteractContext<'_>) -> InteractAction + Send + Sync + 'static,
    {
        self.output_hooks.push(OutputPatternHook {
            pattern: pattern.into(),
            callback: Box::new(callback),
        });
        self
    }

    /// Register a pattern hook for input.
    ///
    /// When the input matches the pattern, the callback is invoked.
    #[must_use]
    pub fn on_input<F>(mut self, pattern: impl Into<Pattern>, callback: F) -> Self
    where
        F: Fn(&InteractContext<'_>) -> InteractAction + Send + Sync + 'static,
    {
        self.input_hooks.push(InputPatternHook {
            pattern: pattern.into(),
            callback: Box::new(callback),
        });
        self
    }

    /// Register a hook for terminal resize events.
    ///
    /// On Unix systems, this is triggered by SIGWINCH. The callback receives
    /// the new terminal size and can optionally return an action.
    ///
    /// # Example
    ///
    /// ```ignore
    /// session.interact()
    ///     .on_resize(|ctx| {
    ///         println!("Terminal resized to {}x{}", ctx.size.cols, ctx.size.rows);
    ///         InteractAction::Continue
    ///     })
    ///     .start()
    ///     .await?;
    /// ```
    ///
    /// # Platform Support
    ///
    /// - **Unix**: Resize events are detected via SIGWINCH signal handling.
    /// - **Windows**: Resize detection is not currently supported; the callback
    ///   will not be invoked.
    #[must_use]
    pub fn on_resize<F>(mut self, callback: F) -> Self
    where
        F: Fn(&ResizeContext) -> InteractAction + Send + Sync + 'static,
    {
        self.resize_hook = Some(Box::new(callback));
        self
    }

    /// Set the interaction mode.
    #[must_use]
    pub const fn with_mode(mut self, mode: InteractionMode) -> Self {
        self.mode = mode;
        self
    }

    /// Set the escape sequence to exit interact mode.
    ///
    /// Default is Ctrl+] (0x1d).
    #[must_use]
    pub fn with_escape(mut self, escape: impl Into<Vec<u8>>) -> Self {
        self.escape_sequence = Some(escape.into());
        self
    }

    /// Disable the escape sequence (interact runs until pattern stops it).
    #[must_use]
    pub fn no_escape(mut self) -> Self {
        self.escape_sequence = None;
        self
    }

    /// Set a timeout for the interaction.
    #[must_use]
    pub const fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Set the output buffer size.
    #[must_use]
    pub const fn with_buffer_size(mut self, size: usize) -> Self {
        self.buffer_size = size;
        self
    }

    /// Add a byte-level input hook.
    #[must_use]
    pub fn with_input_hook<F>(mut self, hook: F) -> Self
    where
        F: Fn(&[u8]) -> Vec<u8> + Send + Sync + 'static,
    {
        self.hook_manager.add_input_hook(hook);
        self
    }

    /// Add a byte-level output hook.
    #[must_use]
    pub fn with_output_hook<F>(mut self, hook: F) -> Self
    where
        F: Fn(&[u8]) -> Vec<u8> + Send + Sync + 'static,
    {
        self.hook_manager.add_output_hook(hook);
        self
    }

    /// Start the interactive session.
    ///
    /// This runs the interaction loop, reading from stdin and the session,
    /// checking patterns, and invoking callbacks when matches occur.
    ///
    /// The interaction continues until:
    /// - A pattern callback returns `InteractAction::Stop`
    /// - The escape sequence is detected
    /// - A timeout occurs (if configured)
    /// - EOF is reached on the session
    ///
    /// # Errors
    ///
    /// Returns an error if I/O fails or a pattern callback returns an error.
    pub async fn start(self) -> Result<InteractResult> {
        let mut runner = InteractRunner::new(
            Arc::clone(self.transport),
            self.output_hooks,
            self.input_hooks,
            self.resize_hook,
            self.hook_manager,
            self.mode,
            self.buffer_size,
            self.escape_sequence,
            self.timeout,
        );
        runner.run().await
    }
}

/// Result of an interactive session.
#[derive(Debug, Clone)]
pub struct InteractResult {
    /// How the interaction ended.
    pub reason: InteractEndReason,
    /// Final buffer contents.
    pub buffer: String,
}

/// Reason the interaction ended.
#[derive(Debug, Clone)]
pub enum InteractEndReason {
    /// A pattern callback returned Stop.
    PatternStop {
        /// Index of the pattern that stopped interaction.
        pattern_index: usize,
    },
    /// Escape sequence was detected.
    Escape,
    /// Timeout occurred.
    Timeout,
    /// EOF was reached on the session.
    Eof,
    /// An error occurred in a pattern callback.
    Error(String),
}

/// Internal runner for the interaction loop.
struct InteractRunner<T>
where
    T: AsyncReadExt + AsyncWriteExt + Unpin + Send + 'static,
{
    transport: Arc<Mutex<T>>,
    output_hooks: Vec<OutputPatternHook>,
    input_hooks: Vec<InputPatternHook>,
    /// Resize hook - used on Unix via SIGWINCH signal handling.
    /// On Windows, terminal resize events aren't currently supported.
    #[cfg_attr(windows, allow(dead_code))]
    resize_hook: Option<ResizeHook>,
    hook_manager: HookManager,
    mode: InteractionMode,
    buffer: String,
    buffer_size: usize,
    escape_sequence: Option<Vec<u8>>,
    timeout: Option<Duration>,
    /// Current terminal size - tracked for resize delta detection on Unix.
    /// On Windows, terminal resize events aren't currently supported.
    #[cfg_attr(windows, allow(dead_code))]
    current_size: Option<TerminalSize>,
}

impl<T> InteractRunner<T>
where
    T: AsyncReadExt + AsyncWriteExt + Unpin + Send + 'static,
{
    #[allow(clippy::too_many_arguments)]
    fn new(
        transport: Arc<Mutex<T>>,
        output_hooks: Vec<OutputPatternHook>,
        input_hooks: Vec<InputPatternHook>,
        resize_hook: Option<ResizeHook>,
        hook_manager: HookManager,
        mode: InteractionMode,
        buffer_size: usize,
        escape_sequence: Option<Vec<u8>>,
        timeout: Option<Duration>,
    ) -> Self {
        // Get initial terminal size
        let current_size = super::terminal::Terminal::size().ok();

        Self {
            transport,
            output_hooks,
            input_hooks,
            resize_hook,
            hook_manager,
            mode,
            buffer: String::with_capacity(buffer_size),
            buffer_size,
            escape_sequence,
            timeout,
            current_size,
        }
    }

    async fn run(&mut self) -> Result<InteractResult> {
        #[cfg(unix)]
        {
            self.run_with_signals().await
        }
        #[cfg(not(unix))]
        {
            self.run_without_signals().await
        }
    }

    /// Run the interaction loop with Unix signal handling (SIGWINCH).
    #[cfg(unix)]
    #[allow(clippy::significant_drop_tightening)]
    async fn run_with_signals(&mut self) -> Result<InteractResult> {
        use tokio::io::{BufReader, stdin, stdout};

        self.hook_manager.notify(&InteractionEvent::Started);

        let mut stdin = BufReader::new(stdin());
        let mut input_buf = [0u8; 1024];
        let mut output_buf = [0u8; 4096];
        let mut escape_buf: Vec<u8> = Vec::new();

        let deadline = self.timeout.map(|t| std::time::Instant::now() + t);

        // Set up SIGWINCH signal handler
        let mut sigwinch =
            tokio::signal::unix::signal(tokio::signal::unix::SignalKind::window_change())
                .map_err(ExpectError::Io)?;

        loop {
            // Check timeout
            if let Some(deadline) = deadline
                && std::time::Instant::now() >= deadline
            {
                self.hook_manager.notify(&InteractionEvent::Ended);
                return Ok(InteractResult {
                    reason: InteractEndReason::Timeout,
                    buffer: self.buffer.clone(),
                });
            }

            let read_timeout = self.mode.read_timeout;
            let mut transport = self.transport.lock().await;

            tokio::select! {
                // Handle SIGWINCH (window resize)
                _ = sigwinch.recv() => {
                    drop(transport); // Release lock before processing

                    if let Some(result) = self.handle_resize().await? {
                        return Ok(result);
                    }
                }

                // Read from session output
                result = transport.read(&mut output_buf) => {
                    drop(transport); // Release lock before processing
                    match result {
                        Ok(0) => {
                            self.hook_manager.notify(&InteractionEvent::Ended);
                            return Ok(InteractResult {
                                reason: InteractEndReason::Eof,
                                buffer: self.buffer.clone(),
                            });
                        }
                        Ok(n) => {
                            let data = &output_buf[..n];
                            let processed = self.hook_manager.process_output(data.to_vec());

                            self.hook_manager.notify(&InteractionEvent::Output(processed.clone()));

                            // Write to stdout
                            let mut stdout = stdout();
                            let _ = stdout.write_all(&processed).await;
                            let _ = stdout.flush().await;

                            // Append to buffer for pattern matching
                            if let Ok(s) = std::str::from_utf8(&processed) {
                                self.buffer.push_str(s);
                                // Trim buffer if too large
                                if self.buffer.len() > self.buffer_size {
                                    let start = self.buffer.len() - self.buffer_size;
                                    self.buffer = self.buffer[start..].to_string();
                                }
                            }

                            // Check output patterns
                            if let Some(result) = self.check_output_patterns().await? {
                                return Ok(result);
                            }
                        }
                        Err(e) => {
                            self.hook_manager.notify(&InteractionEvent::Ended);
                            return Err(ExpectError::Io(e));
                        }
                    }
                }

                // Read from stdin (user input)
                result = tokio::time::timeout(read_timeout, stdin.read(&mut input_buf)) => {
                    drop(transport); // Release lock

                    if let Ok(Ok(n)) = result {
                        if n == 0 {
                            continue;
                        }

                        let data = &input_buf[..n];

                        // Check for escape sequence
                        if let Some(ref esc) = self.escape_sequence {
                            escape_buf.extend_from_slice(data);
                            if escape_buf.ends_with(esc) {
                                self.hook_manager.notify(&InteractionEvent::ExitRequested);
                                self.hook_manager.notify(&InteractionEvent::Ended);
                                return Ok(InteractResult {
                                    reason: InteractEndReason::Escape,
                                    buffer: self.buffer.clone(),
                                });
                            }
                            // Keep only last N bytes where N is escape length
                            if escape_buf.len() > esc.len() {
                                escape_buf = escape_buf[escape_buf.len() - esc.len()..].to_vec();
                            }
                        }

                        // Process through input hooks
                        let processed = self.hook_manager.process_input(data.to_vec());

                        self.hook_manager.notify(&InteractionEvent::Input(processed.clone()));

                        // Check input patterns
                        if let Some(result) = self.check_input_patterns(&processed).await? {
                            return Ok(result);
                        }

                        // Send to session
                        let mut transport = self.transport.lock().await;
                        transport.write_all(&processed).await.map_err(ExpectError::Io)?;
                        transport.flush().await.map_err(ExpectError::Io)?;
                    }
                }
            }
        }
    }

    /// Run the interaction loop without signal handling (non-Unix platforms).
    #[cfg(not(unix))]
    #[allow(clippy::significant_drop_tightening)]
    async fn run_without_signals(&mut self) -> Result<InteractResult> {
        use tokio::io::{BufReader, stdin, stdout};

        self.hook_manager.notify(&InteractionEvent::Started);

        let mut stdin = BufReader::new(stdin());
        let mut input_buf = [0u8; 1024];
        let mut output_buf = [0u8; 4096];
        let mut escape_buf: Vec<u8> = Vec::new();

        let deadline = self.timeout.map(|t| std::time::Instant::now() + t);

        loop {
            // Check timeout
            if let Some(deadline) = deadline {
                if std::time::Instant::now() >= deadline {
                    self.hook_manager.notify(&InteractionEvent::Ended);
                    return Ok(InteractResult {
                        reason: InteractEndReason::Timeout,
                        buffer: self.buffer.clone(),
                    });
                }
            }

            let read_timeout = self.mode.read_timeout;
            let mut transport = self.transport.lock().await;

            tokio::select! {
                // Read from session output
                result = transport.read(&mut output_buf) => {
                    drop(transport); // Release lock before processing
                    match result {
                        Ok(0) => {
                            self.hook_manager.notify(&InteractionEvent::Ended);
                            return Ok(InteractResult {
                                reason: InteractEndReason::Eof,
                                buffer: self.buffer.clone(),
                            });
                        }
                        Ok(n) => {
                            let data = &output_buf[..n];
                            let processed = self.hook_manager.process_output(data.to_vec());

                            self.hook_manager.notify(&InteractionEvent::Output(processed.clone()));

                            // Write to stdout
                            let mut stdout = stdout();
                            let _ = stdout.write_all(&processed).await;
                            let _ = stdout.flush().await;

                            // Append to buffer for pattern matching
                            if let Ok(s) = std::str::from_utf8(&processed) {
                                self.buffer.push_str(s);
                                // Trim buffer if too large
                                if self.buffer.len() > self.buffer_size {
                                    let start = self.buffer.len() - self.buffer_size;
                                    self.buffer = self.buffer[start..].to_string();
                                }
                            }

                            // Check output patterns
                            if let Some(result) = self.check_output_patterns().await? {
                                return Ok(result);
                            }
                        }
                        Err(e) => {
                            self.hook_manager.notify(&InteractionEvent::Ended);
                            return Err(ExpectError::Io(e));
                        }
                    }
                }

                // Read from stdin (user input)
                result = tokio::time::timeout(read_timeout, stdin.read(&mut input_buf)) => {
                    drop(transport); // Release lock

                    if let Ok(Ok(n)) = result {
                        if n == 0 {
                            continue;
                        }

                        let data = &input_buf[..n];

                        // Check for escape sequence
                        if let Some(ref esc) = self.escape_sequence {
                            escape_buf.extend_from_slice(data);
                            if escape_buf.ends_with(esc) {
                                self.hook_manager.notify(&InteractionEvent::ExitRequested);
                                self.hook_manager.notify(&InteractionEvent::Ended);
                                return Ok(InteractResult {
                                    reason: InteractEndReason::Escape,
                                    buffer: self.buffer.clone(),
                                });
                            }
                            // Keep only last N bytes where N is escape length
                            if escape_buf.len() > esc.len() {
                                escape_buf = escape_buf[escape_buf.len() - esc.len()..].to_vec();
                            }
                        }

                        // Process through input hooks
                        let processed = self.hook_manager.process_input(data.to_vec());

                        self.hook_manager.notify(&InteractionEvent::Input(processed.clone()));

                        // Check input patterns
                        if let Some(result) = self.check_input_patterns(&processed).await? {
                            return Ok(result);
                        }

                        // Send to session
                        let mut transport = self.transport.lock().await;
                        transport.write_all(&processed).await.map_err(ExpectError::Io)?;
                        transport.flush().await.map_err(ExpectError::Io)?;
                    }
                }
            }
        }
    }

    #[allow(clippy::significant_drop_tightening)]
    async fn check_output_patterns(&mut self) -> Result<Option<InteractResult>> {
        for (index, hook) in self.output_hooks.iter().enumerate() {
            if let Some(m) = hook.pattern.matches(&self.buffer) {
                let matched = &self.buffer[m.start..m.end];
                let before = &self.buffer[..m.start];
                let after = &self.buffer[m.end..];

                let ctx = InteractContext {
                    matched,
                    before,
                    after,
                    buffer: &self.buffer,
                    pattern_index: index,
                };

                match (hook.callback)(&ctx) {
                    InteractAction::Continue => {
                        // Clear the matched portion to avoid re-triggering
                        self.buffer = after.to_string();
                    }
                    InteractAction::Send(data) => {
                        let mut transport = self.transport.lock().await;
                        transport.write_all(&data).await.map_err(ExpectError::Io)?;
                        transport.flush().await.map_err(ExpectError::Io)?;
                        // Clear matched portion
                        self.buffer = after.to_string();
                    }
                    InteractAction::Stop => {
                        self.hook_manager.notify(&InteractionEvent::Ended);
                        return Ok(Some(InteractResult {
                            reason: InteractEndReason::PatternStop {
                                pattern_index: index,
                            },
                            buffer: self.buffer.clone(),
                        }));
                    }
                    InteractAction::Error(msg) => {
                        self.hook_manager.notify(&InteractionEvent::Ended);
                        return Ok(Some(InteractResult {
                            reason: InteractEndReason::Error(msg),
                            buffer: self.buffer.clone(),
                        }));
                    }
                }
            }
        }
        Ok(None)
    }

    #[allow(clippy::significant_drop_tightening)]
    async fn check_input_patterns(&self, input: &[u8]) -> Result<Option<InteractResult>> {
        let input_str = String::from_utf8_lossy(input);

        for (index, hook) in self.input_hooks.iter().enumerate() {
            if let Some(m) = hook.pattern.matches(&input_str) {
                let matched = &input_str[m.start..m.end];
                let before = &input_str[..m.start];
                let after = &input_str[m.end..];

                let ctx = InteractContext {
                    matched,
                    before,
                    after,
                    buffer: &input_str,
                    pattern_index: index,
                };

                match (hook.callback)(&ctx) {
                    InteractAction::Continue => {}
                    InteractAction::Send(data) => {
                        let mut transport = self.transport.lock().await;
                        transport.write_all(&data).await.map_err(ExpectError::Io)?;
                        transport.flush().await.map_err(ExpectError::Io)?;
                    }
                    InteractAction::Stop => {
                        return Ok(Some(InteractResult {
                            reason: InteractEndReason::PatternStop {
                                pattern_index: index,
                            },
                            buffer: self.buffer.clone(),
                        }));
                    }
                    InteractAction::Error(msg) => {
                        return Ok(Some(InteractResult {
                            reason: InteractEndReason::Error(msg),
                            buffer: self.buffer.clone(),
                        }));
                    }
                }
            }
        }
        Ok(None)
    }

    /// Handle a window resize event.
    ///
    /// This is called on Unix when SIGWINCH is received. On Windows, terminal
    /// resize events aren't currently supported via signals.
    #[cfg_attr(windows, allow(dead_code))]
    #[allow(clippy::significant_drop_tightening)]
    async fn handle_resize(&mut self) -> Result<Option<InteractResult>> {
        // Get the new terminal size
        let Ok(new_size) = super::terminal::Terminal::size() else {
            return Ok(None); // Ignore if we can't get size
        };

        // Build the context with previous size
        let ctx = ResizeContext {
            size: new_size,
            previous: self.current_size,
        };

        // Notify via hook manager
        self.hook_manager.notify(&InteractionEvent::Resize {
            cols: new_size.cols,
            rows: new_size.rows,
        });

        // Update our tracked size
        self.current_size = Some(new_size);

        // Call the user's resize hook if registered
        if let Some(ref hook) = self.resize_hook {
            match hook(&ctx) {
                InteractAction::Continue => {}
                InteractAction::Send(data) => {
                    let mut transport = self.transport.lock().await;
                    transport.write_all(&data).await.map_err(ExpectError::Io)?;
                    transport.flush().await.map_err(ExpectError::Io)?;
                }
                InteractAction::Stop => {
                    self.hook_manager.notify(&InteractionEvent::Ended);
                    return Ok(Some(InteractResult {
                        reason: InteractEndReason::PatternStop { pattern_index: 0 },
                        buffer: self.buffer.clone(),
                    }));
                }
                InteractAction::Error(msg) => {
                    self.hook_manager.notify(&InteractionEvent::Ended);
                    return Ok(Some(InteractResult {
                        reason: InteractEndReason::Error(msg),
                        buffer: self.buffer.clone(),
                    }));
                }
            }
        }

        Ok(None)
    }
}