arf-console 0.4.3

A cross-platform R console written in Rust
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
#![allow(dead_code)]
//! Common test utilities for arf integration tests.
//!
//! This module provides a PTY-based testing infrastructure that properly handles
//! cursor position queries (CSI 6n) from reedline. This is essential for testing
//! interactive features of arf.
//!
//! # Platform Support
//!
//! This module is Unix-only because crossterm's `cursor::position()` uses WinAPI
//! on Windows, which doesn't work correctly inside ConPTY. This matches crossterm's
//! own testing approach where cursor position tests are marked `#[ignore]` in CI.
//!
//! See: <https://github.com/crossterm-rs/crossterm/blob/master/src/cursor.rs>
//!
//! # Architecture
//!
//! The Terminal struct uses:
//! - `portable-pty` for cross-platform PTY management
//! - `vt100` for terminal emulation and cursor query detection
//! - Separate threads for reading PTY output and handling cursor queries
//!
//! # Assertion Style (inspired by radian)
//!
//! This module provides screen-based assertions similar to radian's test framework:
//! - `line(n)` - Get line n from the screen
//! - `current_line()` - Get the line at cursor position
//! - `previous_line(n)` - Get line n lines above cursor
//! - `cursor_position()` - Get cursor (row, col)
//!
//! Each returns a `ScreenLine` that supports fluent assertions with timeouts:
//! - `assert_startswith("prefix")` - Assert line starts with prefix
//! - `assert_endswith("suffix")` - Assert line ends with suffix
//! - `assert_contains("substring")` - Assert line contains substring
//! - `assert_equal("exact")` - Assert line equals exact string
#![cfg(unix)]

