arf-console 0.5.2

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
//! Cross-platform IPC integration tests for arf.
//!
//! These tests verify IPC functionality without relying on terminal output
//! verification, making them runnable on both Unix and Windows.
//!
//! These tests complement `tui_tests.rs`: the TUI cases verify interactive
//! screen and prompt behavior, while this file keeps low-level JSON-RPC and
//! transport coverage independent of those assertions.
//!
//! In particular, these tests make no terminal output assertions and verify
//! JSON-RPC responses over platform-aware transport (Unix sockets / Windows
//! named pipes).
//!
//! Each test spawns a fresh arf process. Run with `--test-threads=1` to avoid
//! resource contention from multiple R processes starting simultaneously.

use std::io::{Read, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::time::{Duration, Instant};

use portable_pty::{CommandBuilder, PtySize, native_pty_system};

/// Timeout for waiting for IPC server to start.
const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);

/// Timeout for IPC request/response.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);

#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CursorQueryState {
    Ground,
    Escape,
    Csi,
    CsiSix,
}

/// Detect the cursor-position queries emitted by crossterm without parsing
/// the PTY as a terminal screen. The detector is deliberately small because
/// this test only needs to answer CSI `n` and CSI `6n` requests.
#[cfg(unix)]
#[derive(Debug, Clone, Copy)]
struct CursorQueryDetector {
    state: CursorQueryState,
}

#[cfg(unix)]
impl CursorQueryDetector {
    fn new() -> Self {
        Self {
            state: CursorQueryState::Ground,
        }
    }

    /// Consume a chunk and return the number of cursor queries it contains.
    /// State is retained between calls so an escape sequence may span reads.
    fn consume(&mut self, bytes: &[u8]) -> usize {
        let mut queries = 0;
        for &byte in bytes {
            self.state = match (self.state, byte) {
                (CursorQueryState::Ground, 0x1b) => CursorQueryState::Escape,
                (CursorQueryState::Ground, _) => CursorQueryState::Ground,
                (CursorQueryState::Escape, b'[') => CursorQueryState::Csi,
                (CursorQueryState::Escape, 0x1b) => CursorQueryState::Escape,
                (CursorQueryState::Escape, _) => CursorQueryState::Ground,
                (CursorQueryState::Csi, b'n') => {
                    queries += 1;
                    CursorQueryState::Ground
                }
                (CursorQueryState::Csi, b'6') => CursorQueryState::CsiSix,
                (CursorQueryState::Csi, 0x1b) => CursorQueryState::Escape,
                (CursorQueryState::Csi, _) => CursorQueryState::Ground,
                (CursorQueryState::CsiSix, b'n') => {
                    queries += 1;
                    CursorQueryState::Ground
                }
                (CursorQueryState::CsiSix, 0x1b) => CursorQueryState::Escape,
                (CursorQueryState::CsiSix, _) => CursorQueryState::Ground,
            };
        }
        queries
    }
}

#[cfg(all(test, unix))]
mod cursor_query_detector_tests {
    use super::{CursorQueryDetector, CursorQueryState};

    #[test]
    fn detects_empty_and_six_parameter_queries() {
        let mut detector = CursorQueryDetector::new();

        assert_eq!(detector.consume(b"\x1b[n"), 1);
        assert_eq!(detector.consume(b"\x1b[6n"), 1);
        assert_eq!(detector.state, CursorQueryState::Ground);
    }

    #[test]
    fn detects_queries_split_across_reads_and_multiple_queries() {
        let mut detector = CursorQueryDetector::new();

        assert_eq!(detector.consume(b"noise\x1b"), 0);
        assert_eq!(detector.consume(b"[6"), 0);
        assert_eq!(detector.consume(b"n\x1b[n"), 2);
    }

    #[test]
    fn ignores_other_parameters_and_recovers_after_noise() {
        let mut detector = CursorQueryDetector::new();

        assert_eq!(detector.consume(b"\x1b[12n\x1b[?6n\x1b[6m"), 0);
        assert_eq!(detector.consume(b"text\x1b[6n"), 1);
    }
}

