arf-console 0.3.0

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
//! 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 :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");
}