arf-console 0.4.4

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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
//! Interactive feature PTY integration tests for arf.
//!
//! These tests cover readline, askpass, shell mode, system command, help browser,
//! history schema pager (display, copy, mouse scroll), and history browser
//! (persistence, navigation, WAL corruption regression).
//!
//! All tests are Unix-only because crossterm's `cursor::position()` uses WinAPI
//! on Windows, which doesn't work correctly inside ConPTY.

mod common;

#[cfg(unix)]
use common::{Terminal, has_askpass};

/// Test R's readline() function in interactive mode.
///
/// This tests that R's readline() can prompt for input and receive it.
/// The readline() function displays a prompt and waits for user input.
///
/// Port of: radian/tests/test_readline.py::test_readline
#[test]
#[cfg(unix)]
fn test_pty_readline() {
    let mut terminal =
        Terminal::spawn_with_args(&["--no-auto-match"]).expect("Failed to spawn arf");

    terminal.wait_for_prompt().expect("Should show prompt");

    // Execute cat() followed by readline() - this should show "hello" then the readline prompt
    terminal
        .send_line("cat('hello'); readline('input> ')")
        .expect("Should send readline command");

    // Should see "hello" output
    terminal.expect("hello").expect("Should see cat output");

    // Should see the readline prompt
    terminal
        .expect("input> ")
        .expect("Should see readline prompt");

    // Provide input to readline
    terminal
        .send_line("user_answer")
        .expect("Should send readline input");

    // The readline result should be returned
    terminal
        .expect(r#""user_answer""#)
        .expect("readline should return the input");

    terminal.quit().expect("Should quit cleanly");
}

/// Test that askpass password input is NOT echoed in plaintext.
///
/// The custom askpass handler reads directly from `/dev/tty` with echo
/// disabled, bypassing reedline which would otherwise echo the password.
///
/// Port of: radian/tests/test_readline.py::test_askpass
#[test]
#[cfg(unix)]
fn test_pty_askpass() {
    if !has_askpass() {
        eprintln!("Skipping test_pty_askpass: askpass package not installed");
        return;
    }

    let mut terminal =
        Terminal::spawn_with_args(&["--no-auto-match"]).expect("Failed to spawn arf");

    terminal.wait_for_prompt().expect("Should show prompt");

    terminal
        .send_line("requireNamespace('askpass', quietly = TRUE)")
        .expect("Should check askpass");
    terminal
        .expect("TRUE")
        .expect("askpass package should be available");

    // Use paste0() so the literal prompt "Enter password: " doesn't appear
    // in the command echo, letting expect() match only the real /dev/tty prompt.
    terminal
        .send_line(r#"askpass::askpass(paste0("Enter ", "password: "))"#)
        .expect("Should send askpass command");

    // The prompt appears after TCSAFLUSH, so it signals readiness for input.
    terminal
        .expect("Enter password:")
        .expect("Should see askpass prompt");

    terminal
        .send_line("secret_answer")
        .expect("Should send askpass input");

    terminal
        .expect(r#""secret_answer""#)
        .expect("askpass should return the input");

    // Wait for next prompt to ensure all output is flushed before checking.
    terminal.wait_for_prompt().expect("Should return to prompt");

    // Every occurrence of "secret_answer" should be within quotes (the R
    // return value). Bare occurrences would indicate password echo.
    let output = terminal.get_output().expect("Should get output");
    let bare_occurrences = output.matches("secret_answer").count();
    let quoted_occurrences = output.matches(r#""secret_answer""#).count();
    assert_eq!(
        bare_occurrences, quoted_occurrences,
        "Password was echoed in plaintext.\n\
         bare={bare_occurrences}, quoted={quoted_occurrences}\n\
         output:\n{output}",
    );

    terminal.quit().expect("Should quit cleanly");
}

/// Test shell mode via :shell command.
///
/// This tests entering shell mode with :shell, executing shell commands,
/// and returning to R mode with :r.
#[test]
#[cfg(unix)]
fn test_pty_shell_mode() {
    let mut terminal = Terminal::spawn_with_args(&["--no-auto-match", "--no-completion"])
        .expect("Failed to spawn arf");

    terminal.wait_for_prompt().expect("Should show prompt");

    // Enter shell mode
    terminal.send_line(":shell").expect("Should send :shell");
    terminal
        .expect("Shell mode enabled")
        .expect("Should show shell mode message");

    // Prompt should now show shell format (e.g., "[bash] $ " or "[sh] $ ")
    // Wait for the shell prompt to appear
    terminal
        .expect("] $")
        .expect("Should show shell mode prompt");

    // Execute a shell command
    terminal
        .send_line("echo hello")
        .expect("Should send shell command");
    terminal.expect("hello").expect("Should see shell output");

    // Return to R mode
    terminal.send_line(":r").expect("Should send :r");
    terminal
        .expect("Returned to R mode")
        .expect("Should show R mode message");

    // Verify we're back in R mode by executing R code
    terminal.send_line("42").expect("Should send R expression");
    terminal.expect("[1] 42").expect("Should evaluate R code");

    terminal.quit().expect("Should quit cleanly");
}

/// Test :system command for single shell execution.
///
/// This tests the :system command which executes a single shell command
/// without entering shell mode.
#[test]
#[cfg(unix)]
fn test_pty_system_command() {
    let mut terminal = Terminal::spawn_with_args(&["--no-auto-match", "--no-completion"])
        .expect("Failed to spawn arf");

    terminal.wait_for_prompt().expect("Should show prompt");

    // Execute a single shell command with :system
    terminal
        .send_line(":system echo test_system_output")
        .expect("Should send :system");

    // Wait for the shell output
    terminal
        .expect("test_system_output")
        .expect("Should see system output");

    // Wait for prompt to return
    std::thread::sleep(std::time::Duration::from_millis(500));

    // Verify we're still in R mode by executing R code
    terminal.send_line("100").expect("Should send R expression");
    terminal
        .clear_and_expect("[1] 100")
        .expect("Should evaluate R code");

    terminal.quit().expect("Should quit cleanly");
}

/// Test Ctrl+C exits shell mode.
///
/// This tests that pressing Ctrl+C while in shell mode returns to R mode.
#[test]
#[cfg(unix)]
fn test_pty_shell_mode_ctrl_c_exit() {
    let mut terminal = Terminal::spawn_with_args(&["--no-auto-match", "--no-completion"])
        .expect("Failed to spawn arf");

    terminal.wait_for_prompt().expect("Should show prompt");

    // Enter shell mode
    terminal.send_line(":shell").expect("Should send :shell");
    terminal
        .clear_and_expect("Shell mode enabled")
        .expect("Should show shell mode message");

    // Clear buffer before sending Ctrl+C, then use expect to avoid a race
    // where clear_and_expect's clear discards the already-arrived message.
    terminal.clear_buffer().expect("Should clear buffer");
    terminal.send_interrupt().expect("Should send Ctrl+C");
    terminal
        .expect("Returned to R mode")
        .expect("Should return to R mode");

    // Verify we're back in R mode
    terminal.send_line("200").expect("Should send R expression");
    terminal
        .clear_and_expect("[1] 200")
        .expect("Should evaluate R code");

    terminal.quit().expect("Should quit cleanly");
}

/// Test `;` shortcut enters shell mode when `experimental.shell_semicolon_shortcut` is enabled.
///
/// Pressing `;` at an empty prompt should automatically insert `:shell` and
/// submit it — no Enter required — switching to shell mode immediately.
#[test]
#[cfg(unix)]
fn test_pty_shell_semicolon_shortcut() {
    use std::io::Write;
    use tempfile::NamedTempFile;

    let mut config_file = NamedTempFile::new().expect("Failed to create temp config file");
    writeln!(
        config_file,
        r#"
[experimental]
shell_semicolon_shortcut = true
"#
    )
    .expect("Failed to write config file");

    let mut terminal = Terminal::spawn_with_args(&[
        "--config",
        config_file.path().to_str().unwrap(),
        "--no-auto-match",
        "--no-completion",
    ])
    .expect("Failed to spawn arf");

    terminal.wait_for_prompt().expect("Should show prompt");

    // Press ';' alone — the keybinding inserts ":shell" and submits without Enter
    terminal.send(";").expect("Should send semicolon");
    terminal
        .expect("Shell mode enabled")
        .expect("Should show shell mode message");
    terminal
        .expect("] $")
        .expect("Should show shell mode prompt");

    // Execute a shell command to verify shell mode is functional
    terminal
        .send_line("echo semicolon_test")
        .expect("Should send shell command");
    terminal
        .expect("semicolon_test")
        .expect("Should see shell output");

    // Return to R mode
    terminal.send_line(":r").expect("Should send :r");
    terminal
        .expect("Returned to R mode")
        .expect("Should return to R mode");

    terminal.quit().expect("Should quit cleanly");
}

/// Test `;` inserts a literal semicolon when `experimental.shell_semicolon_shortcut` is enabled
/// but the buffer is not empty.
///
/// The `;` shortcut must only fire when the prompt is empty; mid-expression
/// semicolons must still be inserted as normal characters.
#[test]
#[cfg(unix)]
fn test_pty_shell_semicolon_shortcut_nonempty_buffer() {
    use std::io::Write;
    use tempfile::NamedTempFile;

    let mut config_file = NamedTempFile::new().expect("Failed to create temp config file");
    writeln!(
        config_file,
        r#"
[experimental]
shell_semicolon_shortcut = true
"#
    )
    .expect("Failed to write config file");

    let mut terminal = Terminal::spawn_with_args(&[
        "--config",
        config_file.path().to_str().unwrap(),
        "--no-auto-match",
        "--no-completion",
    ])
    .expect("Failed to spawn arf");

    terminal.wait_for_prompt().expect("Should show prompt");

    // Type something first so the buffer is not empty, then press ';'
    terminal.send("1").expect("Should send 1");
    terminal.send(";").expect("Should send semicolon");

    // ';' should be inserted literally; submit "1;2" and verify R evaluates both statements
    terminal.send_line("2").expect("Should send 2");
    terminal
        .expect("[1] 2")
        .expect("Semicolon should not trigger shell mode; 1;2 should evaluate as R expression");

    terminal.quit().expect("Should quit cleanly");
}

/// Test :help command opens interactive browser in alternate screen.
///
/// This tests that:
/// 1. `:help` (or `:h`) opens an interactive help browser (alternate screen)
/// 2. The browser displays the search header
/// 3. Pressing Esc exits the browser and returns to the prompt
#[test]
#[cfg(unix)]
fn test_pty_help_browser() {
    let mut terminal = Terminal::spawn_with_args(&["--no-auto-match", "--no-completion"])
        .expect("Failed to spawn arf");

    terminal.wait_for_prompt().expect("Should show prompt");

    // Send :h command to open help browser
    terminal.send_line(":h").expect("Should send :h command");

    // Wait for browser to appear - it should show the header
    std::thread::sleep(std::time::Duration::from_millis(500));
    terminal
        .expect("Help Search")
        .expect("Should show help browser header");

    // Press Esc to exit the browser
    terminal
        .send("\x1b")
        .expect("Should send Esc to exit browser");

    // Wait for prompt to return
    std::thread::sleep(std::time::Duration::from_millis(500));

    // Verify we're back at the R prompt by executing R code
    terminal.send_line("42").expect("Should send R expression");
    terminal
        .clear_and_expect("[1] 42")
        .expect("Should evaluate R code after browser exit");

    terminal.quit().expect("Should quit cleanly");
}

/// Test :history schema command displays pager and exits cleanly.
///
/// This tests that:
/// 1. `:history schema` opens an interactive pager (alternate screen)
/// 2. The pager displays the schema content
/// 3. Pressing 'q' exits the pager and returns to the prompt
#[test]
#[cfg(unix)]
fn test_pty_history_schema_pager() {
    let mut terminal = Terminal::spawn_with_args(&["--no-auto-match", "--no-completion"])
        .expect("Failed to spawn arf");

    terminal.wait_for_prompt().expect("Should show prompt");

    // Send :history schema command
    terminal
        .send_line(":history schema")
        .expect("Should send :history schema");

    // Wait for pager to appear - it should show the header on line 0
    std::thread::sleep(std::time::Duration::from_millis(500));
    terminal
        .line(0)
        .assert_contains("History Schema")
        .expect("Should show pager header");

    // Press 'q' to exit the pager
    terminal.send("q").expect("Should send q to exit pager");

    // Wait for prompt to return
    std::thread::sleep(std::time::Duration::from_millis(500));

    // Verify we're back at the R prompt by executing R code
    terminal.send_line("42").expect("Should send R expression");
    terminal
        .clear_and_expect("[1] 42")
        .expect("Should evaluate R code after pager exit");

    terminal.quit().expect("Should quit cleanly");
}

/// Test 'c' key in history schema pager copies R example code.
///
/// When pressing 'c' in the :history schema pager, it should:
/// 1. Copy the R example code to clipboard via OSC 52
/// 2. Show a feedback message "Copied R example to clipboard"
#[test]
#[cfg(unix)]
fn test_pty_history_schema_pager_copy() {
    let mut terminal = Terminal::spawn_with_args(&["--no-auto-match", "--no-completion"])
        .expect("Failed to spawn arf");

    terminal.wait_for_prompt().expect("Should show prompt");

    // Send :history schema command
    terminal
        .send_line(":history schema")
        .expect("Should send :history schema");

    // Wait for pager to appear (use screen-based assertion)
    std::thread::sleep(std::time::Duration::from_millis(500));
    terminal
        .line(0)
        .assert_contains("History Schema")
        .expect("Should show pager header");

    // Press 'c' to copy R example
    terminal.send("c").expect("Should send c to copy");

    // Wait for feedback message on the footer line (line 23 = row index for 24-row terminal)
    std::thread::sleep(std::time::Duration::from_millis(200));
    terminal
        .line(23)
        .assert_contains("Copied R example to clipboard")
        .expect("Should show copy feedback message");

    // Press 'q' to exit the pager
    terminal.send("q").expect("Should send q to exit pager");

    // Wait for prompt to return
    std::thread::sleep(std::time::Duration::from_millis(500));

    terminal.quit().expect("Should quit cleanly");
}

/// Test mouse scroll in history schema pager.
///
/// When EnableMouseCapture is active, mouse scroll events should:
/// 1. Scroll the pager content
/// 2. Not cause flickering (implicit - we verify scroll works)
///
/// This is a regression test for the mouse event handling fix.
#[test]
#[cfg(unix)]
fn test_pty_history_schema_pager_mouse_scroll() {
    let mut terminal = Terminal::spawn_with_args(&["--no-auto-match", "--no-completion"])
        .expect("Failed to spawn arf");

    terminal.wait_for_prompt().expect("Should show prompt");

    terminal
        .send_line(":history schema")
        .expect("Should send :history schema");

    std::thread::sleep(std::time::Duration::from_millis(500));
    // Use screen-based assertion for header line
    terminal
        .line(0)
        .assert_contains("History Schema")
        .expect("Should show pager header");

    // Verify initial position shows [1/XX] on header line
    terminal
        .line(0)
        .assert_contains("[1/")
        .expect("Should show position 1 initially");

    // Send mouse scroll down event (SGR mouse mode: \x1b[<65;col;rowM)
    // Button 65 = scroll down, column 10, row 10
    terminal
        .send("\x1b[<65;10;10M")
        .expect("Should send mouse scroll down");

    std::thread::sleep(std::time::Duration::from_millis(200));

    // After scrolling down, position should change to [2/XX]
    terminal
        .line(0)
        .assert_contains("[2/")
        .expect("Should show position 2 after scroll down");

    // Send mouse scroll up event (SGR mouse mode: \x1b[<64;col;rowM)
    // Button 64 = scroll up, column 10, row 10
    terminal
        .send("\x1b[<64;10;10M")
        .expect("Should send mouse scroll up");

    std::thread::sleep(std::time::Duration::from_millis(200));

    // After scrolling up, position should go back to [1/XX]
    terminal
        .line(0)
        .assert_contains("[1/")
        .expect("Should show position 1 after scroll up");

    // Exit pager
    terminal.send("q").expect("Should send q to exit pager");

    std::thread::sleep(std::time::Duration::from_millis(500));

    terminal.quit().expect("Should quit cleanly");
}

/// Test that history persists across sessions.
///
/// This test verifies:
/// 1. Commands executed in session 1 are saved to history
/// 2. Session 2 can see history from session 1 in the browser
///
/// This is a regression test to ensure history is properly persisted.
#[test]
#[cfg(unix)]
fn test_pty_history_browser_persists_across_sessions() {
    // Create a temporary directory for history
    let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
    let history_dir = temp_dir.path().to_string_lossy().to_string();

    // Session 1: Execute commands and exit
    {
        let mut terminal = Terminal::spawn_with_args(&[
            "--no-auto-match",
            "--no-completion",
            "--history-dir",
            &history_dir,
        ])
        .expect("Failed to spawn arf (session 1)");

        terminal.wait_for_prompt().expect("Should show prompt");

        // Execute a distinctive command that we can search for later
        terminal
            .send_line("unique_test_value_12345 <- 999")
            .expect("Should send assignment");
        terminal
            .clear_and_expect("unique_test_value_12345")
            .expect("Should see variable name");

        terminal.wait_for_prompt().expect("Should show prompt");

        // Exit cleanly to ensure history is flushed
        terminal.quit().expect("Should quit cleanly (session 1)");
    }

    // Session 2: Open history browser and verify session 1's command is visible
    {
        let mut terminal = Terminal::spawn_with_args(&[
            "--no-auto-match",
            "--no-completion",
            "--history-dir",
            &history_dir,
        ])
        .expect("Failed to spawn arf (session 2)");

        terminal.wait_for_prompt().expect("Should show prompt");

        // Open history browser
        terminal
            .send_line(":history browse")
            .expect("Should send :history browse");

        terminal
            .expect("History Browser")
            .expect("Should show history browser header");

        // Verify the command from session 1 is visible
        terminal
            .expect("unique_test_value_12345")
            .expect("Should see command from session 1 in history browser");

        // Exit browser and wait for prompt to return
        terminal.send("q").expect("Should send q to exit browser");
        terminal
            .clear_and_expect("> ")
            .expect("Should return to prompt after browser exit");

        terminal.quit().expect("Should quit cleanly (session 2)");
    }
}

/// Test history browser with :history browse command.
///
/// This test verifies:
/// 1. The history browser opens with the correct header
/// 2. Navigation and UI work correctly
/// 3. The browser can be exited with 'q'
/// 4. After closing browser, history can be written and browser reopened
///    (regression test for WAL database corruption issue)
#[test]
#[cfg(unix)]
fn test_pty_history_browser() {
    // Create a temporary directory for history
    let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
    let history_dir = temp_dir.path().to_string_lossy().to_string();

    let mut terminal = Terminal::spawn_with_args(&[
        "--no-auto-match",
        "--no-completion",
        "--history-dir",
        &history_dir,
    ])
    .expect("Failed to spawn arf");

    terminal.wait_for_prompt().expect("Should show prompt");

    // First, add some history entries by running commands
    terminal
        .send_line("1 + 1")
        .expect("Should send R expression");
    terminal
        .clear_and_expect("[1] 2")
        .expect("Should evaluate R code");

    terminal.wait_for_prompt().expect("Should show prompt");
    terminal
        .send_line("print('hello')")
        .expect("Should send print command");
    terminal
        .clear_and_expect("[1] \"hello\"")
        .expect("Should print hello");

    terminal.wait_for_prompt().expect("Should show prompt");

    // Open history browser (first time)
    terminal
        .send_line(":history browse")
        .expect("Should send :history browse");

    terminal
        .expect("History Browser")
        .expect("Should show history browser header");

    // Should show [R] mode indicator
    terminal
        .expect("[R]")
        .expect("Should show R mode indicator");

    // Press 'q' to exit the browser and wait for prompt to return
    terminal.send("q").expect("Should send q to exit browser");
    terminal
        .clear_and_expect("> ")
        .expect("Should return to prompt after browser exit");

    // Execute another command (this writes to history database)
    terminal.send_line("42").expect("Should send R expression");
    terminal
        .clear_and_expect("[1] 42")
        .expect("Should evaluate R code after browser exit");

    terminal.wait_for_prompt().expect("Should show prompt");

    // Open history browser again (regression test for WAL corruption)
    // This previously failed with "database disk image is malformed" error
    terminal
        .send_line(":history browse")
        .expect("Should send :history browse again");

    terminal
        .expect("History Browser")
        .expect("Should show history browser header on second open");

    // Exit browser and wait for prompt to return
    terminal.send("q").expect("Should send q to exit browser");
    terminal
        .clear_and_expect("> ")
        .expect("Should return to prompt after second browser exit");

    // Verify we're back at prompt and can still execute commands
    terminal.send_line("99").expect("Should send R expression");
    terminal
        .clear_and_expect("[1] 99")
        .expect("Should evaluate R code after second browser exit");

    terminal.quit().expect("Should quit cleanly");
}

/// Test fish-style abbreviation expansion in shell mode.
///
/// An abbreviation defined via `experimental.shell_abbreviations` should
/// expand automatically when Enter is pressed at the end of the matching word.
/// The expanded text is then executed as a shell command, producing the
/// expected output.
#[test]
#[cfg(unix)]
fn test_pty_shell_abbreviations_expand_in_shell_mode() {
    use std::io::Write;
    use tempfile::NamedTempFile;

    let mut config_file = NamedTempFile::new().expect("Failed to create temp config file");
    writeln!(
        config_file,
        r#"
[experimental.shell_abbreviations]
"abbr_test" = "echo abbr_expanded"
"#
    )
    .expect("Failed to write config file");

    let mut terminal = Terminal::spawn_with_args(&[
        "--config",
        config_file.path().to_str().unwrap(),
        "--no-auto-match",
        "--no-completion",
    ])
    .expect("Failed to spawn arf");

    terminal.wait_for_prompt().expect("Should show prompt");

    // Enter shell mode
    terminal.send_line(":shell").expect("Should send :shell");
    terminal
        .expect("] $")
        .expect("Should show shell mode prompt");

    // Type the abbreviation and wait for the terminal to echo it back
    terminal
        .send("abbr_test")
        .expect("Should type abbreviation");
    terminal
        .expect("abbr_test")
        .expect("Terminal should echo the typed abbreviation");

    // Press Enter — reedline expands the abbreviation and submits the expanded command
    terminal.send_line("").expect("Should press Enter");

    // Search for "abbr_expanded\r\n" to match only the shell output line.
    //
    // The raw PTY buffer contains both the reedline repaint ("echo abbr_expanded"
    // followed by ANSI cursor escape codes) and the shell output ("abbr_expanded\r\n").
    // In the repaint, "abbr_expanded" is followed by \x1b7 (save-cursor escape),
    // while in the shell output it is followed by \r\n. The trailing \r\n therefore
    // uniquely identifies the command output line and avoids matching the repaint.
    terminal
        .expect("abbr_expanded\r\n")
        .expect("Shell should execute 'echo abbr_expanded' and produce output on its own line");

    terminal.quit().expect("Should quit cleanly");
}

/// Test that shell abbreviations do NOT expand in the R editor.
///
/// `experimental.shell_abbreviations` applies only to the shell editor.
/// Typing an abbreviation in the R prompt must not trigger expansion; the
/// word is evaluated as a regular R expression instead.
#[test]
#[cfg(unix)]
fn test_pty_shell_abbreviations_do_not_expand_in_r_mode() {
    use std::io::Write;
    use tempfile::NamedTempFile;

    let mut config_file = NamedTempFile::new().expect("Failed to create temp config file");
    writeln!(
        config_file,
        r#"
[experimental.shell_abbreviations]
"abbr_test" = "echo abbr_expanded"
"#
    )
    .expect("Failed to write config file");

    let mut terminal = Terminal::spawn_with_args(&[
        "--config",
        config_file.path().to_str().unwrap(),
        "--no-auto-match",
        "--no-completion",
    ])
    .expect("Failed to spawn arf");

    terminal.wait_for_prompt().expect("Should show prompt");

    // Type the abbreviation word at the R prompt and press Enter
    terminal
        .send_line("abbr_test")
        .expect("Should send abbreviation word at R prompt");

    // R should evaluate `abbr_test` as an R expression and produce an object-not-found
    // error — this string can only come from R's evaluator, not from local echo.
    // If abbreviation expansion were active, R would never see `abbr_test` as an
    // identifier: the buffer would contain "echo abbr_expanded" instead.
    terminal.expect("not found").expect(
        "R should produce object-not-found error, proving no abbreviation expansion occurred",
    );

    terminal.quit().expect("Should quit cleanly");
}

/// Test fish-style abbreviation expansion triggered by Space in shell mode.
///
/// Abbreviations expand on both Space and Enter. This test exercises the Space
/// path: type the abbreviation, wait for the terminal to echo the typed word
/// (which guarantees reedline has processed it as a separate event batch), then
/// press Space to trigger expansion, wait for the expanded buffer repaint, and
/// finally press Enter to submit the expanded command.
///
/// Synchronizing on observable terminal state (rather than a fixed sleep) keeps
/// the test reliable under CI load: each `expect` blocks until the expected
/// string appears in the PTY output, ensuring the right ordering without
/// depending on timing assumptions.
///
/// Background: reedline fuses consecutive `Edit` events that arrive in the same
/// read batch into one compound event. The space-expansion check only fires when
/// `InsertChar(' ')` is the first command in the fused event. By waiting for the
/// abbreviation echo before sending Space we guarantee they land in separate
/// batches, so the space check sees exactly `InsertChar(' ')` and triggers
/// expansion.
#[test]
#[cfg(unix)]
fn test_pty_shell_abbreviations_expand_on_space_in_shell_mode() {
    use std::io::Write;
    use tempfile::NamedTempFile;

    let mut config_file = NamedTempFile::new().expect("Failed to create temp config file");
    writeln!(
        config_file,
        r#"
[experimental.shell_abbreviations]
"abbr_sp" = "echo space_expanded"
"#
    )
    .expect("Failed to write config file");

    let mut terminal = Terminal::spawn_with_args(&[
        "--config",
        config_file.path().to_str().unwrap(),
        "--no-auto-match",
        "--no-completion",
    ])
    .expect("Failed to spawn arf");

    terminal.wait_for_prompt().expect("Should show prompt");

    // Enter shell mode
    terminal.send_line(":shell").expect("Should send :shell");
    terminal
        .expect("] $")
        .expect("Should show shell mode prompt");

    // Type the abbreviation and wait for the terminal to echo it back.
    // This guarantees reedline has processed `abbr_sp` as its own event batch
    // before the Space arrives, so they don't get fused into one compound event.
    terminal.send("abbr_sp").expect("Should type abbreviation");
    terminal
        .expect("abbr_sp")
        .expect("Terminal should echo the typed abbreviation");

    // Send Space — now in a separate event batch, reedline sees InsertChar(' ')
    // as the sole command and fires abbreviation expansion.
    terminal
        .send(" ")
        .expect("Should press Space to trigger expansion");

    // Wait for the reedline repaint that shows the expanded buffer content.
    // This also ensures expansion has completed before we send Enter.
    terminal
        .expect("echo space_expanded")
        .expect("Buffer repaint should show expanded text after Space");

    // Clear accumulated output so the final expect only matches the shell's
    // command output (not the `space_expanded` substring already in the repaint).
    terminal
        .clear_buffer()
        .expect("Should clear accumulated output before checking shell output");

    // Press Enter to submit the now-expanded command and verify it executes
    terminal.send_line("").expect("Should press Enter");
    terminal
        .expect("space_expanded")
        .expect("Shell should execute 'echo space_expanded' and produce this output");

    terminal.quit().expect("Should quit cleanly");
}