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
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
//! Isolated real arf sessions; terminal transport and emulation belong to tui-test.

use anyhow::{Context, Result, bail, ensure};
use serde_json::Value;
use std::fs;
use std::io::Write;
use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
use std::path::PathBuf;
use std::process::{Child, Command, ExitStatus, Stdio};
use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::mpsc;
use std::thread;
use std::time::{Duration, Instant};
use tempfile::{NamedTempFile, TempDir};
use tui_test::{
    AutomaticRecording, AutomaticRecordingMode, KeyAction, OpenOptions, Operation, OperationResult,
    RunOptions, Session, State,
};

const WAIT: Duration = Duration::from_secs(30);
pub const PROMPT: &str = "ARF>";
pub const ERROR_PROMPT: &str = "ERR ARF>";

struct FormatterFixture {
    bytes: Vec<u8>,
}

static FORMATTER_FIXTURE: OnceLock<std::result::Result<FormatterFixture, String>> = OnceLock::new();

fn compiled_formatter_fixture() -> Result<&'static FormatterFixture> {
    match FORMATTER_FIXTURE.get_or_init(|| {
        let build_dir = tempfile::tempdir().map_err(|error| error.to_string())?;
        let fixture_source = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests")
            .join("fixtures")
            .join("formatter.rs");
        let fixture = build_dir
            .path()
            .join(format!("formatter{}", std::env::consts::EXE_SUFFIX));
        let compiler = std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into());
        let output = Command::new(compiler)
            .arg(fixture_source)
            .arg("--edition=2024")
            .arg("-D")
            .arg("warnings")
            .arg("-o")
            .arg(&fixture)
            .output()
            .map_err(|error| {
                format!("failed to run rustc for the formatter test fixture: {error}")
            })?;
        if !output.status.success() {
            return Err(format!(
                "failed to compile the formatter test fixture: {}{}",
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr)
            ));
        }
        let bytes = fs::read(fixture)
            .map_err(|error| format!("failed to read the formatter test fixture: {error}"))?;
        Ok(FormatterFixture { bytes })
    }) {
        Ok(fixture) => Ok(fixture),
        Err(error) => bail!("{error}"),
    }
}

pub fn build_formatter_fixture_path(
    directory: &std::path::Path,
    formatter: &str,
) -> Result<String> {
    ensure!(
        matches!(formatter, "air" | "arity"),
        "unsupported formatter fixture: {formatter}"
    );
    fs::create_dir_all(directory)?;
    let fixture = directory.join(format!("{formatter}{}", std::env::consts::EXE_SUFFIX));
    fs::write(&fixture, &compiled_formatter_fixture()?.bytes)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(&fixture, fs::Permissions::from_mode(0o755))?;
    }
    let current_path = std::env::var_os("PATH").unwrap_or_default();
    let path = std::env::join_paths(
        std::iter::once(directory.to_path_buf()).chain(std::env::split_paths(&current_path)),
    )?;
    Ok(path.to_string_lossy().into_owned())
}

pub const DEFAULT_CONFIG: &str = r#"[prompt]
format = '{status}ARF> '
[prompt.status.symbol]
error = 'ERR '
"#;

/// Resources which can safely be shared by several terminal sessions.
///
/// In particular, the IPC server uses one directory for all sessions. A
/// session still gets its own working directory, config and history directory
/// so parallel cases cannot overwrite one another's files.
#[derive(Clone)]
pub struct SharedResources {
    root: Arc<TempDir>,
    sessions_dir: PathBuf,
}

impl SharedResources {
    pub fn new() -> Result<Self> {
        let root = Arc::new(tempfile::tempdir()?);
        let sessions_dir = root.path().join("sessions");
        fs::create_dir_all(&sessions_dir)?;
        Ok(Self { root, sessions_dir })
    }

    fn session_work(&self) -> Result<TempDir> {
        Ok(tempfile::tempdir_in(self.root.path())?)
    }

    fn sessions_dir(&self) -> &std::path::Path {
        &self.sessions_dir
    }
}