use portable_pty::{Child, CommandBuilder, ExitStatus, PtySize, native_pty_system};
use regex::Regex;
use std::io::{Read, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

/// Default timeout for waiting on terminal output (in milliseconds).
const DEFAULT_TIMEOUT_MS: u64 = 15000;

/// Default terminal size.
const DEFAULT_ROWS: u16 = 24;
const DEFAULT_COLS: u16 = 80;

/// Screen state snapshot for assertions.
#[derive(Clone)]
pub struct ScreenSnapshot {
    /// Lines of the screen (row 0 at top)
    pub lines: Vec<String>,
    /// Cursor row (0-indexed)
    pub cursor_row: u16,
    /// Cursor column (0-indexed)
    pub cursor_col: u16,
}

/// Shared state between threads.
struct SharedState {
    /// Accumulated output from the terminal (raw bytes as string)
    output_buffer: String,
    /// Whether the terminal is still running
    running: bool,
    /// Current screen snapshot from vt100
    screen: ScreenSnapshot,
}

/// Terminal wrapper for integration testing.
///
/// Provides methods to interact with a PTY-spawned arf process
/// and assert on its output. This implementation properly handles
/// cursor position queries from reedline.
pub struct Terminal {
    /// Shared state protected by mutex
    state: Arc<Mutex<SharedState>>,
    /// Handle to write to the PTY
    pty_writer: Arc<Mutex<Box<dyn Write + Send>>>,
    /// Handle to the reader thread
    _reader_handle: JoinHandle<()>,
    /// Handle to the child process
    child: Box<dyn Child + Send + Sync>,
    /// Flag to signal shutdown
    shutdown: Arc<AtomicBool>,
}

impl Terminal {
    /// Spawn arf in a PTY and return a Terminal handle.
    pub fn spawn() -> Result<Self, String> {
        Self::spawn_with_args(&[])
    }

    /// Spawn arf with additional arguments.
    pub fn spawn_with_args(args: &[&str]) -> Result<Self, String> {
        Self::spawn_with_size(args, DEFAULT_ROWS, DEFAULT_COLS)
    }

    /// Spawn arf with additional arguments and environment variables.
    pub fn spawn_with_args_and_env(args: &[&str], envs: &[(&str, &str)]) -> Result<Self, String> {
        Self::spawn_with_size_and_env(args, envs, DEFAULT_ROWS, DEFAULT_COLS)
    }

    /// Spawn arf with additional arguments and a custom terminal size.
    pub fn spawn_with_size(args: &[&str], rows: u16, cols: u16) -> Result<Self, String> {
        Self::spawn_with_size_and_env(args, &[], rows, cols)
    }

    /// Spawn arf with additional arguments, environment variables, and a custom terminal size.
    pub fn spawn_with_size_and_env(
        args: &[&str],
        envs: &[(&str, &str)],
        rows: u16,
        cols: u16,
    ) -> Result<Self, String> {
        assert!(rows > 0 && cols > 0, "PTY size must be non-zero");
        let bin_path = env!("CARGO_BIN_EXE_arf");

        let pty_system = native_pty_system();
        let pair = pty_system
            .openpty(PtySize {
                rows,
                cols,
                pixel_width: 0,
                pixel_height: 0,
            })
            .map_err(|e| format!("Failed to open PTY: {}", e))?;

        // Build command
        let mut cmd = CommandBuilder::new(bin_path);
        // Disable history by default to avoid writing to user's actual history file during tests.
        // Skip this if --history-dir is explicitly provided (for history-related tests).
        let has_history_dir = args.contains(&"--history-dir");
        if !has_history_dir {
            cmd.arg("--no-history");
        }
        for arg in args {
            cmd.arg(*arg);
        }
        for (key, value) in envs {
            cmd.env(key, value);
        }

        // Spawn the process
        let child = pair
            .slave
            .spawn_command(cmd)
            .map_err(|e| format!("Failed to spawn arf: {}", e))?;

        // Get master reader and writer
        let pty_writer = pair
            .master
            .take_writer()
            .map_err(|e| format!("Failed to get PTY writer: {}", e))?;
        let mut pty_reader = pair
            .master
            .try_clone_reader()
            .map_err(|e| format!("Failed to get PTY reader: {}", e))?;

        // Drop slave end in parent process
        drop(pair.slave);

        // Shared state
        let state = Arc::new(Mutex::new(SharedState {
            output_buffer: String::new(),
            running: true,
            screen: ScreenSnapshot {
                lines: vec![String::new(); rows as usize],
                cursor_row: 0,
                cursor_col: 0,
            },
        }));

        // Shared writer for responding to cursor queries
        let pty_writer = Arc::new(Mutex::new(pty_writer));
        let pty_writer_clone = Arc::clone(&pty_writer);

        // Shutdown flag
        let shutdown = Arc::new(AtomicBool::new(false));
        let shutdown_clone = Arc::clone(&shutdown);

        // State for reader thread
        let state_clone = Arc::clone(&state);

        // Spawn reader thread that handles PTY I/O
        let reader_handle = thread::spawn(move || {
            // vt100 parser for cursor query detection
            let (query_tx, query_rx) = std::sync::mpsc::channel::<()>();

            struct CursorQueryDetector {
                query_tx: std::sync::mpsc::Sender<()>,
            }

            impl vt100::Callbacks for CursorQueryDetector {
                fn unhandled_csi(
                    &mut self,
                    _screen: &mut vt100::Screen,
                    _prefix: Option<u8>,
                    _intermediate: Option<u8>,
                    params: &[&[u16]],
                    c: char,
                ) {
                    if c == 'n' {
                        let is_dsr = params.is_empty()
                            || (params.len() == 1 && params[0].len() == 1 && params[0][0] == 6);
                        if is_dsr {
                            let _ = self.query_tx.send(());
                        }
                    }
                }
            }

            let callbacks = CursorQueryDetector { query_tx };
            let mut parser = vt100::Parser::new_with_callbacks(rows, cols, 0, callbacks);

            let mut buf = [0u8; 4096];

            loop {
                if shutdown_clone.load(Ordering::Relaxed) {
                    break;
                }

                // Read from PTY (this will block until data is available)
                match pty_reader.read(&mut buf) {
                    Ok(0) => {
                        // EOF - process exited
                        if let Ok(mut state) = state_clone.lock() {
                            state.running = false;
                        }
                        break;
                    }
                    Ok(n) => {
                        let data = &buf[..n];

                        // Process through vt100 parser
                        parser.process(data);

                        // Update shared state
                        if let Ok(mut state) = state_clone.lock() {
                            // Add to raw output buffer
                            if let Ok(s) = std::str::from_utf8(data) {
                                state.output_buffer.push_str(s);
                            }

                            // Update screen snapshot from vt100
                            let screen = parser.screen();
                            let (cursor_row, cursor_col) = screen.cursor_position();
                            state.screen.cursor_row = cursor_row;
                            state.screen.cursor_col = cursor_col;
                            for row in 0..rows {
                                let row_content = screen.contents_between(row, 0, row, cols - 1);
                                state.screen.lines[row as usize] = row_content;
                            }
                        }

                        // Check for cursor queries and respond
                        while query_rx.try_recv().is_ok() {
                            let (row, col) = parser.screen().cursor_position();
                            let response = format!("\x1b[{};{}R", row + 1, col + 1);
                            if let Ok(mut writer) = pty_writer_clone.lock() {
                                let _ = writer.write_all(response.as_bytes());
                                let _ = writer.flush();
                            }
                        }
                    }
                    Err(e) => {
                        if e.kind() != std::io::ErrorKind::WouldBlock
                            && e.kind() != std::io::ErrorKind::Interrupted
                        {
                            // Real error
                            if let Ok(mut state) = state_clone.lock() {
                                state.running = false;
                            }
                            break;
                        }
                    }
                }
            }
        });

        Ok(Terminal {
            state,
            pty_writer,
            _reader_handle: reader_handle,
            child,
            shutdown,
        })
    }

    /// Wait for a string pattern in the output with timeout.
    pub fn expect(&mut self, pattern: &str) -> Result<(), String> {
        let timeout = Duration::from_millis(DEFAULT_TIMEOUT_MS);
        let start = Instant::now();

        while start.elapsed() < timeout {
            // Check if still running
            {
                let state = self.state.lock().map_err(|e| e.to_string())?;
                if !state.running && !state.output_buffer.contains(pattern) {
                    return Err(format!(
                        "Process exited before finding pattern '{}'. Output:\n{}",
                        pattern, state.output_buffer
                    ));
                }
                if state.output_buffer.contains(pattern) {
                    return Ok(());
                }
            }

            thread::sleep(Duration::from_millis(50));
        }

        // Timeout - get final output for error message
        let output = self
            .state
            .lock()
            .map(|s| s.output_buffer.clone())
            .unwrap_or_default();
        Err(format!(
            "Timeout waiting for pattern '{}'. Current output:\n{}",
            pattern, output
        ))
    }

    /// Wait for a regex pattern in the output.
    #[allow(dead_code)]
    pub fn expect_regex(&mut self, pattern: &str) -> Result<(), String> {
        let re = Regex::new(pattern).map_err(|e| format!("Invalid regex: {}", e))?;
        let timeout = Duration::from_millis(DEFAULT_TIMEOUT_MS);
        let start = Instant::now();

        while start.elapsed() < timeout {
            {
                let state = self.state.lock().map_err(|e| e.to_string())?;
                if !state.running && !re.is_match(&state.output_buffer) {
                    return Err(format!(
                        "Process exited before matching regex '{}'. Output:\n{}",
                        pattern, state.output_buffer
                    ));
                }
                if re.is_match(&state.output_buffer) {
                    return Ok(());
                }
            }

            thread::sleep(Duration::from_millis(50));
        }

        let output = self
            .state
            .lock()
            .map(|s| s.output_buffer.clone())
            .unwrap_or_default();
        Err(format!(
            "Timeout waiting for regex '{}'. Current output:\n{}",
            pattern, output
        ))
    }

    /// Wait for the prompt to appear.
    /// Looks for "> " which matches both "r> " and "R {version}> " prompts.
    pub fn wait_for_prompt(&mut self) -> Result<(), String> {
        self.expect("> ")
    }

    /// Clear the output buffer and wait for new output matching pattern.
    ///
    /// This is useful when you need to wait for output from a specific command,
    /// not just any matching text that might already be in the buffer.
    pub fn clear_and_expect(&mut self, pattern: &str) -> Result<(), String> {
        // Clear the buffer
        {
            let mut state = self.state.lock().map_err(|e| e.to_string())?;
            state.output_buffer.clear();
        }

        // Now wait for the pattern
        self.expect(pattern)
    }

    /// Clear the output buffer.
    pub fn clear_buffer(&mut self) -> Result<(), String> {
        let mut state = self.state.lock().map_err(|e| e.to_string())?;
        state.output_buffer.clear();
        Ok(())
    }

    /// Get the current output buffer contents.
    pub fn get_output(&self) -> Result<String, String> {
        let state = self.state.lock().map_err(|e| e.to_string())?;
        Ok(state.output_buffer.clone())
    }

    /// Send a line of input (appends newline).
    pub fn send_line(&mut self, text: &str) -> Result<(), String> {
        let data = format!("{}\n", text);
        let mut writer = self.pty_writer.lock().map_err(|e| e.to_string())?;
        writer
            .write_all(data.as_bytes())
            .map_err(|e| format!("Failed to send line: {}", e))?;
        writer
            .flush()
            .map_err(|e| format!("Failed to flush: {}", e))
    }

    /// Send raw text without newline.
    pub fn send(&mut self, text: &str) -> Result<(), String> {
        let mut writer = self.pty_writer.lock().map_err(|e| e.to_string())?;
        writer
            .write_all(text.as_bytes())
            .map_err(|e| format!("Failed to send: {}", e))?;
        writer
            .flush()
            .map_err(|e| format!("Failed to flush: {}", e))
    }

    /// Send Ctrl+C (interrupt).
    pub fn send_interrupt(&mut self) -> Result<(), String> {
        self.send("\x03")
    }

    /// Send Ctrl+D (EOF).
    pub fn send_eof(&mut self) -> Result<(), String> {
        self.send("\x04")
    }

    /// Gracefully quit arf.
    pub fn quit(&mut self) -> Result<(), String> {
        // Try q() first
        let _ = self.send_line("q()");
        thread::sleep(Duration::from_millis(500));

        // If still alive, send Ctrl+D
        {
            let state = self.state.lock().map_err(|e| e.to_string())?;
            if state.running {
                drop(state);
                let _ = self.send_eof();
            }
        }

        // Signal shutdown
        self.shutdown.store(true, Ordering::Relaxed);

        // Kill child if still running
        let _ = self.child.kill();

        Ok(())
    }

    // ========================================================================
    // Screen-based assertions (inspired by radian's test framework)
    // ========================================================================

    /// Get the current screen snapshot.
    pub fn screen(&self) -> Result<ScreenSnapshot, String> {
        let state = self.state.lock().map_err(|e| e.to_string())?;
        Ok(state.screen.clone())
    }

    /// Get a specific line from the screen (0-indexed).
    pub fn line(&self, row: usize) -> ScreenLine {
        ScreenLine {
            state: Arc::clone(&self.state),
            line_getter: LineGetter::Absolute(row),
        }
    }

    /// Get the line at the current cursor position.
    pub fn current_line(&self) -> ScreenLine {
        ScreenLine {
            state: Arc::clone(&self.state),
            line_getter: LineGetter::CurrentLine,
        }
    }

    /// Get a line relative to the cursor (n lines above).
    pub fn previous_line(&self, n: usize) -> ScreenLine {
        ScreenLine {
            state: Arc::clone(&self.state),
            line_getter: LineGetter::PreviousLine(n),
        }
    }

    /// Get the process ID of the child process, if available.
    pub fn process_id(&self) -> Option<u32> {
        self.child.process_id()
    }

    /// Wait for the child process to exit (detected via PTY EOF).
    pub fn wait_for_exit(&mut self, timeout: Duration) -> Result<(), String> {
        self.wait_for_exit_status(timeout).map(|_| ())
    }

    /// Wait for the child process to exit and return its exit status,
    /// including the terminating signal on Unix if any.
    ///
    /// Polls `Child::try_wait` directly rather than relying on the PTY
    /// `running` flag: that flag can also flip on a read error, and PTY EOF
    /// can be observed before the process is actually reapable, so a
    /// blocking `wait()` gated on it could hang past the timeout.
    pub fn wait_for_exit_status(&mut self, timeout: Duration) -> Result<ExitStatus, String> {
        let start = Instant::now();
        loop {
            if let Some(status) = self
                .child
                .try_wait()
                .map_err(|e| format!("Failed to check child process status: {}", e))?
            {
                return Ok(status);
            }
            if start.elapsed() >= timeout {
                return Err(format!(
                    "Process did not exit within {}s",
                    timeout.as_secs()
                ));
            }
            thread::sleep(Duration::from_millis(100));
        }
    }

    /// Get current cursor position as (row, col), both 0-indexed.
    pub fn cursor_position(&self) -> Result<(u16, u16), String> {
        let state = self.state.lock().map_err(|e| e.to_string())?;
        Ok((state.screen.cursor_row, state.screen.cursor_col))
    }

    /// Assert cursor is at a specific position (row, col), both 0-indexed.
    pub fn assert_cursor(&self, expected_row: u16, expected_col: u16) -> Result<(), String> {
        let timeout = Duration::from_millis(DEFAULT_TIMEOUT_MS);
        let start = Instant::now();

        while start.elapsed() < timeout {
            let (row, col) = self.cursor_position()?;
            if row == expected_row && col == expected_col {
                return Ok(());
            }
            thread::sleep(Duration::from_millis(50));
        }

        let (row, col) = self.cursor_position()?;
        Err(format!(
            "Cursor position mismatch: expected ({}, {}), got ({}, {})",
            expected_row, expected_col, row, col
        ))
    }

    /// Debug helper: print current screen state.
    #[allow(dead_code)]
    pub fn dump_screen(&self) -> Result<(), String> {
        let state = self.state.lock().map_err(|e| e.to_string())?;
        eprintln!("=== Screen Dump ===");
        eprintln!(
            "Cursor: ({}, {})",
            state.screen.cursor_row, state.screen.cursor_col
        );
        for (i, line) in state.screen.lines.iter().enumerate() {
            let trimmed = line.trim_end();
            if !trimmed.is_empty() || i == state.screen.cursor_row as usize {
                let marker = if i == state.screen.cursor_row as usize {
                    ">"
                } else {
                    " "
                };
                eprintln!("{} {:2}: {:?}", marker, i, trimmed);
            }
        }
        eprintln!("===================");
        Ok(())
    }
}

/// How to get a line from the screen.
#[allow(dead_code)]
enum LineGetter {
    /// Get line at absolute row index (0-indexed)
    Absolute(usize),
    /// Get line at cursor position
    CurrentLine,
    /// Get line N rows above cursor
    PreviousLine(usize),
}

/// A reference to a screen line that supports fluent assertions.
pub struct ScreenLine {
    state: Arc<Mutex<SharedState>>,
    line_getter: LineGetter,
}

impl ScreenLine {
    /// Get the current line content.
    fn get_line(&self) -> Result<String, String> {
        let state = self.state.lock().map_err(|e| e.to_string())?;
        let row = match self.line_getter {
            LineGetter::Absolute(r) => r,
            LineGetter::CurrentLine => state.screen.cursor_row as usize,
            LineGetter::PreviousLine(n) => (state.screen.cursor_row as usize).saturating_sub(n),
        };
        Ok(state.screen.lines.get(row).cloned().unwrap_or_default())
    }

    /// Assert line starts with prefix (with timeout).
    #[allow(dead_code)]
    pub fn assert_startswith(&self, prefix: &str) -> Result<(), String> {
        let timeout = Duration::from_millis(DEFAULT_TIMEOUT_MS);
        let start = Instant::now();

        while start.elapsed() < timeout {
            let line = self.get_line()?;
            if line.starts_with(prefix) {
                return Ok(());
            }
            thread::sleep(Duration::from_millis(50));
        }

        let line = self.get_line()?;
        Err(format!(
            "Line does not start with '{}': got '{}'",
            prefix, line
        ))
    }

    /// Assert line ends with suffix (with timeout).
    #[allow(dead_code)]
    pub fn assert_endswith(&self, suffix: &str) -> Result<(), String> {
        let timeout = Duration::from_millis(DEFAULT_TIMEOUT_MS);
        let start = Instant::now();

        while start.elapsed() < timeout {
            let line = self.get_line()?;
            if line.trim_end().ends_with(suffix) {
                return Ok(());
            }
            thread::sleep(Duration::from_millis(50));
        }

        let line = self.get_line()?;
        Err(format!(
            "Line does not end with '{}': got '{}'",
            suffix, line
        ))
    }

    /// Assert line contains substring (with timeout).
    pub fn assert_contains(&self, substring: &str) -> Result<(), String> {
        let timeout = Duration::from_millis(DEFAULT_TIMEOUT_MS);
        let start = Instant::now();

        while start.elapsed() < timeout {
            let line = self.get_line()?;
            if line.contains(substring) {
                return Ok(());
            }
            thread::sleep(Duration::from_millis(50));
        }

        let line = self.get_line()?;
        Err(format!(
            "Line does not contain '{}': got '{}'",
            substring, line
        ))
    }

    /// Assert line equals expected (with timeout). Compares trimmed strings.
    #[allow(dead_code)]
    pub fn assert_equal(&self, expected: &str) -> Result<(), String> {
        let timeout = Duration::from_millis(DEFAULT_TIMEOUT_MS);
        let start = Instant::now();

        while start.elapsed() < timeout {
            let line = self.get_line()?;
            if line.trim() == expected.trim() {
                return Ok(());
            }
            thread::sleep(Duration::from_millis(50));
        }

        let line = self.get_line()?;
        Err(format!(
            "Line does not equal '{}': got '{}'",
            expected, line
        ))
    }

    /// Get the trimmed line content (for chaining).
    #[allow(dead_code)]
    pub fn trim(&self) -> TrimmedScreenLine<'_> {
        TrimmedScreenLine { inner: self }
    }
}

