arf-console 0.6.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
use super::support::*;
use std::time::Duration;

#[test]
fn test_headless_starts_and_ipc_ready() {
    let process = HeadlessProcess::spawn().expect("Failed to spawn headless");

    let result = process.ipc_session().expect("ipc session should run");
    assert!(
        result.success,
        "ipc session should succeed. stdout: {}, stderr: {}",
        result.stdout, result.stderr
    );
    let json = parse_ipc_json(&result);
    assert_eq!(
        json["pid"].as_u64(),
        Some(process.pid as u64),
        "session should show correct PID: {}",
        result.stdout
    );
    assert_eq!(
        json["ipc_policy"],
        serde_json::json!({
            "silent": {"mode": "unrestricted"},
            "visible": {"mode": "approval_not_required"}
        })
    );
}

/// Test that `arf ipc eval` returns a visible R value.
#[test]
fn test_headless_eval_value() {
    let process = HeadlessProcess::spawn().expect("Failed to spawn headless");

    let result = process.ipc_eval("1 + 1").expect("eval should run");
    assert!(
        result.success,
        "eval should succeed. stderr: {}",
        result.stderr
    );
    assert!(
        result.stdout.contains("[1] 2"),
        "should capture R value: {}",
        result.stdout
    );
}

/// Restricted headless sessions apply the same exact-target policy as the
/// interactive server, including operator targets.
#[test]
fn test_headless_eval_allowlist() {
    let process = HeadlessProcess::spawn_with_args(&["--ipc-eval-allow-function", "+"])
        .expect("Failed to spawn restricted headless session");

    let session = process.ipc_session().expect("session should run");
    let session_json = parse_ipc_json(&session);
    assert_eq!(session_json["ipc_policy"]["silent"]["mode"], "restricted");
    assert_eq!(
        session_json["ipc_policy"]["silent"]["allowed_functions"],
        serde_json::json!(["+"])
    );
    assert_eq!(
        session_json["ipc_policy"]["visible"],
        serde_json::json!({"mode": "approval_not_required"})
    );

    let allowed = process.ipc_eval("1 + 1").expect("allowed eval should run");
    assert!(
        allowed.success && allowed.stdout.contains("[1] 2"),
        "allowlisted operator should succeed: stdout={}, stderr={}",
        allowed.stdout,
        allowed.stderr
    );

    let denied = process
        .ipc_eval("length('abc')")
        .expect("denied eval should return a protocol response");
    assert_eq!(denied.exit_code, Some(4));
    let error: serde_json::Value = serde_json::from_str(&denied.stderr)
        .unwrap_or_else(|e| panic!("denial should be structured JSON: {e}: {}", denied.stderr));
    assert_eq!(error["error"]["code"], "R_EVAL_NOT_ALLOWED");
}

#[test]
fn headless_uses_arf_config_for_ipc_eval_policy() {
    let config = tempfile::NamedTempFile::new().expect("create config file");
    std::fs::write(
        config.path(),
        r#"[ipc.eval]
allowed_functions = ["length"]
"#,
    )
    .expect("write config file");
    let config_path = config.path().to_string_lossy().into_owned();
    let process = HeadlessProcess::spawn_with_args_and_env(
        &["--ipc-eval-allow-function", "+"],
        &[("ARF_CONFIG", &config_path)],
    )
    .expect("headless should accept ARF_CONFIG");

    let session = process.ipc_session().expect("session should run");
    let session_json = parse_ipc_json(&session);
    assert_eq!(
        session_json["ipc_policy"]["silent"]["allowed_functions"],
        serde_json::json!(["+", "length"])
    );
}

/// Test that `arf ipc eval` captures stdout from `cat()`.
#[test]
fn test_headless_eval_stdout() {
    let process = HeadlessProcess::spawn().expect("Failed to spawn headless");

    let result = process
        .ipc_eval("cat('hello_headless\\n')")
        .expect("eval should run");
    assert!(
        result.success,
        "eval should succeed. stderr: {}",
        result.stderr
    );
    assert!(
        result.stdout.contains("hello_headless"),
        "should capture stdout: {}",
        result.stdout
    );
}

/// Test that `arf ipc eval` reports R errors in the JSON response.
#[test]
fn test_headless_eval_error() {
    let process = HeadlessProcess::spawn().expect("Failed to spawn headless");

    let result = process
        .ipc_eval("stop('headless_error')")
        .expect("eval should run");
    // R errors are returned as part of the JSON response (exit 0)
    assert!(
        result.success,
        "eval should succeed (R errors are in JSON, not exit code). stderr: {}",
        result.stderr
    );
    let json = parse_ipc_json(&result);
    assert!(
        json["error"]
            .as_str()
            .is_some_and(|s| s.contains("headless_error")),
        "should report error in JSON: {}",
        result.stdout
    );
}

