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
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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
//! Headless mode integration tests.
//!
//! These tests verify `arf headless` + `arf ipc` end-to-end without
//! requiring a terminal (PTY/ConPTY). This makes them runnable on
//! Windows CI where ConPTY cursor::position() is problematic.
//!
//! Each test spawns `arf headless`, waits for IPC readiness by monitoring
//! stderr for the "IPC server listening on:" message, then uses
//! `arf ipc eval` / `arf ipc send` CLI commands to interact with R.

use std::io::BufRead;
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

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

/// Parse JSON from an IPC output, including stdout/stderr in the panic
/// message on failure for easier debugging.
fn parse_ipc_json(output: &IpcOutput) -> serde_json::Value {
    serde_json::from_str(&output.stdout).unwrap_or_else(|e| {
        panic!(
            "failed to parse JSON: {e}\nstdout: {}\nstderr: {}",
            output.stdout, output.stderr
        )
    })
}

/// Wrapper around a headless arf process.
///
/// Spawns `arf headless` and waits for IPC readiness by monitoring
/// stderr for the "IPC server listening on:" message.
struct HeadlessProcess {
    child: Child,
    pid: u32,
    _stderr_thread: Option<thread::JoinHandle<()>>,
    _stdout_thread: Option<thread::JoinHandle<()>>,
    shutdown: Arc<AtomicBool>,
    /// Collected stderr from the headless process (status messages, visible eval errors).
    stderr_output: Arc<Mutex<String>>,
    /// Collected stdout from the headless process (visible eval output).
    stdout_output: Arc<Mutex<String>>,
}

impl HeadlessProcess {
    /// Spawn `arf headless` and wait for IPC server to be ready.
    fn spawn() -> Result<Self, String> {
        Self::spawn_with_args(&[])
    }

    /// Spawn `arf headless` with additional R flags and wait for IPC readiness.
    fn spawn_with_args(extra_args: &[&str]) -> Result<Self, String> {
        Self::spawn_inner(extra_args, None)
    }

    /// Spawn with Windows creation flags (e.g., CREATE_NEW_PROCESS_GROUP).
    #[cfg(windows)]
    fn spawn_with_creation_flags(extra_args: &[&str], flags: u32) -> Result<Self, String> {
        Self::spawn_inner(extra_args, Some(flags))
    }

    fn spawn_inner(
        extra_args: &[&str],
        #[allow(unused)] creation_flags: Option<u32>,
    ) -> Result<Self, String> {
        let bin_path = env!("CARGO_BIN_EXE_arf");
        // When --quiet/--json is used, status messages are suppressed on stderr.
        // When --log-file is used, stderr is redirected to the file, so the
        // pipe is disconnected. In these cases, fall back to polling for readiness
        // instead of monitoring stderr for the "IPC server listening" message.
        let poll_for_readiness = extra_args.contains(&"--quiet")
            || extra_args.contains(&"--json")
            || extra_args.contains(&"--log-file");

        let mut cmd = Command::new(bin_path);
        cmd.arg("headless");
        for arg in extra_args {
            cmd.arg(arg);
        }
        cmd.stdin(Stdio::null());
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());

        #[cfg(windows)]
        if let Some(flags) = creation_flags {
            use std::os::windows::process::CommandExt;
            cmd.creation_flags(flags);
        }

        let mut child = cmd
            .spawn()
            .map_err(|e| format!("Failed to spawn arf headless: {e}"))?;
        let pid = child.id();

        let stderr = child.stderr.take().expect("stderr should be piped");
        let stdout = child.stdout.take().expect("stdout should be piped");
        let stderr_output = Arc::new(Mutex::new(String::new()));
        let stdout_output = Arc::new(Mutex::new(String::new()));
        let stderr_clone = Arc::clone(&stderr_output);
        let stdout_clone = Arc::clone(&stdout_output);
        let shutdown = Arc::new(AtomicBool::new(false));
        let shutdown_clone = Arc::clone(&shutdown);
        let shutdown_clone2 = Arc::clone(&shutdown);

        // Channel to signal IPC readiness (used when stderr is available)
        let (ready_tx, ready_rx) = std::sync::mpsc::channel::<()>();
        let mut ready_tx = Some(ready_tx);

        // Spawn a thread to read stderr and detect IPC readiness
        let stderr_thread = thread::spawn(move || {
            let reader = std::io::BufReader::new(stderr);
            for line in reader.lines() {
                if shutdown_clone.load(Ordering::Relaxed) {
                    break;
                }
                match line {
                    Ok(line) => {
                        if line.contains("IPC server listening on:")
                            && let Some(tx) = ready_tx.take()
                        {
                            let _ = tx.send(());
                        }
                        if let Ok(mut output) = stderr_clone.lock() {
                            output.push_str(&line);
                            output.push('\n');
                        }
                    }
                    Err(_) => break,
                }
            }
        });