/// Configuration used to launch one real arf process.
pub struct TerminalBuilder {
    name: String,
    args: Vec<String>,
    config: Option<ConfigSource>,
    config_from_env: bool,
    env: Vec<(String, String)>,
    #[cfg(unix)]
    env_remove: Vec<String>,
    cwd: Option<PathBuf>,
    cols: u16,
    rows: u16,
    history_dir: Option<PathBuf>,
    artifacts: Option<PathBuf>,
    resources: Option<SharedResources>,
    vanilla: bool,
}

enum ConfigSource {
    Contents(String),
    Path(PathBuf),
}

impl TerminalBuilder {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            args: Vec::new(),
            config: None,
            config_from_env: false,
            env: Vec::new(),
            #[cfg(unix)]
            env_remove: Vec::new(),
            cwd: None,
            cols: 100,
            rows: 32,
            history_dir: None,
            artifacts: None,
            resources: None,
            vanilla: true,
        }
    }

    pub fn args<I, S>(mut self, args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.args.extend(args.into_iter().map(Into::into));
        self
    }

    /// Use TOML contents for the process-local config file.
    pub fn config(mut self, config: impl Into<String>) -> Self {
        self.config = Some(ConfigSource::Contents(config.into()));
        self
    }

    /// Use an existing config file without copying it into the session workdir.
    pub fn config_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.config = Some(ConfigSource::Path(path.into()));
        self
    }

    /// Select the generated config file through ARF_CONFIG instead of --config.
    pub fn config_from_env(mut self) -> Self {
        self.config_from_env = true;
        self
    }

    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.env.push((key.into(), value.into()));
        self
    }

    /// Remove inherited environment variables before starting arf.
    #[cfg(unix)]
    pub fn env_remove(mut self, key: impl Into<String>) -> Self {
        self.env_remove.push(key.into());
        self
    }

    pub fn cwd(mut self, path: impl Into<PathBuf>) -> Self {
        self.cwd = Some(path.into());
        self
    }

    pub fn cols(mut self, cols: u16) -> Self {
        self.cols = cols;
        self
    }

    pub fn rows(mut self, rows: u16) -> Self {
        self.rows = rows;
        self
    }

    pub fn history_dir(mut self, path: impl Into<PathBuf>) -> Self {
        self.history_dir = Some(path.into());
        self
    }

    pub fn artifacts(mut self, path: impl Into<PathBuf>) -> Self {
        self.artifacts = Some(path.into());
        self
    }

    pub fn resources(mut self, resources: SharedResources) -> Self {
        self.resources = Some(resources);
        self
    }

    /// Keep the default isolated startup flags unless a startup profile must
    /// be exercised by a test.
    pub fn vanilla(mut self, enabled: bool) -> Self {
        self.vanilla = enabled;
        self
    }

    fn ensure_artifacts(&mut self) -> Result<PathBuf> {
        if let Some(path) = &self.artifacts {
            fs::create_dir_all(path)?;
            return Ok(path.clone());
        }
        let root = std::env::var_os("ARF_TUI_TEST_ARTIFACTS")
            .map(PathBuf::from)
            .unwrap_or_else(std::env::temp_dir);
        fs::create_dir_all(&root)?;
        let path = tempfile::Builder::new()
            .prefix(&format!("arf-tui-{}-", self.name))
            .tempdir_in(root)?
            .keep();
        self.artifacts = Some(path.clone());
        Ok(path)
    }

    /// Spawn arf and return before waiting for its first prompt.
    pub fn spawn(mut self) -> Result<Terminal> {
        let cols = self.cols;
        let rows = self.rows;
        let artifacts = self.ensure_artifacts()?;
        let resources = match self.resources {
            Some(resources) => resources,
            None => SharedResources::new()?,
        };
        let work = resources.session_work()?;
        let config = match self.config {
            Some(ConfigSource::Contents(contents)) => {
                let path = work.path().join("config.toml");
                fs::write(&path, contents)?;
                path
            }
            Some(ConfigSource::Path(path)) => {
                if path.is_absolute() {
                    path
                } else {
                    // Resolve before launching the child: its cwd may be a
                    // session-specific temporary directory.
                    std::env::current_dir()?.join(path)
                }
            }
            None => {
                let path = work.path().join("config.toml");
                fs::write(&path, DEFAULT_CONFIG)?;
                path
            }
        };
        let history_dir = self
            .history_dir
            .unwrap_or_else(|| work.path().join("history"));
        let defaults = OpenOptions::default();
        let mut args = vec!["--no-r-source-overrides".to_owned()];
        if self.vanilla {
            args.insert(0, "--vanilla".to_owned());
        }
        if self.config_from_env {
            if !self.env.iter().any(|(key, _)| key == "ARF_CONFIG") {
                self.env.push((
                    "ARF_CONFIG".to_owned(),
                    config.to_string_lossy().into_owned(),
                ));
            }
        } else {
            args.extend(["--config".to_owned(), config.to_string_lossy().into_owned()]);
        }
        args.extend([
            "--history-dir".to_owned(),
            history_dir.to_string_lossy().into_owned(),
        ]);
        args.extend(self.args);
        #[cfg(unix)]
        let program = if self.env_remove.is_empty() {
            env!("CARGO_BIN_EXE_arf").to_owned()
        } else {
            let mut wrapper_args = Vec::with_capacity(self.env_remove.len() * 2 + args.len() + 1);
            for key in self.env_remove {
                wrapper_args.push("-u".to_owned());
                wrapper_args.push(key);
            }
            wrapper_args.push(env!("CARGO_BIN_EXE_arf").to_owned());
            wrapper_args.extend(args);
            args = wrapper_args;
            "/usr/bin/env".to_owned()
        };
        #[cfg(not(unix))]
        let program = env!("CARGO_BIN_EXE_arf").to_owned();
        let cwd = self.cwd.unwrap_or_else(|| work.path().to_path_buf());
        let mut env = self.env;
        if let Some((_, value)) = env
            .iter_mut()
            .find(|(key, _)| key == "ARF_IPC_SESSIONS_DIR")
        {
            *value = resources.sessions_dir().to_string_lossy().into_owned();
        } else {
            env.push((
                "ARF_IPC_SESSIONS_DIR".into(),
                resources.sessions_dir().to_string_lossy().into_owned(),
            ));
        }
        let mut terminal = Terminal {
            session: Session::new(&self.name),
            artifacts,
            work,
            resources,
            cwd: cwd.clone(),
            pid: None,
            closed: false,
        };
        terminal.stage("spawn")?;
        let opened = terminal.session.run(RunOptions {
            backend: defaults.backend,
            program,
            args,
            profile: defaults.profile,
            cols,
            rows,
            cwd: Some(cwd.to_string_lossy().into_owned()),
            env,
            wait_ready: Some(false),
            restart: false,
            timeouts: defaults.timeouts,
            recording: AutomaticRecording {
                mode: AutomaticRecordingMode::Always,
                directory: Some(terminal.artifacts.clone()),
            },
        })?;
        terminal.pid = opened.shell_pid;
        Ok(terminal)
    }
}

