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
+150 -21
View File
@@ -52,6 +52,11 @@ const COMMANDS: &[&str] = &[
pub struct BrowserState {
inner: Mutex<Option<Worker>>,
sessions: Mutex<HashMap<String, String>>,
/// Tab owners. Each engine uses this table, so a closing window can release its tabs
/// without waiting for the engine lock.
routing: Arc<Mutex<WindowTabs>>,
/// Held while a retired engine stops. A new engine starts after the old one has stopped.
stopping: Mutex<()>,
}
#[derive(Default)]
struct WindowTabs {
@@ -99,6 +104,8 @@ struct Worker {
input: Box<dyn Write + Send>,
replies: mpsc::Receiver<Value>,
routing: Arc<Mutex<WindowTabs>>,
/// Requests that nobody waits for. The reader drops their replies.
discard: Arc<Mutex<HashSet<u64>>>,
sequence: u64,
healthy: bool,
}
@@ -204,6 +211,8 @@ impl Worker {
let (send, replies) = mpsc::sync_channel(16);
let handle = app.clone();
let routes = routing.clone();
let discard = Arc::new(Mutex::new(HashSet::new()));
let unanswered = discard.clone();
std::thread::spawn(move || {
let mut reader = BufReader::new(output);
loop {
@@ -241,7 +250,10 @@ impl Worker {
}
}
_ => {
if send.try_send(value).is_err() {
let dropped = value["id"].as_u64().is_some_and(|id| {
unanswered.lock().is_ok_and(|mut ids| ids.remove(&id))
});
if !dropped && send.try_send(value).is_err() {
break;
}
}
@@ -253,6 +265,7 @@ impl Worker {
input,
replies,
routing,
discard,
sequence: 0,
healthy: true,
};
@@ -278,6 +291,17 @@ impl Worker {
}
Ok(response["result"].clone())
}
/// Send a request and do not wait for its reply. The reader drops the reply.
fn notify(&mut self, command: &str, args: Value) -> Result<()> {
self.sequence += 1;
self.discard.lock()?.insert(self.sequence);
let message = json!({ "id": self.sequence, "command": command, "args": args });
let sent = writeln!(self.input, "{}", message).and_then(|_| self.input.flush());
if sent.is_err() {
self.healthy = false;
}
Ok(sent?)
}
fn exchange(&mut self, command: &str, args: Value) -> Result<Value> {
self.sequence += 1;
let message = json!({ "id": self.sequence, "command": command, "args": args });
@@ -333,7 +357,8 @@ fn copy_profile(source: &Path, target: &Path, files: &mut usize, bytes: &mut u64
return Ok(());
}
let metadata = fs::symlink_metadata(source)?;
if metadata.file_type().is_symlink() {
// A junction is not a symbolic link, but the copy would also follow it.
if crate::fsutil::is_link(&metadata) {
return Err("Profile links cannot be duplicated.".into());
}
if metadata.is_dir() {
@@ -366,19 +391,35 @@ impl BrowserState {
Err("The browser session is unavailable in this window.".into())
}
}
pub fn close_window(&self, owner: &str) {
/// Revoke the window's session and release its tabs. Return the tabs to close in the engine.
/// This step never waits for the engine or for a request in progress.
pub fn release_window(&self, owner: &str) -> Vec<String> {
if let Ok(mut sessions) = self.sessions.lock() { sessions.remove(owner); }
if let Ok(mut guard) = self.inner.lock() {
self.routing.lock().map(|mut routes| routes.close(owner)).unwrap_or_default()
}
/// Close released tabs in the engine, and stop the engine when no window uses it.
/// This can wait for a request in progress. It never holds the engine lock while it waits for a reply.
pub fn close_tabs(&self, closed: Vec<String>) {
let (mut worker, _stopping) = {
let Ok(mut guard) = self.inner.lock() else { return; };
let Some(worker) = guard.as_mut() else { return; };
let (closed, empty) = match worker.routing.lock() {
Ok(mut routes) => { let closed = routes.close(owner); (closed, routes.windows.is_empty()) },
Err(_) => return,
};
for id in closed { let _ = worker.request("closeTab", json!({ "tabId": id })); }
if empty {
if let Some(mut worker) = guard.take() { let _ = worker.stop(); }
if worker.healthy {
for id in closed {
if worker.notify("closeTab", json!({ "tabId": id })).is_err() { break; }
}
}
}
// A request can add a window while this cleanup waits for the lock.
if !self.routing.lock().is_ok_and(|routes| routes.windows.is_empty()) { return; }
let Some(worker) = guard.take() else { return; };
// Take the stop lock before the engine lock opens, so that a new engine waits for this one.
let Ok(stopping) = self.stopping.lock() else { return; };
(worker, stopping)
};
let _ = worker.stop();
}
pub fn close_window(&self, owner: &str) {
let closed = self.release_window(owner);
self.close_tabs(closed);
}
pub fn close_all(&self) {
if let Ok(mut sessions) = self.sessions.lock() { sessions.clear(); }
@@ -397,7 +438,10 @@ impl BrowserState {
guard.take();
}
if guard.is_none() {
*guard = Some(Worker::start(app, Arc::new(Mutex::new(WindowTabs::default())))?);
// Wait until a retired engine has stopped. The new engine has no tabs yet.
let _stopped = self.stopping.lock()?;
*self.routing.lock()? = WindowTabs::default();
*guard = Some(Worker::start(app, self.routing.clone())?);
}
let worker = guard.as_mut().unwrap();
worker.routing.lock()?.windows.insert(owner.to_string());
@@ -494,21 +538,23 @@ pub async fn browser_request(
session: Option<String>,
) -> Result<Value> {
let owner = window.label().to_string();
if let Some(token) = session {
app.state::<BrowserState>().require_session(&owner, &token)?;
} else {
app.state::<crate::plugins::PluginState>()
.require_lease(&app, &owner, PLUGIN)?;
}
// The plugin lease check can wait for the plugin lock, so it also runs on the blocking worker.
tauri::async_runtime::spawn_blocking(move || {
if let Some(token) = session {
app.state::<BrowserState>().require_session(&owner, &token)?;
} else {
app.state::<crate::plugins::PluginState>()
.require_lease(&app, &owner, PLUGIN)?;
}
app.state::<BrowserState>()
.request(&app, &owner, &command, args)
})
.await?
}
#[tauri::command]
pub async fn browser_stop(state: State<'_, BrowserState>, window: tauri::Window) -> Result<()> {
state.close_window(window.label());
pub async fn browser_stop(app: AppHandle, window: tauri::Window) -> Result<()> {
let owner = window.label().to_string();
tauri::async_runtime::spawn_blocking(move || app.state::<BrowserState>().close_window(&owner)).await?;
Ok(())
}
@@ -636,10 +682,93 @@ mod tests {
input: Box::new(Vec::<u8>::new()),
replies,
routing: Arc::new(Mutex::new(WindowTabs::default())),
discard: Arc::new(Mutex::new(HashSet::new())),
sequence: 0,
healthy: true,
}
}
#[derive(Clone, Default)]
struct Sink(Arc<Mutex<Vec<u8>>>);
impl Write for Sink {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[test]
fn closing_a_window_releases_tabs_without_the_engine_lock() {
let state = BrowserState::default();
let token = state.connect("main").unwrap();
{
let mut routes = state.routing.lock().unwrap();
routes.windows.extend(["main".into(), "other".into()]);
routes.assign("a", "main");
routes.assign("b", "other");
}
let (send, replies) = mpsc::channel();
let sink = Sink::default();
let mut worker = test_worker(replies);
worker.input = Box::new(sink.clone());
worker.routing = state.routing.clone();
let discard = worker.discard.clone();
*state.inner.lock().unwrap() = Some(worker);
// A request in progress holds the engine lock, but the window is released at once.
let busy = state.inner.lock().unwrap();
let closed = state.release_window("main");
assert_eq!(closed, vec!["a"]);
assert!(state.require_session("main", &token).is_err());
assert!(!state.routing.lock().unwrap().owners.contains_key("a"));
drop(busy);
// No reply arrives, and the cleanup does not wait for one.
let start = Instant::now();
state.close_tabs(closed);
assert!(start.elapsed() < Duration::from_secs(5));
let sent = String::from_utf8(sink.0.lock().unwrap().clone()).unwrap();
assert!(sent.contains("\"closeTab\"") && sent.contains("\"a\""), "{sent}");
assert_eq!(discard.lock().unwrap().len(), 1);
assert!(state.inner.lock().unwrap().is_some(), "Another window still uses the engine.");
drop(send);
state.close_window("other");
assert!(state.inner.lock().unwrap().is_none(), "The last window stops the engine.");
assert!(state.routing.lock().unwrap().owners.is_empty());
}
#[test]
fn profile_copy_rejects_links_and_junctions() {
let base = std::env::temp_dir().join(format!("runestone-profile-{}", uuid::Uuid::new_v4()));
let source = base.join("source");
let outside = base.join("outside");
fs::create_dir_all(&source).unwrap();
fs::create_dir_all(&outside).unwrap();
fs::write(source.join("Cookies"), b"cookies").unwrap();
fs::write(outside.join("secret.txt"), b"secret").unwrap();
copy_profile(&source, &base.join("plain"), &mut 0, &mut 0).unwrap();
assert_eq!(fs::read(base.join("plain").join("Cookies")).unwrap(), b"cookies");
let link = source.join("linked");
// A junction needs no symbolic-link privilege on Windows.
#[cfg(windows)]
assert!(Command::new("cmd")
.args(["/C", "mklink", "/J"])
.arg(&link)
.arg(&outside)
.stdout(Stdio::null())
.status()
.unwrap()
.success());
#[cfg(unix)]
std::os::unix::fs::symlink(&outside, &link).unwrap();
let error = copy_profile(&source, &base.join("copy"), &mut 0, &mut 0).unwrap_err();
assert!(error.to_string().contains("links"), "{error}");
assert!(!base.join("copy").join("linked").join("secret.txt").exists());
#[cfg(windows)]
fs::remove_dir(&link).unwrap();
#[cfg(unix)]
fs::remove_file(&link).unwrap();
assert!(outside.join("secret.txt").exists());
fs::remove_dir_all(&base).unwrap();
}
#[test]
fn broken_transport_requires_a_fresh_worker() {
let (send, replies) = mpsc::channel();