        // Spawn a thread to read stdout (visible eval output goes here)
        let stdout_thread = thread::spawn(move || {
            let mut reader = std::io::BufReader::new(stdout);
            let mut buf = String::new();
            loop {
                if shutdown_clone2.load(Ordering::Relaxed) {
                    break;
                }
                buf.clear();
                match reader.read_line(&mut buf) {
                    Ok(0) => break,
                    Ok(_) => {
                        if let Ok(mut output) = stdout_clone.lock() {
                            output.push_str(&buf);
                        }
                    }
                    Err(_) => break,
                }
            }
        });

        // Wait for IPC readiness
        if poll_for_readiness {
            // Stderr readiness message is not available (suppressed in --quiet
            // mode, or pipe disconnected in --log-file mode). Probe readiness
            // by running an actual RPC (`arf ipc eval "1"`) until it succeeds.
            // This ensures R is fully initialized and `set_r_at_prompt(true)`
            // has been called, unlike `ipc status` which only checks the
            // session file.
            let start = std::time::Instant::now();
            let mut last_probe_err = String::new();
            loop {
                if start.elapsed() > STARTUP_TIMEOUT {
                    let _ = child.kill();
                    let server_stderr = stderr_output.lock().map(|s| s.clone()).unwrap_or_default();
                    return Err(format!(
                        "Timeout waiting for IPC eval to succeed (polling mode).\n\
                         Server stderr:\n{server_stderr}\n\
                         Last probe error:\n{last_probe_err}"
                    ));
                }
                // Check if the process has exited early (e.g. error)
                if let Ok(Some(status)) = child.try_wait() {
                    let output = stderr_output.lock().map(|s| s.clone()).unwrap_or_default();
                    return Err(format!(
                        "Headless process exited early with {status}. Stderr:\n{output}"
                    ));
                }
                // Try a real RPC to confirm R is ready
                let probe = Command::new(bin_path)
                    .args([
                        "ipc",
                        "eval",
                        "1",
                        "--pid",
                        &pid.to_string(),
                        "--timeout",
                        "500",
                    ])
                    .output();
                match probe {
                    Ok(output) if output.status.success() => break,
                    Ok(output) => {
                        last_probe_err = String::from_utf8_lossy(&output.stderr).into_owned();
                    }
                    Err(e) => {
                        last_probe_err = e.to_string();
                    }
                }
                std::thread::sleep(Duration::from_millis(100));
            }
        } else {
            match ready_rx.recv_timeout(STARTUP_TIMEOUT) {
                Ok(()) => {}
                Err(_) => {
                    // Kill the process and report what we got
                    let _ = child.kill();
                    let output = stderr_output.lock().map(|s| s.clone()).unwrap_or_default();
                    return Err(format!(
                        "Timeout waiting for headless IPC server to start. Stderr:\n{output}"
                    ));
                }
            }
        }