pub struct Terminal {
    session: Session,
    artifacts: PathBuf,
    work: TempDir,
    resources: SharedResources,
    cwd: PathBuf,
    pid: Option<u32>,
    closed: bool,
}

impl Terminal {
    pub fn builder(name: impl Into<String>) -> TerminalBuilder {
        TerminalBuilder::new(name)
    }

    pub fn sessions_dir(&self) -> &std::path::Path {
        self.resources.sessions_dir()
    }

    pub fn pid(&self) -> Option<u32> {
        self.pid
    }

    fn stage(&self, name: &str) -> Result<()> {
        eprintln!("tui-test: {name} (artifacts: {})", self.artifacts.display());
        fs::write(self.artifacts.join("stage.txt"), name)?;
        Ok(())
    }

    pub fn execute(&self, operation: Operation) -> Result<OperationResult> {
        Ok(self.session.execute(operation)?)
    }

    pub fn state(&self) -> Result<State> {
        match self.execute(Operation::State)? {
            OperationResult::State(state) => Ok(*state),
            _ => bail!("unexpected state response"),
        }
    }

    fn current_line(&self, state: &State) -> Result<String> {
        self.screen_line(state.cursor.y, state.cols)
    }

    /// Read one emulated screen row without depending on the cursor position.
    /// Pager headers live above the hidden cursor, so current-line polling is
    /// insufficient when an alternate-screen UI is active.
    pub fn screen_line(&self, y: u16, cols: u16) -> Result<String> {
        match self.execute(Operation::Cells {
            x: 0,
            y,
            w: cols,
            h: 1,
        })? {
            OperationResult::Cells(cells) => Ok(cells.into_iter().map(|cell| cell.char).collect()),
            _ => bail!("unexpected cells response"),
        }
    }

