Move blocking host work off the main thread and fix Git SSH settings
Window close no longer waits on the main thread. The handler revokes browser sessions and plugin leases with short locks. A cleanup thread stops terminals, closes browser tabs, and erases plugin review folders. The browser cleanup sends closeTab without a wait for the reply, and stops the engine outside the engine lock. Terminal, plugin, background, and browser commands do their file, process, and plugin-lock work on blocking workers. Terminal events go to the window that opened the session. Command names, arguments, results, and events do not change. The Git service keeps GIT_SSH, GIT_SSH_COMMAND, GIT_SSH_VARIANT, and a configured core.sshCommand. It adds its SSH defaults only when the user has none. It still removes other inherited GIT_* variables. After the first check, Git status starts 2 processes and an unstaged diff starts 1. The service finds Git once, checks Git once per run, caches the repository check per root until the Git metadata changes, waits on its pipes instead of a 15 ms poll, and locks each root separately. Lease errors name the plugin. A profile copy rejects junctions.
This commit is contained in:
+77
-25
@@ -20,7 +20,7 @@ struct OpenPty {
|
||||
owner: String,
|
||||
integration_file: Option<PathBuf>,
|
||||
master: Box<dyn MasterPty + Send>,
|
||||
writer: Mutex<Box<dyn Write + Send>>,
|
||||
writer: std::sync::Arc<Mutex<Box<dyn Write + Send>>>,
|
||||
killer: Box<dyn portable_pty::ChildKiller + Send + Sync>,
|
||||
}
|
||||
|
||||
@@ -32,10 +32,16 @@ impl Drop for OpenPty {
|
||||
}
|
||||
|
||||
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) {
|
||||
if let Ok(mut sessions) = self.inner.lock() {
|
||||
sessions.retain(|_, session| session.owner != label);
|
||||
}
|
||||
let closed: Vec<OpenPty> = match self.inner.lock() {
|
||||
Ok(mut sessions) => {
|
||||
let ids: Vec<String> = 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
|
||||
@@ -81,8 +87,13 @@ pub struct ShellProfile {
|
||||
executable: PathBuf,
|
||||
}
|
||||
|
||||
/// The installed shells. The search reads `PATH` folders, so it runs on a blocking worker.
|
||||
#[tauri::command]
|
||||
pub fn pty_profiles() -> Vec<ShellProfile> {
|
||||
pub async fn pty_profiles() -> Result<Vec<ShellProfile>> {
|
||||
Ok(tauri::async_runtime::spawn_blocking(profiles).await?)
|
||||
}
|
||||
|
||||
fn profiles() -> Vec<ShellProfile> {
|
||||
let candidates = if cfg!(windows) {
|
||||
vec![("powershell", "PowerShell", "powershell", "powershell.exe"),
|
||||
("pwsh", "PowerShell 7", "powershell", "pwsh.exe"),
|
||||
@@ -158,7 +169,7 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner:
|
||||
pixel_height: 0,
|
||||
})
|
||||
.map_err(Error::from_display)?;
|
||||
let profiles = pty_profiles();
|
||||
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);
|
||||
@@ -176,11 +187,14 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner:
|
||||
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.cwd(root);
|
||||
cmd.env("TERM", "xterm-256color");
|
||||
cmd.env("COLORTERM", "truecolor");
|
||||
let reader = pair
|
||||
@@ -197,18 +211,19 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner:
|
||||
owner: owner.into(),
|
||||
integration_file,
|
||||
master: pair.master,
|
||||
writer: Mutex::new(writer),
|
||||
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]
|
||||
pub fn pty_open(
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn pty_open(
|
||||
app: AppHandle,
|
||||
window: tauri::Window,
|
||||
workspace: State<WorkspaceState>,
|
||||
pty: State<PtyState>,
|
||||
workspace: State<'_, WorkspaceState>,
|
||||
id: String,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
@@ -220,13 +235,29 @@ pub fn pty_open(
|
||||
if root.to_string_lossy() != cwd {
|
||||
return Err(Error::new("workspace changed before the terminal started"));
|
||||
}
|
||||
let owner = window.label().to_owned();
|
||||
tauri::async_runtime::spawn_blocking(move || open(app, owner, root, id, cols, rows, profile, directory)).await?
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn open(
|
||||
app: AppHandle,
|
||||
owner: String,
|
||||
root: PathBuf,
|
||||
id: String,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
profile: Option<String>,
|
||||
directory: Option<String>,
|
||||
) -> Result<()> {
|
||||
let pty = app.state::<PtyState>();
|
||||
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, mut reader, mut child) = spawn_shell(&directory, cols, rows, profile.as_deref(), window.label())?;
|
||||
let (session, mut 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();
|
||||
@@ -248,12 +279,17 @@ pub fn pty_open(
|
||||
let reader_id = id.clone();
|
||||
thread::spawn(move || {
|
||||
let mut buf = [0u8; 4096];
|
||||
// Address the terminal events 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. A listener with a window target does not
|
||||
// receive the events of other windows.
|
||||
loop {
|
||||
match reader.read(&mut buf) {
|
||||
Ok(0) => break,
|
||||
Ok(n) => {
|
||||
let data = buf[..n].to_vec();
|
||||
let _ = app_reader.emit(
|
||||
let _ = app_reader.emit_to(
|
||||
owner.as_str(),
|
||||
"pty-data",
|
||||
PtyData {
|
||||
id: reader_id.clone(),
|
||||
@@ -265,7 +301,8 @@ pub fn pty_open(
|
||||
}
|
||||
}
|
||||
let code = exit_rx.recv().ok().flatten();
|
||||
let _ = app_reader.emit(
|
||||
let _ = app_reader.emit_to(
|
||||
owner.as_str(),
|
||||
"pty-exit",
|
||||
PtyExit {
|
||||
id: reader_id,
|
||||
@@ -276,11 +313,21 @@ pub fn pty_open(
|
||||
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 fn pty_write(pty: State<PtyState>, id: String, data: String) -> 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"))?;
|
||||
let mut writer = session.writer.lock().map_err(|_| Error::new("pty writer lock"))?;
|
||||
pub async fn pty_write(app: AppHandle, id: String, data: String) -> Result<()> {
|
||||
tauri::async_runtime::spawn_blocking(move || write(&app.state::<PtyState>(), &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)?;
|
||||
@@ -304,13 +351,18 @@ pub fn pty_resize(pty: State<PtyState>, id: String, cols: u16, rows: u16) -> Res
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop a shell on a blocking worker. Closing a pseudo console can wait for its output.
|
||||
#[tauri::command]
|
||||
pub fn pty_close(pty: State<PtyState>, id: String) -> Result<()> {
|
||||
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
||||
let session = guard.remove(&id);
|
||||
drop(guard);
|
||||
drop(session);
|
||||
Ok(())
|
||||
pub async fn pty_close(app: AppHandle, id: String) -> Result<()> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let pty = app.state::<PtyState>();
|
||||
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]
|
||||
@@ -356,7 +408,7 @@ mod tests {
|
||||
#[test]
|
||||
fn installed_profiles_start_and_report_shell_prompts() {
|
||||
let root = dunce::canonicalize(std::env::current_dir().unwrap()).unwrap();
|
||||
for profile in pty_profiles() {
|
||||
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();
|
||||
|
||||
Reference in New Issue
Block a user