/// Minimal process wrapper for cross-platform IPC testing.
///
/// Spawns arf in a PTY (required by reedline) with `--with-ipc` and waits
/// for the IPC server to become connectable. Does not parse terminal output.
struct IpcTestProcess {
    child: Box<dyn portable_pty::Child + Send + Sync>,
    _pty_writer: Arc<Mutex<Box<dyn Write + Send>>>,
    pty_output: Arc<(Mutex<String>, Condvar)>,
    shutdown: Arc<AtomicBool>,
    _reader_handle: Option<thread::JoinHandle<()>>,
    socket_path: String,
}

impl IpcTestProcess {
    /// Spawn arf with `--with-ipc` and wait for IPC server to be ready.
    fn spawn() -> Result<Self, String> {
        let bin_path = env!("CARGO_BIN_EXE_arf");

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

        let mut cmd = CommandBuilder::new(bin_path);
        cmd.arg("--no-history");
        cmd.arg("--with-ipc");
        // These transport/capture tests predate the eval policy and exercise
        // arbitrary R expressions. Policy behavior is covered separately.
        cmd.arg("--ipc-eval-unrestricted");

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

        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(pair.slave);

        let pty_writer = Arc::new(Mutex::new(pty_writer));
        let pty_output = Arc::new((Mutex::new(String::new()), Condvar::new()));
        let shutdown = Arc::new(AtomicBool::new(false));
        let shutdown_clone = Arc::clone(&shutdown);
        let pty_output_clone = Arc::clone(&pty_output);

        // On Unix, reedline sends CSI 6n (cursor position query) via the PTY.
        // We must respond or crossterm blocks with a timeout, slowing startup.
        // On Windows, crossterm uses WinAPI for cursor position — no query needed.
        #[cfg(unix)]
        let pty_writer_clone = Arc::clone(&pty_writer);

        let reader_handle = thread::spawn(move || {
            #[cfg(unix)]
            {
                let mut query_detector = CursorQueryDetector::new();
                let mut buf = [0u8; 4096];

                loop {
                    if shutdown_clone.load(Ordering::Relaxed) {
                        break;
                    }
                    match pty_reader.read(&mut buf) {
                        Ok(0) => break,
                        Ok(n) => {
                            if let Ok(mut output) = pty_output_clone.0.lock() {
                                output.push_str(&String::from_utf8_lossy(&buf[..n]));
                                pty_output_clone.1.notify_all();
                            }
                            // Respond to any cursor queries detected
                            for _ in 0..query_detector.consume(&buf[..n]) {
                                let response = b"\x1b[1;1R";
                                if let Ok(mut writer) = pty_writer_clone.lock() {
                                    let _ = writer.write_all(response);
                                    let _ = writer.flush();
                                }
                            }
                        }
                        Err(e) => {
                            if e.kind() != std::io::ErrorKind::WouldBlock
                                && e.kind() != std::io::ErrorKind::Interrupted
                            {
                                break;
                            }
                        }
                    }
                }
            }

            #[cfg(not(unix))]
            {
                // On Windows, just consume PTY output to prevent buffer fill-up.
                let mut buf = [0u8; 4096];
                loop {
                    if shutdown_clone.load(Ordering::Relaxed) {
                        break;
                    }
                    match pty_reader.read(&mut buf) {
                        Ok(0) => break,
                        Ok(n) => {
                            if let Ok(mut output) = pty_output_clone.0.lock() {
                                output.push_str(&String::from_utf8_lossy(&buf[..n]));
                                pty_output_clone.1.notify_all();
                            }
                        }
                        Err(e) => {
                            if e.kind() != std::io::ErrorKind::WouldBlock
                                && e.kind() != std::io::ErrorKind::Interrupted
                            {
                                break;
                            }
                        }
                    }
                }
            }
        });

        // Wait for session file to appear (indicates IPC server is ready)
        let pid = child.process_id();
        let socket_path = find_socket_path(pid, STARTUP_TIMEOUT)
            .ok_or("IPC server did not start within timeout")?;

        Ok(IpcTestProcess {
            child,
            _pty_writer: pty_writer,
            pty_output,
            shutdown,
            _reader_handle: Some(reader_handle),
            socket_path,
        })
    }

