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::{AppHandle, Emitter, Manager, State}; use crate::workspace::{current_root_path, WorkspaceError, WorkspaceState}; use crate::terminal_platform::find_executable; type PtyResult = Result; fn err(msg: impl Into) -> WorkspaceError { WorkspaceError::from_message(msg) } pub struct PtyState { inner: Mutex>, } struct OpenPty { owner: String, integration_file: Option, master: Box, writer: Mutex>, 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 { pub fn close_window(&self, label: &str) { if let Ok(mut sessions) = self.inner.lock() { sessions.retain(|_, session| session.owner != label); } } 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, } type ShellProcess = ( OpenPty, Box, Box, ); #[derive(Clone, Serialize)] pub struct ShellProfile { id: String, title: String, kind: String, #[serde(skip)] executable: PathBuf, } #[tauri::command] pub fn pty_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) -> PtyResult { 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(|e| err(e.to_string()))?; let profiles = pty_profiles(); let selected = profiles.iter().find(|p| profile.map_or(p.kind != "node", |id| p.id == id)) .ok_or_else(|| err("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); } "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(err("Unsupported shell profile")), } cmd.cwd(&root); cmd.env("TERM", "xterm-256color"); cmd.env("COLORTERM", "truecolor"); let reader = pair .master .try_clone_reader() .map_err(|e| err(e.to_string()))?; let writer = pair.master.take_writer().map_err(|e| err(e.to_string()))?; let child = pair .slave .spawn_command(cmd) .map_err(|e| err(e.to_string()))?; drop(pair.slave); let session = OpenPty { owner: owner.into(), integration_file, master: pair.master, writer: Mutex::new(writer), killer: child.clone_killer(), }; Ok((session, reader, child)) } #[tauri::command] pub fn pty_open( app: AppHandle, window: tauri::Window, workspace: State, pty: State, id: String, cols: u16, rows: u16, cwd: String, profile: Option, directory: Option, ) -> PtyResult<()> { let root = current_root_path(&workspace, window.label())?; if root.to_string_lossy() != cwd { return Err(err("workspace changed before the terminal started")); } let mut guard = pty.inner.lock().map_err(|_| err("pty lock"))?; if guard.contains_key(&id) { return Err(err("terminal already exists")); } let directory = directory.map(PathBuf::from).unwrap_or(root); if !directory.is_dir() { return Err(err("Terminal working directory does not exist")); } let (session, mut reader, mut child) = spawn_shell(&directory, cols, rows, profile.as_deref(), window.label())?; 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 app_reader = app.clone(); let reader_id = id.clone(); thread::spawn(move || { let mut buf = [0u8; 4096]; loop { match reader.read(&mut buf) { Ok(0) => break, Ok(n) => { let data = buf[..n].to_vec(); let _ = app_reader.emit( "pty-data", PtyData { id: reader_id.clone(), data, }, ); } Err(_) => break, } } let code = exit_rx.recv().ok().flatten(); let _ = app_reader.emit( "pty-exit", PtyExit { id: reader_id, code, }, ); }); Ok(()) } #[tauri::command] pub fn pty_write(pty: State, id: String, data: String) -> PtyResult<()> { let guard = pty.inner.lock().map_err(|_| err("pty lock"))?; let session = guard.get(&id).ok_or_else(|| err("terminal is not open"))?; let mut writer = session.writer.lock().map_err(|_| err("pty writer lock"))?; writer .write_all(data.as_bytes()) .map_err(|e| err(e.to_string()))?; writer.flush().ok(); Ok(()) } #[tauri::command] pub fn pty_resize(pty: State, id: String, cols: u16, rows: u16) -> PtyResult<()> { let guard = pty.inner.lock().map_err(|_| err("pty lock"))?; let session = guard.get(&id).ok_or_else(|| err("terminal is not open"))?; session .master .resize(PtySize { rows: rows.max(2), cols: cols.max(2), pixel_width: 0, pixel_height: 0, }) .map_err(|e| err(e.to_string()))?; Ok(()) } #[tauri::command] pub fn pty_close(pty: State, id: String) -> PtyResult<()> { let mut guard = pty.inner.lock().map_err(|_| err("pty lock"))?; let session = guard.remove(&id); drop(guard); drop(session); Ok(()) } #[tauri::command] pub async fn pty_new_window(app: AppHandle, window: tauri::Window, workspace: State<'_, WorkspaceState>, id: String) -> PtyResult<()> { let root = current_root_path(&workspace, window.label())?; if !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { return Err(err("Invalid window ID")); } let mut url = tauri::Url::parse("http://localhost/").map_err(|e| err(e.to_string()))?; 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(err("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(|e| err(e.to_string())); if result.is_err() { workspace.close_window(&label); } result?; Ok(()) } #[tauri::command] pub fn pty_dictation() -> PtyResult<()> { #[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(err("Use your operating system's dictation shortcut with the terminal focused.")) } } #[cfg(test)] mod tests { use super::*; use std::time::{Duration, Instant}; #[test] fn installed_profiles_start_and_report_shell_prompts() { let root = dunce::canonicalize(std::env::current_dir().unwrap()).unwrap(); for profile in pty_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)); } } }