feat(v2): add PTY backend with portable-pty

- Implement PtyManager: spawn, write, resize, kill operations
- Wire Tauri commands: pty_spawn, pty_write, pty_resize, pty_kill
- Reader thread streams PTY output via Tauri events (pty-data-{id})
- Process exit detection emits pty-exit-{id} event
- Add portable-pty 0.8 and uuid 1.0 dependencies
This commit is contained in:
Hibryda 2026-03-05 23:42:20 +01:00
parent 406683799b
commit f15e60be60
4 changed files with 384 additions and 17 deletions

View file

@ -1,16 +1,69 @@
mod pty;
mod sidecar;
mod watcher;
mod session;
use pty::{PtyManager, PtyOptions};
use std::sync::Arc;
use tauri::State;
struct AppState {
pty_manager: Arc<PtyManager>,
}
#[tauri::command]
fn pty_spawn(
app: tauri::AppHandle,
state: State<'_, AppState>,
options: PtyOptions,
) -> Result<String, String> {
state.pty_manager.spawn(&app, options)
}
#[tauri::command]
fn pty_write(state: State<'_, AppState>, id: String, data: String) -> Result<(), String> {
state.pty_manager.write(&id, &data)
}
#[tauri::command]
fn pty_resize(
state: State<'_, AppState>,
id: String,
cols: u16,
rows: u16,
) -> Result<(), String> {
state.pty_manager.resize(&id, cols, rows)
}
#[tauri::command]
fn pty_kill(state: State<'_, AppState>, id: String) -> Result<(), String> {
state.pty_manager.kill(&id)
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.setup(|app| {
if cfg!(debug_assertions) {
app.handle().plugin(
tauri_plugin_log::Builder::default()
.level(log::LevelFilter::Info)
.build(),
)?;
}
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
let app_state = AppState {
pty_manager: Arc::new(PtyManager::new()),
};
tauri::Builder::default()
.manage(app_state)
.invoke_handler(tauri::generate_handler![
pty_spawn,
pty_write,
pty_resize,
pty_kill,
])
.setup(|app| {
if cfg!(debug_assertions) {
app.handle().plugin(
tauri_plugin_log::Builder::default()
.level(log::LevelFilter::Info)
.build(),
)?;
}
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

View file

@ -1,2 +1,160 @@
// PTY management via portable-pty
// Phase 2: spawn, resize, I/O streaming to frontend
use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{BufReader, Write};
use std::sync::{Arc, Mutex};
use std::thread;
use tauri::{AppHandle, Emitter};
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PtyOptions {
pub shell: Option<String>,
pub cwd: Option<String>,
pub args: Option<Vec<String>>,
pub cols: Option<u16>,
pub rows: Option<u16>,
}
struct PtyInstance {
master: Box<dyn MasterPty + Send>,
writer: Box<dyn Write + Send>,
}
pub struct PtyManager {
instances: Arc<Mutex<HashMap<String, PtyInstance>>>,
}
impl PtyManager {
pub fn new() -> Self {
Self {
instances: Arc::new(Mutex::new(HashMap::new())),
}
}
pub fn spawn(
&self,
app: &AppHandle,
options: PtyOptions,
) -> Result<String, String> {
let pty_system = native_pty_system();
let cols = options.cols.unwrap_or(80);
let rows = options.rows.unwrap_or(24);
let pair = pty_system
.openpty(PtySize {
rows,
cols,
pixel_width: 0,
pixel_height: 0,
})
.map_err(|e| format!("Failed to open PTY: {e}"))?;
let shell = options.shell.unwrap_or_else(|| {
std::env::var("SHELL").unwrap_or_else(|_| "/bin/bash".to_string())
});
let mut cmd = CommandBuilder::new(&shell);
if let Some(args) = &options.args {
for arg in args {
cmd.arg(arg);
}
}
if let Some(cwd) = &options.cwd {
cmd.cwd(cwd);
}
let _child = pair
.slave
.spawn_command(cmd)
.map_err(|e| format!("Failed to spawn command: {e}"))?;
// Drop the slave side — we only need the master
drop(pair.slave);
let id = Uuid::new_v4().to_string();
let reader = pair
.master
.try_clone_reader()
.map_err(|e| format!("Failed to clone PTY reader: {e}"))?;
let writer = pair
.master
.take_writer()
.map_err(|e| format!("Failed to take PTY writer: {e}"))?;
// Spawn reader thread that emits Tauri events
let event_id = id.clone();
let app_handle = app.clone();
thread::spawn(move || {
let mut buf_reader = BufReader::with_capacity(4096, reader);
let mut buf = vec![0u8; 4096];
loop {
match std::io::Read::read(&mut buf_reader, &mut buf) {
Ok(0) => {
// PTY closed
let _ = app_handle.emit(&format!("pty-exit-{event_id}"), ());
break;
}
Ok(n) => {
let data = String::from_utf8_lossy(&buf[..n]).to_string();
let _ = app_handle.emit(&format!("pty-data-{event_id}"), &data);
}
Err(e) => {
log::error!("PTY read error for {event_id}: {e}");
let _ = app_handle.emit(&format!("pty-exit-{event_id}"), ());
break;
}
}
}
});
let instance = PtyInstance { master: pair.master, writer };
self.instances.lock().unwrap().insert(id.clone(), instance);
log::info!("Spawned PTY {id} ({shell})");
Ok(id)
}
pub fn write(&self, id: &str, data: &str) -> Result<(), String> {
let mut instances = self.instances.lock().unwrap();
let instance = instances
.get_mut(id)
.ok_or_else(|| format!("PTY {id} not found"))?;
instance
.writer
.write_all(data.as_bytes())
.map_err(|e| format!("PTY write error: {e}"))?;
instance
.writer
.flush()
.map_err(|e| format!("PTY flush error: {e}"))?;
Ok(())
}
pub fn resize(&self, id: &str, cols: u16, rows: u16) -> Result<(), String> {
let instances = self.instances.lock().unwrap();
let instance = instances
.get(id)
.ok_or_else(|| format!("PTY {id} not found"))?;
instance
.master
.resize(PtySize {
rows,
cols,
pixel_width: 0,
pixel_height: 0,
})
.map_err(|e| format!("PTY resize error: {e}"))?;
Ok(())
}
pub fn kill(&self, id: &str) -> Result<(), String> {
let mut instances = self.instances.lock().unwrap();
if instances.remove(id).is_some() {
log::info!("Killed PTY {id}");
Ok(())
} else {
Err(format!("PTY {id} not found"))
}
}
}