    /// Send a JSON-RPC request and return the response.
    fn request(
        &self,
        method: &str,
        params: serde_json::Value,
    ) -> Result<serde_json::Value, String> {
        send_ipc_request(&self.socket_path, method, params)
    }

    /// Wait for text to appear in the PTY output.
    fn wait_for_output(&self, expected: &str) -> Result<(), String> {
        let deadline = Instant::now() + REQUEST_TIMEOUT;
        let (output_lock, output_ready) = &*self.pty_output;
        let mut output = output_lock.lock().map_err(|e| e.to_string())?;

        loop {
            if output.contains(expected) {
                return Ok(());
            }
            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return Err(format!(
                    "Timed out waiting for PTY output '{expected}'. Current output:\n{output}"
                ));
            }
            let (new_output, timeout) = output_ready
                .wait_timeout(output, remaining)
                .map_err(|e| e.to_string())?;
            output = new_output;
            if timeout.timed_out() && !output.contains(expected) {
                return Err(format!(
                    "Timed out waiting for PTY output '{expected}'. Current output:\n{output}"
                ));
            }
        }
    }
}

impl Drop for IpcTestProcess {
    fn drop(&mut self) {
        // Signal the reader thread to stop first, so it can exit during the
        // grace period rather than remaining blocked on pty_reader.read().
        self.shutdown.store(true, Ordering::Relaxed);

        // Send q() to trigger clean shutdown (session file cleanup, etc.)
        if let Ok(mut writer) = self._pty_writer.lock() {
            let _ = writer.write_all(b"q()\n");
            let _ = writer.flush();
        }
        // Give it a moment to shut down cleanly
        thread::sleep(Duration::from_millis(500));
        let _ = self.child.kill();

        // Intentionally do NOT join the reader thread — it may be permanently
        // blocked on pty_reader.read() after child kill, which would hang Drop
        // (and thus the entire test run). Leaking the thread is acceptable for
        // tests; the OS reclaims it on process exit.
        let _ = self._reader_handle.take();
    }
}

// ---------------------------------------------------------------------------
// Socket/pipe discovery
// ---------------------------------------------------------------------------

/// Find the IPC socket path by scanning session files.
/// Retries until a connectable session appears or timeout is reached.
///
/// When `pid` is `None` (e.g., platform can't retrieve child PID), this
/// connects to any available session. In parallel test runs this could cause
/// cross-talk; use `--test-threads=1` to avoid this.
fn find_socket_path(pid: Option<u32>, timeout: Duration) -> Option<String> {
    let sessions_dir = dirs::cache_dir()?.join("arf").join("sessions");
    let start = Instant::now();

    while start.elapsed() < timeout {
        if let Ok(entries) = std::fs::read_dir(&sessions_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.extension().is_some_and(|ext| ext == "json")
                    && let Ok(contents) = std::fs::read_to_string(&path)
                    && let Ok(info) = serde_json::from_str::<serde_json::Value>(&contents)
                {
                    if let Some(target_pid) = pid
                        && info.get("pid").and_then(|v| v.as_u64()) != Some(u64::from(target_pid))
                    {
                        continue;
                    }
                    if let Some(socket) = info.get("socket_path").and_then(|v| v.as_str())
                        && is_connectable(socket)
                    {
                        return Some(socket.to_string());
                    }
                }
            }
        }
        std::thread::sleep(Duration::from_millis(100));
    }

    None
}

