vce 0.1.1

A stateful virtual OS engine with an embeddable machine and shell API
Documentation
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
//! The interactive REPL and the scripted line mode.
//!
//! Interactive mode renders the prompt and typed input into the virtual
//! terminal model (so scrollback and the alternate screen behave like a real
//! terminal) and forwards host keys to the model while a command runs, so
//! `man`, `less`, and `nano` are actually interactive. Line mode reads
//! plain lines from piped stdin, for scripting and automated use.

use std::io::{BufRead, Read, Write};
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::sync::mpsc::{Receiver, Sender};

use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use engine::io::{Key, KeyEvent, Size, Terminal};
use engine::{Input, VirtualPath};
use os::runtime::resolve_path_name;
use shell::Shell;

use crate::host::{HostTerminal, TerminalOutput, render, spawn_key_reader};
use crate::{SessionControl, SessionOutcome};

/// How long the session waits for the host terminal to report a settled
/// size after launch (a Ghostty split reports the final size only once the
/// window finishes laying out).
const SIZE_SETTLE_POLL: std::time::Duration = std::time::Duration::from_millis(100);

/// How long prompt key handling waits for a host key before redrawing.
const KEY_WAIT: std::time::Duration = std::time::Duration::from_millis(250);

/// The interactive session: prompt, line editing, history, and command
/// execution against the shared virtual terminal.
pub struct InteractiveSession<'os> {
    shell: Box<dyn Shell + 'os>,
    /// The shared virtual terminal model (screen state).
    terminal: HostTerminal,
    /// Virtual output written by non-interactive commands.
    output: TerminalOutput,
    /// Prompt key events arriving while the shell is idle.
    keys: Receiver<KeyEvent>,
    /// Re-sends leftover command keys back to the prompt channel.
    keys_out: Sender<KeyEvent>,
    /// Whether a command is running and may consume model keys.
    in_command: Arc<std::sync::atomic::AtomicBool>,
    /// The last version the host screen was rendered at (shared with the
    /// render watcher).
    last_version: Arc<std::sync::Mutex<u64>>,
    /// The host stdout, shared between the main thread and the render
    /// watcher so frames never interleave.
    host_lock: Arc<std::sync::Mutex<std::io::Stdout>>,
    /// Stops the render watcher on exit.
    render_stop: Arc<std::sync::atomic::AtomicBool>,
    /// Whether the next prompt is a continuation (`> `) prompt.
    continuing: bool,
    /// The last terminal size the session synced, in `(rows, cols)`.
    last_size: Option<(u16, u16)>,
    /// Cooperative cancellation and deadline state.
    control: SessionControl,
}

impl<'os> InteractiveSession<'os> {
    /// Creates a session over a shell and a fresh virtual terminal.
    pub fn new(shell: Box<dyn Shell + 'os>, control: SessionControl) -> Self {
        // A host terminal may briefly report no size (fresh ptys do); clamp
        // to a sane minimum so the model is always well-defined. Note that
        // crossterm reports `(columns, rows)`.
        let (cols, rows) = crossterm::terminal::size()
            .map(|(cols, rows)| {
                (
                    rows.max(terminal::DEFAULT_ROWS),
                    cols.max(terminal::DEFAULT_COLUMNS),
                )
            })
            .unwrap_or((terminal::DEFAULT_ROWS, terminal::DEFAULT_COLUMNS));
        let terminal = HostTerminal::new(Size::new(rows, cols), control.clone());
        let output = TerminalOutput::new(&terminal);
        let (keys_out, keys, in_command) = spawn_key_reader(Arc::clone(terminal.model()));
        Self {
            shell,
            terminal,
            output,
            keys,
            keys_out,
            in_command,
            last_version: Arc::new(std::sync::Mutex::new(0)),
            host_lock: Arc::new(std::sync::Mutex::new(std::io::stdout())),
            render_stop: Arc::new(std::sync::atomic::AtomicBool::new(false)),
            continuing: false,
            last_size: None,
            control,
        }
    }

