Add completion, browser integration, and workspace improvements

This commit is contained in:
Knotty Wyvern
2026-10-07 11:25:17 -07:00
parent dd9fc64676
commit a8b1defb9d
86 changed files with 3524 additions and 203 deletions
+639
View File
@@ -0,0 +1,639 @@
use serde_json::{json, Value};
use std::{
collections::{HashMap, HashSet},
fs,
io::{BufRead, BufReader, Read, Write},
net::TcpStream,
path::{Path, PathBuf},
process::{Child, Command, Stdio},
sync::{mpsc, Arc, Mutex},
time::{Duration, Instant},
};
use tauri::{AppHandle, Emitter, Manager, State};
type Result<T> = std::result::Result<T, String>;
const PLUGIN: &str = "runestone.browser";
const COMMANDS: &[&str] = &[
"state",
"newTab",
"closeTab",
"navigate",
"back",
"forward",
"reload",
"stop",
"find",
"stopFind",
"openExternal",
"moveToWindow",
"adoptTab",
"resize",
"visible",
"input",
"createProfile",
"renameProfile",
"duplicateProfile",
"bookmark",
"removeBookmark",
"settings",
"clearData",
"agentSnapshot",
];
#[derive(Default)]
pub struct BrowserState {
inner: Mutex<Option<Worker>>,
}
#[derive(Default)]
struct WindowTabs {
windows: HashSet<String>,
owners: HashMap<String, String>,
pending: HashMap<String, String>,
transfer_tokens: HashMap<String, String>,
}
impl WindowTabs {
fn snapshot(&self, mut value: Value, owner: &str) -> Value {
if let Some(tabs) = value.get_mut("tabs").and_then(Value::as_array_mut) {
tabs.retain(|tab| tab["id"].as_str().and_then(|id| self.owners.get(id)).is_some_and(|window| window == owner));
for tab in tabs {
if let Some(token) = tab["id"].as_str().and_then(|id| self.transfer_tokens.get(id)) {
tab["transferToken"] = json!(token);
}
}
}
value
}
fn close(&mut self, owner: &str) -> Vec<String> {
self.windows.remove(owner);
self.pending.retain(|_, target| target != owner);
let closed: Vec<String> = self.owners.iter().filter(|(id, window)| !self.windows.contains(*window) && !self.pending.contains_key(*id)).map(|(id, _)| id.clone()).collect();
for id in &closed { self.owners.remove(id); self.transfer_tokens.remove(id); }
closed
}
fn assign(&mut self, id: &str, owner: &str) {
self.owners.insert(id.into(), owner.into());
self.transfer_tokens.insert(id.into(), uuid::Uuid::new_v4().to_string());
}
fn adopt(&mut self, id: &str, owner: &str, token: Option<&str>) -> Result<String> {
let source = self.owners.get(id).cloned().ok_or("Unknown browser tab.")?;
if source == owner { return Err("This browser tab already belongs to this window.".into()); }
let pending = self.pending.get(id).map(String::as_str);
let dragged = pending.is_none() && token.is_some() && self.transfer_tokens.get(id).map(String::as_str) == token;
if pending != Some(owner) && !dragged { return Err("This browser tab has no valid transfer to this window.".into()); }
self.assign(id, owner);
self.pending.remove(id);
Ok(source)
}
}
struct Worker {
child: Child,
input: Box<dyn Write + Send>,
replies: mpsc::Receiver<Value>,
routing: Arc<Mutex<WindowTabs>>,
sequence: u64,
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"))
}
fn executable(app: &AppHandle) -> Result<PathBuf> {
let name = if cfg!(windows) {
"RuneStone-Browser.exe"
} else {
"RuneStone-Browser"
};
let packaged = app
.path()
.resource_dir()
.map_err(fail)?
.join("browser-engine")
.join(name);
if packaged.is_file() {
return Ok(packaged);
}
#[cfg(debug_assertions)]
{
let development = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("browser-engine")
.join(name);
if development.is_file() {
return Ok(development);
}
}
Err("The browser runtime is missing. Build RuneStone with its browser runtime.".into())
}
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)?);
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)
.ok()
.and_then(|value| value["token"].as_str().map(str::to_string));
if read.is_err() || received.as_deref() != Some(token) {
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)?;
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();
let token = format!(
"{}{}",
uuid::Uuid::new_v4().simple(),
uuid::Uuid::new_v4().simple()
);
let mut command = Command::new(executable(app)?);
command
.arg(format!("--rs-connect={port}"))
.arg(format!("--rs-browser-root={}", directory.display()))
.env("RUNESTONE_BROWSER_TOKEN", &token)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
command
.env_remove("ELECTRON_RUN_AS_NODE")
.env_remove("NODE_OPTIONS")
.env_remove("ELECTRON_DISABLE_SANDBOX");
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x08000000);
}
let mut child = command.spawn().map_err(fail)?;
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() {
if let Some((stream, reader)) = authenticate_connection(stream, &token)? {
break (Box::new(stream), Box::new(reader));
}
}
if Instant::now() >= deadline || child.try_wait().map_err(fail)?.is_some() {
let _ = child.kill();
let _ = child.wait();
return Err("The browser runtime did not start.".into());
}
std::thread::sleep(Duration::from_millis(20));
};
drop(listener);
let (send, replies) = mpsc::sync_channel(16);
let handle = app.clone();
let routes = routing.clone();
std::thread::spawn(move || {
let mut reader = BufReader::new(output);
loop {
let mut bytes = Vec::new();
match reader
.by_ref()
.take(6_000_001)
.read_until(b'\n', &mut bytes)
{
Ok(0) | Err(_) => break,
Ok(_) if bytes.len() > 6_000_000 || !bytes.ends_with(b"\n") => break,
_ => {}
}
let Ok(value) = serde_json::from_slice::<Value>(&bytes) else {
continue;
};
match value.get("event").and_then(Value::as_str) {
Some("frame") => {
if let Ok(routes) = routes.lock() {
if let Some(target) = value["tabId"].as_str().and_then(|id| routes.owners.get(id)) {
let _ = handle.emit_to(target, "browser-frame", &value);
}
}
}
Some("state") | Some("error") => {
if let Ok(routes) = routes.lock() {
for target in &routes.windows {
if let Some(id) = value["tabId"].as_str() {
if routes.owners.get(id) != Some(target) { continue; }
}
let mut payload = value.clone();
if value.get("state").is_some() { payload["state"] = routes.snapshot(value["state"].clone(), target); }
let _ = handle.emit_to(target, "browser-state", &payload);
}
}
}
_ => {
if send.try_send(value).is_err() {
break;
}
}
}
}
});
let mut worker = Self {
child,
input,
replies,
routing,
sequence: 0,
healthy: true,
};
match worker.replies.recv_timeout(Duration::from_secs(30)) {
Ok(value) if value["event"] == "ready" => Ok(worker),
_ => {
let _ = worker.child.kill();
let _ = worker.child.wait();
Err("The browser runtime did not start.".into())
}
}
}
fn request(&mut self, command: &str, args: Value) -> Result<Value> {
let response = match self.exchange(command, args) {
Ok(response) => response,
Err(error) => {
self.healthy = false;
return Err(error);
}
};
if let Some(error) = response["error"].as_str() {
return Err(error.into());
}
Ok(response["result"].clone())
}
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)?;
let response = self
.replies
.recv_timeout(Duration::from_secs(30))
.map_err(|_| {
"The browser stopped responding. Open a new browser tab to restart it.".to_string()
})?;
if response["id"].as_u64() != Some(self.sequence) {
return Err("The browser response did not match the request.".into());
}
Ok(response)
}
fn stop(&mut self) -> Result<()> {
if !self.healthy {
let _ = self.child.kill();
let _ = self.child.wait();
return Ok(());
}
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() {
return requested.map(|_| ());
}
std::thread::sleep(Duration::from_millis(20));
}
let _ = self.child.kill();
let _ = self.child.wait();
Err("The browser did not stop cleanly. Profile duplication was cancelled.".into())
}
}
impl Drop for Worker {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
fn profile_id(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 64
&& value
.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
}
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)?;
return Ok(());
}
let metadata = fs::symlink_metadata(source).map_err(fail)?;
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)?;
copy_profile(&entry.path(), &target.join(entry.file_name()), files, bytes)?;
}
} else if metadata.is_file() {
*files += 1;
*bytes += metadata.len();
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)?;
} else {
return Err("Unsupported profile entry.".into());
}
Ok(())
}
impl BrowserState {
pub fn close_window(&self, owner: &str) {
if let Ok(mut guard) = self.inner.lock() {
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(); }
}
}
}
pub fn close_all(&self) {
if let Ok(mut guard) = self.inner.lock() {
if let Some(mut worker) = guard.take() {
let _ = worker.stop();
}
}
}
fn request(&self, app: &AppHandle, owner: &str, command: &str, args: Value) -> Result<Value> {
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)?;
if guard.as_ref().is_some_and(|worker| !worker.healthy) {
guard.take();
}
if guard.is_none() {
*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());
if command == "adoptTab" {
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
let result = worker.request("state", json!({}))?;
if !result["tabs"].as_array().is_some_and(|tabs| tabs.iter().any(|tab| tab["id"] == id)) {
return Err("Unknown browser tab.".into());
}
let source = {
let mut routes = worker.routing.lock().map_err(fail)?;
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));
}
if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "input", "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) {
Some(window) if window == owner => {},
Some(_) => return Err("This browser tab belongs to another window.".into()),
None => return Err("Unknown browser tab.".into()),
}
}
if command == "moveToWindow" {
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)?;
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)?;
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).drag_and_drop(false).build();
if let Err(error) = result {
worker.routing.lock().map_err(fail)?.close(&label);
return Err(fail(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)?;
if command == "newTab" {
if let Some(id) = result["tabId"].as_str() { routes.assign(id, owner); }
} else if command == "closeTab" {
if let Some(id) = args["tabId"].as_str() { routes.owners.remove(id); routes.pending.remove(id); routes.transfer_tokens.remove(id); }
}
return Ok(routes.snapshot(result, owner));
}
let plan = guard.as_mut().unwrap().request("prepareDuplicate", args)?;
let source_id = plan["sourceId"]
.as_str()
.filter(|id| profile_id(id))
.ok_or("Invalid source profile.")?;
let target_id = plan["id"]
.as_str()
.filter(|id| uuid::Uuid::parse_str(id).is_ok())
.ok_or("Invalid destination profile.")?;
let mut worker = guard.take().unwrap();
let routing = worker.routing.clone();
worker.stop()?;
drop(worker);
// Chromium is fully stopped before its databases are copied.
let partitions = root(app)?.join("Partitions");
let source = partitions.join(format!("runestone-{source_id}"));
let destination = partitions.join(format!("runestone-{target_id}"));
if destination.exists() {
return Err("The destination profile already exists.".into());
}
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);
Ok(snapshot)
}
}
#[tauri::command]
pub async fn browser_request(
app: AppHandle,
window: tauri::Window,
command: String,
args: Value,
) -> Result<Value> {
let owner = window.label().to_string();
app.state::<crate::plugins::PluginState>()
.require_lease(&app, &owner, PLUGIN)?;
tauri::async_runtime::spawn_blocking(move || {
app.state::<BrowserState>()
.request(&app, &owner, &command, args)
})
.await
.map_err(fail)?
}
#[tauri::command]
pub async fn browser_stop(state: State<'_, BrowserState>, window: tauri::Window) -> Result<()> {
state.close_window(window.label());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn drag_transfer_requires_the_owner_token_and_rejects_replays() {
let mut routes = WindowTabs::default();
routes.windows.extend(["main".into(), "browser-other".into()]);
routes.assign("a", "browser-other");
let snapshot = json!({ "tabs": [{ "id": "a" }] });
let token = routes.snapshot(snapshot.clone(), "browser-other")["tabs"][0]["transferToken"].as_str().unwrap().to_string();
assert!(routes.snapshot(snapshot, "main")["tabs"].as_array().unwrap().is_empty());
assert!(routes.adopt("a", "main", None).is_err());
assert!(routes.adopt("a", "main", Some("wrong-token")).is_err());
assert_eq!(routes.owners["a"], "browser-other");
assert_eq!(routes.adopt("a", "main", Some(&token)).unwrap(), "browser-other");
assert!(routes.adopt("a", "browser-other", Some(&token)).is_err());
assert!(routes.close("browser-other").is_empty());
assert_eq!(routes.owners["a"], "main");
assert_ne!(routes.transfer_tokens["a"], token);
assert_eq!(routes.close("main"), vec!["a"]);
assert!(routes.transfer_tokens.is_empty());
}
#[test]
fn a_pending_window_move_cannot_be_taken_by_a_drag() {
let mut routes = WindowTabs::default();
routes.assign("a", "main");
let token = routes.transfer_tokens["a"].clone();
routes.pending.insert("a".into(), "browser-target".into());
assert!(routes.adopt("a", "browser-other", Some(&token)).is_err());
assert_eq!(routes.adopt("a", "browser-target", None).unwrap(), "main");
assert!(routes.pending.is_empty());
}
#[test]
fn window_routing_preserves_moved_tabs_and_filters_snapshots() {
let mut routes = WindowTabs::default();
routes.windows.extend(["main".into(), "browser-other".into()]);
routes.owners.insert("a".into(), "main".into());
routes.owners.insert("b".into(), "browser-other".into());
let snapshot = json!({ "tabs": [{ "id": "a" }, { "id": "b" }], "profiles": [{ "id": "user" }] });
assert_eq!(routes.snapshot(snapshot.clone(), "main")["tabs"], json!([{ "id": "a" }]));
assert_eq!(routes.snapshot(snapshot, "browser-other")["tabs"], json!([{ "id": "b" }]));
routes.pending.insert("a".into(), "browser-other".into());
assert!(routes.close("main").is_empty());
assert!(routes.owners.contains_key("a"));
let mut closed = routes.close("browser-other");
closed.sort();
assert_eq!(closed, vec!["a", "b"]);
assert!(routes.owners.is_empty());
}
#[test]
fn cancelled_window_move_keeps_the_source_tab() {
let mut routes = WindowTabs::default();
routes.windows.extend(["main".into(), "browser-other".into()]);
routes.owners.insert("a".into(), "main".into());
routes.pending.insert("a".into(), "browser-other".into());
assert!(routes.close("browser-other").is_empty());
assert_eq!(routes.owners.get("a").map(String::as_str), Some("main"));
assert!(routes.pending.is_empty());
}
#[test]
fn authenticated_connection_survives_idle_period() {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let address = listener.local_addr().unwrap();
let sender = std::thread::spawn(move || {
let mut stream = TcpStream::connect(address).unwrap();
writeln!(stream, "{}", json!({ "token": "test-token" })).unwrap();
std::thread::sleep(Duration::from_millis(1500));
writeln!(stream, "{}", json!({ "id": 1, "result": { "tabs": [] } })).unwrap();
});
let (stream, _) = listener.accept().unwrap();
let (input, mut reader) = authenticate_connection(stream, "test-token").unwrap().unwrap();
assert_eq!(input.read_timeout().unwrap(), None);
assert_eq!(reader.get_ref().read_timeout().unwrap(), None);
let mut line = String::new();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["id"], 1);
sender.join().unwrap();
}
#[test]
fn authentication_preserves_buffered_messages_and_rejects_other_tokens() {
for accepted in [false, true] {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let address = listener.local_addr().unwrap();
let sender = std::thread::spawn(move || {
let mut stream = TcpStream::connect(address).unwrap();
stream.write_all(b"{\"token\":\"test-token\"}\n{\"event\":\"ready\"}\n").unwrap();
});
let (stream, _) = listener.accept().unwrap();
let connection = authenticate_connection(stream, if accepted { "test-token" } else { "other-token" }).unwrap();
if accepted {
let (_, mut reader) = connection.unwrap();
let mut line = String::new();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["event"], "ready");
} else {
assert!(connection.is_none());
}
sender.join().unwrap();
}
}
fn test_worker(replies: mpsc::Receiver<Value>) -> Worker {
Worker {
child: Command::new(std::env::current_exe().unwrap())
.arg("--list")
.stdout(Stdio::null())
.spawn()
.unwrap(),
input: Box::new(Vec::<u8>::new()),
replies,
routing: Arc::new(Mutex::new(WindowTabs::default())),
sequence: 0,
healthy: true,
}
}
#[test]
fn broken_transport_requires_a_fresh_worker() {
let (send, replies) = mpsc::channel();
drop(send);
let mut worker = test_worker(replies);
assert!(worker.request("state", json!({})).is_err());
assert!(!worker.healthy);
assert!(worker.stop().is_ok());
}
#[test]
fn invalid_settings_do_not_discard_the_worker() {
let (send, replies) = mpsc::channel();
send.send(json!({ "id": 1, "error": "Invalid browser settings." })).unwrap();
send.send(json!({ "id": 2, "result": { "tabs": [] } })).unwrap();
let mut worker = test_worker(replies);
assert!(worker.request("settings", json!({})).is_err());
assert!(worker.healthy);
assert_eq!(worker.request("state", json!({})).unwrap(), json!({ "tabs": [] }));
}
#[test]
fn profile_names_cannot_escape_storage() {
for value in ["../other", "a/b", "a\\b", "C:", "", "."] {
assert!(!profile_id(value));
}
assert!(profile_id("user"));
assert!(profile_id("a-b-123"));
}
#[test]
fn protocol_does_not_expose_raw_execution_or_copy_commands() {
for name in [
"executeJavaScript",
"shell",
"prepareDuplicate",
"commitDuplicate",
"shutdown",
] {
assert!(!COMMANDS.contains(&name));
}
}
}
+81
View File
@@ -0,0 +1,81 @@
use std::{collections::HashMap, io::{BufRead, BufReader}, sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}}, time::Duration};
use reqwest::{blocking::Client, Url};
use serde::Deserialize;
use tauri::{ipc::Channel, State, WebviewWindow};
#[derive(Default)]
pub struct CompletionState { requests: Mutex<HashMap<String, Arc<AtomicBool>>> }
impl CompletionState {
pub fn close_window(&self, window: &str) {
if let Ok(mut requests) = self.requests.lock() {
requests.retain(|key, flag| { if key.starts_with(&format!("{window}:")) { flag.store(true, Ordering::Relaxed); false } else { true } });
}
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CompletionRequest { endpoint: String, route: String, body: Option<String>, timeout_ms: Option<u64> }
fn target(endpoint: &str, route: &str) -> Result<Url, String> {
let mut url = Url::parse(endpoint).map_err(|_| "Enter a local server URL.")?;
if !matches!(url.scheme(), "http" | "https") || !matches!(url.host_str(), Some("127.0.0.1" | "[::1]" | "localhost"))
|| !url.username().is_empty() || url.password().is_some() || url.query().is_some() || url.fragment().is_some()
|| !matches!(url.path(), "" | "/" | "/v1" | "/v1/") {
return Err("This trial connects only to a loopback model server.".into());
}
if !matches!(route, "/v1/models" | "/v1/chat/completions" | "/api/tags" | "/api/generate") { return Err("Unsupported completion route.".into()); }
if url.host_str() == Some("localhost") { url.set_host(Some("127.0.0.1")).map_err(|_| "Invalid local host.")?; }
url.set_path(route); Ok(url)
}
#[tauri::command]
pub fn completion_cancel(window: WebviewWindow, state: State<'_, CompletionState>, id: String) {
if let Ok(requests) = state.requests.lock() { if let Some(flag) = requests.get(&format!("{}:{id}", window.label())) { flag.store(true, Ordering::Relaxed); } }
}
#[tauri::command]
pub async fn completion_request(window: WebviewWindow, state: State<'_, CompletionState>, id: String, request: CompletionRequest, on_line: Channel<String>) -> Result<(), String> {
if id.len() > 80 || request.body.as_ref().is_some_and(|v| v.len() > 32768) { return Err("Completion request is too large.".into()); }
let url = target(&request.endpoint, &request.route)?;
let flag = Arc::new(AtomicBool::new(false));
let key = format!("{}:{id}", window.label());
{
let mut requests = state.requests.lock().map_err(|_| "Completion state is unavailable.")?;
if requests.len() >= 16 { return Err("The local server is busy. Wait before retrying.".into()); }
requests.insert(key.clone(), flag.clone());
}
let result = tauri::async_runtime::spawn_blocking(move || {
let client = Client::builder().no_proxy().redirect(reqwest::redirect::Policy::none())
.connect_timeout(Duration::from_secs(2)).timeout(Duration::from_millis(request.timeout_ms.unwrap_or(5000).clamp(100, 15000)))
.build().map_err(|_| "Could not create a local connection.".to_string())?;
if flag.load(Ordering::Relaxed) { return Ok(()); }
let call = if let Some(body) = request.body { client.post(url).header("Content-Type", "application/json").body(body) } else { client.get(url) };
let response = call.send().map_err(|e| if e.is_timeout() { "The local model timed out." } else { "Cannot connect to the local model server." }.to_string())?;
if !response.status().is_success() { return Err(format!("Local server returned HTTP {}.", response.status().as_u16())); }
let mut reader = BufReader::new(response);
let mut total = 0;
loop {
if flag.load(Ordering::Relaxed) { return Ok(()); }
let mut bytes = Vec::new();
let count = std::io::Read::take(&mut reader, 65537).read_until(b'\n', &mut bytes).map_err(|_| "The local response ended unexpectedly.".to_string())?;
if count == 0 { break; }
total += count;
if count > 65536 || total > 262144 { return Err("Local response exceeded the size limit.".into()); }
if flag.load(Ordering::Relaxed) { return Ok(()); }
let line = String::from_utf8(bytes).map_err(|_| "Local response is not UTF-8.".to_string())?;
if on_line.send(line).is_err() { break; }
}
Ok(())
}).await.map_err(|_| "Local completion task stopped.".to_string());
if let Ok(mut requests) = state.requests.lock() { requests.remove(&key); }
result?
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_loopback_and_fixed_routes() {
assert_eq!(target("http://localhost:8080/v1", "/v1/models").unwrap().as_str(), "http://127.0.0.1:8080/v1/models");
for address in ["https://example.com", "http://127.0.0.1.example.com", "http://user@localhost", "file:///a", "http://localhost/?key=x", "http://localhost/path"] {
assert!(target(address, "/v1/models").is_err(), "{address}");
}
assert!(target("http://127.0.0.1:8080", "/shutdown").is_err());
}
}
+16
View File
@@ -2,6 +2,9 @@ mod pty;
mod plugins;
mod plugin_sources;
mod workspace;
mod browser;
mod completion;
mod settings;
use pty::PtyState;
use tauri::Manager;
@@ -15,13 +18,22 @@ pub fn run() {
.manage(WorkspaceState::new())
.manage(PtyState::new())
.manage(plugins::PluginState::default())
.manage(browser::BrowserState::default())
.manage(completion::CompletionState::default())
.manage(settings::SettingsState::default())
.invoke_handler(tauri::generate_handler![
settings::settings_open_window,
completion::completion_request,
completion::completion_cancel,
browser::browser_request,
browser::browser_stop,
workspace::workspace_open,
workspace::workspace_open_window,
workspace::workspace_last_path,
workspace::workspace_recent,
workspace::workspace_new,
workspace::workspace_list,
workspace::workspace_list_markdown,
workspace::workspace_read,
workspace::workspace_read_bytes,
workspace::workspace_write,
@@ -60,12 +72,16 @@ pub fn run() {
.expect("error while building tauri application")
.run(|app, event| {
if let tauri::RunEvent::WindowEvent { label, event: tauri::WindowEvent::Destroyed, .. } = &event {
settings::close_owned_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);
app.state::<WorkspaceState>().close_window(label);
}
if matches!(event, tauri::RunEvent::Exit) {
app.state::<PtyState>().close_all();
app.state::<browser::BrowserState>().close_all();
}
});
}
+16 -2
View File
@@ -861,6 +861,13 @@ impl Service {
}
}
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()) }
})
}
fn with<T>(
&self,
app: &AppHandle,
@@ -1019,6 +1026,7 @@ pub async fn plugins_set_enabled(
enabled: bool,
hash: Option<String>,
) -> Result<()> {
let stop_browser = id == "runestone.browser" && !enabled;
state.with(&app, |service| {
if service.removing.contains_key(&id) {
return Err("Wait for plugin removal to finish.".into());
@@ -1047,6 +1055,7 @@ pub async fn plugins_set_enabled(
}
Ok(())
})?;
if stop_browser { app.state::<crate::browser::BrowserState>().close_all(); }
changed(&app);
Ok(())
}
@@ -1183,7 +1192,8 @@ pub async fn plugins_data(
id: String,
value: Option<String>,
) -> Result<String> {
state.with(&app, |service| {
let changed = value.is_some();
let result = state.with(&app, |service| {
if !service.row(&id)?.enabled {
return Err("The plugin is disabled.".into());
}
@@ -1211,7 +1221,11 @@ pub async fn plugins_data(
} else {
Ok("null".into())
}
})
})?;
if changed {
let _ = app.emit("plugin-settings-changed", &id);
}
Ok(result)
}
#[tauri::command]
pub async fn plugins_asset(
+222
View File
@@ -0,0 +1,222 @@
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}};
use tauri::{AppHandle, Manager, State};
use crate::workspace::{current_root_path, WorkspaceState};
#[derive(Default)]
pub struct SettingsState(Mutex<HashMap<String, Arc<AtomicBool>>>);
struct PendingOpen<'a> {
state: &'a SettingsState,
label: String,
cancelled: Arc<AtomicBool>,
}
impl SettingsState {
fn reserve(&self, label: &str) -> Result<Option<PendingOpen<'_>>, String> {
let mut pending = self.0.lock().map_err(|_| "Settings window lock failed.")?;
if let Some(cancelled) = pending.get(label) {
return if cancelled.load(Ordering::SeqCst) {
Err("The workspace changed while settings opened. Try again.".into())
} else { Ok(None) };
}
let cancelled = Arc::new(AtomicBool::new(false));
pending.insert(label.into(), cancelled.clone());
Ok(Some(PendingOpen { state: self, label: label.into(), cancelled }))
}
fn cancel(&self, label: &str) {
if let Ok(pending) = self.0.lock() {
if let Some(cancelled) = pending.get(label) { cancelled.store(true, Ordering::SeqCst); }
}
}
}
impl PendingOpen<'_> {
fn can_publish(&self, owner_exists: bool, expected: &Option<PathBuf>, current: &Option<PathBuf>) -> bool {
!self.cancelled.load(Ordering::SeqCst) && owner_exists && expected == current
}
}
impl Drop for PendingOpen<'_> {
fn drop(&mut self) {
if let Ok(mut pending) = self.state.0.lock() { pending.remove(&self.label); }
}
}
fn settings_label(owner: &str) -> Result<String, String> {
if owner == "main" || owner.starts_with("workspace-") {
Ok(format!("settings-{owner}"))
} else {
Err("Open settings from a workspace window.".into())
}
}
fn bind_workspace(workspace: &WorkspaceState, owner: &str, label: &str) -> Result<(), String> {
if let Ok(root) = current_root_path(workspace, owner) {
workspace.bind_terminal(label, root).map_err(|error| error.to_string())?;
} else {
workspace.close_window(label);
}
Ok(())
}
#[tauri::command]
pub async fn settings_open_window(
app: AppHandle,
window: tauri::Window,
state: State<'_, SettingsState>,
workspace: State<'_, WorkspaceState>,
) -> Result<(), String> {
let label = settings_label(window.label())?;
// The reservation survives native calls, but its mutex guard never does.
let Some(pending) = state.reserve(&label)? else { return Ok(()); };
let root = current_root_path(&workspace, window.label()).ok();
let valid = || pending.can_publish(
app.get_webview_window(window.label()).is_some(),
&root, &current_root_path(&workspace, window.label()).ok(),
);
if !valid() { return Err("The workspace closed while settings opened.".into()); }
bind_workspace(&workspace, window.label(), &label)?;
let settings = if let Some(existing) = app.get_webview_window(&label) {
existing
} else {
let title = root.as_ref()
.and_then(|root| root.file_name().map(|name| format!("Settings — {} — RuneStone", name.to_string_lossy())))
.unwrap_or_else(|| "Settings — RuneStone".into());
match tauri::WebviewWindowBuilder::new(
&app, &label, tauri::WebviewUrl::App("?settingsWindow=true".into()),
)
.title(title)
.inner_size(920.0, 650.0)
.min_inner_size(540.0, 420.0)
.decorations(true)
.resizable(true)
.visible(false)
.disable_drag_drop_handler()
.build() {
Ok(settings) => settings,
Err(error) => { workspace.close_window(&label); return Err(error.to_string()); }
}
};
let result = (|| {
if !valid() { return Err("The workspace changed while settings opened.".into()); }
settings.unminimize().map_err(|error| error.to_string())?;
settings.show().map_err(|error| error.to_string())?;
settings.set_focus().map_err(|error| error.to_string())?;
if !valid() { return Err("The workspace changed while settings opened.".into()); }
Ok(())
})();
if result.is_err() {
let _ = settings.destroy();
workspace.close_window(&label);
}
result
}
pub fn close_owned_window(app: &AppHandle, owner: &str) {
if let Ok(label) = settings_label(owner) {
app.state::<SettingsState>().cancel(&label);
if let Some(window) = app.get_webview_window(&label) { let _ = window.destroy(); }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pending_opens_deduplicate_without_holding_the_state_lock() {
let state = SettingsState::default();
let first = state.reserve("settings-main").unwrap().unwrap();
assert!(state.0.try_lock().is_ok());
assert!(state.reserve("settings-main").unwrap().is_none());
assert!(state.reserve("settings-workspace-2").unwrap().is_some());
drop(first);
assert!(state.reserve("settings-main").unwrap().is_some());
}
#[test]
fn lifecycle_cancellation_does_not_wait_for_an_inflight_build() {
let state = Arc::new(SettingsState::default());
let (started_tx, started_rx) = std::sync::mpsc::channel();
let (resume_tx, resume_rx) = std::sync::mpsc::channel();
let worker_state = state.clone();
let worker = std::thread::spawn(move || {
let pending = worker_state.reserve("settings-main").unwrap().unwrap();
started_tx.send(()).unwrap();
// Stand in for a native build waiting for the UI thread.
resume_rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap();
assert!(!pending.can_publish(true, &None, &None));
});
started_rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap();
state.cancel("settings-main");
assert!(state.reserve("settings-main").is_err());
resume_tx.send(()).unwrap();
worker.join().unwrap();
assert!(state.reserve("settings-main").unwrap().is_some());
}
#[test]
fn completed_build_rejects_closed_owners_and_changed_workspaces() {
let state = SettingsState::default();
let pending = state.reserve("settings-main").unwrap().unwrap();
let root = Some(PathBuf::from("/one"));
assert!(pending.can_publish(true, &root, &root));
assert!(!pending.can_publish(false, &root, &root));
assert!(!pending.can_publish(true, &None, &root));
assert!(!pending.can_publish(true, &root, &Some(PathBuf::from("/two"))));
state.cancel("settings-main");
assert!(!pending.can_publish(true, &root, &root));
}
#[test]
fn failed_build_releases_its_reservation_for_retry() {
let state = SettingsState::default();
let failed = || -> Result<(), String> {
let _pending = state.reserve("settings-main")?.unwrap();
Err("Native build failed".into())
};
assert!(failed().is_err());
assert!(state.reserve("settings-main").unwrap().is_some());
}
#[test]
fn each_workspace_reuses_its_own_settings_label() {
assert_eq!(settings_label("main").unwrap(), "settings-main");
assert_eq!(settings_label("workspace-12").unwrap(), "settings-workspace-12");
assert_ne!(settings_label("main").unwrap(), settings_label("workspace-12").unwrap());
}
#[test]
fn auxiliary_windows_cannot_create_settings_windows() {
for owner in ["settings-main", "terminal-123", "browser-123", "external"] {
assert!(settings_label(owner).is_err());
}
}
#[test]
fn settings_use_only_the_owners_workspace_and_release_it_on_close() {
let workspace = WorkspaceState::new();
workspace.bind_terminal("workspace-1", "/one".into()).unwrap();
workspace.bind_terminal("workspace-2", "/two".into()).unwrap();
bind_workspace(&workspace, "workspace-1", "settings-workspace-1").unwrap();
bind_workspace(&workspace, "workspace-2", "settings-workspace-2").unwrap();
assert_eq!(current_root_path(&workspace, "settings-workspace-1").unwrap(), std::path::PathBuf::from("/one"));
assert_eq!(current_root_path(&workspace, "settings-workspace-2").unwrap(), std::path::PathBuf::from("/two"));
workspace.close_window("settings-workspace-1");
assert!(current_root_path(&workspace, "settings-workspace-1").is_err());
assert!(current_root_path(&workspace, "workspace-1").is_ok());
}
#[test]
fn settings_without_a_workspace_never_use_the_recent_workspace() {
let workspace = WorkspaceState::new();
bind_workspace(&workspace, "main", "settings-main").unwrap();
assert!(current_root_path(&workspace, "settings-main").is_err());
workspace.bind_terminal("main", "/opened-later".into()).unwrap();
bind_workspace(&workspace, "main", "settings-main").unwrap();
assert_eq!(current_root_path(&workspace, "settings-main").unwrap(), std::path::PathBuf::from("/opened-later"));
}
}
+64
View File
@@ -450,6 +450,8 @@ pub fn workspace_open(
});
}
let _ = window.set_title(&format!("{} — RuneStone", workspace_info(&root).name));
// A settings session opened before this workspace must start with its new context.
crate::settings::close_owned_window(&app, window.label());
Ok(workspace_info(&root))
}
@@ -510,6 +512,39 @@ fn list_entries(root: &Path, rel: &str) -> WsResult<Vec<TreeEntry>> {
Ok(entries)
}
#[tauri::command]
pub async fn workspace_list_markdown(window: tauri::Window, state: State<'_, WorkspaceState>) -> WsResult<Vec<String>> {
let root = current_root_path(&state, window.label())?;
tauri::async_runtime::spawn_blocking(move || markdown_paths(&root))
.await.map_err(|error| err(format!("Markdown scan failed: {error}")))?
}
fn markdown_paths(root: &Path) -> WsResult<Vec<String>> {
let mut folders = vec![root.to_path_buf()];
let mut paths = Vec::new();
while let Some(folder) = folders.pop() {
for entry in fs::read_dir(folder)? {
let entry = entry?;
let name = entry.file_name();
// Match PM discovery without a desktop request for every directory.
if name.to_string_lossy().starts_with('.') { continue; }
let kind = entry.file_type()?;
if kind.is_symlink() { continue; }
let path = entry.path();
if kind.is_dir() {
folders.push(path);
} else if kind.is_file() {
let extension = path.extension().and_then(|value| value.to_str()).unwrap_or("").to_ascii_lowercase();
if matches!(extension.as_str(), "md" | "markdown" | "mdown") {
if let Some(rel) = to_rel(root, &path) { paths.push(rel); }
}
}
}
}
paths.sort();
Ok(paths)
}
#[tauri::command]
pub fn workspace_read(window: tauri::Window, state: State<WorkspaceState>, rel: String, missing_ok: Option<bool>) -> WsResult<Option<String>> {
let root = current_root(&state, window.label())?;
@@ -812,6 +847,11 @@ pub fn workspace_abs_path(window: tauri::Window, state: State<WorkspaceState>, r
pub fn workspace_reveal(window: tauri::Window, app: AppHandle, state: State<WorkspaceState>, rel: String) -> WsResult<()> {
let root = current_root(&state, window.label())?;
let path = resolve_existing(&root, &rel)?;
if rel.is_empty() {
return app.opener()
.open_path(dunce::simplified(&path).to_string_lossy().into_owned(), None::<&str>)
.map_err(|e| err(e.to_string()));
}
if app.opener().reveal_item_in_dir(&path).is_ok() {
return Ok(());
}
@@ -936,6 +976,30 @@ mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn markdown_listing_preserves_discovery_and_excludes_hidden_storage() {
let root = std::env::temp_dir().join(format!("rs-markdown-list-{}", uuid::Uuid::new_v4()));
for rel in ["Notes", "target/deep", ".runestone/pm/cards", "Notes/.hidden", ".git"] {
fs::create_dir_all(root.join(rel)).unwrap();
}
for rel in ["Board.MD", "Notes/one.markdown", "target/deep/two.mdown", ".runestone/pm/cards/private.md", "Notes/.hidden/secret.md", ".git/hidden.md", "Notes/.hidden.md", "Notes/plain.txt"] {
fs::write(root.join(rel), "text").unwrap();
}
fs::write(root.join(".gitignore"), "Notes/\ntarget/\n").unwrap();
assert_eq!(markdown_paths(&root).unwrap(), vec!["Board.MD", "Notes/one.markdown", "target/deep/two.mdown"]);
fs::remove_dir_all(&root).unwrap();
assert!(markdown_paths(&root).is_err());
}
#[test]
#[ignore = "Set RUNESTONE_SCAN_BENCH_ROOT to an existing workspace."]
fn markdown_listing_workspace_benchmark() {
let root = dunce::canonicalize(std::env::var("RUNESTONE_SCAN_BENCH_ROOT").unwrap()).unwrap();
let start = std::time::Instant::now();
let paths = markdown_paths(&root).unwrap();
println!("Native Markdown discovery: {} paths, {:?}", paths.len(), start.elapsed());
}
#[test]
fn binary_reads_preserve_bytes_and_enforce_workspace_and_size_limits() {
let fixture = std::env::temp_dir().join(format!("rs-binary-{}", std::process::id()));