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:
@@ -3,6 +3,8 @@ use reqwest::{blocking::Client, Url};
|
||||
use serde::Deserialize;
|
||||
use tauri::{ipc::Channel, State, WebviewWindow};
|
||||
|
||||
use crate::error::Result;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct CompletionState { requests: Mutex<HashMap<String, Arc<AtomicBool>>> }
|
||||
impl CompletionState {
|
||||
@@ -15,7 +17,7 @@ impl CompletionState {
|
||||
#[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> {
|
||||
fn target(endpoint: &str, route: &str) -> Result<Url> {
|
||||
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()
|
||||
@@ -31,7 +33,7 @@ pub fn completion_cancel(window: WebviewWindow, state: State<'_, CompletionState
|
||||
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> {
|
||||
pub async fn completion_request(window: WebviewWindow, state: State<'_, CompletionState>, id: String, request: CompletionRequest, on_line: Channel<String>) -> Result<()> {
|
||||
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));
|
||||
@@ -41,29 +43,29 @@ pub async fn completion_request(window: WebviewWindow, state: State<'_, Completi
|
||||
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 result = tauri::async_runtime::spawn_blocking(move || -> Result<()> {
|
||||
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())?;
|
||||
.build().map_err(|_| "Could not create a local connection.")?;
|
||||
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 response = call.send().map_err(|e| if e.is_timeout() { "The local model timed out." } else { "Cannot connect to the local model server." })?;
|
||||
if !response.status().is_success() { return Err(format!("Local server returned HTTP {}.", response.status().as_u16()).into()); }
|
||||
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())?;
|
||||
let count = std::io::Read::take(&mut reader, 65537).read_until(b'\n', &mut bytes).map_err(|_| "The local response ended unexpectedly.")?;
|
||||
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())?;
|
||||
let line = String::from_utf8(bytes).map_err(|_| "Local response is not UTF-8.")?;
|
||||
if on_line.send(line).is_err() { break; }
|
||||
}
|
||||
Ok(())
|
||||
}).await.map_err(|_| "Local completion task stopped.".to_string());
|
||||
}).await.map_err(|_| "Local completion task stopped.");
|
||||
if let Ok(mut requests) = state.requests.lock() { requests.remove(&key); }
|
||||
result?
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user