    /// Runs the interactive loop until `exit`.
    pub fn run(&mut self) -> SessionOutcome {
        enable_raw_mode().expect("raw mode");
        let _ = crossterm::execute!(std::io::stdout(), crossterm::event::EnableMouseCapture);
        let _guard = RestoreTerminal;
        crate::host::spawn_render_watcher(
            Arc::clone(self.terminal.model()),
            Arc::clone(&self.in_command),
            Arc::clone(&self.host_lock),
            Arc::clone(&self.last_version),
            Arc::clone(&self.render_stop),
        );
        // History lives in the shell (one authority, shared with the
        // `history` builtin); the prompt editor navigates it and the
        // session records each completed line through the shell.
        let mut history_index = self.shell.history().len();
        let mut last_status = 0u8;

        // Re-sync the model to the host terminal's actual size before the
        // first frame. Terminals can report a default or intermediate size
        // for a moment after launch (a Ghostty split reports the settled
        // pane size only once the window finishes laying out), so poll until
        // two consecutive reads agree, then sync.
        let mut previous_size: Option<(u16, u16)> = None;
        for _ in 0..30 {
            if self.control.interruption().is_some() {
                break;
            }
            self.sync_terminal_size();
            let current = crossterm::terminal::size().ok();
            if previous_size == current && current.is_some_and(|(cols, rows)| rows > 0 && cols > 0)
            {
                break;
            }
            previous_size = current;
            std::thread::sleep(SIZE_SETTLE_POLL);
        }
        self.sync_terminal_size();

        // The shell's banner (the `Last login` line on Unix, PowerShell's
        // copyright banner on Windows) before the first prompt.
        if let Some(banner) = self.shell.banner() {
            let banner = banner.replace('\n', "\r\n");
            self.terminal.write(banner.as_bytes());
        }
        self.render();

        loop {
            if self.control.interruption().is_some() {
                break;
            }
            let mut pending = String::new();
            self.continuing = false;

            // Read the first line against the primary prompt. Keys typed
            // while the previous command ran are already in the model queue;
            // absorb them as type-ahead.
            self.render_prompt();
            let mut buffer: Vec<char> = Vec::new();
            self.drain_command_leftovers(&mut buffer);
            let line = match self.read_prompt_line(&mut buffer, &mut history_index) {
                Some(line) => line,
                None => break,
            };
            pending.push_str(&line);
            pending.push('\n');

            // Multi-line constructs (here documents, `if`/`while` spanning
            // lines) keep reading until the input parses.
            while self.shell.needs_continuation(&pending) {
                self.render_continuation_prompt();
                let mut continuation: Vec<char> = Vec::new();
                let next = match self.read_prompt_line(&mut continuation, &mut history_index) {
                    Some(next) => next,
                    None => break,
                };
                pending.push_str(&next);
                pending.push('\n');
            }
            // Record the completed line — the whole of a multi-line construct, not
            // its continuation chunks — as one history entry, exactly what
            // the user typed.
            self.shell.record_history(&pending);
            self.in_command.store(true, Ordering::Relaxed);
            let mut command_stdout = self.output.clone();
            let mut command_stderr = self.output.clone();
            // Commands read standard input from the virtual terminal: keys
            // typed during the command reach `cat`, `sh`, and friends as
            // the byte stream a real terminal would deliver.
            let mut command_stdin = crate::host::TerminalInput::new(&self.terminal);
            last_status = self
                .shell
                .execute_with_terminal(
                    &pending,
                    &mut command_stdin,
                    &mut command_stdout,
                    &mut command_stderr,
                    Some(&mut self.terminal),
                )
                .code();
            self.in_command.store(false, Ordering::Relaxed);
            // The editor's arrow-key recall follows the grown history.
            history_index = self.shell.history().len();
            // `exit [N]` ends the session with its status; the decision
            // belongs to the shell language, not to input matching.
            if let Some(status) = self.shell.take_exit_status() {
                last_status = status.code();
                break;
            }
            self.render();
        }
        // Restore the normal screen before leaving.
        self.terminal.leave_alternate_screen();
        self.terminal.write(b"\r\n");
        self.render();
        // Stop the render watcher so the session's threads do not outlive
        // the session (library embedders may run many sessions).
        self.render_stop.store(true, Ordering::Relaxed);
        self.control
            .interruption()
            .map_or(SessionOutcome::Exited(i32::from(last_status)), Into::into)
    }