/// Test sequential evaluations: state persists across calls.
#[test]
fn test_headless_eval_sequential() {
    let process = HeadlessProcess::spawn().expect("Failed to spawn headless");

    // Assign a variable
    let r1 = process.ipc_eval("x <- 42").expect("first eval should run");
    assert!(r1.success, "first eval should succeed");

    // Use the variable
    let r2 = process.ipc_eval("x * 2").expect("second eval should run");
    assert!(r2.success, "second eval should succeed");
    assert!(
        r2.stdout.contains("[1] 84"),
        "should see variable from first eval: {}",
        r2.stdout
    );
}

/// Test that `arf ipc eval` captures both stdout and value.
#[test]
fn test_headless_eval_mixed_output() {
    let process = HeadlessProcess::spawn().expect("Failed to spawn headless");

    let result = process
        .ipc_eval("cat('before\\n'); 42")
        .expect("eval should run");
    assert!(result.success, "eval should succeed");
    assert!(
        result.stdout.contains("before"),
        "should capture stdout: {}",
        result.stdout
    );
    assert!(
        result.stdout.contains("[1] 42"),
        "should capture value: {}",
        result.stdout
    );
}

/// Test that `arf ipc send` (user_input) is accepted in headless mode.
#[test]
fn test_headless_user_input() {
    let process = HeadlessProcess::spawn().expect("Failed to spawn headless");

    let result = process
        .ipc_send("invisible(NULL)")
        .expect("send should run");
    assert!(
        result.success,
        "send should succeed. stderr: {}",
        result.stderr
    );
    let json = parse_ipc_json(&result);
    assert_eq!(
        json["accepted"].as_bool(),
        Some(true),
        "should report acceptance: {}",
        result.stdout
    );
}

/// Test multiline R code evaluation in headless mode.
#[test]
fn test_headless_eval_multiline() {
    let process = HeadlessProcess::spawn().expect("Failed to spawn headless");

    let code = r#"f <- function(x) x + 1; f(10)"#;
    let result = process.ipc_eval(code).expect("eval should run");
    assert!(result.success, "eval should succeed");
    assert!(
        result.stdout.contains("[1] 11"),
        "should evaluate multiline code: {}",
        result.stdout
    );
}

/// Test that `arf ipc eval --visible` outputs to the headless process's stderr.
///
/// When `--visible` is used, the evaluated output should appear both in the
/// JSON-RPC response AND on the headless process's stdout/stderr (via
/// WriteConsoleEx passthrough). This is useful for monitoring/logging.
#[test]
fn test_headless_eval_visible() {
    let process = HeadlessProcess::spawn_with_args(&["--ipc-eval-allow-function", "exists"])
        .expect("Failed to spawn restricted headless");

    // Use a unique marker to avoid matching startup messages
    let code = r#"cat("vis_marker_42\n")"#;
    let result = process
        .ipc_eval_visible(code)
        .expect("visible eval should run");
    assert!(
        result.success,
        "visible eval should succeed. stderr: {}",
        result.stderr
    );
    assert!(
        result.stdout.contains("vis_marker_42"),
        "JSON-RPC response should capture stdout: {}",
        result.stdout
    );

    // Give the headless process a moment to flush output
    std::thread::sleep(std::time::Duration::from_millis(200));

    // Verify the output also appeared on the headless process's stdout/stderr.
    // R's cat() goes through WriteConsoleEx non-error channel → print! → stdout.
    let server_output = process.server_output();
    assert!(
        server_output.contains("vis_marker_42"),
        "visible eval output should appear on headless process output: {}",
        server_output
    );

    // Headless visible evaluate bypasses the allowlist like headless send,
    // while silent evaluate remains protected by the allowlist.
    let silent = process
        .ipc_eval(code)
        .expect("silent eval should return a policy response");
    assert_eq!(silent.exit_code, Some(4));
    let error = serde_json::from_str::<serde_json::Value>(&silent.stderr)
        .expect("silent policy rejection should be structured JSON");
    assert_eq!(error["error"]["code"], "R_EVAL_NOT_ALLOWED");
}

/// Test that silent eval does NOT output to the headless process.
#[test]
fn test_headless_eval_silent_no_server_output() {
    let process = HeadlessProcess::spawn().expect("Failed to spawn headless");

    let result = process
        .ipc_eval("cat('silent_marker_99\\n')")
        .expect("eval should run");
    assert!(result.success, "eval should succeed");
    assert!(
        result.stdout.contains("silent_marker_99"),
        "JSON-RPC response should capture stdout: {}",
        result.stdout
    );

    // Give a moment for any output to flush
    std::thread::sleep(std::time::Duration::from_millis(200));

    // Silent eval should NOT appear on the headless process
    let server_output = process.server_output();
    assert!(
        !server_output.contains("silent_marker_99"),
        "silent eval output should NOT appear on headless process output: {}",
        server_output
    );
}