        Ok(HeadlessProcess {
            child,
            pid,
            _stderr_thread: Some(stderr_thread),
            _stdout_thread: Some(stdout_thread),
            shutdown,
            stderr_output,
            stdout_output,
        })
    }

    /// Run `arf ipc eval <code> --pid <pid>` and return (stdout, stderr, success).
    fn ipc_eval(&self, code: &str) -> Result<IpcOutput, String> {
        let bin_path = env!("CARGO_BIN_EXE_arf");

        let output = Command::new(bin_path)
            .args(["ipc", "eval", code, "--pid", &self.pid.to_string()])
            .output()
            .map_err(|e| format!("Failed to run arf ipc eval: {e}"))?;

        Ok(IpcOutput {
            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            success: output.status.success(),
            exit_code: output.status.code(),
        })
    }

    /// Run `arf ipc eval <code> --pid <pid> --visible` and return output.
    fn ipc_eval_visible(&self, code: &str) -> Result<IpcOutput, String> {
        let bin_path = env!("CARGO_BIN_EXE_arf");

        let output = Command::new(bin_path)
            .args([
                "ipc",
                "eval",
                code,
                "--pid",
                &self.pid.to_string(),
                "--visible",
            ])
            .output()
            .map_err(|e| format!("Failed to run arf ipc eval --visible: {e}"))?;

        Ok(IpcOutput {
            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            success: output.status.success(),
            exit_code: output.status.code(),
        })
    }

    /// Run `arf ipc eval <code> --pid <pid> --timeout <ms>` and return output.
    fn ipc_eval_with_timeout(&self, code: &str, timeout_ms: u64) -> Result<IpcOutput, String> {
        let bin_path = env!("CARGO_BIN_EXE_arf");

        let output = Command::new(bin_path)
            .args([
                "ipc",
                "eval",
                code,
                "--pid",
                &self.pid.to_string(),
                "--timeout",
                &timeout_ms.to_string(),
            ])
            .output()
            .map_err(|e| format!("Failed to run arf ipc eval --timeout: {e}"))?;

        Ok(IpcOutput {
            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            success: output.status.success(),
            exit_code: output.status.code(),
        })
    }

    /// Run `arf ipc send <code> --pid <pid>` and return output.
    fn ipc_send(&self, code: &str) -> Result<IpcOutput, String> {
        let bin_path = env!("CARGO_BIN_EXE_arf");

        let output = Command::new(bin_path)
            .args(["ipc", "send", code, "--pid", &self.pid.to_string()])
            .output()
            .map_err(|e| format!("Failed to run arf ipc send: {e}"))?;

        Ok(IpcOutput {
            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            success: output.status.success(),
            exit_code: output.status.code(),
        })
    }

    /// Run `arf ipc session --pid <pid>` and return output.
    fn ipc_session(&self) -> Result<IpcOutput, String> {
        let bin_path = env!("CARGO_BIN_EXE_arf");

        let output = Command::new(bin_path)
            .args(["ipc", "session", "--pid", &self.pid.to_string()])
            .output()
            .map_err(|e| format!("Failed to run arf ipc session: {e}"))?;

        Ok(IpcOutput {
            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            success: output.status.success(),
            exit_code: output.status.code(),
        })
    }

    /// Run `arf ipc history --pid <pid>` with optional extra args and return output.
    fn ipc_history(&self, extra_args: &[&str]) -> Result<IpcOutput, String> {
        let bin_path = env!("CARGO_BIN_EXE_arf");
        let pid_str = self.pid.to_string();

        let mut args = vec!["ipc", "history", "--pid", &pid_str];
        args.extend_from_slice(extra_args);

        let output = Command::new(bin_path)
            .args(&args)
            .output()
            .map_err(|e| format!("Failed to run arf ipc history: {e}"))?;

        Ok(IpcOutput {
            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            success: output.status.success(),
            exit_code: output.status.code(),
        })
    }

    /// Run `arf ipc shutdown --pid <pid>` and return output.
    fn ipc_shutdown(&self) -> Result<IpcOutput, String> {
        let bin_path = env!("CARGO_BIN_EXE_arf");

        let output = Command::new(bin_path)
            .args(["ipc", "shutdown", "--pid", &self.pid.to_string()])
            .output()
            .map_err(|e| format!("Failed to run arf ipc shutdown: {e}"))?;

        Ok(IpcOutput {
            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            success: output.status.success(),
            exit_code: output.status.code(),
        })
    }

    /// Wait for the headless process to exit, with a timeout.
    /// Returns the `ExitStatus` on success.
    fn wait_for_exit(&mut self, timeout: Duration) -> Result<std::process::ExitStatus, String> {
        let start = std::time::Instant::now();
        loop {
            match self.child.try_wait() {
                Ok(Some(status)) => return Ok(status),
                Ok(None) => {
                    if start.elapsed() > timeout {
                        return Err("Process did not exit within timeout".to_string());
                    }
                    std::thread::sleep(Duration::from_millis(100));
                }
                Err(e) => return Err(format!("Error waiting for process: {e}")),
            }
        }
    }

    /// Get the headless process's stderr output collected so far.
    fn stderr_output(&self) -> String {
        self.stderr_output
            .lock()
            .map(|s| s.clone())
            .unwrap_or_default()
    }

    /// Get the headless process's stdout output collected so far.
    fn stdout_output(&self) -> String {
        self.stdout_output
            .lock()
            .map(|s| s.clone())
            .unwrap_or_default()
    }

    /// Get all output (stdout + stderr) from the headless process.
    fn server_output(&self) -> String {
        format!("{}{}", self.stdout_output(), self.stderr_output())
    }
}

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

/// Output from an `arf ipc` CLI command.
#[derive(Debug)]
struct IpcOutput {
    stdout: String,
    stderr: String,
    success: bool,
    exit_code: Option<i32>,
}

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

/// Test that `arf headless` starts and the IPC server becomes reachable.
#[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
    );
}

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

/// 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().expect("Failed to spawn headless");

    // Use a unique marker to avoid matching startup messages
    let result = process
        .ipc_eval_visible("cat('vis_marker_42\\n')")
        .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
    );
}

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

/// Test that --bind allows specifying a custom socket path.
#[cfg(unix)]
#[test]
fn test_headless_bind_custom_socket() {
    let tmp = tempfile::TempDir::new().expect("create temp dir");
    let sock_path = tmp.path().join("custom.sock");
    let sock_str = sock_path.display().to_string();

    let process = HeadlessProcess::spawn_with_args(&["--bind", &sock_str])
        .expect("Failed to spawn headless with --bind");

    // The custom socket file should exist
    assert!(
        sock_path.exists(),
        "custom socket file should exist at: {}",
        sock_str
    );

    // IPC should work via the session discovery (which picks up the custom path)
    let result = process.ipc_eval("1 + 1").expect("eval should work");
    assert!(result.success, "eval should succeed: {}", result.stderr);
    assert!(
        result.stdout.contains("[1] 2"),
        "should return result: {}",
        result.stdout
    );

    // stderr should mention the custom path
    let stderr = process.stderr_output();
    assert!(
        stderr.contains(&sock_str),
        "stderr should mention custom socket path: {}",
        stderr
    );
}