    /// Reads one line with the prompt editor; returns `None` on exit.
    ///
    /// Character keys echo into the model as they are typed.
    fn read_prompt_line(
        &mut self,
        buffer: &mut Vec<char>,
        history_index: &mut usize,
    ) -> Option<String> {
        loop {
            // Waiting for a key doubles as a resize poll: `COLUMNS`/`LINES`
            // follow the host terminal, so `ls` and friends always lay out
            // against the live width.
            let key = match self.keys.recv_timeout(KEY_WAIT) {
                Ok(key) => key,
                Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                    if self.control.interruption().is_some() {
                        return None;
                    }
                    self.sync_terminal_size();
                    continue;
                }
                Err(_) => return None,
            };
            // Tab completion is a prompt-level feature (it needs the
            // shell's filesystem), handled here rather than in the
            // stateless key editor.
            if key.key == Key::Tab {
                self.complete(buffer);
                let text: String = buffer.iter().collect();
                self.redraw_prompt_line(&text);
                continue;
            }
            match edit_prompt_key(&key, buffer, self.shell.history(), history_index) {
                EditAction::Echo => {
                    let text: String = buffer.iter().collect();
                    self.redraw_prompt_line(&text);
                }
                EditAction::Accept => {
                    // Sync the terminal size before the command runs, so
                    // `COLUMNS`/`LINES` are never stale for the command
                    // (for example `ls` layout after a resize).
                    self.sync_terminal_size();
                    let line: String = buffer.drain(..).collect();
                    self.terminal.write(b"\r\n");
                    self.render();
                    return Some(line);
                }
                EditAction::Exit => return None,
                EditAction::Ignore => {}
            }
        }
    }

    /// Moves keys left in the model queue (typed while a command ran but not
    /// consumed) back to the prompt editor, providing type-ahead.
    ///
    /// Routing keys into the model queue during a command means keys the
    /// command never consumed (for example a Ctrl+D typed during `man`)
    /// would otherwise be lost; they return to the prompt channel instead.
    fn drain_command_leftovers(&mut self, buffer: &mut Vec<char>) {
        let mut keys = Vec::new();
        {
            let mut model = self.terminal.model().lock().expect("model lock poisoned");
            while let Some(key) = model.next_key() {
                keys.push(key);
            }
        }
        for key in keys {
            if key.key == Key::Character && !key.ctrl && !key.alt {
                if let Some(ch) = key.character {
                    buffer.push(ch);
                }
            } else {
                let _ = self.keys_out.send(key);
            }
        }
    }

    /// Completes the word under the cursor (the last word of the buffer)
    /// against the virtual filesystem, replacing it in place. When the word
    /// is the first word and no file matches, command names from `PATH` are
    /// offered, like the real shells.
    fn complete(&mut self, buffer: &mut Vec<char>) {
        let text: String = buffer.iter().collect();
        let word_start = {
            let mut in_single = false;
            let mut in_double = false;
            let mut last_sep: Option<usize> = None;
            for (idx, ch) in text.char_indices() {
                match ch {
                    '\'' if !in_double => in_single = !in_single,
                    '"' if !in_single => in_double = !in_double,
                    ' ' | '\t' | '=' | ':' | ';' | '&' | '|' if !in_single && !in_double => {
                        last_sep = Some(idx + 1)
                    }
                    _ => {}
                }
            }
            last_sep.unwrap_or(0)
        };
        let word: String = text[word_start..].chars().collect();
        if word.is_empty() {
            return;
        }
        let (quote_char, word_inner) = if word.starts_with('"') {
            (Some('"'), word.strip_prefix('"').unwrap().to_owned())
        } else if word.starts_with('\'') {
            (Some('\''), word.strip_prefix('\'').unwrap().to_owned())
        } else {
            (None, word.clone())
        };
        let word_inner = word_inner
            .strip_suffix('"')
            .or_else(|| word_inner.strip_suffix('\''))
            .unwrap_or(&word_inner)
            .to_owned();
        let separator = if self.shell.name() == "powershell" {
            "\\"
        } else {
            "/"
        };
        let (directory, prefix) = match word_inner.rfind(separator) {
            Some(slash) => (
                word_inner[..slash].to_owned(),
                word_inner[slash + 1..].to_owned(),
            ),
            None => (String::new(), word_inner.clone()),
        };
        let environment = self.shell.environment();
        let mut base: Option<VirtualPath> = None;
        if directory.is_empty() {
            base = Some(self.shell.cwd().clone());
        } else if let Some(rest) = directory.strip_prefix("~/") {
            if let Some(home) = environment.get("HOME")
                && let Ok(home_path) = home.parse::<VirtualPath>()
                && let Ok(joined) = resolve_path_name(rest, &home_path)
            {
                base = Some(joined);
            }
        } else if directory == "~" {
            base = environment
                .get("HOME")
                .and_then(|home| home.parse::<VirtualPath>().ok());
        } else if let Ok(resolved) = resolve_path_name(&directory, self.shell.cwd()) {
            base = Some(resolved);
        }
        let Some(base) = base else {
            return;
        };

        let actor = Some(self.shell.actor());
        let engine = self.shell.engine();
        let Ok(base_object) = engine.lookup(actor, &base) else {
            return;
        };
        let Ok(entries) = engine.list(actor, base_object) else {
            return;
        };
        let mut matches: Vec<String> = entries
            .into_iter()
            .filter(|(name, _)| name.as_str().starts_with(&prefix))
            .map(|(name, _)| name.as_str().to_owned())
            .collect();
        matches.sort();
        if matches.is_empty() {
            // No file matches; for the first word, offer command names.
            if word_start == 0
                && let Some(command) = self.complete_command(&prefix)
            {
                buffer.extend(command.chars());
            }
            return;
        }

        // A unique match completes fully, with a trailing slash when it is
        // a directory; several matches complete to their common prefix.
        // If the completion contains whitespace, quote it so the shell
        // sees one word. When the common prefix makes no progress, show
        // the candidates instead of completing to an invalid name.
        let completed_raw = if matches.len() == 1 {
            let name = matches[0].clone();
            let is_directory = engine::Name::new(&name)
                .ok()
                .and_then(|entry| {
                    let object = engine.lookup(actor, &base.join(&entry)).ok()?;
                    Some(engine.children(actor, object).is_ok())
                })
                .unwrap_or(false);
            if is_directory {
                format!("{name}{separator}")
            } else {
                name
            }
        } else {
            let p = common_prefix(&matches);
            if p == prefix {
                // No progress — show the candidates like real shells do on
                // second Tab, instead of leaving an invalid prefix.
                let mut display = String::new();
                display.push_str("\r\n");
                for (idx, name) in matches.iter().enumerate() {
                    display.push_str(name);
                    if idx + 1 < matches.len() {
                        display.push_str("  ");
                    }
                }
                display.push_str("\r\n");
                self.terminal.write(display.as_bytes());
                self.render();
                return;
            }
            p
        };
        // Quote completions that contain whitespace so the shell sees one
        // word. PowerShell and bash both accept double quotes.
        let needs_quote = completed_raw.contains(' ') && quote_char.is_none();
        let completed = if needs_quote {
            format!("\"{}\"", completed_raw)
        } else {
            completed_raw
        };
        let replacement = if let Some(q) = quote_char {
            // Word was already quoted (e.g. "Pro) — keep the opening quote
            // and ensure the replacement stays quoted.
            let inner = completed.trim_matches('"').trim_matches('\'').to_owned();
            let dir_part = if directory.is_empty() {
                String::new()
            } else {
                format!("{directory}{separator}")
            };
            format!("{q}{dir_part}{inner}{q}")
        } else if directory.is_empty() {
            completed
        } else {
            format!("{directory}{separator}{completed}")
        };
        buffer.truncate(word_start);
        buffer.extend(replacement.chars());
    }

    /// Completes the first word as a command name from `PATH`, returning
    /// the longest common prefix of the candidates (or `None` when nothing
    /// matches).
    fn complete_command(&self, prefix: &str) -> Option<String> {
        let actor = Some(self.shell.actor());
        let engine = self.shell.engine();
        let mut candidates: Vec<String> = Vec::new();
        for directory in self.shell.environment().path_entries() {
            let Ok(object) = engine.lookup(actor, &directory) else {
                continue;
            };
            let Ok(entries) = engine.list(actor, object) else {
                continue;
            };
            for (name, _) in entries {
                if name.as_str().starts_with(prefix) {
                    candidates.push(name.as_str().to_owned());
                }
            }
        }
        if candidates.is_empty() {
            return None;
        }
        candidates.sort();
        candidates.dedup();
        if candidates.len() == 1 {
            return Some(candidates[0].clone());
        }
        let shared = common_prefix(&candidates);
        if shared.len() > prefix.len() {
            Some(shared)
        } else {
            None
        }
    }

    /// The virtual host name, from the shell's OS.
    fn hostname(&self) -> String {
        self.shell.hostname()
    }

    /// Syncs the model and the shell's `COLUMNS`/`LINES` to the host
    /// terminal's actual size.
    ///
    /// The size is tracked here rather than via the model, so `COLUMNS` is
    /// exported on every real change even if the render watcher already
    /// resized the model.
    fn sync_terminal_size(&mut self) {
        let Ok((cols, rows)) = crossterm::terminal::size() else {
            return;
        };
        if rows == 0 || cols == 0 {
            return;
        }
        if self.last_size == Some((rows, cols)) {
            return;
        }
        self.last_size = Some((rows, cols));
        self.terminal
            .model()
            .lock()
            .expect("model lock poisoned")
            .resize(Size::new(rows, cols));
        self.shell.set_terminal_size(rows, cols);
        self.render();
    }

    /// Writes the prompt and current input into the model and repaints.
    fn render_prompt(&mut self) {
        let prompt = self.shell.prompt(&self.hostname());
        self.terminal.write(prompt.as_bytes());
        self.render();
    }

    /// Repaints the prompt line after an edit.
    fn redraw_prompt_line(&mut self, text: &str) {
        // Erase the whole prompt region — including rows the prompt text
        // wrapped across — then re-write it, so wide input never leaves
        // stale fragments behind (screen state stays coherent).
        let model = self.terminal.model();
        let mut model = model.lock().expect("model lock poisoned");
        let prompt = if self.continuing {
            "> ".to_owned()
        } else {
            self.shell.prompt(&self.hostname())
        };
        let full = format!("{prompt}{text}");
        let cols = usize::from(model.visible_screen().size().cols).max(1);
        let rows = full.chars().count().div_ceil(cols).max(1);
        let (cursor_row, _) = model.visible_screen().cursor();
        let first_row = (usize::from(cursor_row) + 1).saturating_sub(rows) as u16;
        for offset in 0..rows {
            let clear_row = first_row + u16::try_from(offset).unwrap_or(0);
            model.visible_screen_mut().move_cursor(clear_row, 0);
            model
                .visible_screen_mut()
                .erase(terminal::screen::EraseMode::WholeLine);
        }
        model.visible_screen_mut().move_cursor(first_row, 0);
        model.write(full.as_bytes());
        drop(model);
        self.render();
    }

    /// Renders the secondary (`> `) continuation prompt.
    fn render_continuation_prompt(&mut self) {
        self.continuing = true;
        self.terminal.write(b"> ");
        self.render();
    }

    /// Repaints the host screen if the model changed.
    ///
    /// Painting happens through the shared host lock, so frames from the
    /// main thread and the render watcher never interleave.
    fn render(&mut self) {
        let model = self.terminal.model().lock().expect("model lock poisoned");
        let mut version = self.last_version.lock().expect("version lock poisoned");
        if let Ok(mut host) = self.host_lock.try_lock() {
            let _ = render(&mut host, &model, &mut version);
        }
    }
}