/// Check if a socket/pipe is connectable.
#[cfg(unix)]
fn is_connectable(socket_path: &str) -> bool {
    std::os::unix::net::UnixStream::connect(socket_path).is_ok()
}

#[cfg(windows)]
fn is_connectable(socket_path: &str) -> bool {
    std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .open(socket_path)
        .is_ok()
}

// ---------------------------------------------------------------------------
// IPC transport (platform-specific)
// ---------------------------------------------------------------------------

/// Send a JSON-RPC request and return the parsed response.
fn send_ipc_request(
    socket_path: &str,
    method: &str,
    params: serde_json::Value,
) -> Result<serde_json::Value, String> {
    let request = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": method,
        "params": params
    });

    let body = serde_json::to_string(&request).map_err(|e| e.to_string())?;

    #[cfg(unix)]
    {
        send_ipc_request_unix(socket_path, &body)
    }

    #[cfg(windows)]
    {
        send_ipc_request_windows(socket_path, &body)
    }
}

/// Send via Unix socket with HTTP wrapping.
///
/// The response parser is intentionally simplistic: it reads everything after
/// `\r\n\r\n` as JSON. This works because we send `Connection: close` and the
/// server closes the connection after responding.
#[cfg(unix)]
fn send_ipc_request_unix(socket_path: &str, body: &str) -> Result<serde_json::Value, String> {
    use std::os::unix::net::UnixStream;

    let http_request = format!(
        "POST / HTTP/1.1\r\n\
         Host: localhost\r\n\
         Content-Type: application/json\r\n\
         Content-Length: {}\r\n\
         Connection: close\r\n\
         \r\n{}",
        body.len(),
        body
    );

    let mut stream =
        UnixStream::connect(socket_path).map_err(|e| format!("Connect failed: {e}"))?;
    stream
        .set_read_timeout(Some(REQUEST_TIMEOUT))
        .map_err(|e| e.to_string())?;
    stream
        .write_all(http_request.as_bytes())
        .map_err(|e| format!("Write failed: {e}"))?;
    stream
        .shutdown(std::net::Shutdown::Write)
        .map_err(|e| format!("Shutdown failed: {e}"))?;

    let mut response_buf = Vec::new();
    stream
        .read_to_end(&mut response_buf)
        .map_err(|e| format!("Read failed: {e}"))?;

    let text = String::from_utf8_lossy(&response_buf);
    let json_body = if let Some(pos) = text.find("\r\n\r\n") {
        &text[pos + 4..]
    } else {
        &text
    };

    serde_json::from_str(json_body).map_err(|e| format!("Parse failed: {e}: {json_body}"))
}

#[cfg(windows)]
fn send_ipc_request_windows(socket_path: &str, body: &str) -> Result<serde_json::Value, String> {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::windows::named_pipe::ClientOptions;

    let socket_path = socket_path.to_string();
    let body = body.to_string();

    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|e| format!("Failed to create tokio runtime: {e}"))?;

    rt.block_on(async {
        let mut pipe = ClientOptions::new()
            .open(&socket_path)
            .map_err(|e| format!("Connect failed: {e}"))?;

        pipe.write_all(body.as_bytes())
            .await
            .map_err(|e| format!("Write failed: {e}"))?;
        pipe.flush()
            .await
            .map_err(|e| format!("Flush failed: {e}"))?;

        let mut response_buf = Vec::new();
        match tokio::time::timeout(REQUEST_TIMEOUT, pipe.read_to_end(&mut response_buf)).await {
            Ok(result) => result.map_err(|e| format!("Read failed: {e}"))?,
            Err(_) => return Err("Request timed out".to_string()),
        };

        let text = String::from_utf8_lossy(&response_buf);
        let json_body = if let Some(pos) = text.find("\r\n\r\n") {
            &text[pos + 4..]
        } else {
            &text
        };

        serde_json::from_str(json_body).map_err(|e| format!("Parse failed: {e}: {json_body}"))
    })
}

// ===========================================================================
// Tests
// ===========================================================================