/// Test that --pid-file writes the PID and is cleaned up on shutdown.
#[test]
fn test_headless_pid_file() {
    let tmp = tempfile::TempDir::new().expect("create temp dir");
    let pid_path = tmp.path().join("arf.pid");
    let pid_str = pid_path.display().to_string();

    let mut process = HeadlessProcess::spawn_with_args(&["--pid-file", &pid_str])
        .expect("Failed to spawn headless with --pid-file");

    // PID file is written right after the IPC server starts. Poll until the
    // file exists AND has non-empty content to avoid reading between create
    // and write.
    let start = std::time::Instant::now();
    let pid_content = loop {
        assert!(
            start.elapsed() < Duration::from_secs(5),
            "PID file should appear with content at: {}",
            pid_str
        );
        if let Ok(content) = std::fs::read_to_string(&pid_path)
            && !content.is_empty()
        {
            break content;
        }
        std::thread::sleep(Duration::from_millis(50));
    };
    let expected_pid = process.pid.to_string();
    assert_eq!(
        pid_content.trim(),
        expected_pid,
        "PID file should contain process PID"
    );

    // Shutdown via IPC and verify PID file is cleaned up
    let result = process.ipc_shutdown().expect("shutdown should run");
    assert!(result.success, "shutdown should succeed");

    process
        .wait_for_exit(Duration::from_secs(10))
        .expect("headless process should exit after shutdown");

    // PID file should be removed on clean shutdown
    assert!(
        !pid_path.exists(),
        "PID file should be removed after shutdown"
    );
}

/// Test that --quiet suppresses status messages on stderr.
#[test]
fn test_headless_quiet_mode() {
    let process = HeadlessProcess::spawn_with_args(&["--quiet"])
        .expect("Failed to spawn headless with --quiet");

    // IPC should still work
    let result = process.ipc_eval("1 + 1").expect("eval should work");
    assert!(result.success, "eval should succeed: {}", result.stderr);
    assert!(
        result.stdout.contains("[1] 2"),
        "should return result: {}",
        result.stdout
    );

    // stderr should NOT contain the usual status messages
    let stderr = process.stderr_output();
    assert!(
        !stderr.contains("IPC server listening on:"),
        "quiet mode should suppress IPC listening message, got: {}",
        stderr
    );
    assert!(
        !stderr.contains("Headless mode ready"),
        "quiet mode should suppress ready message, got: {}",
        stderr
    );
}

/// Test that --log-file redirects log output to a file.
#[test]
fn test_headless_log_file() {
    let tmp = tempfile::TempDir::new().expect("create temp dir");
    let log_path = tmp.path().join("arf.log");
    let log_str = log_path.display().to_string();

    let process = HeadlessProcess::spawn_with_args(&["--log-file", &log_str])
        .expect("Failed to spawn headless with --log-file");

    // Run a simple eval to ensure the server is working
    let result = process.ipc_eval("1 + 1").expect("eval should work");
    assert!(result.success, "eval should succeed: {}", result.stderr);

    // The log file should exist (env_logger writes to it)
    assert!(log_path.exists(), "log file should exist at: {}", log_str);

    let log_content = std::fs::read_to_string(&log_path).unwrap_or_default();

    // In headless mode, stderr is redirected to the log file via dup2.
    // Status messages (eprintln) should now appear in the log file.
    assert!(
        log_content.contains("Headless mode ready"),
        "log file should contain status messages (stderr is redirected): {}",
        log_content
    );

    // stderr pipe should be empty (disconnected by dup2 redirect)
    let stderr = process.stderr_output();
    assert!(
        stderr.trim().is_empty(),
        "stderr pipe should be empty when --log-file redirects stderr, but got: {}",
        stderr
    );
}

/// Helper: test that a Unix signal triggers graceful shutdown with PID file cleanup.
#[cfg(unix)]
fn assert_signal_graceful_shutdown(signal: nix::sys::signal::Signal) {
    use nix::sys::signal;
    use nix::unistd::Pid;

    let tmp = tempfile::TempDir::new().expect("create temp dir");
    let pid_path = tmp.path().join("arf.pid");
    let pid_str = pid_path.display().to_string();

    let mut process = HeadlessProcess::spawn_with_args(&["--pid-file", &pid_str])
        .expect("Failed to spawn headless with --pid-file");

    // Wait for "Headless mode ready" on stderr, which is printed after the
    // signal handler has been installed. This avoids a race where the signal
    // arrives before the handler is set up.
    let start = std::time::Instant::now();
    loop {
        if start.elapsed() > Duration::from_secs(10) {
            panic!(
                "Headless mode should become ready.\nServer output:\n{}",
                process.server_output()
            );
        }
        // Fail fast if the process has already exited
        if let Ok(Some(status)) = process.child.try_wait() {
            panic!(
                "Headless process exited early with {status}.\nServer output:\n{}",
                process.server_output()
            );
        }
        if process.stderr_output().contains("Headless mode ready") {
            break;
        }
        std::thread::sleep(Duration::from_millis(50));
    }

    // PID file should also exist by now (written before the handler)
    assert!(pid_path.exists(), "PID file should exist at: {}", pid_str);

    // Send the signal
    signal::kill(Pid::from_raw(process.pid as i32), signal)
        .unwrap_or_else(|e| panic!("failed to send {signal}: {e}"));

    // Process should exit gracefully
    let status = process
        .wait_for_exit(Duration::from_secs(10))
        .unwrap_or_else(|e| panic!("headless process should exit after {signal}: {e}"));
    assert!(
        status.success(),
        "headless process should exit cleanly after {signal}, got: {status}"
    );

    // PID file should be cleaned up
    assert!(
        !pid_path.exists(),
        "PID file should be removed after {signal} shutdown"
    );
}