/// What the prompt editor did with a key.
enum EditAction {
    /// The input changed; redraw it.
    Echo,
    /// Accept the line.
    Accept,
    /// Leave the shell.
    Exit,
    /// Nothing to do.
    Ignore,
}

/// Edits the prompt input buffer from a virtual key event.
///
/// `history` is read-only: up/down-arrow recall navigates the shell's
/// authoritative history; the session records accepted lines through
/// [`Shell::record_history`].
fn edit_prompt_key(
    key: &KeyEvent,
    buffer: &mut Vec<char>,
    history: &[String],
    history_index: &mut usize,
) -> EditAction {
    if key.ctrl && key.character == Some('c') {
        // Ctrl+C: cancel the current line.
        buffer.clear();
        return EditAction::Echo;
    }
    if key.ctrl && key.character == Some('d') && buffer.is_empty() {
        return EditAction::Exit;
    }
    match key.key {
        Key::Character => {
            if let Some(ch) = key.character {
                if !key.ctrl && !key.alt {
                    buffer.push(ch);
                    EditAction::Echo
                } else {
                    EditAction::Ignore
                }
            } else {
                EditAction::Ignore
            }
        }
        Key::Enter => EditAction::Accept,
        Key::Backspace => {
            buffer.pop();
            EditAction::Echo
        }
        Key::ArrowUp => {
            if *history_index > 0 {
                *history_index -= 1;
                buffer.clear();
                buffer.extend(history[*history_index].chars());
                EditAction::Echo
            } else {
                EditAction::Ignore
            }
        }
        Key::ArrowDown => {
            if *history_index + 1 < history.len() {
                *history_index += 1;
                buffer.clear();
                buffer.extend(history[*history_index].chars());
                EditAction::Echo
            } else {
                buffer.clear();
                EditAction::Echo
            }
        }
        _ => EditAction::Ignore,
    }
}

