//! The integrated terminal: `terminal.create`, `terminal.input`, //! `terminal.resize` and `terminal.close`, and the events //! `terminalOutput` and `terminalExited`. //! //! Each terminal is a [`lutra_terminal::Session`]: a shell in a pseudo //! terminal whose reading, writing and waiting happen on threads of its own, //! so no command blocks the engine lock on the shell. Output waits in the //! session's bounded buffer (backpressure when full, see the crate) until //! [`crate::Engine::pump_vfs`] calls [`pump`], which emits one //! `terminalOutput` per terminal with at most [`MAX_OUTPUT_PER_TERMINAL`] //! bytes, at most [`MAX_OUTPUT_PER_PUMP`] bytes over all terminals //! (round-robin, so one busy terminal cannot starve the others). With the //! desktop's pump every 100 ms that caps the stream at about 2.5 MB/s; the //! shell waits when it writes faster. `terminalExited` follows the last //! output of a shell that ended. //! //! Terminals belong to the project open when they were created: closing the //! project (or opening another) closes them ([`sync_project`], run after //! every command and every pump), and so does `app.quit` ([`close_all`]). //! A terminal closed by Lutra reports `terminalExited` with `code: null`. use std::collections::BTreeMap; use std::ops::Bound; use std::path::{Path, PathBuf}; use lutra_terminal::{Session, Shell, SpawnOptions, TerminalError}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use crate::cmd::params::parse; use crate::{Command, CommandSpec, EngineError, Event, Outcome, State}; /// Most terminals open at once. pub const MAX_TERMINALS: usize = 16; /// Most bytes of input one `terminal.input` takes. pub const MAX_INPUT_BYTES: usize = 1 << 20; /// Most bytes of output one pump emits for one terminal. pub const MAX_OUTPUT_PER_TERMINAL: usize = 64 * 1024; /// Most bytes of output one pump emits over all terminals. pub const MAX_OUTPUT_PER_PUMP: usize = 256 * 1024; /// Events of the terminal, appended to [`Event`] untagged: each serialises /// with its own `kind`. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[serde( tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase" )] pub enum TerminalEvent { /// Output of a terminal, as UTF-8 text with the shell's escape /// sequences; at most [`MAX_OUTPUT_PER_TERMINAL`] bytes. TerminalOutput { /// The terminal, as `terminal.create` returned it. terminal_id: u64, /// The text; never empty. data: String, }, /// A terminal ended: its shell exited or Lutra closed it. No events for /// it follow. TerminalExited { /// The terminal. terminal_id: u64, /// The shell's exit code; `null` when Lutra closed the terminal or /// the code is unknown. code: Option, }, } /// The open terminals. #[derive(Debug, Default)] pub struct Terminals { /// The id of the last terminal created; ids are never reused. last_id: u64, /// The terminal the last pump emitted output for first; the next pump /// starts after it. cursor: u64, /// Open terminals by id. sessions: BTreeMap, } impl Terminals { /// Number of open terminals. pub fn len(&self) -> usize { self.sessions.len() } /// Whether no terminal is open. pub fn is_empty(&self) -> bool { self.sessions.is_empty() } } /// One open terminal. #[derive(Debug)] struct Running { /// The shell. session: Session, /// Root of the project it belongs to. root: PathBuf, } /// Root of the open project. fn project_root(state: &State) -> Option { state .project .as_ref() .map(|w| w.project.root().to_path_buf()) } /// An engine error for a session error of command `id`. fn session_error(id: &str, e: TerminalError) -> EngineError { match e { TerminalError::InvalidSize { .. } => EngineError::invalid_params(id, e.to_string()), _ => EngineError::Failed(e.to_string()), } } /// The open terminal `terminal_id`. fn running<'a>(state: &'a State, id: &str, terminal_id: u64) -> Result<&'a Running, EngineError> { state .terminals .sessions .get(&terminal_id) .ok_or_else(|| EngineError::invalid_params(id, format!("no terminal {terminal_id}"))) } /// Params of `terminal.create`. #[derive(Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] struct CreateParams { /// Working directory: project-relative or absolute. cwd: Option, /// Program to run instead of the default shell. shell: Option, /// Columns. cols: u16, /// Rows. rows: u16, } /// `terminal.create`: starts a shell in a new terminal. pub struct Create; impl Command for Create { fn spec(&self) -> &CommandSpec { &CommandSpec { id: "terminal.create", label: "New Terminal", menu_path: None, default_shortcut: None, params: "{ cwd? (project-relative or absolute directory, default the project root), shell? (program name or path; default pwsh, then powershell, then cmd on Windows, $SHELL or /bin/sh elsewhere), cols, rows (1..=1000) }; returns { terminalId }, then events terminalOutput { terminalId, data } and terminalExited { terminalId, code }; at most 16 terminals", } } fn enabled(&self, state: &State) -> bool { state.has_project() } fn run(&self, state: &mut State, params: Value) -> Result { let id = self.spec().id; let p: CreateParams = parse(id, params)?; if state.terminals.sessions.len() >= MAX_TERMINALS { return Err(EngineError::Failed(format!( "at most {MAX_TERMINALS} terminals can be open" ))); } let root = project_root(state).ok_or_else(|| EngineError::Disabled(id.to_string()))?; let cwd = match p.cwd.as_deref() { None | Some("") => root.clone(), Some(dir) => root.join(Path::new(dir)), }; if !cwd.is_dir() { return Err(EngineError::invalid_params( id, format!("{} is not a directory", cwd.display()), )); } let shell = match p.shell.as_deref() { None | Some("") => lutra_terminal::default_shell(), Some(program) => Shell::new( lutra_terminal::find_in_path(program).unwrap_or_else(|| PathBuf::from(program)), ), }; let session = Session::spawn(SpawnOptions { shell, cwd, cols: p.cols, rows: p.rows, env: Vec::new(), }) .map_err(|e| session_error(id, e))?; let terminals = &mut state.terminals; terminals.last_id = terminals.last_id.saturating_add(1); let terminal_id = terminals.last_id; terminals .sessions .insert(terminal_id, Running { session, root }); Ok(Outcome::value(json!({ "terminalId": terminal_id }))) } } /// Params of `terminal.input`. #[derive(Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] struct InputParams { /// The terminal. terminal_id: u64, /// Keys or pasted text, as xterm.js sends them. data: String, } /// `terminal.input`: sends input to a terminal's shell. pub struct Input; impl Command for Input { fn spec(&self) -> &CommandSpec { &CommandSpec { id: "terminal.input", label: "Terminal Input", menu_path: None, default_shortcut: None, params: "{ terminalId, data (at most 1 MiB) }; returns null; failed when the shell has exited or is not reading its input", } } fn run(&self, state: &mut State, params: Value) -> Result { let id = self.spec().id; let p: InputParams = parse(id, params)?; if p.data.len() > MAX_INPUT_BYTES { return Err(EngineError::invalid_params( id, format!("at most {MAX_INPUT_BYTES} bytes of input per call"), )); } running(state, id, p.terminal_id)? .session .write(p.data.as_bytes()) .map_err(|e| session_error(id, e))?; Ok(Outcome::default()) } } /// Params of `terminal.resize`. #[derive(Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] struct ResizeParams { /// The terminal. terminal_id: u64, /// Columns. cols: u16, /// Rows. rows: u16, } /// `terminal.resize`: changes a terminal's size. pub struct Resize; impl Command for Resize { fn spec(&self) -> &CommandSpec { &CommandSpec { id: "terminal.resize", label: "Resize Terminal", menu_path: None, default_shortcut: None, params: "{ terminalId, cols, rows (1..=1000) }; returns null", } } fn run(&self, state: &mut State, params: Value) -> Result { let id = self.spec().id; let p: ResizeParams = parse(id, params)?; running(state, id, p.terminal_id)? .session .resize(p.cols, p.rows) .map_err(|e| session_error(id, e))?; Ok(Outcome::default()) } } /// Params of `terminal.close`. #[derive(Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] struct CloseParams { /// The terminal. terminal_id: u64, } /// `terminal.close`: kills a terminal's shell. pub struct Close; impl Command for Close { fn spec(&self) -> &CommandSpec { &CommandSpec { id: "terminal.close", label: "Close Terminal", menu_path: None, default_shortcut: None, params: "{ terminalId }; returns { closed }: false if the terminal already ended; a closed terminal reports terminalExited { code: null }", } } fn run(&self, state: &mut State, params: Value) -> Result { let p: CloseParams = parse(self.spec().id, params)?; let closed = close(state, p.terminal_id); Ok(Outcome::value(json!({ "closed": closed }))) } } /// Kills terminal `terminal_id`, drops its buffered output and emits /// `terminalExited {code: null}`. /// /// # Returns /// Whether the terminal was open. fn close(state: &mut State, terminal_id: u64) -> bool { let Some(mut running) = state.terminals.sessions.remove(&terminal_id) else { return false; }; running.session.kill(); state.emit(Event::Terminal(TerminalEvent::TerminalExited { terminal_id, code: None, })); true } /// Closes every terminal, for `app.quit`. pub fn close_all(state: &mut State) { let ids: Vec = state.terminals.sessions.keys().copied().collect(); for terminal_id in ids { close(state, terminal_id); } } /// Closes the terminals of a project that is no longer open. pub fn sync_project(state: &mut State) { let root = project_root(state); let stale: Vec = state .terminals .sessions .iter() .filter(|(_, r)| root.as_ref() != Some(&r.root)) .map(|(&id, _)| id) .collect(); for terminal_id in stale { close(state, terminal_id); } } /// Moves buffered output into `terminalOutput` events and reports ended /// shells with `terminalExited`; see the module documentation for the caps. /// Closes the terminals of a project that is no longer open first. pub fn pump(state: &mut State) { sync_project(state); let terminals = &mut state.terminals; let cursor = terminals.cursor; let order: Vec = terminals .sessions .range((Bound::Excluded(cursor), Bound::Unbounded)) .chain(terminals.sessions.range(..=cursor)) .map(|(&id, _)| id) .collect(); let mut budget = MAX_OUTPUT_PER_PUMP; let mut events = Vec::new(); let mut ended = Vec::new(); let mut first = None; for terminal_id in order { let Some(running) = terminals.sessions.get(&terminal_id) else { continue; }; if budget > 0 { let data = running .session .take_output(budget.min(MAX_OUTPUT_PER_TERMINAL)); if !data.is_empty() { budget = budget.saturating_sub(data.len()); first.get_or_insert(terminal_id); events.push(TerminalEvent::TerminalOutput { terminal_id, data }); } } if let Some(exit) = running.session.exit() { events.push(TerminalEvent::TerminalExited { terminal_id, code: exit.code, }); ended.push(terminal_id); } } if let Some(first) = first { terminals.cursor = first; } for terminal_id in ended { terminals.sessions.remove(&terminal_id); } for event in events { state.emit(Event::Terminal(event)); } } #[cfg(test)] mod tests { use serde_json::json; use super::TerminalEvent; use crate::Event; #[test] fn event_shapes() { let e = Event::Terminal(TerminalEvent::TerminalOutput { terminal_id: 1, data: "hi\r\n".into(), }); assert_eq!( serde_json::to_value(e).unwrap(), json!({"kind": "terminalOutput", "terminalId": 1, "data": "hi\r\n"}) ); let e = Event::Terminal(TerminalEvent::TerminalExited { terminal_id: 1, code: Some(3), }); assert_eq!( serde_json::to_value(e).unwrap(), json!({"kind": "terminalExited", "terminalId": 1, "code": 3}) ); let e = Event::Terminal(TerminalEvent::TerminalExited { terminal_id: 2, code: None, }); assert_eq!( serde_json::to_value(e).unwrap(), json!({"kind": "terminalExited", "terminalId": 2, "code": null}) ); } }