/// A trimmed view of a screen line.
pub struct TrimmedScreenLine<'a> {
    inner: &'a ScreenLine,
}

impl TrimmedScreenLine<'_> {
    /// Assert trimmed line starts with prefix.
    #[allow(dead_code)]
    pub fn assert_startswith(&self, prefix: &str) -> Result<(), String> {
        let timeout = Duration::from_millis(DEFAULT_TIMEOUT_MS);
        let start = Instant::now();

        while start.elapsed() < timeout {
            let line = self.inner.get_line()?;
            if line.trim().starts_with(prefix) {
                return Ok(());
            }
            thread::sleep(Duration::from_millis(50));
        }

        let line = self.inner.get_line()?;
        Err(format!(
            "Trimmed line does not start with '{}': got '{}'",
            prefix,
            line.trim()
        ))
    }

    /// Assert trimmed line ends with suffix.
    #[allow(dead_code)]
    pub fn assert_endswith(&self, suffix: &str) -> Result<(), String> {
        let timeout = Duration::from_millis(DEFAULT_TIMEOUT_MS);
        let start = Instant::now();

        while start.elapsed() < timeout {
            let line = self.inner.get_line()?;
            if line.trim().ends_with(suffix) {
                return Ok(());
            }
            thread::sleep(Duration::from_millis(50));
        }

        let line = self.inner.get_line()?;
        Err(format!(
            "Trimmed line does not end with '{}': got '{}'",
            suffix,
            line.trim()
        ))
    }

    /// Assert trimmed line equals expected.
    #[allow(dead_code)]
    pub fn assert_equal(&self, expected: &str) -> Result<(), String> {
        let timeout = Duration::from_millis(DEFAULT_TIMEOUT_MS);
        let start = Instant::now();

        while start.elapsed() < timeout {
            let line = self.inner.get_line()?;
            if line.trim() == expected {
                return Ok(());
            }
            thread::sleep(Duration::from_millis(50));
        }

        let line = self.inner.get_line()?;
        Err(format!(
            "Trimmed line does not equal '{}': got '{}'",
            expected,
            line.trim()
        ))
    }
}

impl Drop for Terminal {
    fn drop(&mut self) {
        self.shutdown.store(true, Ordering::Relaxed);
        let _ = self.child.kill();
    }
}

// ============================================================================
// External tool detection helpers
// ============================================================================

use std::process::Command;

/// Check if Air CLI is available on the system.
///
/// Returns true if `air --version` runs successfully.
pub fn has_air_cli() -> bool {
    Command::new("air")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Check if dplyr R package is available.
///
/// Returns true if R can load dplyr without error.
pub fn has_dplyr() -> bool {
    Command::new("Rscript")
        .args(["-e", "library(dplyr)"])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Check if askpass R package is available.
///
/// Returns true if R can load askpass without error.
pub fn has_askpass() -> bool {
    Command::new("Rscript")
        .args(["-e", "library(askpass)"])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}