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
+179 -73
View File
@@ -8,7 +8,7 @@ use std::{
sync::Mutex,
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use tauri::{AppHandle, Emitter, Manager, State};
use tauri::{AppHandle, Emitter, Manager};
use tauri_plugin_dialog::DialogExt;
use tauri_plugin_opener::OpenerExt;
use uuid::Uuid;
@@ -937,13 +937,59 @@ impl Service {
Ok(())
}
}
impl Service {
/// Accept only a plugin that is enabled and loaded in the window `owner`.
fn require_lease(&self, owner: &str, id: &str) -> Result<()> {
let record = self.catalog.plugins.get(id);
let enabled = record.is_some_and(|record| record.enabled && record.removal.is_none());
let leased = self.leases.get(id).is_some_and(|windows| windows.contains(owner));
if enabled && leased {
return Ok(());
}
Err(match record {
Some(record) => format!("The {} plugin is not enabled in this window.", record.manifest.name),
None => "This plugin is not enabled in this window.".into(),
}
.into())
}
/// Remove the window's leases, removal plans, and reviewed packages.
/// Return the staging folder and the review folders to erase.
fn release_window(&mut self, owner: &str) -> (PathBuf, Vec<PathBuf>) {
for windows in self.leases.values_mut() {
windows.remove(owner);
}
self.plans.retain(|_, plan| plan.owner != owner);
let tokens: Vec<_> = self
.candidates
.iter()
.filter(|(_, candidate)| candidate.owner == owner)
.map(|(token, _)| token.clone())
.collect();
let folders = tokens
.iter()
.filter_map(|token| self.candidates.remove(token))
.map(|candidate| candidate.directory)
.collect();
(self.root.clone(), folders)
}
}
/// Review folders to erase after the plugin lock opens. No other code uses them.
pub struct StagingCleanup(Option<(PathBuf, Vec<PathBuf>)>);
impl StagingCleanup {
pub fn erase(self) {
let Some((root, folders)) = self.0 else { return };
let parent = root.join("plugin-staging");
if folders.is_empty() || safe_child(&root, &parent).is_err() {
return;
}
for folder in folders {
let _ = erase(&parent, &folder);
}
}
}
impl PluginState {
pub fn require_lease(&self, app: &AppHandle, owner: &str, id: &str) -> Result<()> {
self.with(app, |service| {
let enabled = service.catalog.plugins.get(id).is_some_and(|record| record.enabled && record.removal.is_none());
let leased = service.leases.get(id).is_some_and(|windows| windows.contains(owner));
if enabled && leased { Ok(()) } else { Err("The browser plugin is not enabled in this window.".into()) }
})
self.with(app, |service| service.require_lease(owner, id))
}
fn with<T>(
&self,
@@ -956,37 +1002,38 @@ impl PluginState {
}
action(guard.as_mut().unwrap())
}
pub fn close_window(&self, owner: &str) {
if let Ok(mut guard) = self.inner.lock() {
if let Some(service) = guard.as_mut() {
for windows in service.leases.values_mut() {
windows.remove(owner);
}
service.plans.retain(|_, plan| plan.owner != owner);
let tokens: Vec<_> = service
.candidates
.iter()
.filter(|(_, candidate)| candidate.owner == owner)
.map(|(token, _)| token.clone())
.collect();
for token in tokens {
if let Some(candidate) = service.candidates.remove(&token) {
if let Ok(parent) = service.directory("plugin-staging") {
let _ = erase(&parent, &candidate.directory);
}
}
}
}
/// Run `action` on a blocking worker. Package reads, hashes, and copies do not stop an async runtime thread.
async fn run<T: Send + 'static>(
app: &AppHandle,
action: impl FnOnce(&mut Service) -> Result<T> + Send + 'static,
) -> Result<T> {
let app = app.clone();
tauri::async_runtime::spawn_blocking(move || app.state::<PluginState>().with(&app, action)).await?
}
/// Release the window without waiting. Return `None` when another command holds the plugin lock.
pub fn try_release_window(&self, owner: &str) -> Option<StagingCleanup> {
match self.inner.try_lock() {
Ok(mut guard) => Some(StagingCleanup(guard.as_mut().map(|service| service.release_window(owner)))),
Err(std::sync::TryLockError::WouldBlock) => None,
Err(std::sync::TryLockError::Poisoned(_)) => Some(StagingCleanup(None)),
}
}
/// Release the window. Wait for the plugin lock, but erase the review folders after it opens.
pub fn close_window(&self, owner: &str) {
let cleanup = match self.inner.lock() {
Ok(mut guard) => StagingCleanup(guard.as_mut().map(|service| service.release_window(owner))),
Err(_) => return,
};
cleanup.erase();
}
}
fn changed(app: &AppHandle) {
let _ = app.emit("plugins-changed", ());
}
#[tauri::command]
pub async fn plugins_snapshot(app: AppHandle, state: State<'_, PluginState>) -> Result<Snapshot> {
state.with(&app, |service| service.snapshot())
pub async fn plugins_snapshot(app: AppHandle) -> Result<Snapshot> {
PluginState::run(&app, |service| service.snapshot()).await
}
#[tauri::command]
@@ -1011,15 +1058,17 @@ pub async fn plugins_choose(app: AppHandle, window: tauri::Window) -> Result<Vec
.into_iter()
.map(|source| source.into_path().map_err(Error::from_display))
.collect::<Result<_>>()?;
for path in &paths {
require_zip(path)?;
}
app.state::<PluginState>().with(&app, |service| {
let owner = window.label().to_owned();
PluginState::run(&app, move |service| {
for path in &paths {
require_zip(path)?;
}
Ok(paths
.into_iter()
.map(|path| service.inspect(window.label(), path))
.map(|path| service.inspect(&owner, path))
.collect())
})
.await
}
#[tauri::command]
pub async fn plugins_from_git(
@@ -1034,24 +1083,26 @@ pub async fn plugins_from_git(
let download = tauri::async_runtime::spawn_blocking(move || {
crate::plugin_sources::download(&repository, token.as_deref())
}).await??;
app.state::<PluginState>().with(&app, |service| {
Ok(vec![service.inspect_download(window.label(), download)?])
let owner = window.label().to_owned();
PluginState::run(&app, move |service| {
Ok(vec![service.inspect_download(&owner, download)?])
})
.await
}
#[tauri::command]
pub async fn plugins_cancel(
app: AppHandle,
window: tauri::Window,
state: State<'_, PluginState>,
tokens: Vec<String>,
) -> Result<()> {
state.with(&app, |service| {
let owner = window.label().to_owned();
PluginState::run(&app, move |service| {
for token in tokens {
if service
.candidates
.get(&token)
.is_some_and(|c| c.owner == window.label())
.is_some_and(|c| c.owner == owner)
{
let candidate = service.candidates.remove(&token).unwrap();
let _ = erase(&service.directory("plugin-staging")?, &candidate.directory);
@@ -1059,40 +1110,51 @@ pub async fn plugins_cancel(
if service
.plans
.get(&token)
.is_some_and(|p| p.owner == window.label())
.is_some_and(|p| p.owner == owner)
{
service.plans.remove(&token);
}
}
Ok(())
})
.await
}
#[tauri::command]
pub async fn plugins_install(
app: AppHandle,
window: tauri::Window,
state: State<'_, PluginState>,
tokens: Vec<String>,
enabled: bool,
) -> Result<Vec<InstallResult>> {
let owner = window.label().to_owned();
let mut result = Vec::new();
for token in tokens {
let name = state.with(&app, |service| Ok(service.candidates.get(&token)
.map(|candidate| candidate.manifest.name.clone()).unwrap_or_else(|| "Plugin".into())))?;
let updating = state.with(&app, |service| service.begin_update(window.label(), &token));
let name = PluginState::run(&app, {
let token = token.clone();
move |service| Ok(service.candidates.get(&token)
.map(|candidate| candidate.manifest.name.clone()).unwrap_or_else(|| "Plugin".into()))
}).await?;
let updating = PluginState::run(&app, {
let (owner, token) = (owner.clone(), token.clone());
move |service| service.begin_update(&owner, &token)
}).await;
let error = match updating {
Err(error) => Some(error),
Ok(id) => {
if let Some(id) = &id {
changed(&app);
let start = Instant::now();
while state.with(&app, |service| Ok(service.leases.get(id).is_some_and(|windows| !windows.is_empty())))?
while PluginState::run(&app, {
let id = id.clone();
move |service| Ok(service.leases.get(&id).is_some_and(|windows| !windows.is_empty()))
}).await?
&& start.elapsed() < Duration::from_secs(10) {
tauri::async_runtime::spawn_blocking(|| std::thread::sleep(Duration::from_millis(50))).await?;
}
}
let installed = state.with(&app, |service| {
let installed = service.install(window.label(), &token, enabled);
let owner = owner.clone();
let installed = PluginState::run(&app, move |service| {
let installed = service.install(&owner, &token, enabled);
if let Some(id) = &id {
service.removing.remove(id);
if installed.is_err() {
@@ -1103,7 +1165,7 @@ pub async fn plugins_install(
}
}
installed
});
}).await;
installed.err()
}
};
@@ -1115,13 +1177,12 @@ pub async fn plugins_install(
#[tauri::command]
pub async fn plugins_set_enabled(
app: AppHandle,
state: State<'_, PluginState>,
id: String,
enabled: bool,
hash: Option<String>,
) -> Result<()> {
let stop_browser = id == "runestone.browser" && !enabled;
state.with(&app, |service| {
PluginState::run(&app, move |service| {
if service.removing.contains_key(&id) {
return Err("Wait for plugin removal to finish.".into());
}
@@ -1148,8 +1209,12 @@ pub async fn plugins_set_enabled(
return Err(error);
}
Ok(())
})?;
if stop_browser { app.state::<crate::browser::BrowserState>().close_all(); }
}).await?;
if stop_browser {
// Stopping the browser engine waits for its reply.
let browser_app = app.clone();
tauri::async_runtime::spawn_blocking(move || browser_app.state::<crate::browser::BrowserState>().close_all()).await?;
}
changed(&app);
Ok(())
}
@@ -1157,11 +1222,11 @@ pub async fn plugins_set_enabled(
pub async fn plugins_load(
app: AppHandle,
window: tauri::Window,
state: State<'_, PluginState>,
id: String,
hash: String,
) -> Result<String> {
state.with(&app, |service| {
let owner = window.label().to_owned();
PluginState::run(&app, move |service| {
let row = service.row(&id)?;
if !row.enabled || row.hash != hash {
return Err("The plugin is disabled or changed.".into());
@@ -1174,42 +1239,43 @@ pub async fn plugins_load(
.leases
.entry(id)
.or_default()
.insert(window.label().into());
.insert(owner);
String::from_utf8(current.files[&current.manifest.entry].clone()).map_err(Error::from)
})
.await
}
#[tauri::command]
pub async fn plugins_release(
app: AppHandle,
window: tauri::Window,
state: State<'_, PluginState>,
id: String,
error: Option<String>,
) -> Result<()> {
state.with(&app, |service| {
let owner = window.label().to_owned();
PluginState::run(&app, move |service| {
if let Some(error) = error {
service.cleanup_errors.insert(id.clone(), error);
}
if let Some(windows) = service.leases.get_mut(&id) {
windows.remove(window.label());
windows.remove(&owner);
}
Ok(())
})
.await
}
#[tauri::command]
pub async fn plugins_prepare_remove(
app: AppHandle,
window: tauri::Window,
state: State<'_, PluginState>,
id: String,
) -> Result<RemovalPlan> {
state.with(&app, |service| service.prepare(window.label(), &id))
let owner = window.label().to_owned();
PluginState::run(&app, move |service| service.prepare(&owner, &id)).await
}
#[tauri::command]
pub async fn plugins_remove(app: AppHandle, window: tauri::Window, token: String) -> Result<()> {
let id = app
.state::<PluginState>()
.with(&app, |service| service.begin_remove(window.label(), &token))?;
let owner = window.label().to_owned();
let id = PluginState::run(&app, move |service| service.begin_remove(&owner, &token)).await?;
changed(&app);
let worker_app = app.clone();
let result = tauri::async_runtime::spawn_blocking(move || {
@@ -1243,21 +1309,19 @@ pub async fn plugins_remove(app: AppHandle, window: tauri::Window, token: String
#[tauri::command]
pub async fn plugins_retry_remove(
app: AppHandle,
state: State<'_, PluginState>,
id: String,
) -> Result<()> {
let result = state.with(&app, |service| service.retry_removal(&id));
let result = PluginState::run(&app, move |service| service.retry_removal(&id)).await;
changed(&app);
result
}
#[tauri::command]
pub async fn plugins_reveal(
app: AppHandle,
state: State<'_, PluginState>,
id: Option<String>,
) -> Result<()> {
let open_directory = id.is_none();
let path = state.with(&app, |service| {
let path = PluginState::run(&app, move |service| {
let root = service.directory("plugins")?;
if let Some(id) = id {
if !service.catalog.plugins.contains_key(&id) {
@@ -1269,7 +1333,7 @@ pub async fn plugins_reveal(
} else {
Ok(root)
}
})?;
}).await?;
if open_directory {
app.opener()
.open_path(path.to_string_lossy().into_owned(), None::<&str>)
@@ -1281,12 +1345,13 @@ pub async fn plugins_reveal(
#[tauri::command]
pub async fn plugins_data(
app: AppHandle,
state: State<'_, PluginState>,
id: String,
value: Option<String>,
) -> Result<String> {
let changed = value.is_some();
let result = state.with(&app, |service| {
let plugin = id.clone();
let result = PluginState::run(&app, move |service| {
let id = plugin;
if !service.row(&id)?.enabled {
return Err("The plugin is disabled.".into());
}
@@ -1313,7 +1378,7 @@ pub async fn plugins_data(
} else {
Ok("null".into())
}
})?;
}).await?;
if changed {
let _ = app.emit("plugin-settings-changed", &id);
}
@@ -1322,12 +1387,11 @@ pub async fn plugins_data(
#[tauri::command]
pub async fn plugins_asset(
app: AppHandle,
state: State<'_, PluginState>,
id: String,
path: String,
) -> Result<String> {
use base64::Engine;
state.with(&app, |service| {
PluginState::run(&app, move |service| {
if !service.row(&id)?.enabled {
return Err("The plugin is disabled.".into());
}
@@ -1342,6 +1406,7 @@ pub async fn plugins_asset(
.ok_or("The plugin asset is missing.")?;
Ok(base64::engine::general_purpose::STANDARD.encode(bytes))
})
.await
}
#[cfg(test)]
mod tests {
@@ -1834,6 +1899,47 @@ mod tests {
assert!(path.exists());
}
#[test]
fn lease_errors_name_the_plugin_that_is_not_enabled() {
let mut f = Fixture::new();
let id = f.install(true);
let error = f.service.require_lease("main", &id).unwrap_err().to_string();
assert_eq!(error, "The Demo plugin is not enabled in this window.");
assert!(!error.contains("browser"));
assert_eq!(
f.service.require_lease("main", "runestone.backgrounds").unwrap_err().to_string(),
"This plugin is not enabled in this window."
);
f.service.leases.entry(id.clone()).or_default().insert("main".into());
f.service.require_lease("main", &id).unwrap();
assert!(f.service.require_lease("other", &id).is_err());
f.service.catalog.plugins.get_mut(&id).unwrap().enabled = false;
assert!(f.service.require_lease("main", &id).is_err());
}
#[test]
fn closing_a_window_releases_its_leases_and_erases_its_reviews() {
let mut f = Fixture::new();
let id = f.install(true);
f.service.leases.entry(id.clone()).or_default().extend(["main".to_owned(), "other".to_owned()]);
let mine = f.service.inspect("main", f.source.clone());
let theirs = f.service.inspect("other", f.source.clone());
let folder = f.service.candidates[&mine.token].directory.clone();
let kept = f.service.candidates[&theirs.token].directory.clone();
assert!(folder.is_dir());
let (root, folders) = f.service.release_window("main");
// The plugin lock is open again before the files are erased.
assert!(folder.is_dir());
StagingCleanup(Some((root, folders))).erase();
assert!(!folder.exists());
assert!(kept.is_dir());
assert!(!f.service.candidates.contains_key(&mine.token));
assert!(f.service.candidates.contains_key(&theirs.token));
assert_eq!(f.service.leases[&id], BTreeSet::from(["other".to_owned()]));
let state = PluginState::default();
assert!(state.try_release_window("main").is_some());
let _guard = state.inner.lock().unwrap();
assert!(state.try_release_window("main").is_none(), "A busy plugin lock must not stop the caller.");
}
#[test]
fn removal_waits_for_every_window_and_preserves_user_data() {
let mut f = Fixture::new();
let id = f.install(true);