//! Shell sessions for the native Terminal feature of RuneStone (`src/lib/features/terminal/`). use std::collections::{HashMap, VecDeque}; use std::io::{Read, Write}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, RecvTimeoutError}; use std::sync::Mutex; use std::thread; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize}; use serde::Serialize; use tauri::ipc::{Channel, InvokeResponseBody, JavaScriptChannelId}; use tauri::{AppHandle, Manager, State}; use crate::error::{Error, Result}; use crate::workspace::{current_root, WorkspaceState}; use crate::terminal_platform::find_executable; /// The largest output message in bytes. const BATCH_BYTES: usize = 64 * 1024; /// The longest time that output waits for more output before it goes to the webview. const BATCH_WAIT: Duration = Duration::from_millis(8); /// The number of retired page IDs that each window keeps. const RETIRED_PAGES: usize = 16; const NOT_OPEN: &str = "terminal is not open"; const RETIRED_PAGE: &str = "terminal page is no longer active"; pub struct PtyState { inner: Mutex, } #[derive(Default)] struct Sessions { open: HashMap, /// The page IDs of each window, by window label. pages: HashMap, } /// The page loads of one window. Each page load of the frontend makes a new page ID. #[derive(Default)] struct Pages { current: String, retired: VecDeque, } struct OpenPty { owner: String, /// A unique number for this session. A session ID can come back after a reload. serial: u64, integration_file: Option, master: Box, writer: std::sync::Arc>>, killer: Box, } impl Drop for OpenPty { fn drop(&mut self) { let _ = self.killer.kill(); if let Some(path) = &self.integration_file { let _ = std::fs::remove_file(path); } } } impl PtyState { /// Close the window's terminals and forget its pages. Remove the terminals under the lock, /// then stop the shells outside it. pub fn close_window(&self, label: &str) { let closed: Vec = match self.inner.lock() { Ok(mut sessions) => { sessions.pages.remove(label); take_window(&mut sessions.open, label) } Err(_) => return, }; drop(closed); } pub fn close_all(&self) { let sessions = self .inner .lock() .ok() .map(|mut sessions| std::mem::take(&mut *sessions)); drop(sessions); } pub fn new() -> Self { Self { inner: Mutex::new(Sessions::default()), } } } /// Remove the sessions of one window from the map. The caller stops them outside the lock. fn take_window(open: &mut HashMap, owner: &str) -> Vec { let ids: Vec = open.iter().filter(|(_, session)| session.owner == owner).map(|(id, _)| id.clone()).collect(); ids.iter().filter_map(|id| open.remove(id)).collect() } /// The number of open sessions of all windows. fn running(pty: &PtyState) -> Result { Ok(pty.inner.lock().map_err(|_| Error::new("pty lock"))?.open.len()) } /// A page ID has 1 to 64 ASCII letters, digits, and hyphens. fn check_page(page: &str) -> Result<()> { if page.is_empty() || page.len() > 64 || !page.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { return Err(Error::new("Invalid terminal page ID")); } Ok(()) } /// Apply the page rule to an open request of the window `owner`. A new page is a reload of /// the window. It retires the current page and returns the sessions of the earlier page. /// The caller stops them outside the lock. A retired page gets an error, so a late request /// of an old page cannot close the sessions of the new page. fn enter_page(sessions: &mut Sessions, owner: &str, page: &str) -> Result> { let Some(pages) = sessions.pages.get_mut(owner) else { sessions.pages.insert(owner.to_owned(), Pages { current: page.to_owned(), retired: VecDeque::new() }); return Ok(Vec::new()); }; if pages.current == page { return Ok(Vec::new()); } if pages.retired.iter().any(|retired| retired == page) { return Err(Error::new(RETIRED_PAGE)); } let earlier = std::mem::replace(&mut pages.current, page.to_owned()); pages.retired.push_back(earlier); while pages.retired.len() > RETIRED_PAGES { pages.retired.pop_front(); } Ok(take_window(&mut sessions.open, owner)) } /// The destination of the output and the exit status of one terminal session. trait PtyOutput: Send { fn data(&self, bytes: &[u8]); fn exit(&self, code: Option); } /// A channel to the webview that opened the session. Output goes as raw bytes (an /// `ArrayBuffer` in JavaScript). The exit status goes as `{ "exit": code }`. struct ChannelOutput(Channel); impl PtyOutput for ChannelOutput { fn data(&self, bytes: &[u8]) { let _ = self.0.send(InvokeResponseBody::Raw(bytes.to_vec())); } fn exit(&self, code: Option) { let _ = self.0.send(InvokeResponseBody::Json(serde_json::json!({ "exit": code }).to_string())); } } /// Read the PTY until EOF and send each read to `chunks`. fn read_chunks(mut reader: impl Read, chunks: std::sync::mpsc::Sender>) { let mut buf = vec![0u8; 16 * 1024]; loop { match reader.read(&mut buf) { Ok(0) | Err(_) => break, Ok(n) => { if chunks.send(buf[..n].to_vec()).is_err() { break; } } } } } /// Join the output chunks into messages, then send the exit status. A message starts with /// the first chunk that arrives. It collects more chunks until `wait` after that chunk or /// until `max_bytes`. A chunk that does not fit starts the next message. A chunk larger than /// `max_bytes` goes in parts. When the reader stops, the loop sends the rest of the output /// and then the exit status. fn pump(chunks: Receiver>, exit: Receiver>, output: &dyn PtyOutput, max_bytes: usize, wait: Duration) { let max_bytes = max_bytes.max(1); let mut next: Option> = None; loop { let mut message = match next.take() { Some(chunk) => chunk, None => match chunks.recv() { Ok(chunk) => chunk, Err(_) => break, }, }; let deadline = Instant::now() + wait; let mut ended = false; while message.len() < max_bytes { let now = Instant::now(); if now >= deadline { break; } match chunks.recv_timeout(deadline - now) { Ok(chunk) if message.len() + chunk.len() > max_bytes => { next = Some(chunk); break; } Ok(chunk) => message.extend(chunk), Err(RecvTimeoutError::Timeout) => break, Err(RecvTimeoutError::Disconnected) => { ended = true; break; } } } for part in message.chunks(max_bytes) { output.data(part); } if ended { break; } } output.exit(exit.recv().ok().flatten()); } type ShellProcess = ( OpenPty, Box, Box, ); #[derive(Clone, Serialize)] pub struct ShellProfile { id: String, title: String, kind: String, #[serde(skip)] executable: PathBuf, } /// The installed shells. The search reads `PATH` folders, so it runs on a blocking worker. #[tauri::command] pub async fn pty_profiles() -> Result> { Ok(tauri::async_runtime::spawn_blocking(profiles).await?) } fn profiles() -> Vec { let candidates = if cfg!(windows) { vec![("powershell", "PowerShell", "powershell", "powershell.exe"), ("pwsh", "PowerShell 7", "powershell", "pwsh.exe"), ("cmd", "Command Prompt", "cmd", "cmd.exe"), ("node", "JavaScript Debug Terminal", "node", "node.exe")] } else { vec![("bash", "Bash", "bash", "bash"), ("pwsh", "PowerShell", "powershell", "pwsh"), ("node", "JavaScript Debug Terminal", "node", "node")] }; let mut profiles: Vec<_> = candidates.into_iter().filter_map(|(id, title, kind, exe)| { find_executable(exe).map(|executable| ShellProfile { id: id.into(), title: title.into(), kind: kind.into(), executable }) }).collect(); if cfg!(windows) { let mut paths = Vec::new(); for variable in ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"] { if let Some(base) = std::env::var_os(variable) { paths.push(PathBuf::from(&base).join("Git/bin/bash.exe")); paths.push(PathBuf::from(base).join("Programs/Git/bin/bash.exe")); } } if let Some(git) = find_executable("git.exe") { if let Some(base) = git.parent().and_then(Path::parent) { paths.push(base.join("bin/bash.exe")); } } if let Some(executable) = paths.into_iter().find(|path| path.is_file()) { profiles.insert(1.min(profiles.len()), ShellProfile { id: "git-bash".into(), title: "Git Bash".into(), kind: "bash".into(), executable }); } } profiles } // Prompt hooks report executed commands and directories rather than recording keystrokes // (which could include passwords entered into a child application). const POWERSHELL_INTEGRATION: &str = r#" $global:__rsHistory = -1 $global:__rsOriginalPrompt = $function:prompt function global:prompt { $esc = [char]27; $bel = [char]7 $h = Get-History -Count 1 if ($h -and $h.Id -ne $global:__rsHistory) { $global:__rsHistory = $h.Id $b = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($h.CommandLine)) [Console]::Write("${esc}]633;RSCommand;${b}${bel}") } $b = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($pwd.Path)) [Console]::Write("${esc}]633;RSCwd;${b}${bel}${esc}]133;A${bel}") $p = if ($global:__rsOriginalPrompt) { & $global:__rsOriginalPrompt } else { "PS $pwd> " } "${p}${esc}]133;B${bel}" } "#; const BASH_INTEGRATION: &str = r#"__rs_prompt() { local entry entry="$(HISTTIMEFORMAT= builtin history 1)" if [[ "$entry" != "$__rs_last_history" ]]; then __rs_last_history="$entry" entry="$(printf '%s' "$entry" | sed 's/^ *[0-9]* *//')" [[ -n "$entry" ]] && printf '\033]633;RSCommand;%s\007' "$(printf '%s' "$entry" | base64 | tr -d '\r\n')" fi printf '\033]633;RSCwd;%s\007\033]133;A\007' "$(printf '%s' "$(pwd -W 2>/dev/null || printf '%s' "$PWD")" | base64 | tr -d '\r\n')" } __rs_last_history="$(HISTTIMEFORMAT= builtin history 1)" PROMPT_COMMAND=("${PROMPT_COMMAND[@]}" __rs_prompt) PS1="${PS1}"'\[\e]133;B\a\]' "#; fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner: &str) -> Result { let system = native_pty_system(); let pair = system .openpty(PtySize { rows: rows.max(2), cols: cols.max(2), pixel_width: 0, pixel_height: 0, }) .map_err(Error::from_display)?; let profiles = profiles(); let selected = profiles.iter().find(|p| profile.map_or(p.kind != "node", |id| p.id == id)) .ok_or_else(|| Error::new("The selected shell is not installed. Select another terminal profile."))?; let mut cmd = CommandBuilder::new(&selected.executable); let mut integration_file = None; match selected.kind.as_str() { "powershell" => { cmd.args(["-NoLogo", "-NoExit", "-Command", POWERSHELL_INTEGRATION]); } "bash" => { // Use a private integration rc file; the user's bashrc still runs first. let directory = std::env::temp_dir().join("runestone-shell"); std::fs::create_dir_all(&directory)?; static NEXT_RC: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let sequence = NEXT_RC.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let rc = directory.join(format!("bashrc-{}-{sequence}", std::process::id())); std::fs::write(&rc, format!("[[ -f ~/.bashrc ]] && source ~/.bashrc\n{BASH_INTEGRATION}"))?; cmd.args(["--init-file", &rc.to_string_lossy().replace('\\', "/"), "-i"]); integration_file = Some(rc); } // The cmd prompt cannot encode base64, so it reports the folder as plain text with `Cwd`. // The Terminal feature reads both `Cwd` (plain) and `RSCwd` (base64). A Windows path // cannot contain the escape or bell characters that end the sequence. "cmd" => { cmd.args(["/D", "/K", "prompt $E]633;Cwd;$P$E\\$E]133;A$E\\$P$G$E]133;B$E\\"]); } "node" => { cmd.args(["--inspect=127.0.0.1:0", "-i"]); } _ => return Err(Error::new("Unsupported shell profile")), } cmd.cwd(root); cmd.env("TERM", "xterm-256color"); cmd.env("COLORTERM", "truecolor"); let reader = pair .master .try_clone_reader() .map_err(Error::from_display)?; let writer = pair.master.take_writer().map_err(Error::from_display)?; let child = pair .slave .spawn_command(cmd) .map_err(Error::from_display)?; drop(pair.slave); static NEXT_SERIAL: AtomicU64 = AtomicU64::new(0); let session = OpenPty { owner: owner.into(), serial: NEXT_SERIAL.fetch_add(1, Ordering::Relaxed), integration_file, master: pair.master, writer: std::sync::Arc::new(Mutex::new(writer)), killer: child.clone_killer(), }; Ok((session, reader, child)) } /// Start a shell on a blocking worker, because the start creates a process and files. #[tauri::command] #[allow(clippy::too_many_arguments)] pub async fn pty_open( app: AppHandle, window: tauri::Window, webview: tauri::Webview, workspace: State<'_, WorkspaceState>, id: String, page: String, cols: u16, rows: u16, cwd: String, profile: Option, directory: Option, channel: JavaScriptChannelId, ) -> Result<()> { check_page(&page)?; let root = current_root(&workspace, window.label())?; if root.to_string_lossy() != cwd { return Err(Error::new("workspace changed before the terminal started")); } let owner = window.label().to_owned(); let output = ChannelOutput(channel.channel_on(webview)); let request = OpenRequest { owner, page, id, cols, rows, profile, directory: directory.map(PathBuf::from).unwrap_or(root) }; tauri::async_runtime::spawn_blocking(move || open(app, request, output)).await? } struct OpenRequest { owner: String, page: String, id: String, cols: u16, rows: u16, profile: Option, directory: PathBuf, } /// Apply the page rule and start the shell under one lock, so two opens cannot race. fn open(app: AppHandle, request: OpenRequest, output: impl PtyOutput + 'static) -> Result<()> { let pty = app.state::(); let (left, started) = { let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?; let left = enter_page(&mut guard, &request.owner, &request.page)?; (left, start(&mut guard, &request)) }; // A reload left these sessions. Stop their shells outside the lock. drop(left); let (serial, reader, mut child) = started?; let (exit_tx, exit_rx) = std::sync::mpsc::channel(); let wait_app = app.clone(); let wait_id = request.id; thread::spawn(move || { let code = child.wait().ok().map(|status| status.exit_code()); // Close ConPTY after the shell exits so the output reader reaches EOF. // A later session can use the same ID, so remove only this session. let session = wait_app .state::() .inner .lock() .ok() .and_then(|mut sessions| match sessions.open.get(&wait_id) { Some(session) if session.serial == serial => sessions.open.remove(&wait_id), _ => None, }); drop(session); let _ = exit_tx.send(code); }); let (chunk_tx, chunk_rx) = std::sync::mpsc::channel(); thread::spawn(move || read_chunks(reader, chunk_tx)); thread::spawn(move || pump(chunk_rx, exit_rx, &output, BATCH_BYTES, BATCH_WAIT)); Ok(()) } type StartedShell = (u64, Box, Box); /// Start the shell and insert its session. The caller holds the lock. fn start(sessions: &mut Sessions, request: &OpenRequest) -> Result { if sessions.open.contains_key(&request.id) { return Err(Error::new("terminal already exists")); } if !request.directory.is_dir() { return Err(Error::new("Terminal working directory does not exist")); } let (session, reader, child) = spawn_shell(&request.directory, request.cols, request.rows, request.profile.as_deref(), &request.owner)?; let serial = session.serial; sessions.open.insert(request.id.clone(), session); Ok((serial, reader, child)) } /// Find a session of the window `owner`. A session of another window gives the same error /// as a missing session. fn owned<'a>(sessions: &'a Sessions, owner: &str, id: &str) -> Result<&'a OpenPty> { sessions.open.get(id).filter(|session| session.owner == owner).ok_or_else(|| Error::new(NOT_OPEN)) } /// Write input on a blocking worker. A shell that does not read its input can fill the pipe, /// and the write then waits. The Terminal feature waits for each write before the next one. #[tauri::command] pub async fn pty_write(app: AppHandle, window: tauri::Window, id: String, data: String) -> Result<()> { let owner = window.label().to_owned(); tauri::async_runtime::spawn_blocking(move || write(&app.state::(), &owner, &id, &data)).await? } fn write(pty: &PtyState, owner: &str, id: &str, data: &str) -> Result<()> { let writer = { let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?; owned(&guard, owner, id)?.writer.clone() }; // Other terminals stay usable while this write waits. let mut writer = writer.lock().map_err(|_| Error::new("pty writer lock"))?; writer .write_all(data.as_bytes()) .map_err(Error::from_display)?; writer.flush().ok(); Ok(()) } #[tauri::command] pub fn pty_resize(pty: State, window: tauri::Window, id: String, cols: u16, rows: u16) -> Result<()> { resize(&pty, window.label(), &id, cols, rows) } fn resize(pty: &PtyState, owner: &str, id: &str, cols: u16, rows: u16) -> Result<()> { let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?; owned(&guard, owner, id)? .master .resize(PtySize { rows: rows.max(2), cols: cols.max(2), pixel_width: 0, pixel_height: 0, }) .map_err(Error::from_display)?; Ok(()) } /// Stop a shell on a blocking worker. Closing a pseudo console can wait for its output. /// A missing session and a session of another window are not an error. Neither one closes. #[tauri::command] pub async fn pty_close(app: AppHandle, window: tauri::Window, id: String) -> Result<()> { let owner = window.label().to_owned(); tauri::async_runtime::spawn_blocking(move || { let session = close(&app.state::(), &owner, &id)?; drop(session); Ok(()) }) .await? } /// Remove a session of the window `owner` under the lock. The caller stops it outside the lock. fn close(pty: &PtyState, owner: &str, id: &str) -> Result> { let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?; if owned(&guard, owner, id).is_err() { return Ok(None); } Ok(guard.open.remove(id)) } /// The number of open terminals of all windows. The Settings window asks before Terminal /// goes off when shells run. #[tauri::command] pub fn pty_running(pty: State) -> Result { running(&pty) } #[tauri::command] pub async fn pty_new_window(app: AppHandle, window: tauri::Window, workspace: State<'_, WorkspaceState>, id: String) -> Result<()> { let root = current_root(&workspace, window.label())?; if !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { return Err(Error::new("Invalid window ID")); } let mut url = tauri::Url::parse("http://localhost/").map_err(Error::from_display)?; url.query_pairs_mut().append_pair("terminalWindow", &root.to_string_lossy()); let label = format!("terminal-{id}"); if app.get_webview_window(&label).is_some() { return Err(Error::new("Terminal window already exists")); } workspace.bind_terminal(&label, root)?; let result = tauri::WebviewWindowBuilder::new(&app, &label, tauri::WebviewUrl::App(format!("?{}", url.query().unwrap_or_default()).into())) .title("RuneStone — Terminal").inner_size(1000.0, 650.0).min_inner_size(500.0, 300.0).build() .map_err(Error::from_display); if result.is_err() { workspace.close_window(&label); } result?; Ok(()) } #[tauri::command] pub fn pty_dictation() -> Result<()> { #[cfg(windows)] { use windows_sys::Win32::UI::Input::KeyboardAndMouse::{keybd_event, KEYEVENTF_KEYUP, VK_LWIN}; // The frontend focuses xterm before invoking Windows voice typing. unsafe { keybd_event(VK_LWIN as u8, 0, 0, 0); keybd_event(b'H', 0, 0, 0); keybd_event(b'H', 0, KEYEVENTF_KEYUP, 0); keybd_event(VK_LWIN as u8, 0, KEYEVENTF_KEYUP, 0); } Ok(()) } #[cfg(not(windows))] { Err(Error::new("Use your operating system's dictation shortcut with the terminal focused.")) } } #[cfg(test)] mod tests { use super::*; use std::sync::Arc; use std::time::{Duration, Instant}; #[derive(Debug, PartialEq)] enum Sent { Data(Vec), Exit(Option), } /// Records the messages that a session sends. #[derive(Clone, Default)] struct Recorder(Arc>>); impl PtyOutput for Recorder { fn data(&self, bytes: &[u8]) { self.0.lock().unwrap().push(Sent::Data(bytes.to_vec())); } fn exit(&self, code: Option) { self.0.lock().unwrap().push(Sent::Exit(code)); } } impl Recorder { fn take(&self) -> Vec { std::mem::take(&mut *self.0.lock().unwrap()) } } type Pump = (std::sync::mpsc::Sender>, std::sync::mpsc::Sender>, Recorder, thread::JoinHandle<()>); /// Run the batch loop on its own thread. The test sends the chunks and the exit status. fn start_pump(max_bytes: usize, wait: Duration) -> Pump { let (chunk_tx, chunk_rx) = std::sync::mpsc::channel(); let (exit_tx, exit_rx) = std::sync::mpsc::channel(); let recorder = Recorder::default(); let output = recorder.clone(); let handle = thread::spawn(move || pump(chunk_rx, exit_rx, &output, max_bytes, wait)); (chunk_tx, exit_tx, recorder, handle) } fn data_sizes(sent: &[Sent]) -> Vec { sent.iter().filter_map(|message| match message { Sent::Data(bytes) => Some(bytes.len()), Sent::Exit(_) => None }).collect() } #[test] fn small_chunks_within_the_wait_become_one_message() { let (chunks, exit, recorder, handle) = start_pump(BATCH_BYTES, Duration::from_secs(5)); for _ in 0..100 { chunks.send(b"ab".to_vec()).unwrap(); } drop(chunks); exit.send(Some(0)).unwrap(); handle.join().unwrap(); assert_eq!(recorder.take(), vec![Sent::Data(b"ab".repeat(100)), Sent::Exit(Some(0))]); } #[test] fn output_larger_than_the_limit_becomes_several_messages() { let (chunks, exit, recorder, handle) = start_pump(BATCH_BYTES, Duration::from_secs(5)); let mut expected: Vec = Vec::new(); for index in 0..40u8 { let chunk = vec![index; 4000]; expected.extend(&chunk); chunks.send(chunk).unwrap(); } // One chunk larger than the limit goes in parts. let large = vec![b'x'; BATCH_BYTES + 100]; expected.extend(&large); chunks.send(large).unwrap(); drop(chunks); exit.send(None).unwrap(); handle.join().unwrap(); let sent = recorder.take(); let sizes = data_sizes(&sent); assert!(sizes.len() > 1, "{sizes:?}"); assert!(sizes.iter().all(|&size| size > 0 && size <= BATCH_BYTES), "{sizes:?}"); let joined: Vec = sent.iter().flat_map(|message| match message { Sent::Data(bytes) => bytes.clone(), Sent::Exit(_) => Vec::new() }).collect(); assert_eq!(joined, expected); assert_eq!(sent.last(), Some(&Sent::Exit(None))); } #[test] fn a_chunk_after_a_pause_goes_in_a_new_message() { let (chunks, exit, recorder, handle) = start_pump(BATCH_BYTES, Duration::from_millis(20)); chunks.send(b"first".to_vec()).unwrap(); thread::sleep(Duration::from_millis(300)); chunks.send(b"second".to_vec()).unwrap(); drop(chunks); exit.send(Some(1)).unwrap(); handle.join().unwrap(); assert_eq!(recorder.take(), vec![Sent::Data(b"first".to_vec()), Sent::Data(b"second".to_vec()), Sent::Exit(Some(1))]); } #[test] fn the_exit_comes_after_all_output() { let (chunks, exit, recorder, handle) = start_pump(16, Duration::from_secs(5)); // The exit status is ready before the output ends. exit.send(Some(9)).unwrap(); for _ in 0..10 { chunks.send(b"0123456789".to_vec()).unwrap(); } drop(chunks); handle.join().unwrap(); let sent = recorder.take(); assert_eq!(data_sizes(&sent).iter().sum::(), 100); assert!(data_sizes(&sent).iter().all(|&size| size <= 16)); assert_eq!(sent.iter().position(|message| matches!(message, Sent::Exit(_))), Some(sent.len() - 1)); assert_eq!(sent.last(), Some(&Sent::Exit(Some(9)))); } #[test] fn a_channel_session_sends_raw_bytes_then_the_json_exit() { let received = Arc::new(Mutex::new(Vec::new())); let sink = received.clone(); let channel = Channel::new(move |body| { sink.lock().unwrap().push(body); Ok(()) }); let (chunk_tx, chunk_rx) = std::sync::mpsc::channel(); let (exit_tx, exit_rx) = std::sync::mpsc::channel(); exit_tx.send(Some(3)).unwrap(); read_chunks(std::io::Cursor::new(b"hello \xce\xbb".to_vec()), chunk_tx); pump(chunk_rx, exit_rx, &ChannelOutput(channel), BATCH_BYTES, BATCH_WAIT); let received = received.lock().unwrap(); assert_eq!(received.len(), 2); match &received[0] { InvokeResponseBody::Raw(bytes) => assert_eq!(bytes, b"hello \xce\xbb"), InvokeResponseBody::Json(json) => panic!("output must be raw bytes, not JSON: {json}"), } match &received[1] { InvokeResponseBody::Json(json) => assert_eq!(serde_json::from_str::(json).unwrap(), serde_json::json!({ "exit": 3 })), InvokeResponseBody::Raw(_) => panic!("the exit status must be JSON"), } } /// Start a real shell for `owner`. A thread reads its output until EOF. fn shell(owner: &str) -> OpenPty { let root = std::env::current_dir().unwrap(); let (session, mut reader, _child) = spawn_shell(&root, 80, 24, None, owner).unwrap(); thread::spawn(move || { let _ = std::io::copy(&mut reader, &mut std::io::sink()); }); session } fn ids(pty: &PtyState) -> Vec { let mut ids: Vec = pty.inner.lock().unwrap().open.keys().cloned().collect(); ids.sort(); ids } #[test] fn only_the_owner_window_can_use_a_session() { let pty = PtyState::new(); pty.inner.lock().unwrap().open.insert("t1".into(), shell("a")); assert_eq!(write(&pty, "b", "t1", "\r").unwrap_err().to_string(), NOT_OPEN); assert_eq!(resize(&pty, "b", "t1", 100, 40).unwrap_err().to_string(), NOT_OPEN); assert!(close(&pty, "b", "t1").unwrap().is_none()); assert_eq!(ids(&pty), vec!["t1"]); // A missing session gives the same results. assert_eq!(write(&pty, "a", "t2", "\r").unwrap_err().to_string(), NOT_OPEN); assert_eq!(resize(&pty, "a", "t2", 100, 40).unwrap_err().to_string(), NOT_OPEN); assert!(close(&pty, "a", "t2").unwrap().is_none()); write(&pty, "a", "t1", "\r").unwrap(); resize(&pty, "a", "t1", 100, 40).unwrap(); let session = close(&pty, "a", "t1").unwrap(); assert!(session.is_some()); assert!(ids(&pty).is_empty()); drop(session); } #[test] fn a_new_page_closes_the_sessions_of_its_window_only() { let pty = PtyState::new(); let enter = |owner: &str, page: &str| enter_page(&mut pty.inner.lock().unwrap(), owner, page); // The first page of each window becomes current. assert!(enter("a", "page-1").unwrap().is_empty()); assert!(enter("b", "page-b").unwrap().is_empty()); { let mut sessions = pty.inner.lock().unwrap(); sessions.open.insert("a1".into(), shell("a")); sessions.open.insert("b1".into(), shell("b")); } // A second dock of the same page keeps the sessions. assert!(enter("a", "page-1").unwrap().is_empty()); assert_eq!(ids(&pty), vec!["a1", "b1"]); // A reload of window "a" closes its sessions. The session of window "b" stays. let left = enter("a", "page-2").unwrap(); assert_eq!(left.iter().map(|session| session.owner.as_str()).collect::>(), vec!["a"]); drop(left); assert_eq!(ids(&pty), vec!["b1"]); // A late open of the old page is refused and closes nothing. pty.inner.lock().unwrap().open.insert("a2".into(), shell("a")); assert_eq!(enter("a", "page-1").err().map(|error| error.to_string()).as_deref(), Some(RETIRED_PAGE)); assert_eq!(ids(&pty), vec!["a2", "b1"]); // The window forgets its pages when it closes. pty.close_window("a"); assert_eq!(ids(&pty), vec!["b1"]); assert!(!pty.inner.lock().unwrap().pages.contains_key("a")); assert!(enter("a", "page-1").unwrap().is_empty()); pty.close_all(); assert!(ids(&pty).is_empty()); assert!(pty.inner.lock().unwrap().pages.is_empty()); } #[test] fn a_window_keeps_a_limited_number_of_retired_pages() { let mut sessions = Sessions::default(); for index in 0..=RETIRED_PAGES + 4 { assert!(enter_page(&mut sessions, "a", &format!("page-{index}")).unwrap().is_empty()); } let pages = &sessions.pages["a"]; assert_eq!(pages.retired.len(), RETIRED_PAGES); assert_eq!(pages.current, format!("page-{}", RETIRED_PAGES + 4)); assert!(enter_page(&mut sessions, "a", &format!("page-{}", RETIRED_PAGES + 3)).is_err()); } #[test] fn page_ids_are_checked() { assert!(check_page("0f3c-9a1b").is_ok()); assert!(check_page(&"a".repeat(64)).is_ok()); for page in ["", "a b", "../page", "page_1", "λ"] { assert!(check_page(page).is_err(), "{page}"); } assert!(check_page(&"a".repeat(65)).is_err()); } #[test] fn running_counts_the_sessions_of_all_windows() { let pty = PtyState::new(); assert_eq!(running(&pty).unwrap(), 0); { let mut sessions = pty.inner.lock().unwrap(); sessions.open.insert("a1".into(), shell("a")); sessions.open.insert("b1".into(), shell("b")); } assert_eq!(running(&pty).unwrap(), 2); pty.close_window("a"); assert_eq!(running(&pty).unwrap(), 1); pty.close_all(); assert_eq!(running(&pty).unwrap(), 0); } #[test] fn installed_profiles_start_and_report_shell_prompts() { let root = dunce::canonicalize(std::env::current_dir().unwrap()).unwrap(); for profile in profiles() { eprintln!("Checking {}", profile.title); let (session, mut reader, mut child) = spawn_shell(&root, 120, 30, Some(&profile.id), "profile-test").unwrap(); let (tx, rx) = std::sync::mpsc::channel(); thread::spawn(move || { let mut buffer = [0u8; 4096]; while let Ok(n) = reader.read(&mut buffer) { if n == 0 || tx.send(buffer[..n].to_vec()).is_err() { break; } } }); let deadline = Instant::now() + Duration::from_secs(15); let mut bytes = Vec::new(); let mut sent = false; loop { if let Ok(chunk) = rx.recv_timeout(Duration::from_millis(30)) { bytes.extend(chunk); if bytes.windows(4).any(|w| w == b"\x1b[6n") { session.writer.lock().unwrap().write_all(b"\x1b[1;1R").unwrap(); // Avoid answering this same query more than once. for i in 0..bytes.len().saturating_sub(3) { if &bytes[i..i+4] == b"\x1b[6n" { bytes[i] = b' '; } } } } let output = String::from_utf8_lossy(&bytes); let ready = if profile.kind == "node" { output.contains("Debugger listening") && output.contains('>') } else { output.contains("\x1b]133;B") }; if ready && !sent { let command = match profile.kind.as_str() { "powershell" => "Write-Output ('RS_' + 'PROFILE_OK')\r", "bash" => "printf 'RS_%s\\n' PROFILE_OK\r", "cmd" => "echo RS_PROFILE_OK\r", _ => "console.log('RS_' + 'PROFILE_OK')\r", }; session.writer.lock().unwrap().write_all(command.as_bytes()).unwrap(); sent = true; } let history = profile.kind != "powershell" && profile.kind != "bash" || output.contains("\x1b]633;RSCommand;"); if sent && output.contains("RS_PROFILE_OK") && history { break; } if Instant::now() > deadline { let _ = child.kill(); panic!("{} failed integration: {output}", profile.title); } } drop(session); } } #[test] fn real_shell_runs_in_project_and_drains_output_on_exit() { let root = dunce::canonicalize(std::env::current_dir().unwrap()).unwrap(); let (session, mut reader, mut child) = spawn_shell(&root, 120, 30, None, "test").unwrap(); let (tx, rx) = std::sync::mpsc::channel(); thread::spawn(move || { let mut buf = [0u8; 4096]; while let Ok(n) = reader.read(&mut buf) { if n == 0 { break; } if tx.send(buf[..n].to_vec()).is_err() { break; } } }); session .master .resize(PtySize { rows: 40, cols: 100, pixel_width: 0, pixel_height: 0, }) .unwrap(); let command = if cfg!(windows) { "(Get-Location).Path; [Console]::WriteLine([char]0x03BB); exit 7\r\n" } else { "pwd; printf '\\316\\273\\n'; exit 7\n" }; session .writer .lock() .unwrap() .write_all(command.as_bytes()) .unwrap(); let deadline = Instant::now() + Duration::from_secs(20); let mut bytes = Vec::new(); let status = loop { if let Ok(chunk) = rx.recv_timeout(Duration::from_millis(30)) { // A real xterm answers cursor-position queries from PSReadLine. if chunk.windows(4).any(|window| window == b"\x1b[6n") { session .writer .lock() .unwrap() .write_all(b"\x1b[1;1R") .unwrap(); } bytes.extend(chunk); } if let Some(status) = child.try_wait().unwrap() { break status; } if Instant::now() >= deadline { child.kill().unwrap(); panic!("shell failed to exit: {}", String::from_utf8_lossy(&bytes)); } }; drop(session); loop { match rx.recv_timeout(Duration::from_secs(5)) { Ok(chunk) => bytes.extend(chunk), Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, Err(_) => panic!("PTY reader did not reach EOF after shell exit"), } } let output = String::from_utf8(bytes).expect("terminal output must be UTF-8"); assert_eq!(status.exit_code(), 7); assert!( output.contains(root.to_string_lossy().as_ref()), "wrong working directory: {output}" ); assert!(output.contains('λ'), "Unicode output missing: {output}"); } #[test] fn dropping_a_session_terminates_its_shell() { let root = std::env::current_dir().unwrap(); let (session, mut reader, mut child) = spawn_shell(&root, 80, 24, None, "test").unwrap(); thread::spawn(move || { let _ = std::io::copy(&mut reader, &mut std::io::sink()); }); drop(session); let deadline = Instant::now() + Duration::from_secs(5); while child.try_wait().unwrap().is_none() { assert!(Instant::now() < deadline, "shell survived session disposal"); thread::sleep(Duration::from_millis(30)); } } }