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
+22 -17
View File
@@ -18,10 +18,14 @@ pub struct BackgroundFile {
}
fn require_plugin(app: &AppHandle, window: &Window, id: &str) -> Result<()> {
app.state::<PluginState>()
.require_lease(app, window.label(), id)
.map_err(|_| "The plugin is not enabled in this window.".into())
fn require_plugin(app: &AppHandle, label: &str, id: &str) -> Result<()> {
app.state::<PluginState>().require_lease(app, label, id)
}
/// Check the lease on a blocking worker, because the plugin lock can wait for package work.
async fn check_plugin(app: &AppHandle, window: &Window, id: &str) -> Result<()> {
let (app, label, id) = (app.clone(), window.label().to_owned(), id.to_owned());
tauri::async_runtime::spawn_blocking(move || require_plugin(&app, &label, &id)).await?
}
fn folder_root(folder: &Path) -> Result<PathBuf> {
@@ -128,11 +132,12 @@ pub async fn backgrounds_default_folder(
window: Window,
id: String,
) -> Result<String> {
require_plugin(&app, &window, &id)?;
check_plugin(&app, &window, &id).await?;
let pictures = app.path().picture_dir()?;
let folder = pictures.join("RuneStone Backgrounds");
fs::create_dir_all(&folder)?;
require_plugin(&app, &window, &id)?;
let created = folder.clone();
tauri::async_runtime::spawn_blocking(move || fs::create_dir_all(created)).await??;
check_plugin(&app, &window, &id).await?;
folder_root(&folder).map(|root| root.to_string_lossy().into_owned())
}
@@ -142,7 +147,7 @@ pub async fn backgrounds_choose_folder(
window: Window,
id: String,
) -> Result<Option<String>> {
require_plugin(&app, &window, &id)?;
check_plugin(&app, &window, &id).await?;
let picker_app = app.clone();
let picker_window = window.clone();
let selected = tauri::async_runtime::spawn_blocking(move || {
@@ -154,7 +159,7 @@ pub async fn backgrounds_choose_folder(
.blocking_pick_folder()
})
.await?;
require_plugin(&app, &window, &id)?;
check_plugin(&app, &window, &id).await?;
selected
.map(|source| {
let path = source.into_path().map_err(Error::from_display)?;
@@ -170,10 +175,10 @@ pub async fn backgrounds_list(
id: String,
folder: String,
) -> Result<Vec<BackgroundFile>> {
require_plugin(&app, &window, &id)?;
check_plugin(&app, &window, &id).await?;
let result = tauri::async_runtime::spawn_blocking(move || list_images(Path::new(&folder)))
.await??;
require_plugin(&app, &window, &id)?;
check_plugin(&app, &window, &id).await?;
Ok(result)
}
@@ -185,11 +190,11 @@ pub async fn backgrounds_read(
folder: String,
name: String,
) -> Result<String> {
require_plugin(&app, &window, &id)?;
check_plugin(&app, &window, &id).await?;
let result =
tauri::async_runtime::spawn_blocking(move || read_image(Path::new(&folder), &name))
.await??;
require_plugin(&app, &window, &id)?;
check_plugin(&app, &window, &id).await?;
Ok(base64::engine::general_purpose::STANDARD.encode(result))
}
@@ -243,18 +248,18 @@ fn write_image_settings(folder: &Path, contents: &str, expected: Option<&str>) -
#[tauri::command]
pub async fn backgrounds_read_image_settings(app: AppHandle, window: Window, id: String, folder: String) -> Result<Option<String>> {
require_plugin(&app, &window, &id)?;
check_plugin(&app, &window, &id).await?;
let result = tauri::async_runtime::spawn_blocking(move || read_image_settings(Path::new(&folder))).await??;
require_plugin(&app, &window, &id)?;
check_plugin(&app, &window, &id).await?;
Ok(result)
}
#[tauri::command]
pub async fn backgrounds_write_image_settings(app: AppHandle, window: Window, id: String, folder: String, contents: String, expected: Option<String>) -> Result<()> {
require_plugin(&app, &window, &id)?;
check_plugin(&app, &window, &id).await?;
// Check the lease again immediately before the write on the blocking worker.
tauri::async_runtime::spawn_blocking(move || {
require_plugin(&app, &window, &id)?;
require_plugin(&app, window.label(), &id)?;
write_image_settings(Path::new(&folder), &contents, expected.as_deref())
}).await?
}
+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();
+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"));
}
}
+2 -4
View File
@@ -12,10 +12,8 @@ impl Fixture {
&["init", "--bare", "--initial-branch=main", "remote.git"],
);
fixture.git(".", &["clone", "remote.git", "local"]);
for directory in ["local"] {
fixture.git(directory, &["config", "user.name", "RuneStone Test"]);
fixture.git(directory, &["config", "user.email", "[email protected]"]);
}
fixture.git("local", &["config", "user.name", "RuneStone Test"]);
fixture.git("local", &["config", "user.email", "[email protected]"]);
fixture
}
fn path(&self, directory: &str) -> PathBuf {
+18 -3
View File
@@ -106,13 +106,28 @@ pub fn run() {
.expect("error while building tauri application")
.run(|app, event| {
if let tauri::RunEvent::WindowEvent { label, event: tauri::WindowEvent::Destroyed, .. } = &event {
// This handler runs on the main thread. Here, revoke the window's access
// with short locks only. A cleanup thread stops processes and erases files.
settings::close_owned_window(app, label);
spelling::close_window(app, label);
app.state::<PtyState>().close_window(label);
app.state::<completion::CompletionState>().close_window(label);
app.state::<browser::BrowserState>().close_window(label);
app.state::<plugins::PluginState>().close_window(label);
let browser_tabs = app.state::<browser::BrowserState>().release_window(label);
let staging = app.state::<plugins::PluginState>().try_release_window(label);
app.state::<WorkspaceState>().close_window(label);
let app = app.clone();
let label = label.clone();
let cleanup = std::thread::Builder::new().name("window-cleanup".into()).spawn(move || {
app.state::<PtyState>().close_window(&label);
app.state::<browser::BrowserState>().close_tabs(browser_tabs);
match staging {
Some(staging) => staging.erase(),
// Another plugin command held the lock. Wait for it here.
None => app.state::<plugins::PluginState>().close_window(&label),
}
});
if let Err(error) = cleanup {
eprintln!("RuneStone could not start the window cleanup: {error}");
}
}
if matches!(event, tauri::RunEvent::Exit) {
app.state::<PtyState>().close_all();
+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);
+77 -25
View File
@@ -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();
+2 -1
View File
@@ -54,7 +54,8 @@ fn spawn_external_terminal(
"No supported external terminal was found. Install a supported terminal emulator or use RuneStone's Terminal plugin."))
}
#[cfg(test)]
// Every test here checks Unix behavior.
#[cfg(all(test, unix))]
mod tests {
use super::*;