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:
Knotty Wyvern
2026-10-27 23:08:59 -07:00
parent 70510a114f
commit 2448c68abf
8 changed files with 738 additions and 217 deletions
+288 -73
View File
@@ -1,15 +1,28 @@
use crate::error::Result;
use crate::workspace::{current_root, WorkspaceState};
use serde::Serialize;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::io::Read;
use std::path::{Component, Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use std::process::{Child, Command, Output, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc, Mutex, OnceLock};
use std::time::{Duration, Instant, SystemTime};
use tauri::{State, Window};
const OUTPUT_LIMIT: usize = 2 * 1024 * 1024;
static GIT_LOCK: Mutex<()> = Mutex::new(());
const TIMEOUT: Duration = Duration::from_secs(30);
/// RuneStone's SSH settings. Git uses them only when the user has not chosen an SSH command.
const DEFAULT_SSH_COMMAND: &str = "core.sshCommand=ssh -oBatchMode=yes -oConnectTimeout=15";
/// Environment variables that choose the SSH client for Git. The Git service keeps them.
const SSH_VARIABLES: [&str; 3] = ["GIT_SSH", "GIT_SSH_COMMAND", "GIT_SSH_VARIANT"];
#[cfg(test)]
thread_local! {
/// The number of Git processes that this test thread started.
static RUNS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
@@ -60,19 +73,61 @@ fn read_output(mut stream: impl Read) -> Result<Vec<u8>> {
}
}
/// The Git program. Find it on `PATH` once, not at each start.
fn program() -> &'static Path {
static PROGRAM: OnceLock<PathBuf> = OnceLock::new();
PROGRAM.get_or_init(|| {
crate::terminal_platform::find_executable(if cfg!(windows) { "git.exe" } else { "git" })
.unwrap_or_else(|| PathBuf::from("git"))
})
}
/// True for an inherited environment variable that the Git service removes.
///
/// A `GIT_*` variable in RuneStone's own environment can point Git at a different
/// repository, index, or object store (`GIT_DIR`, `GIT_WORK_TREE`, `GIT_INDEX_FILE`),
/// or add configuration (`GIT_CONFIG_*`). A shell or a hook that started RuneStone can
/// leave such variables set. The Git service removes them, so that each command uses
/// only the workspace repository and the checks in `repository`.
/// The SSH variables only select the user's SSH client, so the service keeps them.
fn removed_variable(key: &OsStr) -> bool {
let key = key.to_string_lossy().to_ascii_uppercase();
key.starts_with("GIT_") && !SSH_VARIABLES.contains(&key.as_str())
}
/// Stop a Git process that did not finish in time, with its helpers.
fn stop(child: &mut Child) {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
// Git can start SSH and credential helpers that also hold its output pipes.
let _ = Command::new("taskkill")
.args(["/PID", &child.id().to_string(), "/T", "/F"])
.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
let _ = child.kill();
let _ = child.wait();
}
fn timed_out(child: &mut Child) -> crate::error::Error {
stop(child);
"Git did not finish within 30 seconds. Refresh to check the repository state.".into()
}
fn run(root: &Path, args: &[&str]) -> Result<Output> {
let mut command = Command::new("git");
#[cfg(test)]
RUNS.with(|runs| runs.set(runs.get() + 1));
let mut command = Command::new(program());
command
.current_dir(root)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
for (key, _) in std::env::vars_os() {
if key
.to_string_lossy()
.to_ascii_uppercase()
.starts_with("GIT_")
{
if removed_variable(&key) {
command.env_remove(key);
}
}
@@ -94,49 +149,51 @@ fn run(root: &Path, args: &[&str]) -> Result<Output> {
let mut child = command
.spawn()
.map_err(|e| format!("Could not start Git. Install Git and restart RuneStone. {e}"))?;
GIT_AVAILABLE.store(true, Ordering::Relaxed);
let deadline = Instant::now() + TIMEOUT;
let stdout = child.stdout.take().ok_or("Git output is unavailable.")?;
let stderr = child.stderr.take().ok_or("Git errors are unavailable.")?;
let out = std::thread::spawn(move || read_output(stdout));
let err = std::thread::spawn(move || read_output(stderr));
let start = Instant::now();
let mut completed = None;
// Two readers empty both pipes, so that Git never stops on a full pipe.
let (send, receive) = mpsc::channel();
let send_errors = send.clone();
std::thread::spawn(move || send.send((true, read_output(stdout))));
std::thread::spawn(move || send_errors.send((false, read_output(stderr))));
let (mut out, mut err) = (None, None);
while out.is_none() || err.is_none() {
match receive.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
Ok((true, result)) => out = Some(result),
Ok((false, result)) => err = Some(result),
Err(mpsc::RecvTimeoutError::Timeout) => return Err(timed_out(&mut child)),
Err(mpsc::RecvTimeoutError::Disconnected) => {
stop(&mut child);
return Err("Could not read Git output.".into());
}
}
}
// Git closes its pipes when it exits, so the process ends at once or very soon after.
let status = loop {
if completed.is_none() {
completed = child.try_wait()?;
if let Some(status) = child.try_wait()? {
break status;
}
if let Some(status) = completed {
if out.is_finished() && err.is_finished() {
break status;
}
if Instant::now() >= deadline {
return Err(timed_out(&mut child));
}
if start.elapsed() > Duration::from_secs(30) {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
// Git can start SSH and credential helpers that also hold its output pipes.
let _ = Command::new("taskkill")
.args(["/PID", &child.id().to_string(), "/T", "/F"])
.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
let _ = child.kill();
let _ = child.wait();
return Err(
"Git did not finish within 30 seconds. Refresh to check the repository state."
.into(),
);
}
std::thread::sleep(Duration::from_millis(15));
std::thread::sleep(Duration::from_millis(1));
};
Ok(Output {
status,
stdout: out.join().map_err(|_| "Could not read Git output.")??,
stderr: err.join().map_err(|_| "Could not read Git errors.")??,
stdout: out.ok_or("Could not read Git output.")??,
stderr: err.ok_or("Could not read Git errors.")??,
})
}
/// True after one Git process started. A failed start is checked again on the next status.
static GIT_AVAILABLE: AtomicBool = AtomicBool::new(false);
fn git_available(root: &Path) -> bool {
GIT_AVAILABLE.load(Ordering::Relaxed) || run(root, &["--version"]).is_ok()
}
fn checked(root: &Path, args: &[&str]) -> Result<String> {
let output = run(root, args)?;
if !output.status.success() {
@@ -146,14 +203,58 @@ fn checked(root: &Path, args: &[&str]) -> Result<String> {
.map_err(|_| "Git returned a filename that is not UTF-8.".into())
}
/// The state of the files that decide where a repository's work tree and metadata are.
/// The stamp changes when `.git` is removed or becomes a file (a linked worktree), and when
/// the repository configuration (`core.worktree`) or `commondir` changes.
/// Ordinary Git writes change the `.git` folder's time, so the stamp does not use it.
type Stamp = Vec<Option<(bool, u64, Option<SystemTime>)>>;
fn stamp(root: &Path) -> Stamp {
let git = root.join(".git");
let metadata = |path: &Path| std::fs::symlink_metadata(path).ok();
let mut stamp = vec![metadata(&git).map(|metadata| (metadata.is_dir(), 0, None))];
for path in [git.join("config"), git.join("commondir")] {
stamp.push(metadata(&path).map(|metadata| (metadata.is_dir(), metadata.len(), metadata.modified().ok())));
}
stamp
}
/// Roots that passed the repository check, with the stamp at the time of the check.
static REPOSITORIES: Mutex<Option<HashMap<PathBuf, Stamp>>> = Mutex::new(None);
fn repository(root: &Path) -> Result<()> {
let top = checked(root, &["rev-parse", "--show-toplevel"])?;
let before = stamp(root);
let cached = REPOSITORIES
.lock()
.ok()
.and_then(|cache| cache.as_ref()?.get(root).cloned());
if cached.as_ref() == Some(&before) {
return Ok(());
}
check_repository(root)?;
if let Ok(mut cache) = REPOSITORIES.lock() {
cache.get_or_insert_with(HashMap::new).insert(root.to_owned(), before);
}
Ok(())
}
fn check_repository(root: &Path) -> Result<()> {
if root.to_string_lossy().contains('\n') {
return Err("Git cannot use a workspace path that contains a line break.".into());
}
let output = checked(
root,
&["rev-parse", "--show-toplevel", "--absolute-git-dir", "--git-common-dir"],
)?;
let lines: Vec<&str> = output.lines().collect();
let [top, git_dir, common_dir] = lines[..] else {
return Err("Git returned an invalid repository location.".into());
};
let top = dunce::canonicalize(top.trim())?;
if top != root {
return Err("Open the repository root as your workspace to use Git.".into());
}
for argument in ["--absolute-git-dir", "--git-common-dir"] {
let git_dir = checked(root, &["rev-parse", argument])?;
for git_dir in [git_dir, common_dir] {
let git_dir = dunce::canonicalize(root.join(git_dir.trim()))?;
if !git_dir.starts_with(root) {
return Err(
@@ -165,6 +266,32 @@ fn repository(root: &Path) -> Result<()> {
Ok(())
}
/// The lock for one repository root. Commands in other workspaces do not wait for it.
fn root_lock(root: &Path) -> Result<Arc<Mutex<()>>> {
static LOCKS: Mutex<Option<HashMap<PathBuf, Arc<Mutex<()>>>>> = Mutex::new(None);
let mut locks = LOCKS.lock().map_err(|_| "The Git service lock is unavailable.")?;
let locks = locks.get_or_insert_with(HashMap::new);
// Forget the locks that no command holds or waits for.
locks.retain(|_, lock| Arc::strong_count(lock) > 1);
Ok(locks.entry(root.to_owned()).or_default().clone())
}
/// The `-c` arguments that set RuneStone's SSH command, or none when the user chose an SSH client.
/// `variable` reads one environment variable.
fn ssh_arguments(root: &Path, variable: impl Fn(&str) -> Option<std::ffi::OsString>) -> Vec<&'static str> {
let environment = ["GIT_SSH", "GIT_SSH_COMMAND"]
.into_iter()
.any(|name| variable(name).is_some_and(|value| !value.is_empty()));
// Git reads `core.sshCommand` from every configuration scope, also the repository.
let configured = environment
|| run(root, &["config", "--get", "core.sshCommand"]).is_ok_and(|output| output.status.success());
if configured {
Vec::new()
} else {
vec!["-c", DEFAULT_SSH_COMMAND]
}
}
fn safe_path(root: &Path, value: &str) -> Result<()> {
if value.is_empty() || value.contains('\0') || value.contains('\\') || value.contains(':') {
return Err("Choose a relative Git file path inside the workspace.".into());
@@ -225,6 +352,14 @@ fn parse_status(value: &str) -> Result<Vec<GitChange>> {
Ok(changes)
}
/// The changed files. The caller checks the repository first.
fn changes(root: &Path) -> Result<Vec<GitChange>> {
parse_status(&checked(
root,
&["status", "--porcelain=v1", "-z", "--untracked-files=all"],
)?)
}
fn status(root: &Path) -> Result<GitStatus> {
let empty = |available| GitStatus {
available,
@@ -232,7 +367,7 @@ fn status(root: &Path) -> Result<GitStatus> {
branch: None,
changes: vec![],
};
if run(root, &["--version"]).is_err() {
if !git_available(root) {
return Ok(empty(false));
}
if !root.join(".git").exists() {
@@ -242,10 +377,7 @@ fn status(root: &Path) -> Result<GitStatus> {
let branch = checked(root, &["symbolic-ref", "--quiet", "--short", "HEAD"]).or_else(|_| {
checked(root, &["rev-parse", "--short", "HEAD"]).map(|id| format!("Detached {}", id.trim()))
})?;
let changes = parse_status(&checked(
root,
&["status", "--porcelain=v1", "-z", "--untracked-files=all"],
)?)?;
let changes = changes(root)?;
Ok(GitStatus {
available: true,
repository: true,
@@ -275,8 +407,7 @@ fn diff(root: &Path, path: &str, staged: bool) -> Result<String> {
.collect::<String>()
));
}
let change = status(root)?
.changes
let change = changes(root)?
.into_iter()
.find(|change| change.path == path);
let original = change.and_then(|change| change.original_path);
@@ -360,18 +491,15 @@ fn upstream(root: &Path) -> Result<(String, String)> {
fn synchronize(root: &Path, push: bool) -> Result<()> {
repository(root)?;
let (remote, reference) = upstream(root)?;
if !push && !status(root)?.changes.is_empty() {
if !push && !changes(root)?.is_empty() {
return Err("Commit your changes or stash them with Git before you pull. Pull requires a clean working tree.".into());
}
// Explicit arguments prevent repository defaults from forcing a push or rebasing a pull.
let mirror = format!("remote.{remote}.mirror=false");
let target = format!("HEAD:{reference}");
let mut args = vec![
"-c",
"credential.interactive=false",
"-c",
"core.sshCommand=ssh -oBatchMode=yes -oConnectTimeout=15",
];
let mut args = vec!["-c", "credential.interactive=false"];
// Keep the user's SSH client, for example Windows OpenSSH with its agent, or PuTTY plink.
args.extend(ssh_arguments(root, |name| std::env::var_os(name)));
if push {
args.extend([
"-c",
@@ -558,14 +686,17 @@ fn blame(root: &Path, path: &str, line: u32) -> Result<Option<GitLineInfo>> {
fn root(state: &WorkspaceState, window: &Window) -> Result<PathBuf> {
Ok(dunce::canonicalize(current_root(state, window.label())?)?)
}
/// Run a Git action on a blocking worker. Actions on the same root run one at a time.
async fn task<T: Send + 'static>(
action: impl FnOnce() -> Result<T> + Send + 'static,
root: PathBuf,
action: impl FnOnce(&Path) -> Result<T> + Send + 'static,
) -> Result<T> {
tauri::async_runtime::spawn_blocking(move || {
let _guard = GIT_LOCK
let lock = root_lock(&root)?;
let _guard = lock
.lock()
.map_err(|_| "The Git service lock is unavailable.")?;
action()
action(&root)
})
.await?
}
@@ -575,7 +706,7 @@ pub async fn git_status(
state: State<'_, WorkspaceState>,
) -> Result<GitStatus> {
let root = root(&state, &window)?;
task(move || status(&root)).await
task(root, status).await
}
#[tauri::command]
pub async fn git_diff(
@@ -585,7 +716,7 @@ pub async fn git_diff(
staged: bool,
) -> Result<String> {
let root = root(&state, &window)?;
task(move || diff(&root, &path, staged)).await
task(root, move |root| diff(root, &path, staged)).await
}
#[tauri::command]
pub async fn git_stage(
@@ -594,7 +725,7 @@ pub async fn git_stage(
paths: Vec<String>,
) -> Result<()> {
let root = root(&state, &window)?;
task(move || change_index(&root, &paths, true)).await
task(root, move |root| change_index(root, &paths, true)).await
}
#[tauri::command]
pub async fn git_unstage(
@@ -603,7 +734,7 @@ pub async fn git_unstage(
paths: Vec<String>,
) -> Result<()> {
let root = root(&state, &window)?;
task(move || change_index(&root, &paths, false)).await
task(root, move |root| change_index(root, &paths, false)).await
}
#[tauri::command]
pub async fn git_commit(
@@ -612,7 +743,7 @@ pub async fn git_commit(
message: String,
) -> Result<()> {
let root = root(&state, &window)?;
task(move || commit(&root, &message)).await
task(root, move |root| commit(root, &message)).await
}
#[tauri::command]
pub async fn git_blame(
@@ -622,37 +753,37 @@ pub async fn git_blame(
line: u32,
) -> Result<Option<GitLineInfo>> {
let root = root(&state, &window)?;
task(move || blame(&root, &path, line)).await
task(root, move |root| blame(root, &path, line)).await
}
#[tauri::command]
pub async fn git_push(window: Window, state: State<'_, WorkspaceState>) -> Result<()> {
let root = root(&state, &window)?;
task(move || synchronize(&root, true)).await
task(root, move |root| synchronize(root, true)).await
}
#[tauri::command]
pub async fn git_pull(window: Window, state: State<'_, WorkspaceState>) -> Result<()> {
let root = root(&state, &window)?;
task(move || synchronize(&root, false)).await
task(root, move |root| synchronize(root, false)).await
}
#[tauri::command]
pub async fn git_graph(window: Window, state: State<'_, WorkspaceState>) -> Result<GitGraph> {
let root = root(&state, &window)?;
task(move || graph(&root)).await
task(root, graph).await
}
#[tauri::command]
pub async fn git_commit_details(window: Window, state: State<'_, WorkspaceState>, commit: String) -> Result<GitCommitDetails> {
let root = root(&state, &window)?;
task(move || commit_details(&root, &commit)).await
task(root, move |root| commit_details(root, &commit)).await
}
#[tauri::command]
pub async fn git_commit_diff(window: Window, state: State<'_, WorkspaceState>, commit: String, path: String) -> Result<String> {
let root = root(&state, &window)?;
task(move || commit_diff(&root, &commit, &path)).await
task(root, move |root| commit_diff(root, &commit, &path)).await
}
#[cfg(test)]
@@ -833,4 +964,88 @@ mod tests {
.contains("Test hook rejected"));
assert_eq!(status(&repo.0).unwrap().changes[0].index, "A");
}
#[test]
fn user_ssh_settings_are_kept_and_other_git_variables_are_removed() {
for name in ["GIT_SSH", "GIT_SSH_COMMAND", "GIT_SSH_VARIANT", "git_ssh_command"] {
assert!(!removed_variable(OsStr::new(name)), "removed {name}");
}
for name in ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_CONFIG_PARAMETERS", "GIT_CONFIG_COUNT", "git_dir"] {
assert!(removed_variable(OsStr::new(name)), "kept {name}");
}
assert!(!removed_variable(OsStr::new("SSH_AUTH_SOCK")));
let repo = Repo::new();
let none = |_: &str| None;
let plink = |name: &str| (name == "GIT_SSH").then(|| "C:/PuTTY/plink.exe".into());
let command = |name: &str| (name == "GIT_SSH_COMMAND").then(|| "C:/Windows/System32/OpenSSH/ssh.exe".into());
let empty = |name: &str| (name == "GIT_SSH_COMMAND").then(std::ffi::OsString::new);
assert!(ssh_arguments(&repo.0, plink).is_empty());
assert!(ssh_arguments(&repo.0, command).is_empty());
// Another user scope can set core.sshCommand on a developer computer.
let user_scope = ["--global", "--system"].iter().any(|scope| {
run(&repo.0, &["config", scope, "--get", "core.sshCommand"]).is_ok_and(|output| output.status.success())
});
if !user_scope {
assert_eq!(ssh_arguments(&repo.0, none), vec!["-c", DEFAULT_SSH_COMMAND]);
assert_eq!(ssh_arguments(&repo.0, empty), vec!["-c", DEFAULT_SSH_COMMAND]);
}
checked(&repo.0, &["config", "core.sshCommand", "C:/Windows/System32/OpenSSH/ssh.exe"]).unwrap();
assert!(ssh_arguments(&repo.0, none).is_empty());
}
#[test]
fn repository_check_is_cached_until_git_metadata_changes() {
let repo = Repo::new();
let outside = Repo::new();
repo.write("notes.txt", "notes\n");
let runs = || RUNS.with(std::cell::Cell::get);
status(&repo.0).unwrap();
let start = runs();
let first = status(&repo.0).unwrap();
// One process reads the branch and one reads the changes.
assert_eq!(runs() - start, 2);
assert_eq!(first.branch.as_deref(), Some("main"));
assert_eq!(first.changes[0].path, "notes.txt");
let start = runs();
assert!(diff(&repo.0, "notes.txt", false).unwrap().contains("+notes"));
// One process checks whether Git tracks the file.
assert_eq!(runs() - start, 1);
change_index(&repo.0, &["notes.txt".into()], true).unwrap();
let start = runs();
assert!(diff(&repo.0, "notes.txt", true).unwrap().contains("+notes"));
// One process reads the changes for rename paths and one makes the diff.
assert_eq!(runs() - start, 2);
// A changed configuration starts the full check again.
checked(&repo.0, &["config", "core.worktree", outside.0.to_str().unwrap()]).unwrap();
assert!(repository(&repo.0).is_err());
assert!(status(&repo.0).is_err());
checked(&repo.0, &["config", "--unset", "core.worktree"]).unwrap();
repository(&repo.0).unwrap();
// A removed repository is not a repository from the cache.
std::fs::remove_dir_all(repo.0.join(".git")).unwrap();
assert!(repository(&repo.0).is_err());
assert!(!status(&repo.0).unwrap().repository);
}
#[test]
fn each_root_has_its_own_lock() {
let first = Repo::new();
let second = Repo::new();
let lock = root_lock(&first.0).unwrap();
let _guard = lock.lock().unwrap();
assert!(Arc::ptr_eq(&lock, &root_lock(&first.0).unwrap()));
let other = root_lock(&second.0).unwrap();
assert!(!Arc::ptr_eq(&lock, &other));
assert!(other.try_lock().is_ok(), "A command in one root must not wait for another root.");
assert!(lock.try_lock().is_err());
}
#[test]
fn nonzero_exit_and_large_output_keep_their_results() {
let repo = Repo::new();
let output = run(&repo.0, &["rev-parse", "--verify", "HEAD"]).unwrap();
assert!(!output.status.success());
assert!(!output.stderr.is_empty());
repo.write("large.txt", &"line of text\n".repeat(200_000));
assert!(checked(&repo.0, &["hash-object", "large.txt"]).unwrap().trim().len() >= 40);
change_index(&repo.0, &["large.txt".into()], true).unwrap();
// The staged diff holds about 2.8 MiB, which exceeds the output limit.
assert!(diff(&repo.0, "large.txt", true).unwrap_err().to_string().contains("2 MiB"));
}
}