use std::collections::HashMap; use std::io::{Read, Write}; use std::sync::Mutex; use std::thread; use std::path::{Path, PathBuf}; use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize}; use serde::Serialize; use tauri::ipc::{Channel, InvokeResponseBody, JavaScriptChannelId}; use tauri::{AppHandle, Emitter, Manager, State}; use crate::error::{Error, Result}; use crate::workspace::{current_root, WorkspaceState}; use crate::terminal_platform::find_executable; pub struct PtyState { inner: Mutex>, } struct OpenPty { owner: String, 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. Remove them 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) => { let ids: Vec = sessions.iter().filter(|(_, session)| session.owner == label).map(|(id, _)| id.clone()).collect(); ids.iter().filter_map(|id| sessions.remove(id)).collect() } 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(HashMap::new()), } } } #[derive(Clone, Serialize)] pub struct PtyData { pub id: String, // xterm owns UTF-8 decoding so multibyte characters split across reads survive. pub data: Vec, } #[derive(Clone, Serialize)] pub struct PtyExit { pub id: String, pub code: Option, } /// 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); } /// Window events for the released Terminal plugin, which listens for `pty-data` and `pty-exit`. /// The events go to the window that opened the session. A global `listen` in that window /// receives them. Tauri 2 also delivers an addressed event to a global `listen` in other windows. struct EventOutput { app: AppHandle, owner: String, id: String, } impl PtyOutput for EventOutput { fn data(&self, bytes: &[u8]) { let _ = self.app.emit_to(self.owner.as_str(), "pty-data", PtyData { id: self.id.clone(), data: bytes.to_vec() }); } fn exit(&self, code: Option) { let _ = self.app.emit_to(self.owner.as_str(), "pty-exit", PtyExit { id: self.id.clone(), code }); } } /// 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())); } } /// Use the channel when the caller supplies one. Without a channel, use window events. fn output(channel: Option>, events: impl FnOnce() -> Box) -> Box { match channel { Some(channel) => Box::new(ChannelOutput(channel)), None => events(), } } /// Send the output until the reader reaches EOF. Then send the exit status. fn pump(mut reader: impl Read, exit: std::sync::mpsc::Receiver>, output: &dyn PtyOutput) { let mut buf = [0u8; 4096]; loop { match reader.read(&mut buf) { Ok(0) | Err(_) => break, Ok(n) => output.data(&buf[..n]), } } 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 plugin 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); let session = OpenPty { owner: owner.into(), 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, cols: u16, rows: u16, cwd: String, profile: Option, directory: Option, channel: Option, ) -> Result<()> { 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(); // A session with a channel sends no `pty-data` or `pty-exit` events. let channel = channel.map(|channel| channel.channel_on(webview)); tauri::async_runtime::spawn_blocking(move || open(app, owner, root, id, cols, rows, profile, directory, channel)).await? } #[allow(clippy::too_many_arguments)] fn open( app: AppHandle, owner: String, root: PathBuf, id: String, cols: u16, rows: u16, profile: Option, directory: Option, channel: Option>, ) -> Result<()> { let pty = app.state::(); let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?; if guard.contains_key(&id) { return Err(Error::new("terminal already exists")); } let directory = directory.map(PathBuf::from).unwrap_or(root); if !directory.is_dir() { return Err(Error::new("Terminal working directory does not exist")); } let (session, reader, mut child) = spawn_shell(&directory, cols, rows, profile.as_deref(), &owner)?; guard.insert(id.clone(), session); drop(guard); let (exit_tx, exit_rx) = std::sync::mpsc::channel(); let wait_app = app.clone(); let wait_id = id.clone(); 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. let session = wait_app .state::() .inner .lock() .ok() .and_then(|mut sessions| sessions.remove(&wait_id)); drop(session); let _ = exit_tx.send(code); }); let output = output(channel, || Box::new(EventOutput { app: app.clone(), owner, id })); thread::spawn(move || pump(reader, exit_rx, output.as_ref())); Ok(()) } /// 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 plugin waits for each write before the next one. #[tauri::command] pub async fn pty_write(app: AppHandle, id: String, data: String) -> Result<()> { tauri::async_runtime::spawn_blocking(move || write(&app.state::(), &id, &data)).await? } fn write(pty: &PtyState, id: &str, data: &str) -> Result<()> { let writer = { let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?; let session = guard.get(id).ok_or_else(|| Error::new("terminal is not open"))?; session.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, id: String, cols: u16, rows: u16) -> Result<()> { let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?; let session = guard.get(&id).ok_or_else(|| Error::new("terminal is not open"))?; session .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. #[tauri::command] pub async fn pty_close(app: AppHandle, id: String) -> Result<()> { tauri::async_runtime::spawn_blocking(move || { let pty = app.state::(); let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?; let session = guard.remove(&id); drop(guard); drop(session); Ok(()) }) .await? } #[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}; /// Records the window events that a session would send. struct FakeEvents(Arc>>); impl PtyOutput for FakeEvents { fn data(&self, bytes: &[u8]) { self.0.lock().unwrap().push(format!("pty-data {}", String::from_utf8_lossy(bytes))); } fn exit(&self, code: Option) { self.0.lock().unwrap().push(format!("pty-exit {code:?}")); } } fn run_pump(channel: Option>, events: Arc>>) { let (exit_tx, exit_rx) = std::sync::mpsc::channel(); exit_tx.send(Some(3)).unwrap(); let output = output(channel, move || Box::new(FakeEvents(events))); pump(std::io::Cursor::new(b"hello \xce\xbb".to_vec()), exit_rx, output.as_ref()); } #[test] fn a_channel_session_sends_raw_bytes_and_no_window_events() { let events = Arc::new(Mutex::new(Vec::new())); let received = Arc::new(Mutex::new(Vec::new())); let sink = received.clone(); let channel = Channel::new(move |body| { sink.lock().unwrap().push(body); Ok(()) }); run_pump(Some(channel), events.clone()); assert!(events.lock().unwrap().is_empty(), "a channel session must not send pty-data or pty-exit events"); 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"), } } #[test] fn a_session_without_a_channel_keeps_the_window_events() { let events = Arc::new(Mutex::new(Vec::new())); run_pump(None, events.clone()); assert_eq!(*events.lock().unwrap(), vec!["pty-data hello λ".to_owned(), "pty-exit Some(3)".to_owned()]); } #[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)); } } }