/// Test that SIGTERM triggers graceful shutdown with PID file cleanup.
#[cfg(unix)]
#[test]
fn test_headless_sigterm_shutdown() {
    assert_signal_graceful_shutdown(nix::sys::signal::Signal::SIGTERM);
}

/// Test that SIGHUP triggers graceful shutdown with PID file cleanup.
#[cfg(unix)]
#[test]
fn test_headless_sighup_shutdown() {
    assert_signal_graceful_shutdown(nix::sys::signal::Signal::SIGHUP);
}

/// Test that Ctrl+C triggers graceful shutdown with PID file cleanup.
///
/// On Unix, sends SIGINT directly. On Windows, uses CTRL_BREAK_EVENT via
/// CREATE_NEW_PROCESS_GROUP + GenerateConsoleCtrlEvent, which is the only
/// way to signal a specific child process (CTRL_C_EVENT cannot target a
/// single process). The ctrlc crate handles both equivalently.
#[cfg(unix)]
#[test]
fn test_headless_ctrlc_shutdown() {
    assert_signal_graceful_shutdown(nix::sys::signal::Signal::SIGINT);
}

/// See [`test_headless_ctrlc_shutdown`] for rationale.
#[cfg(windows)]
#[test]
fn test_headless_ctrlc_shutdown() {
    const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;

    let tmp = tempfile::TempDir::new().expect("create temp dir");
    let pid_path = tmp.path().join("arf.pid");
    let pid_str = pid_path.display().to_string();

    let mut process = HeadlessProcess::spawn_with_creation_flags(
        &["--pid-file", &pid_str],
        CREATE_NEW_PROCESS_GROUP,
    )
    .expect("Failed to spawn headless with --pid-file");

    // Wait for "Headless mode ready" on stderr (signal handler is installed by then)
    let start = std::time::Instant::now();
    loop {
        if start.elapsed() > Duration::from_secs(10) {
            panic!(
                "Headless mode should become ready.\nServer output:\n{}",
                process.server_output()
            );
        }
        if let Ok(Some(status)) = process.child.try_wait() {
            panic!(
                "Headless process exited early with {status}.\nServer output:\n{}",
                process.server_output()
            );
        }
        if process.stderr_output().contains("Headless mode ready") {
            break;
        }
        std::thread::sleep(Duration::from_millis(50));
    }

    assert!(pid_path.exists(), "PID file should exist");

    // Send CTRL_BREAK_EVENT to the child's process group
    let result = unsafe {
        windows_sys::Win32::System::Console::GenerateConsoleCtrlEvent(
            windows_sys::Win32::System::Console::CTRL_BREAK_EVENT,
            process.pid,
        )
    };
    assert!(
        result != 0,
        "GenerateConsoleCtrlEvent failed: {}",
        std::io::Error::last_os_error()
    );

    // Process should exit within timeout (not hang)
    let status = process
        .wait_for_exit(Duration::from_secs(10))
        .unwrap_or_else(|e| {
            panic!(
                "headless process should exit after CTRL_BREAK: {e}\nServer output:\n{}",
                process.server_output()
            )
        });

    assert!(
        status.success(),
        "headless process should exit cleanly after CTRL_BREAK, got: {status}\n\
         Server output:\n{}",
        process.server_output()
    );

    // PID file should be cleaned up
    assert!(
        !pid_path.exists(),
        "PID file should be removed after CTRL_BREAK shutdown\nServer output:\n{}",
        process.server_output()
    );
}