/// Restores the host terminal on drop.
struct RestoreTerminal;

impl Drop for RestoreTerminal {
    fn drop(&mut self) {
        let _ = crossterm::execute!(
            std::io::stdout(),
            crossterm::event::DisableMouseCapture,
            crossterm::cursor::Show
        );
        let _ = disable_raw_mode();
    }
}

/// Runs scripted line mode with cooperative control checks between commands.
pub fn run_line_mode_controlled<R: Read + Send + Sync>(
    shell: &mut dyn Shell,
    input: &mut R,
    control: &SessionControl,
) -> SessionOutcome {
    let mut stdout = std::io::stdout();
    let mut stderr = std::io::stderr();
    let status = run_lines(
        shell,
        input,
        &mut StdoutWriter(&mut stdout),
        &mut StdoutWriter(&mut stderr),
        Some(control),
    );
    control
        .interruption()
        .map_or(SessionOutcome::Exited(status), Into::into)
}

/// The line-mode core, over generic streams (testable).
fn run_lines<R: Read + Send + Sync>(
    shell: &mut dyn Shell,
    input: &mut R,
    stdout: &mut dyn engine::Output,
    stderr: &mut dyn engine::Output,
    control: Option<&SessionControl>,
) -> i32 {
    let mut reader = std::io::BufReader::new(input);
    let mut last_status = 0u8;
    let mut pending = String::new();
    let mut line = String::new();
    loop {
        if control.is_some_and(|control| control.interruption().is_some()) {
            break;
        }
        line.clear();
        match reader.read_line(&mut line) {
            Ok(0) => break,
            Ok(_) => {}
            Err(_) => break,
        }
        pending.push_str(&line);
        if shell.needs_continuation(&pending) {
            continue;
        }
        let trimmed = pending.trim();
        // Commands share the script's reader, so stdin-driven tools read
        // the script itself: `sudo -S` takes the following line as its
        // password, like a real scripted shell.
        let status = shell.execute(trimmed, &mut ReadInput(&mut reader), stdout, stderr);
        last_status = status.code();
        pending.clear();
        // `exit [N]` ends the session with its status.
        if let Some(exit_status) = shell.take_exit_status() {
            last_status = exit_status.code();
            break;
        }
    }
    if !pending.trim().is_empty() {
        let _ = stderr.write(b"bash: syntax error: incomplete input\n");
    }
    i32::from(last_status)
}