// On Windows, crossterm's cursor::position() uses WinAPI which doesn't work
// inside ConPTY. This prevents reedline from initializing, so arf never
// reaches the prompt and the IPC server never starts. True Windows IPC
// testing requires a headless mode (no reedline, just R + IPC server).

/// Test that IPC `evaluate` captures a visible R value.
#[test]
#[cfg_attr(windows, ignore = "ConPTY cursor position incompatibility")]
fn test_ipc_evaluate_value() {
    let process = IpcTestProcess::spawn().expect("Failed to spawn arf with IPC");

    let response = process
        .request("evaluate", serde_json::json!({ "code": "1 + 1" }))
        .expect("evaluate should succeed");

    let result = response.get("result").expect("should have result");
    assert_eq!(
        result.get("value").and_then(|v| v.as_str()),
        Some("[1] 2"),
        "should capture printed value"
    );
    assert!(
        result.get("error").is_none() || result.get("error").unwrap().is_null(),
        "should have no error"
    );
}

/// Test that IPC `evaluate` captures stdout from `cat()`.
#[test]
#[cfg_attr(windows, ignore = "ConPTY cursor position incompatibility")]
fn test_ipc_evaluate_stdout() {
    let process = IpcTestProcess::spawn().expect("Failed to spawn arf with IPC");

    let response = process
        .request(
            "evaluate",
            serde_json::json!({ "code": "cat('hello_stdout\\n')" }),
        )
        .expect("evaluate should succeed");

    let result = response.get("result").expect("should have result");
    assert!(
        result
            .get("stdout")
            .and_then(|v| v.as_str())
            .is_some_and(|s| s.contains("hello_stdout")),
        "should capture stdout from cat(): {result:?}"
    );
}

/// Test that IPC `evaluate` captures R errors via `tryCatch`.
#[test]
#[cfg_attr(windows, ignore = "ConPTY cursor position incompatibility")]
fn test_ipc_evaluate_error() {
    let process = IpcTestProcess::spawn().expect("Failed to spawn arf with IPC");

    let response = process
        .request(
            "evaluate",
            serde_json::json!({ "code": "stop('test_error_msg')" }),
        )
        .expect("evaluate should succeed");

    let result = response.get("result").expect("should have result");
    assert!(
        result
            .get("error")
            .and_then(|v| v.as_str())
            .is_some_and(|s| s.contains("test_error_msg")),
        "should capture error message: {result:?}"
    );
}

/// Test that IPC `evaluate` captures both stdout and value in a mixed expression.
#[test]
#[cfg_attr(windows, ignore = "ConPTY cursor position incompatibility")]
fn test_ipc_evaluate_mixed() {
    let process = IpcTestProcess::spawn().expect("Failed to spawn arf with IPC");

    let response = process
        .request(
            "evaluate",
            serde_json::json!({ "code": "cat('before\\n'); 42" }),
        )
        .expect("evaluate should succeed");

    let result = response.get("result").expect("should have result");
    assert!(
        result
            .get("stdout")
            .and_then(|v| v.as_str())
            .is_some_and(|s| s.contains("before")),
        "should capture stdout: {result:?}"
    );
    assert_eq!(
        result.get("value").and_then(|v| v.as_str()),
        Some("[1] 42"),
        "should capture value: {result:?}"
    );
}