/// Test that headless mode persists evaluated commands to the history database.
///
/// Verifies that:
/// - IPC evaluate commands are saved with correct command_line and exit_status
/// - Metadata fields (hostname, cwd) are populated
/// - Errors are recorded with exit_status=1
/// - The --history-dir flag controls the database location
#[test]
fn test_headless_history_persistence() {
    let tmp = tempfile::TempDir::new().expect("create temp dir");
    let history_dir = tmp.path().to_str().unwrap();

    let process = HeadlessProcess::spawn_with_args(&["--history-dir", history_dir])
        .expect("Failed to spawn headless with --history-dir");

    // Run a successful command
    let r1 = process.ipc_eval("1 + 1").expect("eval should run");
    assert!(r1.success, "first eval should succeed");

    // Run a command that errors (R errors are returned in JSON, exit 0)
    let r2 = process
        .ipc_eval("stop('test_error')")
        .expect("error eval should run");
    assert!(r2.success, "eval should succeed (R error is in JSON)");

    // Run a send (user_input) command
    let r3 = process
        .ipc_send("invisible(NULL)")
        .expect("send should run");
    assert!(r3.success, "send should succeed");

    // Whitespace-only commands should NOT be persisted to history.
    let _ = process
        .ipc_eval("   \n")
        .expect("whitespace eval should run");
    let _ = process
        .ipc_send("  \t  ")
        .expect("whitespace send should run");

    // Small delay to let SQLite flush
    std::thread::sleep(Duration::from_millis(200));

    // Read the history database directly
    let db_path = tmp.path().join("r.db");
    assert!(db_path.exists(), "history database should exist");

    let conn =
        rusqlite::Connection::open_with_flags(&db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)
            .expect("open history db");

    let mut stmt = conn
        .prepare(
            "SELECT command_line, exit_status, hostname, cwd \
             FROM history ORDER BY id",
        )
        .expect("prepare query");
    let rows: Vec<_> = stmt
        .query_map([], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, Option<i64>>(1)?,
                row.get::<_, Option<String>>(2)?,
                row.get::<_, Option<String>>(3)?,
            ))
        })
        .expect("query")
        .collect::<Result<Vec<_>, _>>()
        .expect("collect rows");

    // Filter to just our known commands for assertion stability.
    let success_row = rows.iter().find(|r| r.0 == "1 + 1");
    let error_row = rows.iter().find(|r| r.0 == "stop('test_error')");
    let send_row = rows.iter().find(|r| r.0 == "invisible(NULL)");

    // Successful eval
    let success_row = success_row.expect("should find '1 + 1' in history");
    assert_eq!(
        success_row.1,
        Some(0),
        "successful eval should have exit_status=0"
    );
    assert!(success_row.2.is_some(), "hostname should be populated");
    assert!(success_row.3.is_some(), "cwd should be populated");

    // Error eval
    let error_row = error_row.expect("should find error command in history");
    assert_eq!(error_row.1, Some(1), "error eval should have exit_status=1");

    // user_input (send)
    let send_row = send_row.expect("should find send command in history");
    assert_eq!(send_row.1, Some(0), "send should have exit_status=0");

    // Whitespace-only commands should not appear in history.
    let whitespace_rows: Vec<_> = rows.iter().filter(|r| r.0.trim().is_empty()).collect();
    assert!(
        whitespace_rows.is_empty(),
        "whitespace-only commands should not be persisted to history"
    );
}

/// Test that --no-history prevents history from being saved in headless mode.
#[test]
fn test_headless_no_history_flag() {
    let tmp = tempfile::TempDir::new().expect("create temp dir");
    let history_dir = tmp.path().to_str().unwrap();

    let process = HeadlessProcess::spawn_with_args(&["--history-dir", history_dir, "--no-history"])
        .expect("Failed to spawn headless with --no-history");

    // Run a command
    let result = process.ipc_eval("1 + 1").expect("eval should run");
    assert!(result.success, "eval should succeed");

    // History database should NOT be created
    let db_path = tmp.path().join("r.db");
    assert!(
        !db_path.exists(),
        "history database should not exist with --no-history"
    );
}

/// Test that --json outputs valid JSON with session info to stdout.
#[test]
fn test_headless_json_output() {
    let process =
        HeadlessProcess::spawn_with_args(&["--json"]).expect("Failed to spawn with --json");

    // Wait for the stdout reader thread to capture the JSON output.
    // spawn_with_args already confirmed IPC readiness, so the JSON has been
    // written; we just need the reader thread to catch up.
    let deadline = std::time::Instant::now() + Duration::from_secs(5);
    while process.stdout_output().trim().is_empty() {
        assert!(
            std::time::Instant::now() < deadline,
            "Timed out waiting for JSON on stdout"
        );
        std::thread::sleep(Duration::from_millis(50));
    }

    let stdout = process.stdout_output();

    // stdout should contain valid JSON with expected fields
    let json: serde_json::Value = serde_json::from_str(stdout.trim())
        .unwrap_or_else(|e| panic!("Invalid JSON: {e}\nstdout: {stdout}"));

    assert_eq!(
        json["pid"].as_u64().unwrap() as u32,
        process.pid,
        "JSON pid should match process PID"
    );
    assert!(
        json["socket_path"].is_string(),
        "JSON should have socket_path: {json}"
    );
    assert!(
        json["r_version"].is_string() || json["r_version"].is_null(),
        "JSON r_version should be a string or null: {json}"
    );
    assert!(json["cwd"].is_string(), "JSON should have cwd: {json}");
    assert!(
        json["started_at"].is_string(),
        "JSON should have started_at: {json}"
    );
    assert!(
        json["log_file"].is_null(),
        "JSON log_file should be null without --log-file: {json}"
    );
    assert!(
        json["warnings"].is_array(),
        "JSON should have warnings array: {json}"
    );

    // IPC should still work
    let result = process.ipc_eval("1 + 1").expect("eval should work");
    assert!(result.success, "eval should succeed: {}", result.stderr);

    // stderr should NOT contain status messages (--json implies --quiet)
    let stderr = process.stderr_output();
    assert!(
        !stderr.contains("IPC server listening on:"),
        "json mode should suppress IPC listening message, got: {}",
        stderr
    );
    assert!(
        !stderr.contains("Headless mode ready"),
        "json mode should suppress ready message, got: {}",
        stderr
    );
}