/// Adapts a host writer to an [`engine::Output`].
struct StdoutWriter<'a, W: Write + Send + Sync>(&'a mut W);

impl<W: Write + Send + Sync> engine::Output for StdoutWriter<'_, W> {
    fn write(&mut self, bytes: &[u8]) -> Result<(), engine::OutputError> {
        self.0.write_all(bytes).map_err(engine::OutputError::Io)
    }
}
/// The longest common character prefix of the candidates.
fn common_prefix(candidates: &[String]) -> String {
    let Some(first) = candidates.first() else {
        return String::new();
    };
    let mut prefix = first.clone();
    for candidate in candidates.iter().skip(1) {
        while !candidate.starts_with(&prefix) {
            prefix.pop();
        }
        if prefix.is_empty() {
            break;
        }
    }
    prefix
}

/// An [`engine::Input`] over a byte reader (line mode, scripts, tests).
///
/// Commands receive the session's own reader, so stdin-driven commands
/// read the script's remaining input — the real behavior of a scripted
/// shell. Commands that never read stdin are unaffected.
struct ReadInput<'a, R: std::io::Read + Send + Sync>(&'a mut R);

impl<R: std::io::Read + Send + Sync> Input for ReadInput<'_, R> {
    fn read(&mut self, buffer: &mut [u8]) -> Result<usize, engine::InputError> {
        self.0.read(buffer).map_err(engine::InputError::Io)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use engine::{BytesOutput, Timestamp};
    use os::HostIdentity;
    use os::linux::Linux;

    fn shell() -> Box<dyn Shell + 'static> {
        let linux = Box::leak(Box::new(
            Linux::with_identity(
                &HostIdentity::new("demo", "demo-host"),
                Timestamp::from_nanos(1_000_000),
            )
            .unwrap(),
        ));
        let credentials = linux
            .unix()
            .users()
            .authenticate("demo", "demo", linux.unix().groups())
            .unwrap();
        Box::new(shell::bash::Bash::new(linux.unix(), credentials).unwrap())
    }

    #[test]
    fn line_mode_runs_commands_and_reports_status() {
        let mut shell = shell();
        let input = "ls /tmp\necho hi > /tmp/lm.txt && cat /tmp/lm.txt\nexit\n";
        let mut stdout = BytesOutput::new();
        let mut stderr = BytesOutput::new();
        let status = run_lines(
            &mut *shell,
            &mut std::io::Cursor::new(input),
            &mut stdout,
            &mut stderr,
            None,
        );
        assert_eq!(status, 0);
        let output = String::from_utf8(stdout.into_bytes()).unwrap();
        assert!(
            output.contains("hi\n"),
            "redirection output flows: {output:?}"
        );
    }

    #[test]
    fn line_mode_buffers_heredocs_across_lines() {
        let mut shell = shell();
        let input = "cat <<EOF > /tmp/heredoc.txt\nbody line\nEOF\ncat /tmp/heredoc.txt\nexit\n";
        let mut stdout = BytesOutput::new();
        let mut stderr = BytesOutput::new();
        let status = run_lines(
            &mut *shell,
            &mut std::io::Cursor::new(input),
            &mut stdout,
            &mut stderr,
            None,
        );
        assert_eq!(status, 0);
        let output = String::from_utf8(stdout.into_bytes()).unwrap();
        assert!(output.contains("body line"), "heredoc content: {output:?}");
    }

    #[test]
    fn line_mode_propagates_failure_status() {
        let mut shell = shell();
        let input = "false\n";
        let mut stdout = BytesOutput::new();
        let mut stderr = BytesOutput::new();
        let status = run_lines(
            &mut *shell,
            &mut std::io::Cursor::new(input),
            &mut stdout,
            &mut stderr,
            None,
        );
        assert_eq!(status, 1);
    }

    #[test]
    fn powershell_cd_backslash_no_leading_space() {
        let windows = Box::leak(Box::new(
            os::windows::Windows::with_identity(
                &HostIdentity::new("demo", "demo-host"),
                Timestamp::from_nanos(1_000_000),
            )
            .unwrap(),
        ));
        let actor = windows.authenticate("demo", "demo").unwrap();
        let mut shell: Box<dyn Shell> = Box::new(
            shell::powershell::PowerShell::new(windows, actor, windows.environment().clone())
                .unwrap(),
        );
        let input = "cd C:\\Windows\ncd \\\npwd\n";
        let mut stdout = BytesOutput::new();
        let mut stderr = BytesOutput::new();
        run_lines(
            &mut *shell,
            &mut std::io::Cursor::new(input),
            &mut stdout,
            &mut stderr,
            None,
        );
        let out = String::from_utf8_lossy(stdout.bytes()).to_string();
        let err = String::from_utf8_lossy(stderr.bytes()).to_string();
        assert!(
            !err.contains("C:\\npwd") && !out.contains("C:\\npwd"),
            "should not have npwd error, out={out} err={err}"
        );
        // pwd after cd \ should be root
        assert!(
            out.contains("C:\\") || shell.cwd().to_string() == "/",
            "cwd should be root, out={out} cwd={}",
            shell.cwd()
        );
    }

    #[test]
    fn powershell_cd_variants_via_run_lines() {
        let windows = Box::leak(Box::new(
            os::windows::Windows::with_identity(
                &HostIdentity::new("demo", "demo-host"),
                Timestamp::from_nanos(1_000_000),
            )
            .unwrap(),
        ));
        let actor = windows.authenticate("demo", "demo").unwrap();
        let mut shell: Box<dyn Shell> = Box::new(
            shell::powershell::PowerShell::new(windows, actor, windows.environment().clone())
                .unwrap(),
        );
        let input = "pwd\ncd C:\\Windows\npwd\ncd \\\npwd\ncd\\\npwd\ncd C:\\\npwd\ncd ..\npwd\n";
        let mut stdout = BytesOutput::new();
        let mut stderr = BytesOutput::new();
        run_lines(
            &mut *shell,
            &mut std::io::Cursor::new(input),
            &mut stdout,
            &mut stderr,
            None,
        );
        let out = String::from_utf8_lossy(stdout.bytes()).to_string();
        let err = String::from_utf8_lossy(stderr.bytes()).to_string();
        println!("OUT: {}", out);
        println!("ERR: {}", err);
        println!("CWD: {}", shell.cwd());
        assert!(
            !err.contains("npwd"),
            "should not have npwd error, err={err}"
        );
    }

    #[test]
    fn common_prefix_of_candidates() {
        assert_eq!(
            common_prefix(&["fruits.txt".to_owned(), "fruits.log".to_owned()]),
            "fruits."
        );
        assert_eq!(common_prefix(&["a.txt".to_owned(), "b.txt".to_owned()]), "");
        assert_eq!(common_prefix(&["only".to_owned()]), "only");
    }

    #[test]
    fn powershell_cd_backslash_in_line_mode() {
        let windows = Box::leak(Box::new(
            os::windows::Windows::with_identity(
                &HostIdentity::new("demo", "demo-host"),
                Timestamp::from_nanos(1_000_000),
            )
            .unwrap(),
        ));
        let actor = windows.authenticate("demo", "demo").unwrap();
        let mut shell: Box<dyn Shell> = Box::new(
            shell::powershell::PowerShell::new(windows, actor, windows.environment().clone())
                .unwrap(),
        );
        // cd to subdir then back to root via cd \
        let input = "cd C:\\Windows\npwd\ncd \\\n pwd\n";
        let mut stdout = BytesOutput::new();
        let mut stderr = BytesOutput::new();
        let status = run_lines(
            &mut *shell,
            &mut std::io::Cursor::new(input),
            &mut stdout,
            &mut stderr,
            None,
        );
        let out = String::from_utf8_lossy(stdout.bytes()).to_string();
        // Should have two pwds: first C:\Windows, second C:\ (root)
        assert!(out.contains("C:\\Windows"), "first pwd: {out}");
        assert!(
            out.contains("C:\\\n") || out.contains("C:\\\r\n") || out.trim().ends_with("C:"),
            "second pwd should be root, got: {out} stderr: {}",
            String::from_utf8_lossy(stderr.bytes())
        );
        assert_eq!(status, 0);
    }
}