/// Test that `--vanilla` flag works in headless mode.
#[test]
fn test_headless_vanilla_flag() {
    let process =
        HeadlessProcess::spawn_with_args(&["--vanilla"]).expect("Failed to spawn with --vanilla");

    let result = process.ipc_eval("1 + 1").expect("eval should run");
    assert!(
        result.success,
        "eval should succeed with --vanilla. stderr: {}",
        result.stderr
    );
    assert!(
        result.stdout.contains("[1] 2"),
        "should return result: {}",
        result.stdout
    );
}

/// Test that --timeout option works: a fast eval completes within timeout.
#[test]
fn test_headless_eval_timeout_sufficient() {
    let process = HeadlessProcess::spawn().expect("Failed to spawn headless");

    // Fast expression with generous timeout should succeed
    let result = process
        .ipc_eval_with_timeout("1 + 1", 30000)
        .expect("eval with timeout should run");
    assert!(result.success, "should succeed: {}", result.stderr);
    assert!(
        result.stdout.contains("[1] 2"),
        "should return result: {}",
        result.stdout
    );
}

/// Test that --timeout option works: a slow eval times out.
#[test]
fn test_headless_eval_timeout_exceeded() {
    let process = HeadlessProcess::spawn().expect("Failed to spawn headless");

    // Sys.sleep(10) with a 1-second timeout should fail
    let result = process
        .ipc_eval_with_timeout("Sys.sleep(10)", 1000)
        .expect("eval with timeout should run");
    assert!(
        !result.success,
        "should fail due to timeout. stdout: {}, stderr: {}",
        result.stdout, result.stderr
    );
    assert!(
        result.stderr.contains("timed out"),
        "should mention timeout: {}",
        result.stderr
    );
}

/// Test that `arf ipc shutdown` gracefully stops a headless process.
#[test]
fn test_headless_shutdown_via_ipc() {
    let mut process = HeadlessProcess::spawn().expect("Failed to spawn headless");

    // Verify it's running
    let session = process.ipc_session().expect("session should work");
    assert!(session.success, "should be running");

    // Send shutdown
    let result = process.ipc_shutdown().expect("shutdown should run");
    assert!(
        result.success,
        "shutdown should succeed. stderr: {}",
        result.stderr
    );
    let json = parse_ipc_json(&result);
    assert_eq!(
        json["accepted"].as_bool(),
        Some(true),
        "should report acceptance: {}",
        result.stdout
    );

    // Process should exit within a few seconds
    process
        .wait_for_exit(Duration::from_secs(10))
        .expect("headless process should exit after shutdown");
}

/// Test that help pages are captured via the custom pager instead of
/// spawning an interactive pager like `less`.
#[test]
fn test_headless_help_does_not_hang() {
    let process = HeadlessProcess::spawn().expect("Failed to spawn headless");

    // ?mean triggers R's help system which would normally open a pager.
    // With our custom pager, the help text should be captured in stdout.
    let result = process
        .ipc_eval_with_timeout("?mean", 15000)
        .expect("help eval should run");
    assert!(
        result.success,
        "help should succeed without hanging. stderr: {}",
        result.stderr
    );
    // The help text for `mean` should contain the word "mean" somewhere
    assert!(
        result.stdout.to_lowercase().contains("mean"),
        "help output should contain 'mean': {}",
        result.stdout
    );
}

/// Test that plot() does not hang or error in headless mode.
/// The graphics device should default to a file-based device (png/pdf).
#[test]
fn test_headless_plot_does_not_hang() {
    let process = HeadlessProcess::spawn().expect("Failed to spawn headless");

    // plot() would normally try to open X11/quartz. In headless mode,
    // our custom device function should create a file-based device instead.
    let result = process
        .ipc_eval_with_timeout(
            "plot(1:10); dev_name <- names(dev.cur()); dev.off(); cat(dev_name)",
            15000,
        )
        .expect("plot eval should run");
    assert!(
        result.success,
        "plot should succeed without hanging. stderr: {}",
        result.stderr
    );
    // Verify the device is non-interactive: png/pdf from our custom device,
    // or quartz_off_screen on macOS (quartz works headlessly unlike X11)
    let stdout = &result.stdout;
    assert!(
        stdout.contains("png") || stdout.contains("pdf") || stdout.contains("quartz_off_screen"),
        "graphics device should be non-interactive, got: {}",
        stdout
    );
}

/// Test that browseURL() prints the URL to stdout instead of opening a browser.
#[test]
fn test_headless_browse_url_does_not_hang() {
    let process = HeadlessProcess::spawn().expect("Failed to spawn headless");

    let result = process
        .ipc_eval_with_timeout("browseURL('https://example.com')", 15000)
        .expect("browseURL eval should run");
    assert!(
        result.success,
        "browseURL should succeed without hanging. stderr: {}",
        result.stderr
    );
    assert!(
        result.stdout.contains("https://example.com"),
        "URL should be captured in stdout: {}",
        result.stdout
    );
}