    pub fn screen_cells(&self, y: u16, cols: u16) -> Result<Vec<tui_test::Cell>> {
        match self.execute(Operation::Cells {
            x: 0,
            y,
            w: cols,
            h: 1,
        })? {
            OperationResult::Cells(cells) => Ok(cells),
            _ => bail!("unexpected cells response"),
        }
    }

    pub fn wait_for(
        &self,
        description: &str,
        predicate: impl Fn(&State, &str) -> bool,
    ) -> Result<()> {
        self.stage(description)?;
        let started = Instant::now();
        loop {
            let state = self.state()?;
            let line = self.current_line(&state)?;
            // Keep the last observation if a later PTY operation blocks.
            fs::write(
                self.artifacts.join("state.json"),
                serde_json::to_vec_pretty(&state)?,
            )?;
            ensure!(
                state.exited.is_none(),
                "arf exited waiting for {description}: {state:?}"
            );
            if predicate(&state, &line) {
                return Ok(());
            }
            ensure!(
                started.elapsed() < WAIT,
                "timed out waiting for {description}: {state:?}"
            );
            thread::sleep(Duration::from_millis(25));
        }
    }

    /// Poll a fixed emulated screen row, which is useful for pager headers
    /// rendered above the hidden cursor.
    pub fn wait_for_screen_line(
        &self,
        description: &str,
        y: u16,
        predicate: impl Fn(&State, &str) -> bool,
    ) -> Result<()> {
        self.stage(description)?;
        let started = Instant::now();
        loop {
            let state = self.state()?;
            let line = self.screen_line(y, state.cols)?;
            fs::write(
                self.artifacts.join("state.json"),
                serde_json::to_vec_pretty(&state)?,
            )?;
            ensure!(
                state.exited.is_none(),
                "arf exited waiting for {description}: {state:?}"
            );
            if predicate(&state, &line) {
                return Ok(());
            }
            ensure!(
                started.elapsed() < WAIT,
                "timed out waiting for {description}: {state:?}"
            );
            thread::sleep(Duration::from_millis(25));
        }
    }

    pub fn wait_for_prompt(&self, output: Option<&str>, prompt: &str) -> Result<()> {
        // A new, independent output line plus the cursor's prompt line avoids
        // matching old prompts and source echoes. Each command's marker must be
        // unique within the session. For repeated commands, compare the cursor
        // row before and after submission, then check the result on screen.
        // Recording checkpoints are for stream-only checks such as erased
        // output, complete echoes, and non-leak behavior.
        // arf emits no shell integration: WaitReady/WaitCommand are not suitable.
        // tui-test's text locator currently takes only the first character in each cell
        // and treats empty wide-character continuation cells as spaces, so it
        // can miss wide or combining text; use State.text/cells instead.
        self.wait_for("output and input prompt", |state, line| {
            line.trim_end() == prompt
                && usize::from(state.cursor.x) == prompt.len() + 1
                && output.is_none_or(|text| state.text.lines().any(|line| line == text))
        })
    }

    /// Wait for the first application prompt after spawning the process.
    ///
    /// Spawning and readiness are intentionally separate so callers can
    /// inspect startup output or coordinate several sessions before waiting.
    pub fn wait_for_first_prompt(&self) -> Result<()> {
        self.wait_for_prompt(None, PROMPT)
    }

    pub fn enter(&self, source: &str) -> Result<()> {
        self.stage("submit input")?;
        self.execute(Operation::Submit {
            data: Some(source.into()),
        })?;
        Ok(())
    }

