Add a shared error type and shared file helpers to the Rust host

Replace the three error styles with one Error type and one Result alias in
error.rs. The error crosses IPC as the same plain string as before. The
message text does not change.

Move the shared file mechanics to fsutil.rs. These are the reserved-name
check, the link and junction check, the limited reads, and the atomic
writes. Each module keeps its own path rules, limits, and messages. The
plugin settings writer now flushes its file to disk before the rename.

Remove the current_root_path and list_entries wrappers and an unused mime
value. Use named windows-sys constants for the process, file, drive, and
error codes.

Add a test that compares the command lists in lib.rs, build.rs, and the
capability files. The settings capability must be a subset of the full list.

In Cargo.toml, set the author, keep only the rlib crate type, and remove
the unused thiserror dependency. Remove panic = "abort" from the release
profile. A panic on a worker thread then stops only that thread. It does
not stop the editor with unsaved buffers.
This commit is contained in:
Knotty Wyvern
2026-10-27 22:41:11 -07:00
parent 69f90df571
commit bd46f3a189
18 changed files with 1103 additions and 882 deletions
+40 -44
View File
@@ -11,7 +11,8 @@ use std::{
};
use tauri::{AppHandle, Emitter, Manager, State};
type Result<T> = std::result::Result<T, String>;
use crate::error::{Error, Result};
const PLUGIN: &str = "runestone.browser";
const COMMANDS: &[&str] = &[
"state",
@@ -102,11 +103,8 @@ struct Worker {
healthy: bool,
}
fn fail(error: impl std::fmt::Display) -> String {
error.to_string()
}
fn root(app: &AppHandle) -> Result<PathBuf> {
Ok(app.path().app_data_dir().map_err(fail)?.join("browser"))
Ok(app.path().app_data_dir()?.join("browser"))
}
fn executable(app: &AppHandle) -> Result<PathBuf> {
let name = if cfg!(windows) {
@@ -127,8 +125,7 @@ fn executable(app: &AppHandle) -> Result<PathBuf> {
}
let packaged = app
.path()
.resource_dir()
.map_err(fail)?
.resource_dir()?
.join("browser-engine")
.join(name);
if packaged.is_file() {
@@ -141,10 +138,10 @@ fn authenticate_connection(
stream: TcpStream,
token: &str,
) -> Result<Option<(TcpStream, BufReader<TcpStream>)>> {
stream.set_nonblocking(false).map_err(fail)?;
stream.set_nodelay(true).map_err(fail)?;
stream.set_read_timeout(Some(Duration::from_secs(1))).map_err(fail)?;
let mut reader = BufReader::new(stream.try_clone().map_err(fail)?);
stream.set_nonblocking(false)?;
stream.set_nodelay(true)?;
stream.set_read_timeout(Some(Duration::from_secs(1)))?;
let mut reader = BufReader::new(stream.try_clone()?);
let mut bytes = Vec::new();
let read = reader.by_ref().take(256).read_until(b'\n', &mut bytes);
let received = serde_json::from_slice::<Value>(&bytes)
@@ -154,18 +151,18 @@ fn authenticate_connection(
return Ok(None);
}
// Windows keeps the timeout on the cloned socket after the original changes.
reader.get_ref().set_read_timeout(None).map_err(fail)?;
stream.set_read_timeout(None).map_err(fail)?;
reader.get_ref().set_read_timeout(None)?;
stream.set_read_timeout(None)?;
Ok(Some((stream, reader)))
}
impl Worker {
fn start(app: &AppHandle, routing: Arc<Mutex<WindowTabs>>) -> Result<Self> {
let directory = root(app)?;
fs::create_dir_all(&directory).map_err(fail)?;
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).map_err(fail)?;
listener.set_nonblocking(true).map_err(fail)?;
let port = listener.local_addr().map_err(fail)?.port();
fs::create_dir_all(&directory)?;
let listener = std::net::TcpListener::bind(("127.0.0.1", 0))?;
listener.set_nonblocking(true)?;
let port = listener.local_addr()?.port();
let token = format!(
"{}{}",
uuid::Uuid::new_v4().simple(),
@@ -186,9 +183,9 @@ impl Worker {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x08000000);
command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW);
}
let mut child = command.spawn().map_err(fail)?;
let mut child = command.spawn()?;
let deadline = Instant::now() + Duration::from_secs(30);
let (input, output): (Box<dyn Write + Send>, Box<dyn Read + Send>) = loop {
if let Ok((stream, _)) = listener.accept() {
@@ -196,7 +193,7 @@ impl Worker {
break (Box::new(stream), Box::new(reader));
}
}
if Instant::now() >= deadline || child.try_wait().map_err(fail)?.is_some() {
if Instant::now() >= deadline || child.try_wait()?.is_some() {
let _ = child.kill();
let _ = child.wait();
return Err("The browser runtime did not start.".into());
@@ -284,8 +281,8 @@ impl Worker {
fn exchange(&mut self, command: &str, args: Value) -> Result<Value> {
self.sequence += 1;
let message = json!({ "id": self.sequence, "command": command, "args": args });
writeln!(self.input, "{}", message).map_err(fail)?;
self.input.flush().map_err(fail)?;
writeln!(self.input, "{}", message)?;
self.input.flush()?;
let response = self
.replies
.recv_timeout(Duration::from_secs(30))
@@ -306,7 +303,7 @@ impl Worker {
let requested = self.request("shutdown", json!({}));
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline {
if self.child.try_wait().map_err(fail)?.is_some() {
if self.child.try_wait()?.is_some() {
return requested.map(|_| ());
}
std::thread::sleep(Duration::from_millis(20));
@@ -332,17 +329,17 @@ fn profile_id(value: &str) -> bool {
}
fn copy_profile(source: &Path, target: &Path, files: &mut usize, bytes: &mut u64) -> Result<()> {
if !source.exists() {
fs::create_dir_all(target).map_err(fail)?;
fs::create_dir_all(target)?;
return Ok(());
}
let metadata = fs::symlink_metadata(source).map_err(fail)?;
let metadata = fs::symlink_metadata(source)?;
if metadata.file_type().is_symlink() {
return Err("Profile links cannot be duplicated.".into());
}
if metadata.is_dir() {
fs::create_dir_all(target).map_err(fail)?;
for entry in fs::read_dir(source).map_err(fail)? {
let entry = entry.map_err(fail)?;
fs::create_dir_all(target)?;
for entry in fs::read_dir(source)? {
let entry = entry?;
copy_profile(&entry.path(), &target.join(entry.file_name()), files, bytes)?;
}
} else if metadata.is_file() {
@@ -351,7 +348,7 @@ fn copy_profile(source: &Path, target: &Path, files: &mut usize, bytes: &mut u64
if *files > 50_000 || *bytes > 2_000_000_000 {
return Err("This profile exceeds the duplication limit.".into());
}
fs::copy(source, target).map_err(fail)?;
fs::copy(source, target)?;
} else {
return Err("Unsupported profile entry.".into());
}
@@ -359,11 +356,11 @@ fn copy_profile(source: &Path, target: &Path, files: &mut usize, bytes: &mut u64
}
impl BrowserState {
fn connect(&self, owner: &str) -> Result<String> {
let mut sessions = self.sessions.lock().map_err(fail)?;
let mut sessions = self.sessions.lock()?;
Ok(sessions.entry(owner.to_string()).or_insert_with(|| uuid::Uuid::new_v4().to_string()).clone())
}
fn require_session(&self, owner: &str, token: &str) -> Result<()> {
if self.sessions.lock().map_err(fail)?.get(owner).is_some_and(|saved| saved == token) {
if self.sessions.lock()?.get(owner).is_some_and(|saved| saved == token) {
Ok(())
} else {
Err("The browser session is unavailable in this window.".into())
@@ -395,7 +392,7 @@ impl BrowserState {
if !COMMANDS.contains(&command) || args.to_string().len() > 180_000 || !args.is_object() {
return Err("Invalid browser request.".into());
}
let mut guard = self.inner.lock().map_err(fail)?;
let mut guard = self.inner.lock()?;
if guard.as_ref().is_some_and(|worker| !worker.healthy) {
guard.take();
}
@@ -403,7 +400,7 @@ impl BrowserState {
*guard = Some(Worker::start(app, Arc::new(Mutex::new(WindowTabs::default())))?);
}
let worker = guard.as_mut().unwrap();
worker.routing.lock().map_err(fail)?.windows.insert(owner.to_string());
worker.routing.lock()?.windows.insert(owner.to_string());
if command == "adoptTab" {
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
let result = worker.request("state", json!({}))?;
@@ -411,15 +408,15 @@ impl BrowserState {
return Err("Unknown browser tab.".into());
}
let source = {
let mut routes = worker.routing.lock().map_err(fail)?;
let mut routes = worker.routing.lock()?;
routes.adopt(id, owner, args["transferToken"].as_str())?
};
let _ = app.emit_to(&source, "browser-tab-moved", json!({ "tabId": id }));
return Ok(worker.routing.lock().map_err(fail)?.snapshot(result, owner));
return Ok(worker.routing.lock()?.snapshot(result, owner));
}
if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "focus", "input", "insertText", "edit", "contextAction", "frameAck", "bookmark", "agentSnapshot"].contains(&command) {
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
match worker.routing.lock().map_err(fail)?.owners.get(id) {
match worker.routing.lock()?.owners.get(id) {
Some(window) if window == owner => {},
Some(_) => return Err("This browser tab belongs to another window.".into()),
None => return Err("Unknown browser tab.".into()),
@@ -429,26 +426,26 @@ impl BrowserState {
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
let label = format!("browser-{}", uuid::Uuid::new_v4());
{
let mut routes = worker.routing.lock().map_err(fail)?;
let mut routes = worker.routing.lock()?;
if routes.pending.contains_key(id) { return Err("This tab already has a pending window move.".into()); }
routes.pending.insert(id.into(), label.clone());
routes.windows.insert(label.clone());
}
let mut url = tauri::Url::parse("http://localhost/").map_err(fail)?;
let mut url = tauri::Url::parse("http://localhost/").map_err(Error::from_display)?;
url.query_pairs_mut().append_pair("browserWindow", "true");
url.query_pairs_mut().append_pair("browserTab", id);
if args["pinned"] == true { url.query_pairs_mut().append_pair("browserPinned", "true"); }
let result = tauri::WebviewWindowBuilder::new(app, &label, tauri::WebviewUrl::App(format!("?{}", url.query().unwrap_or_default()).into()))
.title("RuneStone Browser").inner_size(1100.0, 750.0).min_inner_size(500.0, 300.0).decorations(false).disable_drag_drop_handler().build();
if let Err(error) = result {
worker.routing.lock().map_err(fail)?.close(&label);
return Err(fail(error));
worker.routing.lock()?.close(&label);
return Err(Error::from(error));
}
return Ok(json!({ "windowLabel": label }));
}
if command != "duplicateProfile" {
let result = worker.request(command, args.clone())?;
let mut routes = worker.routing.lock().map_err(fail)?;
let mut routes = worker.routing.lock()?;
if command == "newTab" {
if let Some(id) = result["tabId"].as_str() { routes.assign(id, owner); }
} else if command == "closeTab" {
@@ -479,7 +476,7 @@ impl BrowserState {
copy_profile(&source, &destination, &mut 0, &mut 0)?;
*guard = Some(Worker::start(app, routing.clone())?);
let result = guard.as_mut().unwrap().request("commitDuplicate", plan)?;
let snapshot = routing.lock().map_err(fail)?.snapshot(result, owner);
let snapshot = routing.lock()?.snapshot(result, owner);
Ok(snapshot)
}
}
@@ -507,8 +504,7 @@ pub async fn browser_request(
app.state::<BrowserState>()
.request(&app, &owner, &command, args)
})
.await
.map_err(fail)?
.await?
}
#[tauri::command]
pub async fn browser_stop(state: State<'_, BrowserState>, window: tauri::Window) -> Result<()> {