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};
const SIZE_SETTLE_POLL: std::time::Duration = std::time::Duration::from_millis(100);
const KEY_WAIT: std::time::Duration = std::time::Duration::from_millis(250);
pub struct InteractiveSession<'os> {
shell: Box<dyn Shell + 'os>,
terminal: HostTerminal,
output: TerminalOutput,
keys: Receiver<KeyEvent>,
keys_out: Sender<KeyEvent>,
in_command: Arc<std::sync::atomic::AtomicBool>,
last_version: Arc<std::sync::Mutex<u64>>,
host_lock: Arc<std::sync::Mutex<std::io::Stdout>>,
render_stop: Arc<std::sync::atomic::AtomicBool>,
continuing: bool,
last_size: Option<(u16, u16)>,
control: SessionControl,
}
impl<'os> InteractiveSession<'os> {
pub fn new(shell: Box<dyn Shell + 'os>, control: SessionControl) -> Self {
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,
}
}
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),
);
let mut history_index = self.shell.history().len();
let mut last_status = 0u8;
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();
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;
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');
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');
}
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();
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);
history_index = self.shell.history().len();
if let Some(status) = self.shell.take_exit_status() {
last_status = status.code();
break;
}
self.render();
}
self.terminal.leave_alternate_screen();
self.terminal.write(b"\r\n");
self.render();
self.render_stop.store(true, Ordering::Relaxed);
self.control
.interruption()
.map_or(SessionOutcome::Exited(i32::from(last_status)), Into::into)
}
fn read_prompt_line(
&mut self,
buffer: &mut Vec<char>,
history_index: &mut usize,
) -> Option<String> {
loop {
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,
};
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 => {
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 => {}
}
}
}
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);
}
}
}
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() {
if word_start == 0
&& let Some(command) = self.complete_command(&prefix)
{
buffer.extend(command.chars());
}
return;
}
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 {
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
};
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 {
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());
}
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
}
}
fn hostname(&self) -> String {
self.shell.hostname()
}
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();
}
fn render_prompt(&mut self) {
let prompt = self.shell.prompt(&self.hostname());
self.terminal.write(prompt.as_bytes());
self.render();
}
fn redraw_prompt_line(&mut self, text: &str) {
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();
}
fn render_continuation_prompt(&mut self) {
self.continuing = true;
self.terminal.write(b"> ");
self.render();
}
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);
}
}
}
enum EditAction {
Echo,
Accept,
Exit,
Ignore,
}
fn edit_prompt_key(
key: &KeyEvent,
buffer: &mut Vec<char>,
history: &[String],
history_index: &mut usize,
) -> EditAction {
if key.ctrl && key.character == Some('c') {
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,
}
}
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();
}
}
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)
}
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();
let status = shell.execute(trimmed, &mut ReadInput(&mut reader), stdout, stderr);
last_status = status.code();
pending.clear();
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)
}
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)
}
}
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
}
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}"
);
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(),
);
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();
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);
}
}