// ── IPC history query tests ─────────────────────────────────────────────

/// Test basic `arf ipc history` query returns evaluated commands.
#[test]
fn test_ipc_history_basic() {
    let tmp = tempfile::TempDir::new().expect("create temp dir");
    let history_dir = tmp.path().to_str().unwrap();

    let process =
        HeadlessProcess::spawn_with_args(&["--history-dir", history_dir]).expect("spawn headless");

    // Evaluate a few commands
    let r1 = process.ipc_eval("1 + 1").expect("eval 1");
    assert!(r1.success);
    let r2 = process.ipc_eval("cat('hello')").expect("eval 2");
    assert!(r2.success);

    // Small delay for SQLite flush
    std::thread::sleep(Duration::from_millis(200));

    // Query history
    let result = process.ipc_history(&[]).expect("history query");
    assert!(result.success, "history should succeed: {}", result.stderr);

    let json = parse_ipc_json(&result);
    let entries = json["entries"].as_array().expect("entries should be array");

    // Should contain both commands (newest first)
    assert!(
        entries.len() >= 2,
        "should have at least 2 entries, got {}: {json}",
        entries.len()
    );

    let commands: Vec<&str> = entries
        .iter()
        .filter_map(|e| e["command"].as_str())
        .collect();
    assert!(
        commands.contains(&"1 + 1"),
        "should contain '1 + 1': {commands:?}"
    );
    assert!(
        commands.contains(&"cat('hello')"),
        "should contain cat('hello'): {commands:?}"
    );

    // Should have a session_id
    assert!(
        json["session_id"].is_number(),
        "should have session_id: {json}"
    );
}

/// Test `--limit` flag restricts the number of returned entries.
#[test]
fn test_ipc_history_limit() {
    let tmp = tempfile::TempDir::new().expect("create temp dir");
    let history_dir = tmp.path().to_str().unwrap();

    let process =
        HeadlessProcess::spawn_with_args(&["--history-dir", history_dir]).expect("spawn headless");

    // Evaluate 3 commands
    for i in 1..=3 {
        let r = process
            .ipc_eval(&format!("{i} + {i}"))
            .expect("eval should run");
        assert!(r.success);
    }

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

    // Query with limit=2
    let result = process
        .ipc_history(&["--limit", "2"])
        .expect("history query");
    assert!(result.success);

    let json = parse_ipc_json(&result);
    let entries = json["entries"].as_array().expect("entries array");
    assert_eq!(entries.len(), 2, "should return exactly 2 entries: {json}");
}

/// Test `--grep` flag filters by command substring.
#[test]
fn test_ipc_history_grep() {
    let tmp = tempfile::TempDir::new().expect("create temp dir");
    let history_dir = tmp.path().to_str().unwrap();

    let process =
        HeadlessProcess::spawn_with_args(&["--history-dir", history_dir]).expect("spawn headless");

    let r1 = process.ipc_eval("print('apple')").expect("eval 1");
    assert!(r1.success);
    let r2 = process.ipc_eval("cat('banana')").expect("eval 2");
    assert!(r2.success);
    let r3 = process.ipc_eval("print('apricot')").expect("eval 3");
    assert!(r3.success);

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

    // Search for "apple"
    let result = process
        .ipc_history(&["--grep", "apple"])
        .expect("history grep");
    assert!(result.success);

    let json = parse_ipc_json(&result);
    let entries = json["entries"].as_array().expect("entries array");

    let commands: Vec<&str> = entries
        .iter()
        .filter_map(|e| e["command"].as_str())
        .collect();
    assert!(
        commands.iter().all(|c| c.contains("apple")),
        "all results should contain 'apple': {commands:?}"
    );
    assert!(
        !commands.iter().any(|c| c.contains("banana")),
        "should not contain 'banana': {commands:?}"
    );
}

/// Test that the default query returns only the current session's entries.
///
/// By default (without `--all-sessions`), history is scoped to the
/// current session. All returned entries must share the session_id.
#[test]
fn test_ipc_history_default_session_scoped() {
    let tmp = tempfile::TempDir::new().expect("create temp dir");
    let history_dir = tmp.path().to_str().unwrap();

    let process =
        HeadlessProcess::spawn_with_args(&["--history-dir", history_dir]).expect("spawn headless");

    let r1 = process.ipc_eval("42").expect("eval");
    assert!(r1.success);

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

    // Default query — should be scoped to the current session
    let result = process.ipc_history(&[]).expect("history default");
    assert!(result.success);

    let json = parse_ipc_json(&result);
    let entries = json["entries"].as_array().expect("entries array");
    assert!(
        !entries.is_empty(),
        "default query should find entries: {json}"
    );

    // All entries should have the same session_id as the response
    let session_id = json["session_id"].as_i64().expect("session_id");
    for entry in entries {
        assert_eq!(
            entry["session_id"].as_i64(),
            Some(session_id),
            "all entries should match session_id: {entry}"
        );
    }
}