/// Test that `visible=true` evaluate returns captured output.
///
/// This transport-only test verifies the JSON-RPC response; the corresponding
/// tui-test case additionally verifies terminal output and prompt completion.
#[test]
#[cfg_attr(windows, ignore = "ConPTY cursor position incompatibility")]
fn test_ipc_evaluate_visible() {
    let process = IpcTestProcess::spawn().expect("Failed to spawn arf with IPC");

    let socket_path = process.socket_path.clone();
    let request = thread::spawn(move || {
        send_ipc_request(
            &socket_path,
            "evaluate",
            serde_json::json!({
                "code": r#"cat("vis_marker\n"); 99"#,
                "visible": true
            }),
        )
    });
    process
        .wait_for_output("Press y to approve, any other key declines: ")
        .expect("approval prompt should appear on the PTY");
    {
        let mut writer = process
            ._pty_writer
            .lock()
            .expect("PTY writer should not be poisoned");
        writer.write_all(b"y\n").expect("approve visible evaluate");
        writer.flush().expect("flush approval");
    }
    let response = request
        .join()
        .expect("request thread should not panic")
        .expect("visible evaluate should succeed");

    let result = response.get("result").expect("should have result");
    let stdout = result.get("stdout").and_then(|v| v.as_str()).unwrap_or("");
    assert!(
        stdout.contains("vis_marker"),
        "visible eval should capture stdout: {result:?}"
    );
    assert!(
        stdout.contains("[1] 99"),
        "visible eval should capture auto-printed value in stdout: {result:?}"
    );
    // Structured value/error fields are not available in visible mode
    assert!(
        result.get("value").is_none() || result.get("value").unwrap().is_null(),
        "visible mode should not have structured value: {result:?}"
    );
}

/// Test that IPC `user_input` is accepted when R is at the prompt.
#[test]
#[cfg_attr(windows, ignore = "ConPTY cursor position incompatibility")]
fn test_ipc_user_input() {
    let process = IpcTestProcess::spawn().expect("Failed to spawn arf with IPC");

    let socket_path = process.socket_path.clone();
    let request = thread::spawn(move || {
        send_ipc_request(
            &socket_path,
            "user_input",
            serde_json::json!({ "code": "cat('ipc_input_test')" }),
        )
    });
    process
        .wait_for_output("Press y to approve, any other key declines: ")
        .expect("approval prompt should appear on the PTY");
    {
        let mut writer = process
            ._pty_writer
            .lock()
            .expect("PTY writer should not be poisoned");
        writer.write_all(b"y\n").expect("approve user_input");
        writer.flush().expect("flush approval");
    }
    let response = request
        .join()
        .expect("request thread should not panic")
        .expect("user_input should succeed");

    assert!(
        response
            .get("result")
            .and_then(|r| r.get("accepted"))
            .and_then(|a| a.as_bool())
            == Some(true),
        "user_input should be accepted: {response:?}"
    );
}

/// Test that `shutdown` is rejected in REPL mode (only available in headless).
#[test]
#[cfg_attr(windows, ignore = "ConPTY cursor position incompatibility")]
fn test_ipc_shutdown_rejected_in_repl() {
    let process = IpcTestProcess::spawn().expect("Failed to spawn arf with IPC");

    let response = process
        .request("shutdown", serde_json::json!({}))
        .expect("shutdown request should get a response");

    let error = response
        .get("error")
        .expect("should have error for shutdown in REPL mode");
    assert_eq!(
        error.get("code").and_then(|v| v.as_i64()),
        Some(-32601), // METHOD_NOT_FOUND
        "should return METHOD_NOT_FOUND: {error:?}"
    );
}

/// Test that sequential evaluations work correctly (no stale state).
#[test]
#[cfg_attr(windows, ignore = "ConPTY cursor position incompatibility")]
fn test_ipc_evaluate_sequential() {
    let process = IpcTestProcess::spawn().expect("Failed to spawn arf with IPC");

    // First evaluation
    let r1 = process
        .request("evaluate", serde_json::json!({ "code": "x <- 123" }))
        .expect("first eval should succeed");
    assert!(r1.get("result").is_some(), "first eval should have result");

    // Second evaluation uses result of first
    let r2 = process
        .request("evaluate", serde_json::json!({ "code": "x + 1" }))
        .expect("second eval should succeed");
    let result = r2.get("result").expect("should have result");
    assert_eq!(
        result.get("value").and_then(|v| v.as_str()),
        Some("[1] 124"),
        "second eval should see variable from first: {result:?}"
    );
}