    pub fn submit(&self, source: &str, output: &str, prompt: &str) -> Result<()> {
        self.enter(source)?;
        self.wait_for_prompt(Some(output), prompt)
    }

    pub fn write(&self, text: &str) -> Result<()> {
        self.execute(Operation::Write { data: text.into() })?;
        Ok(())
    }

    pub fn key(&self, key: &str) -> Result<()> {
        self.execute(Operation::Key {
            keys: vec![key.into()],
            action: KeyAction::Press,
        })?;
        Ok(())
    }

    /// Read output events, including text subsequently erased from the screen.
    pub fn output(&self) -> Result<String> {
        output_events(&self.session.recording()?)
    }

    pub fn checkpoint(&self) -> Result<usize> {
        Ok(self.output()?.len())
    }

    pub fn output_since(&self, checkpoint: usize) -> Result<String> {
        self.output()?
            .get(checkpoint..)
            .map(str::to_owned)
            .context("invalid output checkpoint")
    }

    fn ipc_sessions_dir(&self) -> &std::path::Path {
        self.resources.sessions_dir()
    }

    /// Use the real CLI's platform-aware IPC transport, targeting only this R process.
    pub fn start_ipc(&self, args: &[&str]) -> Result<IpcCommand> {
        self.start_ipc_with_pid(args, self.pid.context("missing arf PID")?)
    }

    /// Use the real CLI IPC transport with a caller-selected process ID.
    ///
    /// Restarting arf keeps the tui-test session alive while the process ID
    /// changes on platforms that spawn a replacement child. Callers can read
    /// the active PID from the process's lifecycle artifact and target that
    /// replacement explicitly.
    pub fn start_ipc_with_pid(&self, args: &[&str], pid: u32) -> Result<IpcCommand> {
        let stdout = NamedTempFile::new_in(self.work.path())?;
        let stderr = NamedTempFile::new_in(self.work.path())?;
        let child = Command::new(env!("CARGO_BIN_EXE_arf"))
            .arg("ipc")
            .args(args)
            .arg("--pid")
            .arg(pid.to_string())
            .env("ARF_IPC_SESSIONS_DIR", self.ipc_sessions_dir())
            .current_dir(&self.cwd)
            .stdin(Stdio::null())
            .stdout(stdout.reopen()?)
            .stderr(stderr.reopen()?)
            .spawn()?;
        Ok(IpcCommand {
            child,
            stdout,
            stderr,
        })
    }

    pub fn start_cli_tty(&self, args: &[&str]) -> Result<CliSession> {
        CliSession::new("arf-cli-tty", args, &self.cwd, self.ipc_sessions_dir())
    }

    pub fn quit(&self) -> Result<()> {
        self.stage("normal exit")?;
        self.enter("q('no')")?;
        let exit_code = self.wait_for_exit()?;
        ensure!(exit_code == 0, "wrong process exit: {exit_code}");
        Ok(())
    }

    /// Wait for an explicitly requested process exit and return its status.
    ///
    /// This is separate from `quit` so lifecycle tests can exercise Ctrl+D or
    /// startup failures without sending an unconditional R command first.
    pub fn wait_for_exit(&self) -> Result<i32> {
        self.execute(Operation::WaitExit {
            timeout_ms: Some(30_000),
        })?;
        let state = self.state()?;
        fs::write(
            self.artifacts.join("state.json"),
            serde_json::to_vec_pretty(&state)?,
        )?;
        state
            .exited
            .context("process did not report an exit status")
    }
}

/// A short-lived CLI process attached to its own tui-test PTY.
pub struct CliSession {
    session: Session,
}

impl CliSession {
    fn new(
        name: &str,
        args: &[&str],
        cwd: &std::path::Path,
        sessions_dir: &std::path::Path,
    ) -> Result<Self> {
        let session = Session::new(name);
        let defaults = OpenOptions::default();
        session.run(RunOptions {
            backend: defaults.backend,
            program: env!("CARGO_BIN_EXE_arf").into(),
            args: args.iter().map(|arg| (*arg).to_owned()).collect(),
            profile: defaults.profile,
            cols: defaults.cols,
            rows: defaults.rows,
            cwd: Some(cwd.to_string_lossy().into_owned()),
            env: vec![(
                "ARF_IPC_SESSIONS_DIR".to_owned(),
                sessions_dir.to_string_lossy().into_owned(),
            )],
            wait_ready: Some(false),
            restart: false,
            timeouts: defaults.timeouts,
            recording: AutomaticRecording::default(),
        })?;
        Ok(Self { session })
    }