/// Test that history entries include metadata (timestamp, cwd, exit_status).
#[test]
fn test_ipc_history_metadata() {
    let tmp = tempfile::TempDir::new().expect("create temp dir");
    let history_dir = tmp.path().to_str().unwrap();

    let process =
        HeadlessProcess::spawn_with_args(&["--history-dir", history_dir]).expect("spawn headless");

    let r1 = process.ipc_eval("1 + 1").expect("eval success");
    assert!(r1.success);
    let r2 = process.ipc_eval("stop('oops')").expect("eval error");
    assert!(r2.success, "eval should succeed (R error is in JSON)");

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

    let result = process.ipc_history(&[]).expect("history query");
    assert!(result.success);

    let json = parse_ipc_json(&result);
    let entries = json["entries"].as_array().expect("entries array");

    let success_entry = entries
        .iter()
        .find(|e| e["command"].as_str() == Some("1 + 1"))
        .expect("should find success entry");
    assert!(
        success_entry["timestamp"].is_string(),
        "should have timestamp: {success_entry}"
    );
    assert!(
        success_entry["cwd"].is_string(),
        "should have cwd: {success_entry}"
    );
    assert_eq!(
        success_entry["exit_status"].as_i64(),
        Some(0),
        "success should have exit_status=0: {success_entry}"
    );

    let error_entry = entries
        .iter()
        .find(|e| e["command"].as_str() == Some("stop('oops')"))
        .expect("should find error entry");
    assert_eq!(
        error_entry["exit_status"].as_i64(),
        Some(1),
        "error should have exit_status=1: {error_entry}"
    );
}

/// Test that history returns an error when history is disabled.
#[test]
fn test_ipc_history_disabled() {
    let tmp = tempfile::TempDir::new().expect("create temp dir");
    let history_dir = tmp.path().to_str().unwrap();

    let process = HeadlessProcess::spawn_with_args(&["--history-dir", history_dir, "--no-history"])
        .expect("spawn headless");

    let result = process.ipc_history(&[]).expect("history query");
    // Should fail because history is not configured
    assert!(
        !result.success,
        "history should fail when disabled: stdout={}, stderr={}",
        result.stdout, result.stderr
    );
}

// ── Exit code and structured error tests ─────────────────────────────

/// Test that `arf ipc eval --pid <wrong>` exits with code 3 (SESSION_NOT_FOUND)
/// and produces structured JSON error on stderr.
#[test]
fn test_ipc_exit_code_session_not_found() {
    let bin_path = env!("CARGO_BIN_EXE_arf");

    // Derive a PID unlikely to match any running arf session.
    let fake_pid = std::process::id().saturating_add(900_000).to_string();

    let output = Command::new(bin_path)
        .args(["ipc", "eval", "1", "--pid", &fake_pid])
        .output()
        .expect("should run");

    assert_eq!(
        output.status.code(),
        Some(3),
        "exit code should be 3 (session)"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    let json: serde_json::Value = serde_json::from_str(&stderr)
        .unwrap_or_else(|e| panic!("stderr should be JSON: {e}\nstderr: {stderr}"));
    assert_eq!(json["error"]["code"].as_str(), Some("SESSION_NOT_FOUND"));
    assert!(json["error"]["message"].as_str().is_some());
    assert!(json["error"]["hint"].as_str().is_some());
}

/// Test that `arf ipc list` outputs valid JSON even with no sessions.
#[test]
fn test_ipc_list_empty_json() {
    // This test runs without a headless process, so list should return
    // an empty sessions array (or whatever sessions are running).
    let bin_path = env!("CARGO_BIN_EXE_arf");
    let output = Command::new(bin_path)
        .args(["ipc", "list"])
        .output()
        .expect("should run");

    assert!(output.status.success(), "list should always succeed");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("stdout should be JSON: {e}\nstdout: {stdout}"));
    assert!(json["sessions"].is_array(), "should have sessions array");
}

/// Test that protocol errors (e.g. timeout) produce exit code 4 and
/// structured JSON error on stderr.
#[test]
fn test_ipc_exit_code_protocol_error() {
    let process = HeadlessProcess::spawn().expect("spawn headless");

    // Use a very short timeout to trigger a protocol-level timeout error
    let result = process
        .ipc_eval_with_timeout("Sys.sleep(10)", 500)
        .expect("eval should run");

    assert!(!result.success, "should fail due to timeout");
    assert_eq!(
        result.exit_code,
        Some(4),
        "exit code should be 4 (protocol)"
    );

    let json: serde_json::Value = serde_json::from_str(&result.stderr)
        .unwrap_or_else(|e| panic!("stderr should be JSON: {e}\nstderr: {}", result.stderr));
    assert!(
        json["error"]["code"].as_str().is_some(),
        "should have string error code"
    );
    assert!(
        json["error"]["message"].as_str().is_some(),
        "should have message"
    );
}