    pub fn state(&self) -> Result<State> {
        match self.session.execute(Operation::State)? {
            OperationResult::State(state) => Ok(*state),
            _ => bail!("unexpected CLI state response"),
        }
    }

    pub fn wait_for_exit(&self) -> Result<i32> {
        self.session.execute(Operation::WaitExit {
            timeout_ms: Some(30_000),
        })?;
        self.state()?
            .exited
            .context("CLI process did not report an exit status")
    }
}

impl Drop for CliSession {
    fn drop(&mut self) {
        let _ = self.session.close();
    }
}

/// Wait for a lifecycle artifact to disappear without assuming a cleanup delay.
pub fn wait_for_path_absent(path: &std::path::Path) -> Result<()> {
    let started = Instant::now();
    while path.exists() {
        ensure!(
            started.elapsed() < WAIT,
            "path remained after process cleanup: {}",
            path.display()
        );
        thread::sleep(Duration::from_millis(25));
    }
    Ok(())
}

impl Drop for Terminal {
    fn drop(&mut self) {
        if !self.closed {
            let _ = self.session.close();
            self.closed = true;
        }
    }
}

pub struct IpcCommand {
    child: Child,
    stdout: NamedTempFile,
    stderr: NamedTempFile,
}

/// Completed CLI IPC invocation, including expected non-zero responses.
pub struct IpcOutcome {
    pub status: ExitStatus,
    pub stdout: String,
    pub stderr: String,
    pub json: Value,
}

impl IpcCommand {
    pub fn finish(self) -> Result<Value> {
        let outcome = self.finish_with_status()?;
        ensure!(
            outcome.status.success(),
            "IPC failed: {}; stdout={}; stderr={}",
            outcome.status,
            outcome.stdout,
            outcome.stderr
        );
        Ok(outcome.json)
    }

    /// Wait for the CLI and retain its parsed JSON even when it exits non-zero.
    ///
    /// The ordinary `finish` path remains success-only; this variant is for
    /// policy and approval responses whose structured error is expected.
    pub fn finish_with_status(mut self) -> Result<IpcOutcome> {
        let start = Instant::now();
        loop {
            if let Some(status) = self.child.try_wait()? {
                let stdout = fs::read_to_string(self.stdout.path())?;
                let stderr = fs::read_to_string(self.stderr.path())?;
                let json = serde_json::from_str(&stdout).or_else(|stdout_error| {
                    serde_json::from_str(&stderr).with_context(|| {
                        format!(
                            "invalid IPC JSON (stdout: {stdout_error}): stdout={stdout}; stderr={stderr}"
                        )
                    })
                })?;
                return Ok(IpcOutcome {
                    status,
                    stdout,
                    stderr,
                    json,
                });
            }
            ensure!(start.elapsed() < WAIT, "IPC client timed out");
            thread::sleep(Duration::from_millis(25));
        }
    }
}

impl Drop for IpcCommand {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

fn output_events(recording: &str) -> Result<String> {
    let mut lines = recording.lines();
    let header: Value = serde_json::from_str(lines.next().context("missing recording header")?)?;
    ensure!(header.is_object(), "invalid recording header");
    let mut output = String::new();
    for line in lines {
        let event: Value = serde_json::from_str(line)?;
        let fields = event
            .as_array()
            .context("recording event must be an array")?;
        ensure!(fields.len() == 3, "invalid recording event: {event}");
        if fields[1] == "o" {
            output.push_str(
                fields[2]
                    .as_str()
                    .context("output event must contain text")?,
            );
        }
    }
    Ok(output)
}

/// Bound the whole case through close/drop, not just polling calls. The watchdog
/// never touches terminal locks. This test binary fails if any case hangs.
pub fn run_case(
    name: &str,
    args: &[&str],
    test: impl FnOnce(&Terminal) -> Result<()>,
) -> Result<()> {
    let builder = Terminal::builder(name).args(args.iter().copied());
    run_case_with(builder, |terminal| {
        terminal.wait_for_first_prompt()?;
        test(terminal)?;
        terminal.quit()
    })
}

/// Run a terminal case with the common watchdog, diagnostics and cleanup.
///
/// The callback runs immediately after spawning. This deliberately leaves
/// readiness and process exit policy to the caller: migration tests may need
/// to inspect startup output, send a signal, or observe an already-exited
/// process instead of unconditionally submitting `q('no')`.
pub fn run_case_with(
    mut builder: TerminalBuilder,
    test: impl FnOnce(&Terminal) -> Result<()>,
) -> Result<()> {
    let name = builder.name.clone();
    let artifacts = builder.ensure_artifacts()?;
    let (_watchdog, deadline) = mpsc::channel::<()>();
    let diagnostics = artifacts.clone();
    thread::spawn(move || {
        if matches!(
            deadline.recv_timeout(Duration::from_secs(180)),
            Err(mpsc::RecvTimeoutError::Timeout)
        ) {
            let message = format!(
                "tui-test exceeded 180s; diagnostics: {}\n",
                diagnostics.display()
            );
            let _ = fs::write(diagnostics.join("timeout.txt"), &message);
            // Bypass libtest's per-test capture: process::exit does not flush it.
            let _ = std::io::stderr().lock().write_all(message.as_bytes());
            std::process::exit(1);
        }
    });
    let mut terminal = None;
    let result = catch_unwind(AssertUnwindSafe(|| {
        terminal = Some(builder.spawn()?);
        let terminal_ref = terminal.as_ref().expect("terminal was just spawned");
        test(terminal_ref)
    }));
    if let Some(terminal_ref) = terminal.as_ref() {
        match &result {
            Ok(Err(error)) => {
                let _ = fs::write(
                    terminal_ref.artifacts.join("failure.txt"),
                    format!("{error:#}"),
                );
            }
            Err(_) => {
                let _ = fs::write(
                    terminal_ref.artifacts.join("failure.txt"),
                    "test panicked; see cargo test output",
                );
            }
            _ => {}
        }
    } else if let Ok(Err(error)) = &result {
        let _ = fs::write(artifacts.join("failure.txt"), format!("{error:#}"));
    }
    // Always close an opened session, including when the test body returned an
    // error or panicked. Session's own Drop is a final backstop for failures
    // before this point (for example, a spawn error).
    let close_stage = terminal
        .as_ref()
        .map(|terminal_ref| terminal_ref.stage("close"));
    let close = terminal
        .as_ref()
        .map(|terminal_ref| terminal_ref.session.close());
    if close.as_ref().is_some_and(Result::is_ok) {
        let terminal_ref = terminal.as_mut().expect("close result has a terminal");
        terminal_ref.closed = true;
    }
    let result = match result {
        Ok(result) => result,
        Err(panic) => resume_unwind(panic),
    };
    let diagnostics = terminal
        .as_ref()
        .map(|terminal_ref| terminal_ref.artifacts.display().to_string())
        .unwrap_or_else(|| artifacts.display().to_string());
    result.with_context(|| format!("{name}; diagnostics: {diagnostics}"))?;
    if let Some(close) = close {
        close.context("close PTY")?;
    }
    if let Some(close_stage) = close_stage {
        close_stage?;
    }
    if let Some(terminal_ref) = terminal.as_ref() {
        terminal_ref.stage("passed")?;
    }
    Ok(())
}

#[test]
fn recording_concatenates_output_without_input_or_resize_events() -> Result<()> {
    let recording = r#"{"version":3}
[0,"o","æ—¥"]
[0,"i","secret"]
[0,"r","80x24"]
[0,"o","本語\r\u001b[2K"]
"#;
    ensure!(output_events(recording)? == "日本語\r\x1b[2K");
    Ok(())
}

#[test]
fn fragmented_history_recording_does_not_contain_visual_result() -> Result<()> {
    // Reduced from a Windows ConPTY artifact: the corresponding saved screen
    // state displayed `[1] 3`, but this reduced raw recording does not contain
    // that visual result as a contiguous substring.
    let recording = r#"{"version":3}
[0,"o","[1] 2\r\n"]
[0,"o","\u001b[2K\rARF> "]
[0,"o","\u001b[2K\r[1]\r\u001b[3C 3\r\nARF> "]
"#;
    let output = output_events(recording)?;
    ensure!(
        output.matches("[1] 2").count() == 1,
        "initial result missing from fragmented recording: {output:?}"
    );
    ensure!(
        output.contains("\r\x1b[3C"),
        "cursor-control boundary missing from fragmented recording: {output:?}"
    );
    ensure!(
        !output.contains("[1] 3"),
        "raw recording unexpectedly contains the visual replay result: {output:?}"
    );
    Ok(())
}

#[test]
fn malformed_recordings_fail_instead_of_dropping_output() {
    for recording in [
        "",
        r#"{}
[0,"o",123]
"#,
        r#"{}
[0,"o"]
"#,
        r#"{}
truncated"#,
    ] {
        assert!(output_events(recording).is_err(), "accepted {recording:?}");
    }
}

#[test]
fn builder_applies_process_settings_and_shares_ipc_resources() -> Result<()> {
    let cwd = tempfile::tempdir()?;
    let history = tempfile::tempdir()?;
    let artifacts = tempfile::tempdir()?;
    let second_artifacts = tempfile::tempdir()?;
    let current_dir = std::env::current_dir()?;
    let config_file = tempfile::Builder::new()
        .prefix("arf-tui-config-")
        .tempfile_in(&current_dir)?;
    fs::write(
        config_file.path(),
        "[startup]\nshow_banner = false\n[prompt]\nformat = 'PATH> '",
    )?;
    let config_relative = config_file
        .path()
        .file_name()
        .context("temporary config has no file name")?
        .to_owned();
    let resources = SharedResources::new()?;
    let cwd_text = cwd.path().to_string_lossy().replace('\\', "/");
    let shared_sessions = resources.sessions_dir().to_path_buf();

    run_case_with(
        Terminal::builder("builder-settings")
            .config("[startup]\nshow_banner = false\n".to_owned() + DEFAULT_CONFIG)
            .env("ARF_BUILDER_ENV", "configured")
            .cwd(cwd.path())
            .cols(90)
            .rows(20)
            .history_dir(history.path())
            .artifacts(artifacts.path())
            .resources(resources.clone()),
        |terminal| {
            terminal.wait_for_first_prompt()?;
            let state = terminal.state()?;
            ensure!(
                (state.cols, state.rows) == (90, 20),
                "wrong size: {state:?}"
            );
            ensure!(terminal.pid().is_some(), "missing arf PID");
            ensure!(
                terminal.sessions_dir() == shared_sessions,
                "wrong shared IPC directory"
            );
            ensure!(
                !state.text.contains("# arf console v"),
                "custom config did not disable the banner"
            );
            terminal.submit(
                "Sys.getenv('ARF_BUILDER_ENV')",
                r#"[1] "configured""#,
                PROMPT,
            )?;
            terminal.submit(
                &format!(
                    "normalizePath(getwd(), winslash='/') == normalizePath('{cwd_text}', winslash='/')"
                ),
                "[1] TRUE",
                PROMPT,
            )?;
            terminal.quit()
        },
    )?;
    ensure!(
        fs::read_dir(artifacts.path())?.next().is_some(),
        "recording artifacts were not retained"
    );
    ensure!(
        history.path().join("r.db").is_file(),
        "custom history directory did not contain r.db"
    );

    run_case_with(
        Terminal::builder("builder-shared-resource")
            .config_path(config_relative)
            .artifacts(second_artifacts.path())
            .resources(resources),
        |terminal| {
            terminal.wait_for_prompt(None, "PATH>")?;
            ensure!(
                terminal.sessions_dir() == shared_sessions,
                "second session did not reuse shared IPC directory"
            );
            terminal.quit()
        },
    )
}